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