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