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