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 if (Ty->isAtomicType() || typeIsSuitableForInlineAtomic(Ty, Volatile)) { 1277 LValue lvalue = 1278 LValue::MakeAddr(Addr, Ty, getContext(), AlignSource, TBAAInfo); 1279 return EmitAtomicLoad(lvalue, 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 if (Ty->isAtomicType() || 1388 (!isInit && typeIsSuitableForInlineAtomic(Ty, Volatile))) { 1389 EmitAtomicStore(RValue::get(Value), 1390 LValue::MakeAddr(Addr, Ty, getContext(), 1391 AlignSource, TBAAInfo), 1392 isInit); 1393 return; 1394 } 1395 1396 llvm::StoreInst *Store = Builder.CreateStore(Value, Addr, Volatile); 1397 if (isNontemporal) { 1398 llvm::MDNode *Node = 1399 llvm::MDNode::get(Store->getContext(), 1400 llvm::ConstantAsMetadata::get(Builder.getInt32(1))); 1401 Store->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node); 1402 } 1403 if (TBAAInfo) { 1404 llvm::MDNode *TBAAPath = CGM.getTBAAStructTagInfo(TBAABaseType, TBAAInfo, 1405 TBAAOffset); 1406 if (TBAAPath) 1407 CGM.DecorateInstructionWithTBAA(Store, TBAAPath, 1408 false /*ConvertTypeToTag*/); 1409 } 1410 } 1411 1412 void CodeGenFunction::EmitStoreOfScalar(llvm::Value *value, LValue lvalue, 1413 bool isInit) { 1414 EmitStoreOfScalar(value, lvalue.getAddress(), lvalue.isVolatile(), 1415 lvalue.getType(), lvalue.getAlignmentSource(), 1416 lvalue.getTBAAInfo(), isInit, lvalue.getTBAABaseType(), 1417 lvalue.getTBAAOffset(), lvalue.isNontemporal()); 1418 } 1419 1420 /// EmitLoadOfLValue - Given an expression that represents a value lvalue, this 1421 /// method emits the address of the lvalue, then loads the result as an rvalue, 1422 /// returning the rvalue. 1423 RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, SourceLocation Loc) { 1424 if (LV.isObjCWeak()) { 1425 // load of a __weak object. 1426 Address AddrWeakObj = LV.getAddress(); 1427 return RValue::get(CGM.getObjCRuntime().EmitObjCWeakRead(*this, 1428 AddrWeakObj)); 1429 } 1430 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) { 1431 // In MRC mode, we do a load+autorelease. 1432 if (!getLangOpts().ObjCAutoRefCount) { 1433 return RValue::get(EmitARCLoadWeak(LV.getAddress())); 1434 } 1435 1436 // In ARC mode, we load retained and then consume the value. 1437 llvm::Value *Object = EmitARCLoadWeakRetained(LV.getAddress()); 1438 Object = EmitObjCConsumeObject(LV.getType(), Object); 1439 return RValue::get(Object); 1440 } 1441 1442 if (LV.isSimple()) { 1443 assert(!LV.getType()->isFunctionType()); 1444 1445 // Everything needs a load. 1446 return RValue::get(EmitLoadOfScalar(LV, Loc)); 1447 } 1448 1449 if (LV.isVectorElt()) { 1450 llvm::LoadInst *Load = Builder.CreateLoad(LV.getVectorAddress(), 1451 LV.isVolatileQualified()); 1452 return RValue::get(Builder.CreateExtractElement(Load, LV.getVectorIdx(), 1453 "vecext")); 1454 } 1455 1456 // If this is a reference to a subset of the elements of a vector, either 1457 // shuffle the input or extract/insert them as appropriate. 1458 if (LV.isExtVectorElt()) 1459 return EmitLoadOfExtVectorElementLValue(LV); 1460 1461 // Global Register variables always invoke intrinsics 1462 if (LV.isGlobalReg()) 1463 return EmitLoadOfGlobalRegLValue(LV); 1464 1465 assert(LV.isBitField() && "Unknown LValue type!"); 1466 return EmitLoadOfBitfieldLValue(LV); 1467 } 1468 1469 RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV) { 1470 const CGBitFieldInfo &Info = LV.getBitFieldInfo(); 1471 1472 // Get the output type. 1473 llvm::Type *ResLTy = ConvertType(LV.getType()); 1474 1475 Address Ptr = LV.getBitFieldAddress(); 1476 llvm::Value *Val = Builder.CreateLoad(Ptr, LV.isVolatileQualified(), "bf.load"); 1477 1478 if (Info.IsSigned) { 1479 assert(static_cast<unsigned>(Info.Offset + Info.Size) <= Info.StorageSize); 1480 unsigned HighBits = Info.StorageSize - Info.Offset - Info.Size; 1481 if (HighBits) 1482 Val = Builder.CreateShl(Val, HighBits, "bf.shl"); 1483 if (Info.Offset + HighBits) 1484 Val = Builder.CreateAShr(Val, Info.Offset + HighBits, "bf.ashr"); 1485 } else { 1486 if (Info.Offset) 1487 Val = Builder.CreateLShr(Val, Info.Offset, "bf.lshr"); 1488 if (static_cast<unsigned>(Info.Offset) + Info.Size < Info.StorageSize) 1489 Val = Builder.CreateAnd(Val, llvm::APInt::getLowBitsSet(Info.StorageSize, 1490 Info.Size), 1491 "bf.clear"); 1492 } 1493 Val = Builder.CreateIntCast(Val, ResLTy, Info.IsSigned, "bf.cast"); 1494 1495 return RValue::get(Val); 1496 } 1497 1498 // If this is a reference to a subset of the elements of a vector, create an 1499 // appropriate shufflevector. 1500 RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV) { 1501 llvm::Value *Vec = Builder.CreateLoad(LV.getExtVectorAddress(), 1502 LV.isVolatileQualified()); 1503 1504 const llvm::Constant *Elts = LV.getExtVectorElts(); 1505 1506 // If the result of the expression is a non-vector type, we must be extracting 1507 // a single element. Just codegen as an extractelement. 1508 const VectorType *ExprVT = LV.getType()->getAs<VectorType>(); 1509 if (!ExprVT) { 1510 unsigned InIdx = getAccessedFieldNo(0, Elts); 1511 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx); 1512 return RValue::get(Builder.CreateExtractElement(Vec, Elt)); 1513 } 1514 1515 // Always use shuffle vector to try to retain the original program structure 1516 unsigned NumResultElts = ExprVT->getNumElements(); 1517 1518 SmallVector<llvm::Constant*, 4> Mask; 1519 for (unsigned i = 0; i != NumResultElts; ++i) 1520 Mask.push_back(Builder.getInt32(getAccessedFieldNo(i, Elts))); 1521 1522 llvm::Value *MaskV = llvm::ConstantVector::get(Mask); 1523 Vec = Builder.CreateShuffleVector(Vec, llvm::UndefValue::get(Vec->getType()), 1524 MaskV); 1525 return RValue::get(Vec); 1526 } 1527 1528 /// @brief Generates lvalue for partial ext_vector access. 1529 Address CodeGenFunction::EmitExtVectorElementLValue(LValue LV) { 1530 Address VectorAddress = LV.getExtVectorAddress(); 1531 const VectorType *ExprVT = LV.getType()->getAs<VectorType>(); 1532 QualType EQT = ExprVT->getElementType(); 1533 llvm::Type *VectorElementTy = CGM.getTypes().ConvertType(EQT); 1534 1535 Address CastToPointerElement = 1536 Builder.CreateElementBitCast(VectorAddress, VectorElementTy, 1537 "conv.ptr.element"); 1538 1539 const llvm::Constant *Elts = LV.getExtVectorElts(); 1540 unsigned ix = getAccessedFieldNo(0, Elts); 1541 1542 Address VectorBasePtrPlusIx = 1543 Builder.CreateConstInBoundsGEP(CastToPointerElement, ix, 1544 getContext().getTypeSizeInChars(EQT), 1545 "vector.elt"); 1546 1547 return VectorBasePtrPlusIx; 1548 } 1549 1550 /// @brief Load of global gamed gegisters are always calls to intrinsics. 1551 RValue CodeGenFunction::EmitLoadOfGlobalRegLValue(LValue LV) { 1552 assert((LV.getType()->isIntegerType() || LV.getType()->isPointerType()) && 1553 "Bad type for register variable"); 1554 llvm::MDNode *RegName = cast<llvm::MDNode>( 1555 cast<llvm::MetadataAsValue>(LV.getGlobalReg())->getMetadata()); 1556 1557 // We accept integer and pointer types only 1558 llvm::Type *OrigTy = CGM.getTypes().ConvertType(LV.getType()); 1559 llvm::Type *Ty = OrigTy; 1560 if (OrigTy->isPointerTy()) 1561 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy); 1562 llvm::Type *Types[] = { Ty }; 1563 1564 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::read_register, Types); 1565 llvm::Value *Call = Builder.CreateCall( 1566 F, llvm::MetadataAsValue::get(Ty->getContext(), RegName)); 1567 if (OrigTy->isPointerTy()) 1568 Call = Builder.CreateIntToPtr(Call, OrigTy); 1569 return RValue::get(Call); 1570 } 1571 1572 1573 /// EmitStoreThroughLValue - Store the specified rvalue into the specified 1574 /// lvalue, where both are guaranteed to the have the same type, and that type 1575 /// is 'Ty'. 1576 void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst, 1577 bool isInit) { 1578 if (!Dst.isSimple()) { 1579 if (Dst.isVectorElt()) { 1580 // Read/modify/write the vector, inserting the new element. 1581 llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddress(), 1582 Dst.isVolatileQualified()); 1583 Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(), 1584 Dst.getVectorIdx(), "vecins"); 1585 Builder.CreateStore(Vec, Dst.getVectorAddress(), 1586 Dst.isVolatileQualified()); 1587 return; 1588 } 1589 1590 // If this is an update of extended vector elements, insert them as 1591 // appropriate. 1592 if (Dst.isExtVectorElt()) 1593 return EmitStoreThroughExtVectorComponentLValue(Src, Dst); 1594 1595 if (Dst.isGlobalReg()) 1596 return EmitStoreThroughGlobalRegLValue(Src, Dst); 1597 1598 assert(Dst.isBitField() && "Unknown LValue type"); 1599 return EmitStoreThroughBitfieldLValue(Src, Dst); 1600 } 1601 1602 // There's special magic for assigning into an ARC-qualified l-value. 1603 if (Qualifiers::ObjCLifetime Lifetime = Dst.getQuals().getObjCLifetime()) { 1604 switch (Lifetime) { 1605 case Qualifiers::OCL_None: 1606 llvm_unreachable("present but none"); 1607 1608 case Qualifiers::OCL_ExplicitNone: 1609 // nothing special 1610 break; 1611 1612 case Qualifiers::OCL_Strong: 1613 EmitARCStoreStrong(Dst, Src.getScalarVal(), /*ignore*/ true); 1614 return; 1615 1616 case Qualifiers::OCL_Weak: 1617 EmitARCStoreWeak(Dst.getAddress(), Src.getScalarVal(), /*ignore*/ true); 1618 return; 1619 1620 case Qualifiers::OCL_Autoreleasing: 1621 Src = RValue::get(EmitObjCExtendObjectLifetime(Dst.getType(), 1622 Src.getScalarVal())); 1623 // fall into the normal path 1624 break; 1625 } 1626 } 1627 1628 if (Dst.isObjCWeak() && !Dst.isNonGC()) { 1629 // load of a __weak object. 1630 Address LvalueDst = Dst.getAddress(); 1631 llvm::Value *src = Src.getScalarVal(); 1632 CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst); 1633 return; 1634 } 1635 1636 if (Dst.isObjCStrong() && !Dst.isNonGC()) { 1637 // load of a __strong object. 1638 Address LvalueDst = Dst.getAddress(); 1639 llvm::Value *src = Src.getScalarVal(); 1640 if (Dst.isObjCIvar()) { 1641 assert(Dst.getBaseIvarExp() && "BaseIvarExp is NULL"); 1642 llvm::Type *ResultType = IntPtrTy; 1643 Address dst = EmitPointerWithAlignment(Dst.getBaseIvarExp()); 1644 llvm::Value *RHS = dst.getPointer(); 1645 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast"); 1646 llvm::Value *LHS = 1647 Builder.CreatePtrToInt(LvalueDst.getPointer(), ResultType, 1648 "sub.ptr.lhs.cast"); 1649 llvm::Value *BytesBetween = Builder.CreateSub(LHS, RHS, "ivar.offset"); 1650 CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, dst, 1651 BytesBetween); 1652 } else if (Dst.isGlobalObjCRef()) { 1653 CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst, 1654 Dst.isThreadLocalRef()); 1655 } 1656 else 1657 CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst); 1658 return; 1659 } 1660 1661 assert(Src.isScalar() && "Can't emit an agg store with this method"); 1662 EmitStoreOfScalar(Src.getScalarVal(), Dst, isInit); 1663 } 1664 1665 void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst, 1666 llvm::Value **Result) { 1667 const CGBitFieldInfo &Info = Dst.getBitFieldInfo(); 1668 llvm::Type *ResLTy = ConvertTypeForMem(Dst.getType()); 1669 Address Ptr = Dst.getBitFieldAddress(); 1670 1671 // Get the source value, truncated to the width of the bit-field. 1672 llvm::Value *SrcVal = Src.getScalarVal(); 1673 1674 // Cast the source to the storage type and shift it into place. 1675 SrcVal = Builder.CreateIntCast(SrcVal, Ptr.getElementType(), 1676 /*IsSigned=*/false); 1677 llvm::Value *MaskedVal = SrcVal; 1678 1679 // See if there are other bits in the bitfield's storage we'll need to load 1680 // and mask together with source before storing. 1681 if (Info.StorageSize != Info.Size) { 1682 assert(Info.StorageSize > Info.Size && "Invalid bitfield size."); 1683 llvm::Value *Val = 1684 Builder.CreateLoad(Ptr, Dst.isVolatileQualified(), "bf.load"); 1685 1686 // Mask the source value as needed. 1687 if (!hasBooleanRepresentation(Dst.getType())) 1688 SrcVal = Builder.CreateAnd(SrcVal, 1689 llvm::APInt::getLowBitsSet(Info.StorageSize, 1690 Info.Size), 1691 "bf.value"); 1692 MaskedVal = SrcVal; 1693 if (Info.Offset) 1694 SrcVal = Builder.CreateShl(SrcVal, Info.Offset, "bf.shl"); 1695 1696 // Mask out the original value. 1697 Val = Builder.CreateAnd(Val, 1698 ~llvm::APInt::getBitsSet(Info.StorageSize, 1699 Info.Offset, 1700 Info.Offset + Info.Size), 1701 "bf.clear"); 1702 1703 // Or together the unchanged values and the source value. 1704 SrcVal = Builder.CreateOr(Val, SrcVal, "bf.set"); 1705 } else { 1706 assert(Info.Offset == 0); 1707 } 1708 1709 // Write the new value back out. 1710 Builder.CreateStore(SrcVal, Ptr, Dst.isVolatileQualified()); 1711 1712 // Return the new value of the bit-field, if requested. 1713 if (Result) { 1714 llvm::Value *ResultVal = MaskedVal; 1715 1716 // Sign extend the value if needed. 1717 if (Info.IsSigned) { 1718 assert(Info.Size <= Info.StorageSize); 1719 unsigned HighBits = Info.StorageSize - Info.Size; 1720 if (HighBits) { 1721 ResultVal = Builder.CreateShl(ResultVal, HighBits, "bf.result.shl"); 1722 ResultVal = Builder.CreateAShr(ResultVal, HighBits, "bf.result.ashr"); 1723 } 1724 } 1725 1726 ResultVal = Builder.CreateIntCast(ResultVal, ResLTy, Info.IsSigned, 1727 "bf.result.cast"); 1728 *Result = EmitFromMemory(ResultVal, Dst.getType()); 1729 } 1730 } 1731 1732 void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src, 1733 LValue Dst) { 1734 // This access turns into a read/modify/write of the vector. Load the input 1735 // value now. 1736 llvm::Value *Vec = Builder.CreateLoad(Dst.getExtVectorAddress(), 1737 Dst.isVolatileQualified()); 1738 const llvm::Constant *Elts = Dst.getExtVectorElts(); 1739 1740 llvm::Value *SrcVal = Src.getScalarVal(); 1741 1742 if (const VectorType *VTy = Dst.getType()->getAs<VectorType>()) { 1743 unsigned NumSrcElts = VTy->getNumElements(); 1744 unsigned NumDstElts = 1745 cast<llvm::VectorType>(Vec->getType())->getNumElements(); 1746 if (NumDstElts == NumSrcElts) { 1747 // Use shuffle vector is the src and destination are the same number of 1748 // elements and restore the vector mask since it is on the side it will be 1749 // stored. 1750 SmallVector<llvm::Constant*, 4> Mask(NumDstElts); 1751 for (unsigned i = 0; i != NumSrcElts; ++i) 1752 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i); 1753 1754 llvm::Value *MaskV = llvm::ConstantVector::get(Mask); 1755 Vec = Builder.CreateShuffleVector(SrcVal, 1756 llvm::UndefValue::get(Vec->getType()), 1757 MaskV); 1758 } else if (NumDstElts > NumSrcElts) { 1759 // Extended the source vector to the same length and then shuffle it 1760 // into the destination. 1761 // FIXME: since we're shuffling with undef, can we just use the indices 1762 // into that? This could be simpler. 1763 SmallVector<llvm::Constant*, 4> ExtMask; 1764 for (unsigned i = 0; i != NumSrcElts; ++i) 1765 ExtMask.push_back(Builder.getInt32(i)); 1766 ExtMask.resize(NumDstElts, llvm::UndefValue::get(Int32Ty)); 1767 llvm::Value *ExtMaskV = llvm::ConstantVector::get(ExtMask); 1768 llvm::Value *ExtSrcVal = 1769 Builder.CreateShuffleVector(SrcVal, 1770 llvm::UndefValue::get(SrcVal->getType()), 1771 ExtMaskV); 1772 // build identity 1773 SmallVector<llvm::Constant*, 4> Mask; 1774 for (unsigned i = 0; i != NumDstElts; ++i) 1775 Mask.push_back(Builder.getInt32(i)); 1776 1777 // When the vector size is odd and .odd or .hi is used, the last element 1778 // of the Elts constant array will be one past the size of the vector. 1779 // Ignore the last element here, if it is greater than the mask size. 1780 if (getAccessedFieldNo(NumSrcElts - 1, Elts) == Mask.size()) 1781 NumSrcElts--; 1782 1783 // modify when what gets shuffled in 1784 for (unsigned i = 0; i != NumSrcElts; ++i) 1785 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i+NumDstElts); 1786 llvm::Value *MaskV = llvm::ConstantVector::get(Mask); 1787 Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, MaskV); 1788 } else { 1789 // We should never shorten the vector 1790 llvm_unreachable("unexpected shorten vector length"); 1791 } 1792 } else { 1793 // If the Src is a scalar (not a vector) it must be updating one element. 1794 unsigned InIdx = getAccessedFieldNo(0, Elts); 1795 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx); 1796 Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt); 1797 } 1798 1799 Builder.CreateStore(Vec, Dst.getExtVectorAddress(), 1800 Dst.isVolatileQualified()); 1801 } 1802 1803 /// @brief Store of global named registers are always calls to intrinsics. 1804 void CodeGenFunction::EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst) { 1805 assert((Dst.getType()->isIntegerType() || Dst.getType()->isPointerType()) && 1806 "Bad type for register variable"); 1807 llvm::MDNode *RegName = cast<llvm::MDNode>( 1808 cast<llvm::MetadataAsValue>(Dst.getGlobalReg())->getMetadata()); 1809 assert(RegName && "Register LValue is not metadata"); 1810 1811 // We accept integer and pointer types only 1812 llvm::Type *OrigTy = CGM.getTypes().ConvertType(Dst.getType()); 1813 llvm::Type *Ty = OrigTy; 1814 if (OrigTy->isPointerTy()) 1815 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy); 1816 llvm::Type *Types[] = { Ty }; 1817 1818 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::write_register, Types); 1819 llvm::Value *Value = Src.getScalarVal(); 1820 if (OrigTy->isPointerTy()) 1821 Value = Builder.CreatePtrToInt(Value, Ty); 1822 Builder.CreateCall( 1823 F, {llvm::MetadataAsValue::get(Ty->getContext(), RegName), Value}); 1824 } 1825 1826 // setObjCGCLValueClass - sets class of the lvalue for the purpose of 1827 // generating write-barries API. It is currently a global, ivar, 1828 // or neither. 1829 static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E, 1830 LValue &LV, 1831 bool IsMemberAccess=false) { 1832 if (Ctx.getLangOpts().getGC() == LangOptions::NonGC) 1833 return; 1834 1835 if (isa<ObjCIvarRefExpr>(E)) { 1836 QualType ExpTy = E->getType(); 1837 if (IsMemberAccess && ExpTy->isPointerType()) { 1838 // If ivar is a structure pointer, assigning to field of 1839 // this struct follows gcc's behavior and makes it a non-ivar 1840 // writer-barrier conservatively. 1841 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType(); 1842 if (ExpTy->isRecordType()) { 1843 LV.setObjCIvar(false); 1844 return; 1845 } 1846 } 1847 LV.setObjCIvar(true); 1848 auto *Exp = cast<ObjCIvarRefExpr>(const_cast<Expr *>(E)); 1849 LV.setBaseIvarExp(Exp->getBase()); 1850 LV.setObjCArray(E->getType()->isArrayType()); 1851 return; 1852 } 1853 1854 if (const auto *Exp = dyn_cast<DeclRefExpr>(E)) { 1855 if (const auto *VD = dyn_cast<VarDecl>(Exp->getDecl())) { 1856 if (VD->hasGlobalStorage()) { 1857 LV.setGlobalObjCRef(true); 1858 LV.setThreadLocalRef(VD->getTLSKind() != VarDecl::TLS_None); 1859 } 1860 } 1861 LV.setObjCArray(E->getType()->isArrayType()); 1862 return; 1863 } 1864 1865 if (const auto *Exp = dyn_cast<UnaryOperator>(E)) { 1866 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess); 1867 return; 1868 } 1869 1870 if (const auto *Exp = dyn_cast<ParenExpr>(E)) { 1871 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess); 1872 if (LV.isObjCIvar()) { 1873 // If cast is to a structure pointer, follow gcc's behavior and make it 1874 // a non-ivar write-barrier. 1875 QualType ExpTy = E->getType(); 1876 if (ExpTy->isPointerType()) 1877 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType(); 1878 if (ExpTy->isRecordType()) 1879 LV.setObjCIvar(false); 1880 } 1881 return; 1882 } 1883 1884 if (const auto *Exp = dyn_cast<GenericSelectionExpr>(E)) { 1885 setObjCGCLValueClass(Ctx, Exp->getResultExpr(), LV); 1886 return; 1887 } 1888 1889 if (const auto *Exp = dyn_cast<ImplicitCastExpr>(E)) { 1890 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess); 1891 return; 1892 } 1893 1894 if (const auto *Exp = dyn_cast<CStyleCastExpr>(E)) { 1895 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess); 1896 return; 1897 } 1898 1899 if (const auto *Exp = dyn_cast<ObjCBridgedCastExpr>(E)) { 1900 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess); 1901 return; 1902 } 1903 1904 if (const auto *Exp = dyn_cast<ArraySubscriptExpr>(E)) { 1905 setObjCGCLValueClass(Ctx, Exp->getBase(), LV); 1906 if (LV.isObjCIvar() && !LV.isObjCArray()) 1907 // Using array syntax to assigning to what an ivar points to is not 1908 // same as assigning to the ivar itself. {id *Names;} Names[i] = 0; 1909 LV.setObjCIvar(false); 1910 else if (LV.isGlobalObjCRef() && !LV.isObjCArray()) 1911 // Using array syntax to assigning to what global points to is not 1912 // same as assigning to the global itself. {id *G;} G[i] = 0; 1913 LV.setGlobalObjCRef(false); 1914 return; 1915 } 1916 1917 if (const auto *Exp = dyn_cast<MemberExpr>(E)) { 1918 setObjCGCLValueClass(Ctx, Exp->getBase(), LV, true); 1919 // We don't know if member is an 'ivar', but this flag is looked at 1920 // only in the context of LV.isObjCIvar(). 1921 LV.setObjCArray(E->getType()->isArrayType()); 1922 return; 1923 } 1924 } 1925 1926 static llvm::Value * 1927 EmitBitCastOfLValueToProperType(CodeGenFunction &CGF, 1928 llvm::Value *V, llvm::Type *IRType, 1929 StringRef Name = StringRef()) { 1930 unsigned AS = cast<llvm::PointerType>(V->getType())->getAddressSpace(); 1931 return CGF.Builder.CreateBitCast(V, IRType->getPointerTo(AS), Name); 1932 } 1933 1934 static LValue EmitThreadPrivateVarDeclLValue( 1935 CodeGenFunction &CGF, const VarDecl *VD, QualType T, Address Addr, 1936 llvm::Type *RealVarTy, SourceLocation Loc) { 1937 Addr = CGF.CGM.getOpenMPRuntime().getAddrOfThreadPrivate(CGF, VD, Addr, Loc); 1938 Addr = CGF.Builder.CreateElementBitCast(Addr, RealVarTy); 1939 return CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl); 1940 } 1941 1942 Address CodeGenFunction::EmitLoadOfReference(Address Addr, 1943 const ReferenceType *RefTy, 1944 AlignmentSource *Source) { 1945 llvm::Value *Ptr = Builder.CreateLoad(Addr); 1946 return Address(Ptr, getNaturalTypeAlignment(RefTy->getPointeeType(), 1947 Source, /*forPointee*/ true)); 1948 1949 } 1950 1951 LValue CodeGenFunction::EmitLoadOfReferenceLValue(Address RefAddr, 1952 const ReferenceType *RefTy) { 1953 AlignmentSource Source; 1954 Address Addr = EmitLoadOfReference(RefAddr, RefTy, &Source); 1955 return MakeAddrLValue(Addr, RefTy->getPointeeType(), Source); 1956 } 1957 1958 Address CodeGenFunction::EmitLoadOfPointer(Address Ptr, 1959 const PointerType *PtrTy, 1960 AlignmentSource *Source) { 1961 llvm::Value *Addr = Builder.CreateLoad(Ptr); 1962 return Address(Addr, getNaturalTypeAlignment(PtrTy->getPointeeType(), Source, 1963 /*forPointeeType=*/true)); 1964 } 1965 1966 LValue CodeGenFunction::EmitLoadOfPointerLValue(Address PtrAddr, 1967 const PointerType *PtrTy) { 1968 AlignmentSource Source; 1969 Address Addr = EmitLoadOfPointer(PtrAddr, PtrTy, &Source); 1970 return MakeAddrLValue(Addr, PtrTy->getPointeeType(), Source); 1971 } 1972 1973 static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF, 1974 const Expr *E, const VarDecl *VD) { 1975 QualType T = E->getType(); 1976 1977 // If it's thread_local, emit a call to its wrapper function instead. 1978 if (VD->getTLSKind() == VarDecl::TLS_Dynamic && 1979 CGF.CGM.getCXXABI().usesThreadWrapperFunction()) 1980 return CGF.CGM.getCXXABI().EmitThreadLocalVarDeclLValue(CGF, VD, T); 1981 1982 llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD); 1983 llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType()); 1984 V = EmitBitCastOfLValueToProperType(CGF, V, RealVarTy); 1985 CharUnits Alignment = CGF.getContext().getDeclAlign(VD); 1986 Address Addr(V, Alignment); 1987 LValue LV; 1988 // Emit reference to the private copy of the variable if it is an OpenMP 1989 // threadprivate variable. 1990 if (CGF.getLangOpts().OpenMP && VD->hasAttr<OMPThreadPrivateDeclAttr>()) 1991 return EmitThreadPrivateVarDeclLValue(CGF, VD, T, Addr, RealVarTy, 1992 E->getExprLoc()); 1993 if (auto RefTy = VD->getType()->getAs<ReferenceType>()) { 1994 LV = CGF.EmitLoadOfReferenceLValue(Addr, RefTy); 1995 } else { 1996 LV = CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl); 1997 } 1998 setObjCGCLValueClass(CGF.getContext(), E, LV); 1999 return LV; 2000 } 2001 2002 static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF, 2003 const Expr *E, const FunctionDecl *FD) { 2004 llvm::Value *V = CGF.CGM.GetAddrOfFunction(FD); 2005 if (!FD->hasPrototype()) { 2006 if (const FunctionProtoType *Proto = 2007 FD->getType()->getAs<FunctionProtoType>()) { 2008 // Ugly case: for a K&R-style definition, the type of the definition 2009 // isn't the same as the type of a use. Correct for this with a 2010 // bitcast. 2011 QualType NoProtoType = 2012 CGF.getContext().getFunctionNoProtoType(Proto->getReturnType()); 2013 NoProtoType = CGF.getContext().getPointerType(NoProtoType); 2014 V = CGF.Builder.CreateBitCast(V, CGF.ConvertType(NoProtoType)); 2015 } 2016 } 2017 CharUnits Alignment = CGF.getContext().getDeclAlign(FD); 2018 return CGF.MakeAddrLValue(V, E->getType(), Alignment, AlignmentSource::Decl); 2019 } 2020 2021 static LValue EmitCapturedFieldLValue(CodeGenFunction &CGF, const FieldDecl *FD, 2022 llvm::Value *ThisValue) { 2023 QualType TagType = CGF.getContext().getTagDeclType(FD->getParent()); 2024 LValue LV = CGF.MakeNaturalAlignAddrLValue(ThisValue, TagType); 2025 return CGF.EmitLValueForField(LV, FD); 2026 } 2027 2028 /// Named Registers are named metadata pointing to the register name 2029 /// which will be read from/written to as an argument to the intrinsic 2030 /// @llvm.read/write_register. 2031 /// So far, only the name is being passed down, but other options such as 2032 /// register type, allocation type or even optimization options could be 2033 /// passed down via the metadata node. 2034 static LValue EmitGlobalNamedRegister(const VarDecl *VD, CodeGenModule &CGM) { 2035 SmallString<64> Name("llvm.named.register."); 2036 AsmLabelAttr *Asm = VD->getAttr<AsmLabelAttr>(); 2037 assert(Asm->getLabel().size() < 64-Name.size() && 2038 "Register name too big"); 2039 Name.append(Asm->getLabel()); 2040 llvm::NamedMDNode *M = 2041 CGM.getModule().getOrInsertNamedMetadata(Name); 2042 if (M->getNumOperands() == 0) { 2043 llvm::MDString *Str = llvm::MDString::get(CGM.getLLVMContext(), 2044 Asm->getLabel()); 2045 llvm::Metadata *Ops[] = {Str}; 2046 M->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops)); 2047 } 2048 2049 CharUnits Alignment = CGM.getContext().getDeclAlign(VD); 2050 2051 llvm::Value *Ptr = 2052 llvm::MetadataAsValue::get(CGM.getLLVMContext(), M->getOperand(0)); 2053 return LValue::MakeGlobalReg(Address(Ptr, Alignment), VD->getType()); 2054 } 2055 2056 LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) { 2057 const NamedDecl *ND = E->getDecl(); 2058 QualType T = E->getType(); 2059 2060 if (const auto *VD = dyn_cast<VarDecl>(ND)) { 2061 // Global Named registers access via intrinsics only 2062 if (VD->getStorageClass() == SC_Register && 2063 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl()) 2064 return EmitGlobalNamedRegister(VD, CGM); 2065 2066 // A DeclRefExpr for a reference initialized by a constant expression can 2067 // appear without being odr-used. Directly emit the constant initializer. 2068 const Expr *Init = VD->getAnyInitializer(VD); 2069 if (Init && !isa<ParmVarDecl>(VD) && VD->getType()->isReferenceType() && 2070 VD->isUsableInConstantExpressions(getContext()) && 2071 VD->checkInitIsICE() && 2072 // Do not emit if it is private OpenMP variable. 2073 !(E->refersToEnclosingVariableOrCapture() && CapturedStmtInfo && 2074 LocalDeclMap.count(VD))) { 2075 llvm::Constant *Val = 2076 CGM.EmitConstantValue(*VD->evaluateValue(), VD->getType(), this); 2077 assert(Val && "failed to emit reference constant expression"); 2078 // FIXME: Eventually we will want to emit vector element references. 2079 2080 // Should we be using the alignment of the constant pointer we emitted? 2081 CharUnits Alignment = getNaturalTypeAlignment(E->getType(), nullptr, 2082 /*pointee*/ true); 2083 2084 return MakeAddrLValue(Address(Val, Alignment), T, AlignmentSource::Decl); 2085 } 2086 2087 // Check for captured variables. 2088 if (E->refersToEnclosingVariableOrCapture()) { 2089 if (auto *FD = LambdaCaptureFields.lookup(VD)) 2090 return EmitCapturedFieldLValue(*this, FD, CXXABIThisValue); 2091 else if (CapturedStmtInfo) { 2092 auto it = LocalDeclMap.find(VD); 2093 if (it != LocalDeclMap.end()) { 2094 if (auto RefTy = VD->getType()->getAs<ReferenceType>()) { 2095 return EmitLoadOfReferenceLValue(it->second, RefTy); 2096 } 2097 return MakeAddrLValue(it->second, T); 2098 } 2099 LValue CapLVal = 2100 EmitCapturedFieldLValue(*this, CapturedStmtInfo->lookup(VD), 2101 CapturedStmtInfo->getContextValue()); 2102 return MakeAddrLValue( 2103 Address(CapLVal.getPointer(), getContext().getDeclAlign(VD)), 2104 CapLVal.getType(), AlignmentSource::Decl); 2105 } 2106 2107 assert(isa<BlockDecl>(CurCodeDecl)); 2108 Address addr = GetAddrOfBlockDecl(VD, VD->hasAttr<BlocksAttr>()); 2109 return MakeAddrLValue(addr, T, AlignmentSource::Decl); 2110 } 2111 } 2112 2113 // FIXME: We should be able to assert this for FunctionDecls as well! 2114 // FIXME: We should be able to assert this for all DeclRefExprs, not just 2115 // those with a valid source location. 2116 assert((ND->isUsed(false) || !isa<VarDecl>(ND) || 2117 !E->getLocation().isValid()) && 2118 "Should not use decl without marking it used!"); 2119 2120 if (ND->hasAttr<WeakRefAttr>()) { 2121 const auto *VD = cast<ValueDecl>(ND); 2122 ConstantAddress Aliasee = CGM.GetWeakRefReference(VD); 2123 return MakeAddrLValue(Aliasee, T, AlignmentSource::Decl); 2124 } 2125 2126 if (const auto *VD = dyn_cast<VarDecl>(ND)) { 2127 // Check if this is a global variable. 2128 if (VD->hasLinkage() || VD->isStaticDataMember()) 2129 return EmitGlobalVarDeclLValue(*this, E, VD); 2130 2131 Address addr = Address::invalid(); 2132 2133 // The variable should generally be present in the local decl map. 2134 auto iter = LocalDeclMap.find(VD); 2135 if (iter != LocalDeclMap.end()) { 2136 addr = iter->second; 2137 2138 // Otherwise, it might be static local we haven't emitted yet for 2139 // some reason; most likely, because it's in an outer function. 2140 } else if (VD->isStaticLocal()) { 2141 addr = Address(CGM.getOrCreateStaticVarDecl( 2142 *VD, CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false)), 2143 getContext().getDeclAlign(VD)); 2144 2145 // No other cases for now. 2146 } else { 2147 llvm_unreachable("DeclRefExpr for Decl not entered in LocalDeclMap?"); 2148 } 2149 2150 2151 // Check for OpenMP threadprivate variables. 2152 if (getLangOpts().OpenMP && VD->hasAttr<OMPThreadPrivateDeclAttr>()) { 2153 return EmitThreadPrivateVarDeclLValue( 2154 *this, VD, T, addr, getTypes().ConvertTypeForMem(VD->getType()), 2155 E->getExprLoc()); 2156 } 2157 2158 // Drill into block byref variables. 2159 bool isBlockByref = VD->hasAttr<BlocksAttr>(); 2160 if (isBlockByref) { 2161 addr = emitBlockByrefAddress(addr, VD); 2162 } 2163 2164 // Drill into reference types. 2165 LValue LV; 2166 if (auto RefTy = VD->getType()->getAs<ReferenceType>()) { 2167 LV = EmitLoadOfReferenceLValue(addr, RefTy); 2168 } else { 2169 LV = MakeAddrLValue(addr, T, AlignmentSource::Decl); 2170 } 2171 2172 bool isLocalStorage = VD->hasLocalStorage(); 2173 2174 bool NonGCable = isLocalStorage && 2175 !VD->getType()->isReferenceType() && 2176 !isBlockByref; 2177 if (NonGCable) { 2178 LV.getQuals().removeObjCGCAttr(); 2179 LV.setNonGC(true); 2180 } 2181 2182 bool isImpreciseLifetime = 2183 (isLocalStorage && !VD->hasAttr<ObjCPreciseLifetimeAttr>()); 2184 if (isImpreciseLifetime) 2185 LV.setARCPreciseLifetime(ARCImpreciseLifetime); 2186 setObjCGCLValueClass(getContext(), E, LV); 2187 return LV; 2188 } 2189 2190 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) 2191 return EmitFunctionDeclLValue(*this, E, FD); 2192 2193 llvm_unreachable("Unhandled DeclRefExpr"); 2194 } 2195 2196 LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) { 2197 // __extension__ doesn't affect lvalue-ness. 2198 if (E->getOpcode() == UO_Extension) 2199 return EmitLValue(E->getSubExpr()); 2200 2201 QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType()); 2202 switch (E->getOpcode()) { 2203 default: llvm_unreachable("Unknown unary operator lvalue!"); 2204 case UO_Deref: { 2205 QualType T = E->getSubExpr()->getType()->getPointeeType(); 2206 assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type"); 2207 2208 AlignmentSource AlignSource; 2209 Address Addr = EmitPointerWithAlignment(E->getSubExpr(), &AlignSource); 2210 LValue LV = MakeAddrLValue(Addr, T, AlignSource); 2211 LV.getQuals().setAddressSpace(ExprTy.getAddressSpace()); 2212 2213 // We should not generate __weak write barrier on indirect reference 2214 // of a pointer to object; as in void foo (__weak id *param); *param = 0; 2215 // But, we continue to generate __strong write barrier on indirect write 2216 // into a pointer to object. 2217 if (getLangOpts().ObjC1 && 2218 getLangOpts().getGC() != LangOptions::NonGC && 2219 LV.isObjCWeak()) 2220 LV.setNonGC(!E->isOBJCGCCandidate(getContext())); 2221 return LV; 2222 } 2223 case UO_Real: 2224 case UO_Imag: { 2225 LValue LV = EmitLValue(E->getSubExpr()); 2226 assert(LV.isSimple() && "real/imag on non-ordinary l-value"); 2227 2228 // __real is valid on scalars. This is a faster way of testing that. 2229 // __imag can only produce an rvalue on scalars. 2230 if (E->getOpcode() == UO_Real && 2231 !LV.getAddress().getElementType()->isStructTy()) { 2232 assert(E->getSubExpr()->getType()->isArithmeticType()); 2233 return LV; 2234 } 2235 2236 assert(E->getSubExpr()->getType()->isAnyComplexType()); 2237 2238 Address Component = 2239 (E->getOpcode() == UO_Real 2240 ? emitAddrOfRealComponent(LV.getAddress(), LV.getType()) 2241 : emitAddrOfImagComponent(LV.getAddress(), LV.getType())); 2242 return MakeAddrLValue(Component, ExprTy, LV.getAlignmentSource()); 2243 } 2244 case UO_PreInc: 2245 case UO_PreDec: { 2246 LValue LV = EmitLValue(E->getSubExpr()); 2247 bool isInc = E->getOpcode() == UO_PreInc; 2248 2249 if (E->getType()->isAnyComplexType()) 2250 EmitComplexPrePostIncDec(E, LV, isInc, true/*isPre*/); 2251 else 2252 EmitScalarPrePostIncDec(E, LV, isInc, true/*isPre*/); 2253 return LV; 2254 } 2255 } 2256 } 2257 2258 LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) { 2259 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromLiteral(E), 2260 E->getType(), AlignmentSource::Decl); 2261 } 2262 2263 LValue CodeGenFunction::EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E) { 2264 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromObjCEncode(E), 2265 E->getType(), AlignmentSource::Decl); 2266 } 2267 2268 LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) { 2269 auto SL = E->getFunctionName(); 2270 assert(SL != nullptr && "No StringLiteral name in PredefinedExpr"); 2271 StringRef FnName = CurFn->getName(); 2272 if (FnName.startswith("\01")) 2273 FnName = FnName.substr(1); 2274 StringRef NameItems[] = { 2275 PredefinedExpr::getIdentTypeName(E->getIdentType()), FnName}; 2276 std::string GVName = llvm::join(NameItems, NameItems + 2, "."); 2277 if (CurCodeDecl && isa<BlockDecl>(CurCodeDecl)) { 2278 auto C = CGM.GetAddrOfConstantCString(FnName, GVName.c_str()); 2279 return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl); 2280 } 2281 auto C = CGM.GetAddrOfConstantStringFromLiteral(SL, GVName); 2282 return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl); 2283 } 2284 2285 /// Emit a type description suitable for use by a runtime sanitizer library. The 2286 /// format of a type descriptor is 2287 /// 2288 /// \code 2289 /// { i16 TypeKind, i16 TypeInfo } 2290 /// \endcode 2291 /// 2292 /// followed by an array of i8 containing the type name. TypeKind is 0 for an 2293 /// integer, 1 for a floating point value, and -1 for anything else. 2294 llvm::Constant *CodeGenFunction::EmitCheckTypeDescriptor(QualType T) { 2295 // Only emit each type's descriptor once. 2296 if (llvm::Constant *C = CGM.getTypeDescriptorFromMap(T)) 2297 return C; 2298 2299 uint16_t TypeKind = -1; 2300 uint16_t TypeInfo = 0; 2301 2302 if (T->isIntegerType()) { 2303 TypeKind = 0; 2304 TypeInfo = (llvm::Log2_32(getContext().getTypeSize(T)) << 1) | 2305 (T->isSignedIntegerType() ? 1 : 0); 2306 } else if (T->isFloatingType()) { 2307 TypeKind = 1; 2308 TypeInfo = getContext().getTypeSize(T); 2309 } 2310 2311 // Format the type name as if for a diagnostic, including quotes and 2312 // optionally an 'aka'. 2313 SmallString<32> Buffer; 2314 CGM.getDiags().ConvertArgToString(DiagnosticsEngine::ak_qualtype, 2315 (intptr_t)T.getAsOpaquePtr(), 2316 StringRef(), StringRef(), None, Buffer, 2317 None); 2318 2319 llvm::Constant *Components[] = { 2320 Builder.getInt16(TypeKind), Builder.getInt16(TypeInfo), 2321 llvm::ConstantDataArray::getString(getLLVMContext(), Buffer) 2322 }; 2323 llvm::Constant *Descriptor = llvm::ConstantStruct::getAnon(Components); 2324 2325 auto *GV = new llvm::GlobalVariable( 2326 CGM.getModule(), Descriptor->getType(), 2327 /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage, Descriptor); 2328 GV->setUnnamedAddr(true); 2329 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(GV); 2330 2331 // Remember the descriptor for this type. 2332 CGM.setTypeDescriptorInMap(T, GV); 2333 2334 return GV; 2335 } 2336 2337 llvm::Value *CodeGenFunction::EmitCheckValue(llvm::Value *V) { 2338 llvm::Type *TargetTy = IntPtrTy; 2339 2340 // Floating-point types which fit into intptr_t are bitcast to integers 2341 // and then passed directly (after zero-extension, if necessary). 2342 if (V->getType()->isFloatingPointTy()) { 2343 unsigned Bits = V->getType()->getPrimitiveSizeInBits(); 2344 if (Bits <= TargetTy->getIntegerBitWidth()) 2345 V = Builder.CreateBitCast(V, llvm::Type::getIntNTy(getLLVMContext(), 2346 Bits)); 2347 } 2348 2349 // Integers which fit in intptr_t are zero-extended and passed directly. 2350 if (V->getType()->isIntegerTy() && 2351 V->getType()->getIntegerBitWidth() <= TargetTy->getIntegerBitWidth()) 2352 return Builder.CreateZExt(V, TargetTy); 2353 2354 // Pointers are passed directly, everything else is passed by address. 2355 if (!V->getType()->isPointerTy()) { 2356 Address Ptr = CreateDefaultAlignTempAlloca(V->getType()); 2357 Builder.CreateStore(V, Ptr); 2358 V = Ptr.getPointer(); 2359 } 2360 return Builder.CreatePtrToInt(V, TargetTy); 2361 } 2362 2363 /// \brief Emit a representation of a SourceLocation for passing to a handler 2364 /// in a sanitizer runtime library. The format for this data is: 2365 /// \code 2366 /// struct SourceLocation { 2367 /// const char *Filename; 2368 /// int32_t Line, Column; 2369 /// }; 2370 /// \endcode 2371 /// For an invalid SourceLocation, the Filename pointer is null. 2372 llvm::Constant *CodeGenFunction::EmitCheckSourceLocation(SourceLocation Loc) { 2373 llvm::Constant *Filename; 2374 int Line, Column; 2375 2376 PresumedLoc PLoc = getContext().getSourceManager().getPresumedLoc(Loc); 2377 if (PLoc.isValid()) { 2378 StringRef FilenameString = PLoc.getFilename(); 2379 2380 int PathComponentsToStrip = 2381 CGM.getCodeGenOpts().EmitCheckPathComponentsToStrip; 2382 if (PathComponentsToStrip < 0) { 2383 assert(PathComponentsToStrip != INT_MIN); 2384 int PathComponentsToKeep = -PathComponentsToStrip; 2385 auto I = llvm::sys::path::rbegin(FilenameString); 2386 auto E = llvm::sys::path::rend(FilenameString); 2387 while (I != E && --PathComponentsToKeep) 2388 ++I; 2389 2390 FilenameString = FilenameString.substr(I - E); 2391 } else if (PathComponentsToStrip > 0) { 2392 auto I = llvm::sys::path::begin(FilenameString); 2393 auto E = llvm::sys::path::end(FilenameString); 2394 while (I != E && PathComponentsToStrip--) 2395 ++I; 2396 2397 if (I != E) 2398 FilenameString = 2399 FilenameString.substr(I - llvm::sys::path::begin(FilenameString)); 2400 else 2401 FilenameString = llvm::sys::path::filename(FilenameString); 2402 } 2403 2404 auto FilenameGV = CGM.GetAddrOfConstantCString(FilenameString, ".src"); 2405 CGM.getSanitizerMetadata()->disableSanitizerForGlobal( 2406 cast<llvm::GlobalVariable>(FilenameGV.getPointer())); 2407 Filename = FilenameGV.getPointer(); 2408 Line = PLoc.getLine(); 2409 Column = PLoc.getColumn(); 2410 } else { 2411 Filename = llvm::Constant::getNullValue(Int8PtrTy); 2412 Line = Column = 0; 2413 } 2414 2415 llvm::Constant *Data[] = {Filename, Builder.getInt32(Line), 2416 Builder.getInt32(Column)}; 2417 2418 return llvm::ConstantStruct::getAnon(Data); 2419 } 2420 2421 namespace { 2422 /// \brief Specify under what conditions this check can be recovered 2423 enum class CheckRecoverableKind { 2424 /// Always terminate program execution if this check fails. 2425 Unrecoverable, 2426 /// Check supports recovering, runtime has both fatal (noreturn) and 2427 /// non-fatal handlers for this check. 2428 Recoverable, 2429 /// Runtime conditionally aborts, always need to support recovery. 2430 AlwaysRecoverable 2431 }; 2432 } 2433 2434 static CheckRecoverableKind getRecoverableKind(SanitizerMask Kind) { 2435 assert(llvm::countPopulation(Kind) == 1); 2436 switch (Kind) { 2437 case SanitizerKind::Vptr: 2438 return CheckRecoverableKind::AlwaysRecoverable; 2439 case SanitizerKind::Return: 2440 case SanitizerKind::Unreachable: 2441 return CheckRecoverableKind::Unrecoverable; 2442 default: 2443 return CheckRecoverableKind::Recoverable; 2444 } 2445 } 2446 2447 static void emitCheckHandlerCall(CodeGenFunction &CGF, 2448 llvm::FunctionType *FnType, 2449 ArrayRef<llvm::Value *> FnArgs, 2450 StringRef CheckName, 2451 CheckRecoverableKind RecoverKind, bool IsFatal, 2452 llvm::BasicBlock *ContBB) { 2453 assert(IsFatal || RecoverKind != CheckRecoverableKind::Unrecoverable); 2454 bool NeedsAbortSuffix = 2455 IsFatal && RecoverKind != CheckRecoverableKind::Unrecoverable; 2456 std::string FnName = ("__ubsan_handle_" + CheckName + 2457 (NeedsAbortSuffix ? "_abort" : "")).str(); 2458 bool MayReturn = 2459 !IsFatal || RecoverKind == CheckRecoverableKind::AlwaysRecoverable; 2460 2461 llvm::AttrBuilder B; 2462 if (!MayReturn) { 2463 B.addAttribute(llvm::Attribute::NoReturn) 2464 .addAttribute(llvm::Attribute::NoUnwind); 2465 } 2466 B.addAttribute(llvm::Attribute::UWTable); 2467 2468 llvm::Value *Fn = CGF.CGM.CreateRuntimeFunction( 2469 FnType, FnName, 2470 llvm::AttributeSet::get(CGF.getLLVMContext(), 2471 llvm::AttributeSet::FunctionIndex, B)); 2472 llvm::CallInst *HandlerCall = CGF.EmitNounwindRuntimeCall(Fn, FnArgs); 2473 if (!MayReturn) { 2474 HandlerCall->setDoesNotReturn(); 2475 CGF.Builder.CreateUnreachable(); 2476 } else { 2477 CGF.Builder.CreateBr(ContBB); 2478 } 2479 } 2480 2481 void CodeGenFunction::EmitCheck( 2482 ArrayRef<std::pair<llvm::Value *, SanitizerMask>> Checked, 2483 StringRef CheckName, ArrayRef<llvm::Constant *> StaticArgs, 2484 ArrayRef<llvm::Value *> DynamicArgs) { 2485 assert(IsSanitizerScope); 2486 assert(Checked.size() > 0); 2487 2488 llvm::Value *FatalCond = nullptr; 2489 llvm::Value *RecoverableCond = nullptr; 2490 llvm::Value *TrapCond = nullptr; 2491 for (int i = 0, n = Checked.size(); i < n; ++i) { 2492 llvm::Value *Check = Checked[i].first; 2493 // -fsanitize-trap= overrides -fsanitize-recover=. 2494 llvm::Value *&Cond = 2495 CGM.getCodeGenOpts().SanitizeTrap.has(Checked[i].second) 2496 ? TrapCond 2497 : CGM.getCodeGenOpts().SanitizeRecover.has(Checked[i].second) 2498 ? RecoverableCond 2499 : FatalCond; 2500 Cond = Cond ? Builder.CreateAnd(Cond, Check) : Check; 2501 } 2502 2503 if (TrapCond) 2504 EmitTrapCheck(TrapCond); 2505 if (!FatalCond && !RecoverableCond) 2506 return; 2507 2508 llvm::Value *JointCond; 2509 if (FatalCond && RecoverableCond) 2510 JointCond = Builder.CreateAnd(FatalCond, RecoverableCond); 2511 else 2512 JointCond = FatalCond ? FatalCond : RecoverableCond; 2513 assert(JointCond); 2514 2515 CheckRecoverableKind RecoverKind = getRecoverableKind(Checked[0].second); 2516 assert(SanOpts.has(Checked[0].second)); 2517 #ifndef NDEBUG 2518 for (int i = 1, n = Checked.size(); i < n; ++i) { 2519 assert(RecoverKind == getRecoverableKind(Checked[i].second) && 2520 "All recoverable kinds in a single check must be same!"); 2521 assert(SanOpts.has(Checked[i].second)); 2522 } 2523 #endif 2524 2525 llvm::BasicBlock *Cont = createBasicBlock("cont"); 2526 llvm::BasicBlock *Handlers = createBasicBlock("handler." + CheckName); 2527 llvm::Instruction *Branch = Builder.CreateCondBr(JointCond, Cont, Handlers); 2528 // Give hint that we very much don't expect to execute the handler 2529 // Value chosen to match UR_NONTAKEN_WEIGHT, see BranchProbabilityInfo.cpp 2530 llvm::MDBuilder MDHelper(getLLVMContext()); 2531 llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1); 2532 Branch->setMetadata(llvm::LLVMContext::MD_prof, Node); 2533 EmitBlock(Handlers); 2534 2535 // Handler functions take an i8* pointing to the (handler-specific) static 2536 // information block, followed by a sequence of intptr_t arguments 2537 // representing operand values. 2538 SmallVector<llvm::Value *, 4> Args; 2539 SmallVector<llvm::Type *, 4> ArgTypes; 2540 Args.reserve(DynamicArgs.size() + 1); 2541 ArgTypes.reserve(DynamicArgs.size() + 1); 2542 2543 // Emit handler arguments and create handler function type. 2544 if (!StaticArgs.empty()) { 2545 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs); 2546 auto *InfoPtr = 2547 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false, 2548 llvm::GlobalVariable::PrivateLinkage, Info); 2549 InfoPtr->setUnnamedAddr(true); 2550 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr); 2551 Args.push_back(Builder.CreateBitCast(InfoPtr, Int8PtrTy)); 2552 ArgTypes.push_back(Int8PtrTy); 2553 } 2554 2555 for (size_t i = 0, n = DynamicArgs.size(); i != n; ++i) { 2556 Args.push_back(EmitCheckValue(DynamicArgs[i])); 2557 ArgTypes.push_back(IntPtrTy); 2558 } 2559 2560 llvm::FunctionType *FnType = 2561 llvm::FunctionType::get(CGM.VoidTy, ArgTypes, false); 2562 2563 if (!FatalCond || !RecoverableCond) { 2564 // Simple case: we need to generate a single handler call, either 2565 // fatal, or non-fatal. 2566 emitCheckHandlerCall(*this, FnType, Args, CheckName, RecoverKind, 2567 (FatalCond != nullptr), Cont); 2568 } else { 2569 // Emit two handler calls: first one for set of unrecoverable checks, 2570 // another one for recoverable. 2571 llvm::BasicBlock *NonFatalHandlerBB = 2572 createBasicBlock("non_fatal." + CheckName); 2573 llvm::BasicBlock *FatalHandlerBB = createBasicBlock("fatal." + CheckName); 2574 Builder.CreateCondBr(FatalCond, NonFatalHandlerBB, FatalHandlerBB); 2575 EmitBlock(FatalHandlerBB); 2576 emitCheckHandlerCall(*this, FnType, Args, CheckName, RecoverKind, true, 2577 NonFatalHandlerBB); 2578 EmitBlock(NonFatalHandlerBB); 2579 emitCheckHandlerCall(*this, FnType, Args, CheckName, RecoverKind, false, 2580 Cont); 2581 } 2582 2583 EmitBlock(Cont); 2584 } 2585 2586 void CodeGenFunction::EmitCfiSlowPathCheck( 2587 SanitizerMask Kind, llvm::Value *Cond, llvm::ConstantInt *TypeId, 2588 llvm::Value *Ptr, ArrayRef<llvm::Constant *> StaticArgs) { 2589 llvm::BasicBlock *Cont = createBasicBlock("cfi.cont"); 2590 2591 llvm::BasicBlock *CheckBB = createBasicBlock("cfi.slowpath"); 2592 llvm::BranchInst *BI = Builder.CreateCondBr(Cond, Cont, CheckBB); 2593 2594 llvm::MDBuilder MDHelper(getLLVMContext()); 2595 llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1); 2596 BI->setMetadata(llvm::LLVMContext::MD_prof, Node); 2597 2598 EmitBlock(CheckBB); 2599 2600 bool WithDiag = !CGM.getCodeGenOpts().SanitizeTrap.has(Kind); 2601 2602 llvm::CallInst *CheckCall; 2603 if (WithDiag) { 2604 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs); 2605 auto *InfoPtr = 2606 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false, 2607 llvm::GlobalVariable::PrivateLinkage, Info); 2608 InfoPtr->setUnnamedAddr(true); 2609 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr); 2610 2611 llvm::Constant *SlowPathDiagFn = CGM.getModule().getOrInsertFunction( 2612 "__cfi_slowpath_diag", 2613 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy}, 2614 false)); 2615 CheckCall = Builder.CreateCall( 2616 SlowPathDiagFn, 2617 {TypeId, Ptr, Builder.CreateBitCast(InfoPtr, Int8PtrTy)}); 2618 } else { 2619 llvm::Constant *SlowPathFn = CGM.getModule().getOrInsertFunction( 2620 "__cfi_slowpath", 2621 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy}, false)); 2622 CheckCall = Builder.CreateCall(SlowPathFn, {TypeId, Ptr}); 2623 } 2624 2625 CheckCall->setDoesNotThrow(); 2626 2627 EmitBlock(Cont); 2628 } 2629 2630 // This function is basically a switch over the CFI failure kind, which is 2631 // extracted from CFICheckFailData (1st function argument). Each case is either 2632 // llvm.trap or a call to one of the two runtime handlers, based on 2633 // -fsanitize-trap and -fsanitize-recover settings. Default case (invalid 2634 // failure kind) traps, but this should really never happen. CFICheckFailData 2635 // can be nullptr if the calling module has -fsanitize-trap behavior for this 2636 // check kind; in this case __cfi_check_fail traps as well. 2637 void CodeGenFunction::EmitCfiCheckFail() { 2638 SanitizerScope SanScope(this); 2639 FunctionArgList Args; 2640 ImplicitParamDecl ArgData(getContext(), nullptr, SourceLocation(), nullptr, 2641 getContext().VoidPtrTy); 2642 ImplicitParamDecl ArgAddr(getContext(), nullptr, SourceLocation(), nullptr, 2643 getContext().VoidPtrTy); 2644 Args.push_back(&ArgData); 2645 Args.push_back(&ArgAddr); 2646 2647 const CGFunctionInfo &FI = 2648 CGM.getTypes().arrangeBuiltinFunctionDeclaration(getContext().VoidTy, Args); 2649 2650 llvm::Function *F = llvm::Function::Create( 2651 llvm::FunctionType::get(VoidTy, {VoidPtrTy, VoidPtrTy}, false), 2652 llvm::GlobalValue::WeakODRLinkage, "__cfi_check_fail", &CGM.getModule()); 2653 F->setVisibility(llvm::GlobalValue::HiddenVisibility); 2654 2655 StartFunction(GlobalDecl(), CGM.getContext().VoidTy, F, FI, Args, 2656 SourceLocation()); 2657 2658 llvm::Value *Data = 2659 EmitLoadOfScalar(GetAddrOfLocalVar(&ArgData), /*Volatile=*/false, 2660 CGM.getContext().VoidPtrTy, ArgData.getLocation()); 2661 llvm::Value *Addr = 2662 EmitLoadOfScalar(GetAddrOfLocalVar(&ArgAddr), /*Volatile=*/false, 2663 CGM.getContext().VoidPtrTy, ArgAddr.getLocation()); 2664 2665 // Data == nullptr means the calling module has trap behaviour for this check. 2666 llvm::Value *DataIsNotNullPtr = 2667 Builder.CreateICmpNE(Data, llvm::ConstantPointerNull::get(Int8PtrTy)); 2668 EmitTrapCheck(DataIsNotNullPtr); 2669 2670 llvm::StructType *SourceLocationTy = 2671 llvm::StructType::get(VoidPtrTy, Int32Ty, Int32Ty, nullptr); 2672 llvm::StructType *CfiCheckFailDataTy = 2673 llvm::StructType::get(Int8Ty, SourceLocationTy, VoidPtrTy, nullptr); 2674 2675 llvm::Value *V = Builder.CreateConstGEP2_32( 2676 CfiCheckFailDataTy, 2677 Builder.CreatePointerCast(Data, CfiCheckFailDataTy->getPointerTo(0)), 0, 2678 0); 2679 Address CheckKindAddr(V, getIntAlign()); 2680 llvm::Value *CheckKind = Builder.CreateLoad(CheckKindAddr); 2681 2682 llvm::Value *AllVtables = llvm::MetadataAsValue::get( 2683 CGM.getLLVMContext(), 2684 llvm::MDString::get(CGM.getLLVMContext(), "all-vtables")); 2685 llvm::Value *ValidVtable = Builder.CreateZExt( 2686 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::bitset_test), 2687 {Addr, AllVtables}), 2688 IntPtrTy); 2689 2690 const std::pair<int, SanitizerMask> CheckKinds[] = { 2691 {CFITCK_VCall, SanitizerKind::CFIVCall}, 2692 {CFITCK_NVCall, SanitizerKind::CFINVCall}, 2693 {CFITCK_DerivedCast, SanitizerKind::CFIDerivedCast}, 2694 {CFITCK_UnrelatedCast, SanitizerKind::CFIUnrelatedCast}, 2695 {CFITCK_ICall, SanitizerKind::CFIICall}}; 2696 2697 SmallVector<std::pair<llvm::Value *, SanitizerMask>, 5> Checks; 2698 for (auto CheckKindMaskPair : CheckKinds) { 2699 int Kind = CheckKindMaskPair.first; 2700 SanitizerMask Mask = CheckKindMaskPair.second; 2701 llvm::Value *Cond = 2702 Builder.CreateICmpNE(CheckKind, llvm::ConstantInt::get(Int8Ty, Kind)); 2703 if (CGM.getLangOpts().Sanitize.has(Mask)) 2704 EmitCheck(std::make_pair(Cond, Mask), "cfi_check_fail", {}, 2705 {Data, Addr, ValidVtable}); 2706 else 2707 EmitTrapCheck(Cond); 2708 } 2709 2710 FinishFunction(); 2711 // The only reference to this function will be created during LTO link. 2712 // Make sure it survives until then. 2713 CGM.addUsedGlobal(F); 2714 } 2715 2716 void CodeGenFunction::EmitTrapCheck(llvm::Value *Checked) { 2717 llvm::BasicBlock *Cont = createBasicBlock("cont"); 2718 2719 // If we're optimizing, collapse all calls to trap down to just one per 2720 // function to save on code size. 2721 if (!CGM.getCodeGenOpts().OptimizationLevel || !TrapBB) { 2722 TrapBB = createBasicBlock("trap"); 2723 Builder.CreateCondBr(Checked, Cont, TrapBB); 2724 EmitBlock(TrapBB); 2725 llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap); 2726 TrapCall->setDoesNotReturn(); 2727 TrapCall->setDoesNotThrow(); 2728 Builder.CreateUnreachable(); 2729 } else { 2730 Builder.CreateCondBr(Checked, Cont, TrapBB); 2731 } 2732 2733 EmitBlock(Cont); 2734 } 2735 2736 llvm::CallInst *CodeGenFunction::EmitTrapCall(llvm::Intrinsic::ID IntrID) { 2737 llvm::CallInst *TrapCall = Builder.CreateCall(CGM.getIntrinsic(IntrID)); 2738 2739 if (!CGM.getCodeGenOpts().TrapFuncName.empty()) 2740 TrapCall->addAttribute(llvm::AttributeSet::FunctionIndex, 2741 "trap-func-name", 2742 CGM.getCodeGenOpts().TrapFuncName); 2743 2744 return TrapCall; 2745 } 2746 2747 Address CodeGenFunction::EmitArrayToPointerDecay(const Expr *E, 2748 AlignmentSource *AlignSource) { 2749 assert(E->getType()->isArrayType() && 2750 "Array to pointer decay must have array source type!"); 2751 2752 // Expressions of array type can't be bitfields or vector elements. 2753 LValue LV = EmitLValue(E); 2754 Address Addr = LV.getAddress(); 2755 if (AlignSource) *AlignSource = LV.getAlignmentSource(); 2756 2757 // If the array type was an incomplete type, we need to make sure 2758 // the decay ends up being the right type. 2759 llvm::Type *NewTy = ConvertType(E->getType()); 2760 Addr = Builder.CreateElementBitCast(Addr, NewTy); 2761 2762 // Note that VLA pointers are always decayed, so we don't need to do 2763 // anything here. 2764 if (!E->getType()->isVariableArrayType()) { 2765 assert(isa<llvm::ArrayType>(Addr.getElementType()) && 2766 "Expected pointer to array"); 2767 Addr = Builder.CreateStructGEP(Addr, 0, CharUnits::Zero(), "arraydecay"); 2768 } 2769 2770 QualType EltType = E->getType()->castAsArrayTypeUnsafe()->getElementType(); 2771 return Builder.CreateElementBitCast(Addr, ConvertTypeForMem(EltType)); 2772 } 2773 2774 /// isSimpleArrayDecayOperand - If the specified expr is a simple decay from an 2775 /// array to pointer, return the array subexpression. 2776 static const Expr *isSimpleArrayDecayOperand(const Expr *E) { 2777 // If this isn't just an array->pointer decay, bail out. 2778 const auto *CE = dyn_cast<CastExpr>(E); 2779 if (!CE || CE->getCastKind() != CK_ArrayToPointerDecay) 2780 return nullptr; 2781 2782 // If this is a decay from variable width array, bail out. 2783 const Expr *SubExpr = CE->getSubExpr(); 2784 if (SubExpr->getType()->isVariableArrayType()) 2785 return nullptr; 2786 2787 return SubExpr; 2788 } 2789 2790 static llvm::Value *emitArraySubscriptGEP(CodeGenFunction &CGF, 2791 llvm::Value *ptr, 2792 ArrayRef<llvm::Value*> indices, 2793 bool inbounds, 2794 const llvm::Twine &name = "arrayidx") { 2795 if (inbounds) { 2796 return CGF.Builder.CreateInBoundsGEP(ptr, indices, name); 2797 } else { 2798 return CGF.Builder.CreateGEP(ptr, indices, name); 2799 } 2800 } 2801 2802 static CharUnits getArrayElementAlign(CharUnits arrayAlign, 2803 llvm::Value *idx, 2804 CharUnits eltSize) { 2805 // If we have a constant index, we can use the exact offset of the 2806 // element we're accessing. 2807 if (auto constantIdx = dyn_cast<llvm::ConstantInt>(idx)) { 2808 CharUnits offset = constantIdx->getZExtValue() * eltSize; 2809 return arrayAlign.alignmentAtOffset(offset); 2810 2811 // Otherwise, use the worst-case alignment for any element. 2812 } else { 2813 return arrayAlign.alignmentOfArrayElement(eltSize); 2814 } 2815 } 2816 2817 static QualType getFixedSizeElementType(const ASTContext &ctx, 2818 const VariableArrayType *vla) { 2819 QualType eltType; 2820 do { 2821 eltType = vla->getElementType(); 2822 } while ((vla = ctx.getAsVariableArrayType(eltType))); 2823 return eltType; 2824 } 2825 2826 static Address emitArraySubscriptGEP(CodeGenFunction &CGF, Address addr, 2827 ArrayRef<llvm::Value*> indices, 2828 QualType eltType, bool inbounds, 2829 const llvm::Twine &name = "arrayidx") { 2830 // All the indices except that last must be zero. 2831 #ifndef NDEBUG 2832 for (auto idx : indices.drop_back()) 2833 assert(isa<llvm::ConstantInt>(idx) && 2834 cast<llvm::ConstantInt>(idx)->isZero()); 2835 #endif 2836 2837 // Determine the element size of the statically-sized base. This is 2838 // the thing that the indices are expressed in terms of. 2839 if (auto vla = CGF.getContext().getAsVariableArrayType(eltType)) { 2840 eltType = getFixedSizeElementType(CGF.getContext(), vla); 2841 } 2842 2843 // We can use that to compute the best alignment of the element. 2844 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType); 2845 CharUnits eltAlign = 2846 getArrayElementAlign(addr.getAlignment(), indices.back(), eltSize); 2847 2848 llvm::Value *eltPtr = 2849 emitArraySubscriptGEP(CGF, addr.getPointer(), indices, inbounds, name); 2850 return Address(eltPtr, eltAlign); 2851 } 2852 2853 LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E, 2854 bool Accessed) { 2855 // The index must always be an integer, which is not an aggregate. Emit it. 2856 llvm::Value *Idx = EmitScalarExpr(E->getIdx()); 2857 QualType IdxTy = E->getIdx()->getType(); 2858 bool IdxSigned = IdxTy->isSignedIntegerOrEnumerationType(); 2859 2860 if (SanOpts.has(SanitizerKind::ArrayBounds)) 2861 EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, Accessed); 2862 2863 // If the base is a vector type, then we are forming a vector element lvalue 2864 // with this subscript. 2865 if (E->getBase()->getType()->isVectorType() && 2866 !isa<ExtVectorElementExpr>(E->getBase())) { 2867 // Emit the vector as an lvalue to get its address. 2868 LValue LHS = EmitLValue(E->getBase()); 2869 assert(LHS.isSimple() && "Can only subscript lvalue vectors here!"); 2870 return LValue::MakeVectorElt(LHS.getAddress(), Idx, 2871 E->getBase()->getType(), 2872 LHS.getAlignmentSource()); 2873 } 2874 2875 // All the other cases basically behave like simple offsetting. 2876 2877 // Extend or truncate the index type to 32 or 64-bits. 2878 if (Idx->getType() != IntPtrTy) 2879 Idx = Builder.CreateIntCast(Idx, IntPtrTy, IdxSigned, "idxprom"); 2880 2881 // Handle the extvector case we ignored above. 2882 if (isa<ExtVectorElementExpr>(E->getBase())) { 2883 LValue LV = EmitLValue(E->getBase()); 2884 Address Addr = EmitExtVectorElementLValue(LV); 2885 2886 QualType EltType = LV.getType()->castAs<VectorType>()->getElementType(); 2887 Addr = emitArraySubscriptGEP(*this, Addr, Idx, EltType, /*inbounds*/ true); 2888 return MakeAddrLValue(Addr, EltType, LV.getAlignmentSource()); 2889 } 2890 2891 AlignmentSource AlignSource; 2892 Address Addr = Address::invalid(); 2893 if (const VariableArrayType *vla = 2894 getContext().getAsVariableArrayType(E->getType())) { 2895 // The base must be a pointer, which is not an aggregate. Emit 2896 // it. It needs to be emitted first in case it's what captures 2897 // the VLA bounds. 2898 Addr = EmitPointerWithAlignment(E->getBase(), &AlignSource); 2899 2900 // The element count here is the total number of non-VLA elements. 2901 llvm::Value *numElements = getVLASize(vla).first; 2902 2903 // Effectively, the multiply by the VLA size is part of the GEP. 2904 // GEP indexes are signed, and scaling an index isn't permitted to 2905 // signed-overflow, so we use the same semantics for our explicit 2906 // multiply. We suppress this if overflow is not undefined behavior. 2907 if (getLangOpts().isSignedOverflowDefined()) { 2908 Idx = Builder.CreateMul(Idx, numElements); 2909 } else { 2910 Idx = Builder.CreateNSWMul(Idx, numElements); 2911 } 2912 2913 Addr = emitArraySubscriptGEP(*this, Addr, Idx, vla->getElementType(), 2914 !getLangOpts().isSignedOverflowDefined()); 2915 2916 } else if (const ObjCObjectType *OIT = E->getType()->getAs<ObjCObjectType>()){ 2917 // Indexing over an interface, as in "NSString *P; P[4];" 2918 CharUnits InterfaceSize = getContext().getTypeSizeInChars(OIT); 2919 llvm::Value *InterfaceSizeVal = 2920 llvm::ConstantInt::get(Idx->getType(), InterfaceSize.getQuantity());; 2921 2922 llvm::Value *ScaledIdx = Builder.CreateMul(Idx, InterfaceSizeVal); 2923 2924 // Emit the base pointer. 2925 Addr = EmitPointerWithAlignment(E->getBase(), &AlignSource); 2926 2927 // We don't necessarily build correct LLVM struct types for ObjC 2928 // interfaces, so we can't rely on GEP to do this scaling 2929 // correctly, so we need to cast to i8*. FIXME: is this actually 2930 // true? A lot of other things in the fragile ABI would break... 2931 llvm::Type *OrigBaseTy = Addr.getType(); 2932 Addr = Builder.CreateElementBitCast(Addr, Int8Ty); 2933 2934 // Do the GEP. 2935 CharUnits EltAlign = 2936 getArrayElementAlign(Addr.getAlignment(), Idx, InterfaceSize); 2937 llvm::Value *EltPtr = 2938 emitArraySubscriptGEP(*this, Addr.getPointer(), ScaledIdx, false); 2939 Addr = Address(EltPtr, EltAlign); 2940 2941 // Cast back. 2942 Addr = Builder.CreateBitCast(Addr, OrigBaseTy); 2943 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) { 2944 // If this is A[i] where A is an array, the frontend will have decayed the 2945 // base to be a ArrayToPointerDecay implicit cast. While correct, it is 2946 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a 2947 // "gep x, i" here. Emit one "gep A, 0, i". 2948 assert(Array->getType()->isArrayType() && 2949 "Array to pointer decay must have array source type!"); 2950 LValue ArrayLV; 2951 // For simple multidimensional array indexing, set the 'accessed' flag for 2952 // better bounds-checking of the base expression. 2953 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array)) 2954 ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true); 2955 else 2956 ArrayLV = EmitLValue(Array); 2957 2958 // Propagate the alignment from the array itself to the result. 2959 Addr = emitArraySubscriptGEP(*this, ArrayLV.getAddress(), 2960 {CGM.getSize(CharUnits::Zero()), Idx}, 2961 E->getType(), 2962 !getLangOpts().isSignedOverflowDefined()); 2963 AlignSource = ArrayLV.getAlignmentSource(); 2964 } else { 2965 // The base must be a pointer; emit it with an estimate of its alignment. 2966 Addr = EmitPointerWithAlignment(E->getBase(), &AlignSource); 2967 Addr = emitArraySubscriptGEP(*this, Addr, Idx, E->getType(), 2968 !getLangOpts().isSignedOverflowDefined()); 2969 } 2970 2971 LValue LV = MakeAddrLValue(Addr, E->getType(), AlignSource); 2972 2973 // TODO: Preserve/extend path TBAA metadata? 2974 2975 if (getLangOpts().ObjC1 && 2976 getLangOpts().getGC() != LangOptions::NonGC) { 2977 LV.setNonGC(!E->isOBJCGCCandidate(getContext())); 2978 setObjCGCLValueClass(getContext(), E, LV); 2979 } 2980 return LV; 2981 } 2982 2983 static Address emitOMPArraySectionBase(CodeGenFunction &CGF, const Expr *Base, 2984 AlignmentSource &AlignSource, 2985 QualType BaseTy, QualType ElTy, 2986 bool IsLowerBound) { 2987 LValue BaseLVal; 2988 if (auto *ASE = dyn_cast<OMPArraySectionExpr>(Base->IgnoreParenImpCasts())) { 2989 BaseLVal = CGF.EmitOMPArraySectionExpr(ASE, IsLowerBound); 2990 if (BaseTy->isArrayType()) { 2991 Address Addr = BaseLVal.getAddress(); 2992 AlignSource = BaseLVal.getAlignmentSource(); 2993 2994 // If the array type was an incomplete type, we need to make sure 2995 // the decay ends up being the right type. 2996 llvm::Type *NewTy = CGF.ConvertType(BaseTy); 2997 Addr = CGF.Builder.CreateElementBitCast(Addr, NewTy); 2998 2999 // Note that VLA pointers are always decayed, so we don't need to do 3000 // anything here. 3001 if (!BaseTy->isVariableArrayType()) { 3002 assert(isa<llvm::ArrayType>(Addr.getElementType()) && 3003 "Expected pointer to array"); 3004 Addr = CGF.Builder.CreateStructGEP(Addr, 0, CharUnits::Zero(), 3005 "arraydecay"); 3006 } 3007 3008 return CGF.Builder.CreateElementBitCast(Addr, 3009 CGF.ConvertTypeForMem(ElTy)); 3010 } 3011 CharUnits Align = CGF.getNaturalTypeAlignment(ElTy, &AlignSource); 3012 return Address(CGF.Builder.CreateLoad(BaseLVal.getAddress()), Align); 3013 } 3014 return CGF.EmitPointerWithAlignment(Base, &AlignSource); 3015 } 3016 3017 LValue CodeGenFunction::EmitOMPArraySectionExpr(const OMPArraySectionExpr *E, 3018 bool IsLowerBound) { 3019 QualType BaseTy; 3020 if (auto *ASE = 3021 dyn_cast<OMPArraySectionExpr>(E->getBase()->IgnoreParenImpCasts())) 3022 BaseTy = OMPArraySectionExpr::getBaseOriginalType(ASE); 3023 else 3024 BaseTy = E->getBase()->getType(); 3025 QualType ResultExprTy; 3026 if (auto *AT = getContext().getAsArrayType(BaseTy)) 3027 ResultExprTy = AT->getElementType(); 3028 else 3029 ResultExprTy = BaseTy->getPointeeType(); 3030 llvm::Value *Idx = nullptr; 3031 if (IsLowerBound || E->getColonLoc().isInvalid()) { 3032 // Requesting lower bound or upper bound, but without provided length and 3033 // without ':' symbol for the default length -> length = 1. 3034 // Idx = LowerBound ?: 0; 3035 if (auto *LowerBound = E->getLowerBound()) { 3036 Idx = Builder.CreateIntCast( 3037 EmitScalarExpr(LowerBound), IntPtrTy, 3038 LowerBound->getType()->hasSignedIntegerRepresentation()); 3039 } else 3040 Idx = llvm::ConstantInt::getNullValue(IntPtrTy); 3041 } else { 3042 // Try to emit length or lower bound as constant. If this is possible, 1 3043 // is subtracted from constant length or lower bound. Otherwise, emit LLVM 3044 // IR (LB + Len) - 1. 3045 auto &C = CGM.getContext(); 3046 auto *Length = E->getLength(); 3047 llvm::APSInt ConstLength; 3048 if (Length) { 3049 // Idx = LowerBound + Length - 1; 3050 if (Length->isIntegerConstantExpr(ConstLength, C)) { 3051 ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits); 3052 Length = nullptr; 3053 } 3054 auto *LowerBound = E->getLowerBound(); 3055 llvm::APSInt ConstLowerBound(PointerWidthInBits, /*isUnsigned=*/false); 3056 if (LowerBound && LowerBound->isIntegerConstantExpr(ConstLowerBound, C)) { 3057 ConstLowerBound = ConstLowerBound.zextOrTrunc(PointerWidthInBits); 3058 LowerBound = nullptr; 3059 } 3060 if (!Length) 3061 --ConstLength; 3062 else if (!LowerBound) 3063 --ConstLowerBound; 3064 3065 if (Length || LowerBound) { 3066 auto *LowerBoundVal = 3067 LowerBound 3068 ? Builder.CreateIntCast( 3069 EmitScalarExpr(LowerBound), IntPtrTy, 3070 LowerBound->getType()->hasSignedIntegerRepresentation()) 3071 : llvm::ConstantInt::get(IntPtrTy, ConstLowerBound); 3072 auto *LengthVal = 3073 Length 3074 ? Builder.CreateIntCast( 3075 EmitScalarExpr(Length), IntPtrTy, 3076 Length->getType()->hasSignedIntegerRepresentation()) 3077 : llvm::ConstantInt::get(IntPtrTy, ConstLength); 3078 Idx = Builder.CreateAdd(LowerBoundVal, LengthVal, "lb_add_len", 3079 /*HasNUW=*/false, 3080 !getLangOpts().isSignedOverflowDefined()); 3081 if (Length && LowerBound) { 3082 Idx = Builder.CreateSub( 3083 Idx, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "idx_sub_1", 3084 /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined()); 3085 } 3086 } else 3087 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength + ConstLowerBound); 3088 } else { 3089 // Idx = ArraySize - 1; 3090 QualType ArrayTy = BaseTy->isPointerType() 3091 ? E->getBase()->IgnoreParenImpCasts()->getType() 3092 : BaseTy; 3093 if (auto *VAT = C.getAsVariableArrayType(ArrayTy)) { 3094 Length = VAT->getSizeExpr(); 3095 if (Length->isIntegerConstantExpr(ConstLength, C)) 3096 Length = nullptr; 3097 } else { 3098 auto *CAT = C.getAsConstantArrayType(ArrayTy); 3099 ConstLength = CAT->getSize(); 3100 } 3101 if (Length) { 3102 auto *LengthVal = Builder.CreateIntCast( 3103 EmitScalarExpr(Length), IntPtrTy, 3104 Length->getType()->hasSignedIntegerRepresentation()); 3105 Idx = Builder.CreateSub( 3106 LengthVal, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "len_sub_1", 3107 /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined()); 3108 } else { 3109 ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits); 3110 --ConstLength; 3111 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength); 3112 } 3113 } 3114 } 3115 assert(Idx); 3116 3117 Address EltPtr = Address::invalid(); 3118 AlignmentSource AlignSource; 3119 if (auto *VLA = getContext().getAsVariableArrayType(ResultExprTy)) { 3120 // The base must be a pointer, which is not an aggregate. Emit 3121 // it. It needs to be emitted first in case it's what captures 3122 // the VLA bounds. 3123 Address Base = 3124 emitOMPArraySectionBase(*this, E->getBase(), AlignSource, BaseTy, 3125 VLA->getElementType(), IsLowerBound); 3126 // The element count here is the total number of non-VLA elements. 3127 llvm::Value *NumElements = getVLASize(VLA).first; 3128 3129 // Effectively, the multiply by the VLA size is part of the GEP. 3130 // GEP indexes are signed, and scaling an index isn't permitted to 3131 // signed-overflow, so we use the same semantics for our explicit 3132 // multiply. We suppress this if overflow is not undefined behavior. 3133 if (getLangOpts().isSignedOverflowDefined()) 3134 Idx = Builder.CreateMul(Idx, NumElements); 3135 else 3136 Idx = Builder.CreateNSWMul(Idx, NumElements); 3137 EltPtr = emitArraySubscriptGEP(*this, Base, Idx, VLA->getElementType(), 3138 !getLangOpts().isSignedOverflowDefined()); 3139 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) { 3140 // If this is A[i] where A is an array, the frontend will have decayed the 3141 // base to be a ArrayToPointerDecay implicit cast. While correct, it is 3142 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a 3143 // "gep x, i" here. Emit one "gep A, 0, i". 3144 assert(Array->getType()->isArrayType() && 3145 "Array to pointer decay must have array source type!"); 3146 LValue ArrayLV; 3147 // For simple multidimensional array indexing, set the 'accessed' flag for 3148 // better bounds-checking of the base expression. 3149 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array)) 3150 ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true); 3151 else 3152 ArrayLV = EmitLValue(Array); 3153 3154 // Propagate the alignment from the array itself to the result. 3155 EltPtr = emitArraySubscriptGEP( 3156 *this, ArrayLV.getAddress(), {CGM.getSize(CharUnits::Zero()), Idx}, 3157 ResultExprTy, !getLangOpts().isSignedOverflowDefined()); 3158 AlignSource = ArrayLV.getAlignmentSource(); 3159 } else { 3160 Address Base = emitOMPArraySectionBase(*this, E->getBase(), AlignSource, 3161 BaseTy, ResultExprTy, IsLowerBound); 3162 EltPtr = emitArraySubscriptGEP(*this, Base, Idx, ResultExprTy, 3163 !getLangOpts().isSignedOverflowDefined()); 3164 } 3165 3166 return MakeAddrLValue(EltPtr, ResultExprTy, AlignSource); 3167 } 3168 3169 LValue CodeGenFunction:: 3170 EmitExtVectorElementExpr(const ExtVectorElementExpr *E) { 3171 // Emit the base vector as an l-value. 3172 LValue Base; 3173 3174 // ExtVectorElementExpr's base can either be a vector or pointer to vector. 3175 if (E->isArrow()) { 3176 // If it is a pointer to a vector, emit the address and form an lvalue with 3177 // it. 3178 AlignmentSource AlignSource; 3179 Address Ptr = EmitPointerWithAlignment(E->getBase(), &AlignSource); 3180 const PointerType *PT = E->getBase()->getType()->getAs<PointerType>(); 3181 Base = MakeAddrLValue(Ptr, PT->getPointeeType(), AlignSource); 3182 Base.getQuals().removeObjCGCAttr(); 3183 } else if (E->getBase()->isGLValue()) { 3184 // Otherwise, if the base is an lvalue ( as in the case of foo.x.x), 3185 // emit the base as an lvalue. 3186 assert(E->getBase()->getType()->isVectorType()); 3187 Base = EmitLValue(E->getBase()); 3188 } else { 3189 // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such. 3190 assert(E->getBase()->getType()->isVectorType() && 3191 "Result must be a vector"); 3192 llvm::Value *Vec = EmitScalarExpr(E->getBase()); 3193 3194 // Store the vector to memory (because LValue wants an address). 3195 Address VecMem = CreateMemTemp(E->getBase()->getType()); 3196 Builder.CreateStore(Vec, VecMem); 3197 Base = MakeAddrLValue(VecMem, E->getBase()->getType(), 3198 AlignmentSource::Decl); 3199 } 3200 3201 QualType type = 3202 E->getType().withCVRQualifiers(Base.getQuals().getCVRQualifiers()); 3203 3204 // Encode the element access list into a vector of unsigned indices. 3205 SmallVector<uint32_t, 4> Indices; 3206 E->getEncodedElementAccess(Indices); 3207 3208 if (Base.isSimple()) { 3209 llvm::Constant *CV = 3210 llvm::ConstantDataVector::get(getLLVMContext(), Indices); 3211 return LValue::MakeExtVectorElt(Base.getAddress(), CV, type, 3212 Base.getAlignmentSource()); 3213 } 3214 assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!"); 3215 3216 llvm::Constant *BaseElts = Base.getExtVectorElts(); 3217 SmallVector<llvm::Constant *, 4> CElts; 3218 3219 for (unsigned i = 0, e = Indices.size(); i != e; ++i) 3220 CElts.push_back(BaseElts->getAggregateElement(Indices[i])); 3221 llvm::Constant *CV = llvm::ConstantVector::get(CElts); 3222 return LValue::MakeExtVectorElt(Base.getExtVectorAddress(), CV, type, 3223 Base.getAlignmentSource()); 3224 } 3225 3226 LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) { 3227 Expr *BaseExpr = E->getBase(); 3228 3229 // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar. 3230 LValue BaseLV; 3231 if (E->isArrow()) { 3232 AlignmentSource AlignSource; 3233 Address Addr = EmitPointerWithAlignment(BaseExpr, &AlignSource); 3234 QualType PtrTy = BaseExpr->getType()->getPointeeType(); 3235 EmitTypeCheck(TCK_MemberAccess, E->getExprLoc(), Addr.getPointer(), PtrTy); 3236 BaseLV = MakeAddrLValue(Addr, PtrTy, AlignSource); 3237 } else 3238 BaseLV = EmitCheckedLValue(BaseExpr, TCK_MemberAccess); 3239 3240 NamedDecl *ND = E->getMemberDecl(); 3241 if (auto *Field = dyn_cast<FieldDecl>(ND)) { 3242 LValue LV = EmitLValueForField(BaseLV, Field); 3243 setObjCGCLValueClass(getContext(), E, LV); 3244 return LV; 3245 } 3246 3247 if (auto *VD = dyn_cast<VarDecl>(ND)) 3248 return EmitGlobalVarDeclLValue(*this, E, VD); 3249 3250 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) 3251 return EmitFunctionDeclLValue(*this, E, FD); 3252 3253 llvm_unreachable("Unhandled member declaration!"); 3254 } 3255 3256 /// Given that we are currently emitting a lambda, emit an l-value for 3257 /// one of its members. 3258 LValue CodeGenFunction::EmitLValueForLambdaField(const FieldDecl *Field) { 3259 assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent()->isLambda()); 3260 assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent() == Field->getParent()); 3261 QualType LambdaTagType = 3262 getContext().getTagDeclType(Field->getParent()); 3263 LValue LambdaLV = MakeNaturalAlignAddrLValue(CXXABIThisValue, LambdaTagType); 3264 return EmitLValueForField(LambdaLV, Field); 3265 } 3266 3267 /// Drill down to the storage of a field without walking into 3268 /// reference types. 3269 /// 3270 /// The resulting address doesn't necessarily have the right type. 3271 static Address emitAddrOfFieldStorage(CodeGenFunction &CGF, Address base, 3272 const FieldDecl *field) { 3273 const RecordDecl *rec = field->getParent(); 3274 3275 unsigned idx = 3276 CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field); 3277 3278 CharUnits offset; 3279 // Adjust the alignment down to the given offset. 3280 // As a special case, if the LLVM field index is 0, we know that this 3281 // is zero. 3282 assert((idx != 0 || CGF.getContext().getASTRecordLayout(rec) 3283 .getFieldOffset(field->getFieldIndex()) == 0) && 3284 "LLVM field at index zero had non-zero offset?"); 3285 if (idx != 0) { 3286 auto &recLayout = CGF.getContext().getASTRecordLayout(rec); 3287 auto offsetInBits = recLayout.getFieldOffset(field->getFieldIndex()); 3288 offset = CGF.getContext().toCharUnitsFromBits(offsetInBits); 3289 } 3290 3291 return CGF.Builder.CreateStructGEP(base, idx, offset, field->getName()); 3292 } 3293 3294 LValue CodeGenFunction::EmitLValueForField(LValue base, 3295 const FieldDecl *field) { 3296 AlignmentSource fieldAlignSource = 3297 getFieldAlignmentSource(base.getAlignmentSource()); 3298 3299 if (field->isBitField()) { 3300 const CGRecordLayout &RL = 3301 CGM.getTypes().getCGRecordLayout(field->getParent()); 3302 const CGBitFieldInfo &Info = RL.getBitFieldInfo(field); 3303 Address Addr = base.getAddress(); 3304 unsigned Idx = RL.getLLVMFieldNo(field); 3305 if (Idx != 0) 3306 // For structs, we GEP to the field that the record layout suggests. 3307 Addr = Builder.CreateStructGEP(Addr, Idx, Info.StorageOffset, 3308 field->getName()); 3309 // Get the access type. 3310 llvm::Type *FieldIntTy = 3311 llvm::Type::getIntNTy(getLLVMContext(), Info.StorageSize); 3312 if (Addr.getElementType() != FieldIntTy) 3313 Addr = Builder.CreateElementBitCast(Addr, FieldIntTy); 3314 3315 QualType fieldType = 3316 field->getType().withCVRQualifiers(base.getVRQualifiers()); 3317 return LValue::MakeBitfield(Addr, Info, fieldType, fieldAlignSource); 3318 } 3319 3320 const RecordDecl *rec = field->getParent(); 3321 QualType type = field->getType(); 3322 3323 bool mayAlias = rec->hasAttr<MayAliasAttr>(); 3324 3325 Address addr = base.getAddress(); 3326 unsigned cvr = base.getVRQualifiers(); 3327 bool TBAAPath = CGM.getCodeGenOpts().StructPathTBAA; 3328 if (rec->isUnion()) { 3329 // For unions, there is no pointer adjustment. 3330 assert(!type->isReferenceType() && "union has reference member"); 3331 // TODO: handle path-aware TBAA for union. 3332 TBAAPath = false; 3333 } else { 3334 // For structs, we GEP to the field that the record layout suggests. 3335 addr = emitAddrOfFieldStorage(*this, addr, field); 3336 3337 // If this is a reference field, load the reference right now. 3338 if (const ReferenceType *refType = type->getAs<ReferenceType>()) { 3339 llvm::LoadInst *load = Builder.CreateLoad(addr, "ref"); 3340 if (cvr & Qualifiers::Volatile) load->setVolatile(true); 3341 3342 // Loading the reference will disable path-aware TBAA. 3343 TBAAPath = false; 3344 if (CGM.shouldUseTBAA()) { 3345 llvm::MDNode *tbaa; 3346 if (mayAlias) 3347 tbaa = CGM.getTBAAInfo(getContext().CharTy); 3348 else 3349 tbaa = CGM.getTBAAInfo(type); 3350 if (tbaa) 3351 CGM.DecorateInstructionWithTBAA(load, tbaa); 3352 } 3353 3354 mayAlias = false; 3355 type = refType->getPointeeType(); 3356 3357 CharUnits alignment = 3358 getNaturalTypeAlignment(type, &fieldAlignSource, /*pointee*/ true); 3359 addr = Address(load, alignment); 3360 3361 // Qualifiers on the struct don't apply to the referencee, and 3362 // we'll pick up CVR from the actual type later, so reset these 3363 // additional qualifiers now. 3364 cvr = 0; 3365 } 3366 } 3367 3368 // Make sure that the address is pointing to the right type. This is critical 3369 // for both unions and structs. A union needs a bitcast, a struct element 3370 // will need a bitcast if the LLVM type laid out doesn't match the desired 3371 // type. 3372 addr = Builder.CreateElementBitCast(addr, 3373 CGM.getTypes().ConvertTypeForMem(type), 3374 field->getName()); 3375 3376 if (field->hasAttr<AnnotateAttr>()) 3377 addr = EmitFieldAnnotations(field, addr); 3378 3379 LValue LV = MakeAddrLValue(addr, type, fieldAlignSource); 3380 LV.getQuals().addCVRQualifiers(cvr); 3381 if (TBAAPath) { 3382 const ASTRecordLayout &Layout = 3383 getContext().getASTRecordLayout(field->getParent()); 3384 // Set the base type to be the base type of the base LValue and 3385 // update offset to be relative to the base type. 3386 LV.setTBAABaseType(mayAlias ? getContext().CharTy : base.getTBAABaseType()); 3387 LV.setTBAAOffset(mayAlias ? 0 : base.getTBAAOffset() + 3388 Layout.getFieldOffset(field->getFieldIndex()) / 3389 getContext().getCharWidth()); 3390 } 3391 3392 // __weak attribute on a field is ignored. 3393 if (LV.getQuals().getObjCGCAttr() == Qualifiers::Weak) 3394 LV.getQuals().removeObjCGCAttr(); 3395 3396 // Fields of may_alias structs act like 'char' for TBAA purposes. 3397 // FIXME: this should get propagated down through anonymous structs 3398 // and unions. 3399 if (mayAlias && LV.getTBAAInfo()) 3400 LV.setTBAAInfo(CGM.getTBAAInfo(getContext().CharTy)); 3401 3402 return LV; 3403 } 3404 3405 LValue 3406 CodeGenFunction::EmitLValueForFieldInitialization(LValue Base, 3407 const FieldDecl *Field) { 3408 QualType FieldType = Field->getType(); 3409 3410 if (!FieldType->isReferenceType()) 3411 return EmitLValueForField(Base, Field); 3412 3413 Address V = emitAddrOfFieldStorage(*this, Base.getAddress(), Field); 3414 3415 // Make sure that the address is pointing to the right type. 3416 llvm::Type *llvmType = ConvertTypeForMem(FieldType); 3417 V = Builder.CreateElementBitCast(V, llvmType, Field->getName()); 3418 3419 // TODO: access-path TBAA? 3420 auto FieldAlignSource = getFieldAlignmentSource(Base.getAlignmentSource()); 3421 return MakeAddrLValue(V, FieldType, FieldAlignSource); 3422 } 3423 3424 LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr *E){ 3425 if (E->isFileScope()) { 3426 ConstantAddress GlobalPtr = CGM.GetAddrOfConstantCompoundLiteral(E); 3427 return MakeAddrLValue(GlobalPtr, E->getType(), AlignmentSource::Decl); 3428 } 3429 if (E->getType()->isVariablyModifiedType()) 3430 // make sure to emit the VLA size. 3431 EmitVariablyModifiedType(E->getType()); 3432 3433 Address DeclPtr = CreateMemTemp(E->getType(), ".compoundliteral"); 3434 const Expr *InitExpr = E->getInitializer(); 3435 LValue Result = MakeAddrLValue(DeclPtr, E->getType(), AlignmentSource::Decl); 3436 3437 EmitAnyExprToMem(InitExpr, DeclPtr, E->getType().getQualifiers(), 3438 /*Init*/ true); 3439 3440 return Result; 3441 } 3442 3443 LValue CodeGenFunction::EmitInitListLValue(const InitListExpr *E) { 3444 if (!E->isGLValue()) 3445 // Initializing an aggregate temporary in C++11: T{...}. 3446 return EmitAggExprToLValue(E); 3447 3448 // An lvalue initializer list must be initializing a reference. 3449 assert(E->getNumInits() == 1 && "reference init with multiple values"); 3450 return EmitLValue(E->getInit(0)); 3451 } 3452 3453 /// Emit the operand of a glvalue conditional operator. This is either a glvalue 3454 /// or a (possibly-parenthesized) throw-expression. If this is a throw, no 3455 /// LValue is returned and the current block has been terminated. 3456 static Optional<LValue> EmitLValueOrThrowExpression(CodeGenFunction &CGF, 3457 const Expr *Operand) { 3458 if (auto *ThrowExpr = dyn_cast<CXXThrowExpr>(Operand->IgnoreParens())) { 3459 CGF.EmitCXXThrowExpr(ThrowExpr, /*KeepInsertionPoint*/false); 3460 return None; 3461 } 3462 3463 return CGF.EmitLValue(Operand); 3464 } 3465 3466 LValue CodeGenFunction:: 3467 EmitConditionalOperatorLValue(const AbstractConditionalOperator *expr) { 3468 if (!expr->isGLValue()) { 3469 // ?: here should be an aggregate. 3470 assert(hasAggregateEvaluationKind(expr->getType()) && 3471 "Unexpected conditional operator!"); 3472 return EmitAggExprToLValue(expr); 3473 } 3474 3475 OpaqueValueMapping binding(*this, expr); 3476 3477 const Expr *condExpr = expr->getCond(); 3478 bool CondExprBool; 3479 if (ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) { 3480 const Expr *live = expr->getTrueExpr(), *dead = expr->getFalseExpr(); 3481 if (!CondExprBool) std::swap(live, dead); 3482 3483 if (!ContainsLabel(dead)) { 3484 // If the true case is live, we need to track its region. 3485 if (CondExprBool) 3486 incrementProfileCounter(expr); 3487 return EmitLValue(live); 3488 } 3489 } 3490 3491 llvm::BasicBlock *lhsBlock = createBasicBlock("cond.true"); 3492 llvm::BasicBlock *rhsBlock = createBasicBlock("cond.false"); 3493 llvm::BasicBlock *contBlock = createBasicBlock("cond.end"); 3494 3495 ConditionalEvaluation eval(*this); 3496 EmitBranchOnBoolExpr(condExpr, lhsBlock, rhsBlock, getProfileCount(expr)); 3497 3498 // Any temporaries created here are conditional. 3499 EmitBlock(lhsBlock); 3500 incrementProfileCounter(expr); 3501 eval.begin(*this); 3502 Optional<LValue> lhs = 3503 EmitLValueOrThrowExpression(*this, expr->getTrueExpr()); 3504 eval.end(*this); 3505 3506 if (lhs && !lhs->isSimple()) 3507 return EmitUnsupportedLValue(expr, "conditional operator"); 3508 3509 lhsBlock = Builder.GetInsertBlock(); 3510 if (lhs) 3511 Builder.CreateBr(contBlock); 3512 3513 // Any temporaries created here are conditional. 3514 EmitBlock(rhsBlock); 3515 eval.begin(*this); 3516 Optional<LValue> rhs = 3517 EmitLValueOrThrowExpression(*this, expr->getFalseExpr()); 3518 eval.end(*this); 3519 if (rhs && !rhs->isSimple()) 3520 return EmitUnsupportedLValue(expr, "conditional operator"); 3521 rhsBlock = Builder.GetInsertBlock(); 3522 3523 EmitBlock(contBlock); 3524 3525 if (lhs && rhs) { 3526 llvm::PHINode *phi = Builder.CreatePHI(lhs->getPointer()->getType(), 3527 2, "cond-lvalue"); 3528 phi->addIncoming(lhs->getPointer(), lhsBlock); 3529 phi->addIncoming(rhs->getPointer(), rhsBlock); 3530 Address result(phi, std::min(lhs->getAlignment(), rhs->getAlignment())); 3531 AlignmentSource alignSource = 3532 std::max(lhs->getAlignmentSource(), rhs->getAlignmentSource()); 3533 return MakeAddrLValue(result, expr->getType(), alignSource); 3534 } else { 3535 assert((lhs || rhs) && 3536 "both operands of glvalue conditional are throw-expressions?"); 3537 return lhs ? *lhs : *rhs; 3538 } 3539 } 3540 3541 /// EmitCastLValue - Casts are never lvalues unless that cast is to a reference 3542 /// type. If the cast is to a reference, we can have the usual lvalue result, 3543 /// otherwise if a cast is needed by the code generator in an lvalue context, 3544 /// then it must mean that we need the address of an aggregate in order to 3545 /// access one of its members. This can happen for all the reasons that casts 3546 /// are permitted with aggregate result, including noop aggregate casts, and 3547 /// cast from scalar to union. 3548 LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) { 3549 switch (E->getCastKind()) { 3550 case CK_ToVoid: 3551 case CK_BitCast: 3552 case CK_ArrayToPointerDecay: 3553 case CK_FunctionToPointerDecay: 3554 case CK_NullToMemberPointer: 3555 case CK_NullToPointer: 3556 case CK_IntegralToPointer: 3557 case CK_PointerToIntegral: 3558 case CK_PointerToBoolean: 3559 case CK_VectorSplat: 3560 case CK_IntegralCast: 3561 case CK_BooleanToSignedIntegral: 3562 case CK_IntegralToBoolean: 3563 case CK_IntegralToFloating: 3564 case CK_FloatingToIntegral: 3565 case CK_FloatingToBoolean: 3566 case CK_FloatingCast: 3567 case CK_FloatingRealToComplex: 3568 case CK_FloatingComplexToReal: 3569 case CK_FloatingComplexToBoolean: 3570 case CK_FloatingComplexCast: 3571 case CK_FloatingComplexToIntegralComplex: 3572 case CK_IntegralRealToComplex: 3573 case CK_IntegralComplexToReal: 3574 case CK_IntegralComplexToBoolean: 3575 case CK_IntegralComplexCast: 3576 case CK_IntegralComplexToFloatingComplex: 3577 case CK_DerivedToBaseMemberPointer: 3578 case CK_BaseToDerivedMemberPointer: 3579 case CK_MemberPointerToBoolean: 3580 case CK_ReinterpretMemberPointer: 3581 case CK_AnyPointerToBlockPointerCast: 3582 case CK_ARCProduceObject: 3583 case CK_ARCConsumeObject: 3584 case CK_ARCReclaimReturnedObject: 3585 case CK_ARCExtendBlockObject: 3586 case CK_CopyAndAutoreleaseBlockObject: 3587 case CK_AddressSpaceConversion: 3588 return EmitUnsupportedLValue(E, "unexpected cast lvalue"); 3589 3590 case CK_Dependent: 3591 llvm_unreachable("dependent cast kind in IR gen!"); 3592 3593 case CK_BuiltinFnToFnPtr: 3594 llvm_unreachable("builtin functions are handled elsewhere"); 3595 3596 // These are never l-values; just use the aggregate emission code. 3597 case CK_NonAtomicToAtomic: 3598 case CK_AtomicToNonAtomic: 3599 return EmitAggExprToLValue(E); 3600 3601 case CK_Dynamic: { 3602 LValue LV = EmitLValue(E->getSubExpr()); 3603 Address V = LV.getAddress(); 3604 const auto *DCE = cast<CXXDynamicCastExpr>(E); 3605 return MakeNaturalAlignAddrLValue(EmitDynamicCast(V, DCE), E->getType()); 3606 } 3607 3608 case CK_ConstructorConversion: 3609 case CK_UserDefinedConversion: 3610 case CK_CPointerToObjCPointerCast: 3611 case CK_BlockPointerToObjCPointerCast: 3612 case CK_NoOp: 3613 case CK_LValueToRValue: 3614 return EmitLValue(E->getSubExpr()); 3615 3616 case CK_UncheckedDerivedToBase: 3617 case CK_DerivedToBase: { 3618 const RecordType *DerivedClassTy = 3619 E->getSubExpr()->getType()->getAs<RecordType>(); 3620 auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl()); 3621 3622 LValue LV = EmitLValue(E->getSubExpr()); 3623 Address This = LV.getAddress(); 3624 3625 // Perform the derived-to-base conversion 3626 Address Base = GetAddressOfBaseClass( 3627 This, DerivedClassDecl, E->path_begin(), E->path_end(), 3628 /*NullCheckValue=*/false, E->getExprLoc()); 3629 3630 return MakeAddrLValue(Base, E->getType(), LV.getAlignmentSource()); 3631 } 3632 case CK_ToUnion: 3633 return EmitAggExprToLValue(E); 3634 case CK_BaseToDerived: { 3635 const RecordType *DerivedClassTy = E->getType()->getAs<RecordType>(); 3636 auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl()); 3637 3638 LValue LV = EmitLValue(E->getSubExpr()); 3639 3640 // Perform the base-to-derived conversion 3641 Address Derived = 3642 GetAddressOfDerivedClass(LV.getAddress(), DerivedClassDecl, 3643 E->path_begin(), E->path_end(), 3644 /*NullCheckValue=*/false); 3645 3646 // C++11 [expr.static.cast]p2: Behavior is undefined if a downcast is 3647 // performed and the object is not of the derived type. 3648 if (sanitizePerformTypeCheck()) 3649 EmitTypeCheck(TCK_DowncastReference, E->getExprLoc(), 3650 Derived.getPointer(), E->getType()); 3651 3652 if (SanOpts.has(SanitizerKind::CFIDerivedCast)) 3653 EmitVTablePtrCheckForCast(E->getType(), Derived.getPointer(), 3654 /*MayBeNull=*/false, 3655 CFITCK_DerivedCast, E->getLocStart()); 3656 3657 return MakeAddrLValue(Derived, E->getType(), LV.getAlignmentSource()); 3658 } 3659 case CK_LValueBitCast: { 3660 // This must be a reinterpret_cast (or c-style equivalent). 3661 const auto *CE = cast<ExplicitCastExpr>(E); 3662 3663 CGM.EmitExplicitCastExprType(CE, this); 3664 LValue LV = EmitLValue(E->getSubExpr()); 3665 Address V = Builder.CreateBitCast(LV.getAddress(), 3666 ConvertType(CE->getTypeAsWritten())); 3667 3668 if (SanOpts.has(SanitizerKind::CFIUnrelatedCast)) 3669 EmitVTablePtrCheckForCast(E->getType(), V.getPointer(), 3670 /*MayBeNull=*/false, 3671 CFITCK_UnrelatedCast, E->getLocStart()); 3672 3673 return MakeAddrLValue(V, E->getType(), LV.getAlignmentSource()); 3674 } 3675 case CK_ObjCObjectLValueCast: { 3676 LValue LV = EmitLValue(E->getSubExpr()); 3677 Address V = Builder.CreateElementBitCast(LV.getAddress(), 3678 ConvertType(E->getType())); 3679 return MakeAddrLValue(V, E->getType(), LV.getAlignmentSource()); 3680 } 3681 case CK_ZeroToOCLEvent: 3682 llvm_unreachable("NULL to OpenCL event lvalue cast is not valid"); 3683 } 3684 3685 llvm_unreachable("Unhandled lvalue cast kind?"); 3686 } 3687 3688 LValue CodeGenFunction::EmitOpaqueValueLValue(const OpaqueValueExpr *e) { 3689 assert(OpaqueValueMappingData::shouldBindAsLValue(e)); 3690 return getOpaqueLValueMapping(e); 3691 } 3692 3693 RValue CodeGenFunction::EmitRValueForField(LValue LV, 3694 const FieldDecl *FD, 3695 SourceLocation Loc) { 3696 QualType FT = FD->getType(); 3697 LValue FieldLV = EmitLValueForField(LV, FD); 3698 switch (getEvaluationKind(FT)) { 3699 case TEK_Complex: 3700 return RValue::getComplex(EmitLoadOfComplex(FieldLV, Loc)); 3701 case TEK_Aggregate: 3702 return FieldLV.asAggregateRValue(); 3703 case TEK_Scalar: 3704 // This routine is used to load fields one-by-one to perform a copy, so 3705 // don't load reference fields. 3706 if (FD->getType()->isReferenceType()) 3707 return RValue::get(FieldLV.getPointer()); 3708 return EmitLoadOfLValue(FieldLV, Loc); 3709 } 3710 llvm_unreachable("bad evaluation kind"); 3711 } 3712 3713 //===--------------------------------------------------------------------===// 3714 // Expression Emission 3715 //===--------------------------------------------------------------------===// 3716 3717 RValue CodeGenFunction::EmitCallExpr(const CallExpr *E, 3718 ReturnValueSlot ReturnValue) { 3719 // Builtins never have block type. 3720 if (E->getCallee()->getType()->isBlockPointerType()) 3721 return EmitBlockCallExpr(E, ReturnValue); 3722 3723 if (const auto *CE = dyn_cast<CXXMemberCallExpr>(E)) 3724 return EmitCXXMemberCallExpr(CE, ReturnValue); 3725 3726 if (const auto *CE = dyn_cast<CUDAKernelCallExpr>(E)) 3727 return EmitCUDAKernelCallExpr(CE, ReturnValue); 3728 3729 const Decl *TargetDecl = E->getCalleeDecl(); 3730 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) { 3731 if (unsigned builtinID = FD->getBuiltinID()) 3732 return EmitBuiltinExpr(FD, builtinID, E, ReturnValue); 3733 } 3734 3735 if (const auto *CE = dyn_cast<CXXOperatorCallExpr>(E)) 3736 if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(TargetDecl)) 3737 return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue); 3738 3739 if (const auto *PseudoDtor = 3740 dyn_cast<CXXPseudoDestructorExpr>(E->getCallee()->IgnoreParens())) { 3741 QualType DestroyedType = PseudoDtor->getDestroyedType(); 3742 if (DestroyedType.hasStrongOrWeakObjCLifetime()) { 3743 // Automatic Reference Counting: 3744 // If the pseudo-expression names a retainable object with weak or 3745 // strong lifetime, the object shall be released. 3746 Expr *BaseExpr = PseudoDtor->getBase(); 3747 Address BaseValue = Address::invalid(); 3748 Qualifiers BaseQuals; 3749 3750 // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar. 3751 if (PseudoDtor->isArrow()) { 3752 BaseValue = EmitPointerWithAlignment(BaseExpr); 3753 const PointerType *PTy = BaseExpr->getType()->getAs<PointerType>(); 3754 BaseQuals = PTy->getPointeeType().getQualifiers(); 3755 } else { 3756 LValue BaseLV = EmitLValue(BaseExpr); 3757 BaseValue = BaseLV.getAddress(); 3758 QualType BaseTy = BaseExpr->getType(); 3759 BaseQuals = BaseTy.getQualifiers(); 3760 } 3761 3762 switch (DestroyedType.getObjCLifetime()) { 3763 case Qualifiers::OCL_None: 3764 case Qualifiers::OCL_ExplicitNone: 3765 case Qualifiers::OCL_Autoreleasing: 3766 break; 3767 3768 case Qualifiers::OCL_Strong: 3769 EmitARCRelease(Builder.CreateLoad(BaseValue, 3770 PseudoDtor->getDestroyedType().isVolatileQualified()), 3771 ARCPreciseLifetime); 3772 break; 3773 3774 case Qualifiers::OCL_Weak: 3775 EmitARCDestroyWeak(BaseValue); 3776 break; 3777 } 3778 } else { 3779 // C++ [expr.pseudo]p1: 3780 // The result shall only be used as the operand for the function call 3781 // operator (), and the result of such a call has type void. The only 3782 // effect is the evaluation of the postfix-expression before the dot or 3783 // arrow. 3784 EmitScalarExpr(E->getCallee()); 3785 } 3786 3787 return RValue::get(nullptr); 3788 } 3789 3790 llvm::Value *Callee = EmitScalarExpr(E->getCallee()); 3791 return EmitCall(E->getCallee()->getType(), Callee, E, ReturnValue, 3792 TargetDecl); 3793 } 3794 3795 LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) { 3796 // Comma expressions just emit their LHS then their RHS as an l-value. 3797 if (E->getOpcode() == BO_Comma) { 3798 EmitIgnoredExpr(E->getLHS()); 3799 EnsureInsertPoint(); 3800 return EmitLValue(E->getRHS()); 3801 } 3802 3803 if (E->getOpcode() == BO_PtrMemD || 3804 E->getOpcode() == BO_PtrMemI) 3805 return EmitPointerToDataMemberBinaryExpr(E); 3806 3807 assert(E->getOpcode() == BO_Assign && "unexpected binary l-value"); 3808 3809 // Note that in all of these cases, __block variables need the RHS 3810 // evaluated first just in case the variable gets moved by the RHS. 3811 3812 switch (getEvaluationKind(E->getType())) { 3813 case TEK_Scalar: { 3814 switch (E->getLHS()->getType().getObjCLifetime()) { 3815 case Qualifiers::OCL_Strong: 3816 return EmitARCStoreStrong(E, /*ignored*/ false).first; 3817 3818 case Qualifiers::OCL_Autoreleasing: 3819 return EmitARCStoreAutoreleasing(E).first; 3820 3821 // No reason to do any of these differently. 3822 case Qualifiers::OCL_None: 3823 case Qualifiers::OCL_ExplicitNone: 3824 case Qualifiers::OCL_Weak: 3825 break; 3826 } 3827 3828 RValue RV = EmitAnyExpr(E->getRHS()); 3829 LValue LV = EmitCheckedLValue(E->getLHS(), TCK_Store); 3830 EmitStoreThroughLValue(RV, LV); 3831 return LV; 3832 } 3833 3834 case TEK_Complex: 3835 return EmitComplexAssignmentLValue(E); 3836 3837 case TEK_Aggregate: 3838 return EmitAggExprToLValue(E); 3839 } 3840 llvm_unreachable("bad evaluation kind"); 3841 } 3842 3843 LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) { 3844 RValue RV = EmitCallExpr(E); 3845 3846 if (!RV.isScalar()) 3847 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(), 3848 AlignmentSource::Decl); 3849 3850 assert(E->getCallReturnType(getContext())->isReferenceType() && 3851 "Can't have a scalar return unless the return type is a " 3852 "reference type!"); 3853 3854 return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType()); 3855 } 3856 3857 LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) { 3858 // FIXME: This shouldn't require another copy. 3859 return EmitAggExprToLValue(E); 3860 } 3861 3862 LValue CodeGenFunction::EmitCXXConstructLValue(const CXXConstructExpr *E) { 3863 assert(E->getType()->getAsCXXRecordDecl()->hasTrivialDestructor() 3864 && "binding l-value to type which needs a temporary"); 3865 AggValueSlot Slot = CreateAggTemp(E->getType()); 3866 EmitCXXConstructExpr(E, Slot); 3867 return MakeAddrLValue(Slot.getAddress(), E->getType(), 3868 AlignmentSource::Decl); 3869 } 3870 3871 LValue 3872 CodeGenFunction::EmitCXXTypeidLValue(const CXXTypeidExpr *E) { 3873 return MakeNaturalAlignAddrLValue(EmitCXXTypeidExpr(E), E->getType()); 3874 } 3875 3876 Address CodeGenFunction::EmitCXXUuidofExpr(const CXXUuidofExpr *E) { 3877 return Builder.CreateElementBitCast(CGM.GetAddrOfUuidDescriptor(E), 3878 ConvertType(E->getType())); 3879 } 3880 3881 LValue CodeGenFunction::EmitCXXUuidofLValue(const CXXUuidofExpr *E) { 3882 return MakeAddrLValue(EmitCXXUuidofExpr(E), E->getType(), 3883 AlignmentSource::Decl); 3884 } 3885 3886 LValue 3887 CodeGenFunction::EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E) { 3888 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue"); 3889 Slot.setExternallyDestructed(); 3890 EmitAggExpr(E->getSubExpr(), Slot); 3891 EmitCXXTemporary(E->getTemporary(), E->getType(), Slot.getAddress()); 3892 return MakeAddrLValue(Slot.getAddress(), E->getType(), 3893 AlignmentSource::Decl); 3894 } 3895 3896 LValue 3897 CodeGenFunction::EmitLambdaLValue(const LambdaExpr *E) { 3898 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue"); 3899 EmitLambdaExpr(E, Slot); 3900 return MakeAddrLValue(Slot.getAddress(), E->getType(), 3901 AlignmentSource::Decl); 3902 } 3903 3904 LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) { 3905 RValue RV = EmitObjCMessageExpr(E); 3906 3907 if (!RV.isScalar()) 3908 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(), 3909 AlignmentSource::Decl); 3910 3911 assert(E->getMethodDecl()->getReturnType()->isReferenceType() && 3912 "Can't have a scalar return unless the return type is a " 3913 "reference type!"); 3914 3915 return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType()); 3916 } 3917 3918 LValue CodeGenFunction::EmitObjCSelectorLValue(const ObjCSelectorExpr *E) { 3919 Address V = 3920 CGM.getObjCRuntime().GetAddrOfSelector(*this, E->getSelector()); 3921 return MakeAddrLValue(V, E->getType(), AlignmentSource::Decl); 3922 } 3923 3924 llvm::Value *CodeGenFunction::EmitIvarOffset(const ObjCInterfaceDecl *Interface, 3925 const ObjCIvarDecl *Ivar) { 3926 return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar); 3927 } 3928 3929 LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy, 3930 llvm::Value *BaseValue, 3931 const ObjCIvarDecl *Ivar, 3932 unsigned CVRQualifiers) { 3933 return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue, 3934 Ivar, CVRQualifiers); 3935 } 3936 3937 LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) { 3938 // FIXME: A lot of the code below could be shared with EmitMemberExpr. 3939 llvm::Value *BaseValue = nullptr; 3940 const Expr *BaseExpr = E->getBase(); 3941 Qualifiers BaseQuals; 3942 QualType ObjectTy; 3943 if (E->isArrow()) { 3944 BaseValue = EmitScalarExpr(BaseExpr); 3945 ObjectTy = BaseExpr->getType()->getPointeeType(); 3946 BaseQuals = ObjectTy.getQualifiers(); 3947 } else { 3948 LValue BaseLV = EmitLValue(BaseExpr); 3949 BaseValue = BaseLV.getPointer(); 3950 ObjectTy = BaseExpr->getType(); 3951 BaseQuals = ObjectTy.getQualifiers(); 3952 } 3953 3954 LValue LV = 3955 EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(), 3956 BaseQuals.getCVRQualifiers()); 3957 setObjCGCLValueClass(getContext(), E, LV); 3958 return LV; 3959 } 3960 3961 LValue CodeGenFunction::EmitStmtExprLValue(const StmtExpr *E) { 3962 // Can only get l-value for message expression returning aggregate type 3963 RValue RV = EmitAnyExprToTemp(E); 3964 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(), 3965 AlignmentSource::Decl); 3966 } 3967 3968 RValue CodeGenFunction::EmitCall(QualType CalleeType, llvm::Value *Callee, 3969 const CallExpr *E, ReturnValueSlot ReturnValue, 3970 CGCalleeInfo CalleeInfo, llvm::Value *Chain) { 3971 // Get the actual function type. The callee type will always be a pointer to 3972 // function type or a block pointer type. 3973 assert(CalleeType->isFunctionPointerType() && 3974 "Call must have function pointer type!"); 3975 3976 // Preserve the non-canonical function type because things like exception 3977 // specifications disappear in the canonical type. That information is useful 3978 // to drive the generation of more accurate code for this call later on. 3979 const FunctionProtoType *NonCanonicalFTP = CalleeType->getAs<PointerType>() 3980 ->getPointeeType() 3981 ->getAs<FunctionProtoType>(); 3982 3983 const Decl *TargetDecl = CalleeInfo.getCalleeDecl(); 3984 3985 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) 3986 // We can only guarantee that a function is called from the correct 3987 // context/function based on the appropriate target attributes, 3988 // so only check in the case where we have both always_inline and target 3989 // since otherwise we could be making a conditional call after a check for 3990 // the proper cpu features (and it won't cause code generation issues due to 3991 // function based code generation). 3992 if (TargetDecl->hasAttr<AlwaysInlineAttr>() && 3993 TargetDecl->hasAttr<TargetAttr>()) 3994 checkTargetFeatures(E, FD); 3995 3996 CalleeType = getContext().getCanonicalType(CalleeType); 3997 3998 const auto *FnType = 3999 cast<FunctionType>(cast<PointerType>(CalleeType)->getPointeeType()); 4000 4001 if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function) && 4002 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) { 4003 if (llvm::Constant *PrefixSig = 4004 CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) { 4005 SanitizerScope SanScope(this); 4006 llvm::Constant *FTRTTIConst = 4007 CGM.GetAddrOfRTTIDescriptor(QualType(FnType, 0), /*ForEH=*/true); 4008 llvm::Type *PrefixStructTyElems[] = { 4009 PrefixSig->getType(), 4010 FTRTTIConst->getType() 4011 }; 4012 llvm::StructType *PrefixStructTy = llvm::StructType::get( 4013 CGM.getLLVMContext(), PrefixStructTyElems, /*isPacked=*/true); 4014 4015 llvm::Value *CalleePrefixStruct = Builder.CreateBitCast( 4016 Callee, llvm::PointerType::getUnqual(PrefixStructTy)); 4017 llvm::Value *CalleeSigPtr = 4018 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 0); 4019 llvm::Value *CalleeSig = 4020 Builder.CreateAlignedLoad(CalleeSigPtr, getIntAlign()); 4021 llvm::Value *CalleeSigMatch = Builder.CreateICmpEQ(CalleeSig, PrefixSig); 4022 4023 llvm::BasicBlock *Cont = createBasicBlock("cont"); 4024 llvm::BasicBlock *TypeCheck = createBasicBlock("typecheck"); 4025 Builder.CreateCondBr(CalleeSigMatch, TypeCheck, Cont); 4026 4027 EmitBlock(TypeCheck); 4028 llvm::Value *CalleeRTTIPtr = 4029 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 1); 4030 llvm::Value *CalleeRTTI = 4031 Builder.CreateAlignedLoad(CalleeRTTIPtr, getPointerAlign()); 4032 llvm::Value *CalleeRTTIMatch = 4033 Builder.CreateICmpEQ(CalleeRTTI, FTRTTIConst); 4034 llvm::Constant *StaticData[] = { 4035 EmitCheckSourceLocation(E->getLocStart()), 4036 EmitCheckTypeDescriptor(CalleeType) 4037 }; 4038 EmitCheck(std::make_pair(CalleeRTTIMatch, SanitizerKind::Function), 4039 "function_type_mismatch", StaticData, Callee); 4040 4041 Builder.CreateBr(Cont); 4042 EmitBlock(Cont); 4043 } 4044 } 4045 4046 // If we are checking indirect calls and this call is indirect, check that the 4047 // function pointer is a member of the bit set for the function type. 4048 if (SanOpts.has(SanitizerKind::CFIICall) && 4049 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) { 4050 SanitizerScope SanScope(this); 4051 EmitSanitizerStatReport(llvm::SanStat_CFI_ICall); 4052 4053 llvm::Metadata *MD = CGM.CreateMetadataIdentifierForType(QualType(FnType, 0)); 4054 llvm::Value *BitSetName = llvm::MetadataAsValue::get(getLLVMContext(), MD); 4055 4056 llvm::Value *CastedCallee = Builder.CreateBitCast(Callee, Int8PtrTy); 4057 llvm::Value *BitSetTest = 4058 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::bitset_test), 4059 {CastedCallee, BitSetName}); 4060 4061 auto TypeId = CGM.CreateCfiIdForTypeMetadata(MD); 4062 llvm::Constant *StaticData[] = { 4063 llvm::ConstantInt::get(Int8Ty, CFITCK_ICall), 4064 EmitCheckSourceLocation(E->getLocStart()), 4065 EmitCheckTypeDescriptor(QualType(FnType, 0)), 4066 }; 4067 if (CGM.getCodeGenOpts().SanitizeCfiCrossDso && TypeId) { 4068 EmitCfiSlowPathCheck(SanitizerKind::CFIICall, BitSetTest, TypeId, 4069 CastedCallee, StaticData); 4070 } else { 4071 EmitCheck(std::make_pair(BitSetTest, SanitizerKind::CFIICall), 4072 "cfi_check_fail", StaticData, 4073 {CastedCallee, llvm::UndefValue::get(IntPtrTy)}); 4074 } 4075 } 4076 4077 CallArgList Args; 4078 if (Chain) 4079 Args.add(RValue::get(Builder.CreateBitCast(Chain, CGM.VoidPtrTy)), 4080 CGM.getContext().VoidPtrTy); 4081 EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), E->arguments(), 4082 E->getDirectCallee(), /*ParamsToSkip*/ 0); 4083 4084 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeFreeFunctionCall( 4085 Args, FnType, /*isChainCall=*/Chain); 4086 4087 // C99 6.5.2.2p6: 4088 // If the expression that denotes the called function has a type 4089 // that does not include a prototype, [the default argument 4090 // promotions are performed]. If the number of arguments does not 4091 // equal the number of parameters, the behavior is undefined. If 4092 // the function is defined with a type that includes a prototype, 4093 // and either the prototype ends with an ellipsis (, ...) or the 4094 // types of the arguments after promotion are not compatible with 4095 // the types of the parameters, the behavior is undefined. If the 4096 // function is defined with a type that does not include a 4097 // prototype, and the types of the arguments after promotion are 4098 // not compatible with those of the parameters after promotion, 4099 // the behavior is undefined [except in some trivial cases]. 4100 // That is, in the general case, we should assume that a call 4101 // through an unprototyped function type works like a *non-variadic* 4102 // call. The way we make this work is to cast to the exact type 4103 // of the promoted arguments. 4104 // 4105 // Chain calls use this same code path to add the invisible chain parameter 4106 // to the function type. 4107 if (isa<FunctionNoProtoType>(FnType) || Chain) { 4108 llvm::Type *CalleeTy = getTypes().GetFunctionType(FnInfo); 4109 CalleeTy = CalleeTy->getPointerTo(); 4110 Callee = Builder.CreateBitCast(Callee, CalleeTy, "callee.knr.cast"); 4111 } 4112 4113 return EmitCall(FnInfo, Callee, ReturnValue, Args, 4114 CGCalleeInfo(NonCanonicalFTP, TargetDecl)); 4115 } 4116 4117 LValue CodeGenFunction:: 4118 EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E) { 4119 Address BaseAddr = Address::invalid(); 4120 if (E->getOpcode() == BO_PtrMemI) { 4121 BaseAddr = EmitPointerWithAlignment(E->getLHS()); 4122 } else { 4123 BaseAddr = EmitLValue(E->getLHS()).getAddress(); 4124 } 4125 4126 llvm::Value *OffsetV = EmitScalarExpr(E->getRHS()); 4127 4128 const MemberPointerType *MPT 4129 = E->getRHS()->getType()->getAs<MemberPointerType>(); 4130 4131 AlignmentSource AlignSource; 4132 Address MemberAddr = 4133 EmitCXXMemberDataPointerAddress(E, BaseAddr, OffsetV, MPT, 4134 &AlignSource); 4135 4136 return MakeAddrLValue(MemberAddr, MPT->getPointeeType(), AlignSource); 4137 } 4138 4139 /// Given the address of a temporary variable, produce an r-value of 4140 /// its type. 4141 RValue CodeGenFunction::convertTempToRValue(Address addr, 4142 QualType type, 4143 SourceLocation loc) { 4144 LValue lvalue = MakeAddrLValue(addr, type, AlignmentSource::Decl); 4145 switch (getEvaluationKind(type)) { 4146 case TEK_Complex: 4147 return RValue::getComplex(EmitLoadOfComplex(lvalue, loc)); 4148 case TEK_Aggregate: 4149 return lvalue.asAggregateRValue(); 4150 case TEK_Scalar: 4151 return RValue::get(EmitLoadOfScalar(lvalue, loc)); 4152 } 4153 llvm_unreachable("bad evaluation kind"); 4154 } 4155 4156 void CodeGenFunction::SetFPAccuracy(llvm::Value *Val, float Accuracy) { 4157 assert(Val->getType()->isFPOrFPVectorTy()); 4158 if (Accuracy == 0.0 || !isa<llvm::Instruction>(Val)) 4159 return; 4160 4161 llvm::MDBuilder MDHelper(getLLVMContext()); 4162 llvm::MDNode *Node = MDHelper.createFPMath(Accuracy); 4163 4164 cast<llvm::Instruction>(Val)->setMetadata(llvm::LLVMContext::MD_fpmath, Node); 4165 } 4166 4167 namespace { 4168 struct LValueOrRValue { 4169 LValue LV; 4170 RValue RV; 4171 }; 4172 } 4173 4174 static LValueOrRValue emitPseudoObjectExpr(CodeGenFunction &CGF, 4175 const PseudoObjectExpr *E, 4176 bool forLValue, 4177 AggValueSlot slot) { 4178 SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques; 4179 4180 // Find the result expression, if any. 4181 const Expr *resultExpr = E->getResultExpr(); 4182 LValueOrRValue result; 4183 4184 for (PseudoObjectExpr::const_semantics_iterator 4185 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) { 4186 const Expr *semantic = *i; 4187 4188 // If this semantic expression is an opaque value, bind it 4189 // to the result of its source expression. 4190 if (const auto *ov = dyn_cast<OpaqueValueExpr>(semantic)) { 4191 4192 // If this is the result expression, we may need to evaluate 4193 // directly into the slot. 4194 typedef CodeGenFunction::OpaqueValueMappingData OVMA; 4195 OVMA opaqueData; 4196 if (ov == resultExpr && ov->isRValue() && !forLValue && 4197 CodeGenFunction::hasAggregateEvaluationKind(ov->getType())) { 4198 CGF.EmitAggExpr(ov->getSourceExpr(), slot); 4199 4200 LValue LV = CGF.MakeAddrLValue(slot.getAddress(), ov->getType(), 4201 AlignmentSource::Decl); 4202 opaqueData = OVMA::bind(CGF, ov, LV); 4203 result.RV = slot.asRValue(); 4204 4205 // Otherwise, emit as normal. 4206 } else { 4207 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr()); 4208 4209 // If this is the result, also evaluate the result now. 4210 if (ov == resultExpr) { 4211 if (forLValue) 4212 result.LV = CGF.EmitLValue(ov); 4213 else 4214 result.RV = CGF.EmitAnyExpr(ov, slot); 4215 } 4216 } 4217 4218 opaques.push_back(opaqueData); 4219 4220 // Otherwise, if the expression is the result, evaluate it 4221 // and remember the result. 4222 } else if (semantic == resultExpr) { 4223 if (forLValue) 4224 result.LV = CGF.EmitLValue(semantic); 4225 else 4226 result.RV = CGF.EmitAnyExpr(semantic, slot); 4227 4228 // Otherwise, evaluate the expression in an ignored context. 4229 } else { 4230 CGF.EmitIgnoredExpr(semantic); 4231 } 4232 } 4233 4234 // Unbind all the opaques now. 4235 for (unsigned i = 0, e = opaques.size(); i != e; ++i) 4236 opaques[i].unbind(CGF); 4237 4238 return result; 4239 } 4240 4241 RValue CodeGenFunction::EmitPseudoObjectRValue(const PseudoObjectExpr *E, 4242 AggValueSlot slot) { 4243 return emitPseudoObjectExpr(*this, E, false, slot).RV; 4244 } 4245 4246 LValue CodeGenFunction::EmitPseudoObjectLValue(const PseudoObjectExpr *E) { 4247 return emitPseudoObjectExpr(*this, E, true, AggValueSlot::ignored()).LV; 4248 } 4249