clang  14.0.0git
CGObjC.cpp
Go to the documentation of this file.
1 //===---- CGObjC.cpp - Emit LLVM Code for Objective-C ---------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This contains code to emit Objective-C code as LLVM code.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "CGDebugInfo.h"
14 #include "CGObjCRuntime.h"
15 #include "CodeGenFunction.h"
16 #include "CodeGenModule.h"
17 #include "ConstantEmitter.h"
18 #include "TargetInfo.h"
19 #include "clang/AST/ASTContext.h"
20 #include "clang/AST/Attr.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/StmtObjC.h"
23 #include "clang/Basic/Diagnostic.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/Analysis/ObjCARCUtil.h"
27 #include "llvm/BinaryFormat/MachO.h"
28 #include "llvm/IR/DataLayout.h"
29 #include "llvm/IR/InlineAsm.h"
30 using namespace clang;
31 using namespace CodeGen;
32 
33 typedef llvm::PointerIntPair<llvm::Value*,1,bool> TryEmitResult;
34 static TryEmitResult
37  QualType ET,
38  RValue Result);
39 
40 /// Given the address of a variable of pointer type, find the correct
41 /// null to store into it.
42 static llvm::Constant *getNullForVariable(Address addr) {
43  llvm::Type *type = addr.getElementType();
44  return llvm::ConstantPointerNull::get(cast<llvm::PointerType>(type));
45 }
46 
47 /// Emits an instance of NSConstantString representing the object.
49 {
50  llvm::Constant *C =
52  // FIXME: This bitcast should just be made an invariant on the Runtime.
53  return llvm::ConstantExpr::getBitCast(C, ConvertType(E->getType()));
54 }
55 
56 /// EmitObjCBoxedExpr - This routine generates code to call
57 /// the appropriate expression boxing method. This will either be
58 /// one of +[NSNumber numberWith<Type>:], or +[NSString stringWithUTF8String:],
59 /// or [NSValue valueWithBytes:objCType:].
60 ///
63  // Generate the correct selector for this literal's concrete type.
64  // Get the method.
65  const ObjCMethodDecl *BoxingMethod = E->getBoxingMethod();
66  const Expr *SubExpr = E->getSubExpr();
67 
69  ConstantEmitter ConstEmitter(CGM);
70  return ConstEmitter.tryEmitAbstract(E, E->getType());
71  }
72 
73  assert(BoxingMethod->isClassMethod() && "BoxingMethod must be a class method");
74  Selector Sel = BoxingMethod->getSelector();
75 
76  // Generate a reference to the class pointer, which will be the receiver.
77  // Assumes that the method was introduced in the class that should be
78  // messaged (avoids pulling it out of the result type).
79  CGObjCRuntime &Runtime = CGM.getObjCRuntime();
80  const ObjCInterfaceDecl *ClassDecl = BoxingMethod->getClassInterface();
81  llvm::Value *Receiver = Runtime.GetClass(*this, ClassDecl);
82 
83  CallArgList Args;
84  const ParmVarDecl *ArgDecl = *BoxingMethod->param_begin();
85  QualType ArgQT = ArgDecl->getType().getUnqualifiedType();
86 
87  // ObjCBoxedExpr supports boxing of structs and unions
88  // via [NSValue valueWithBytes:objCType:]
89  const QualType ValueType(SubExpr->getType().getCanonicalType());
90  if (ValueType->isObjCBoxableRecordType()) {
91  // Emit CodeGen for first parameter
92  // and cast value to correct type
93  Address Temporary = CreateMemTemp(SubExpr->getType());
94  EmitAnyExprToMem(SubExpr, Temporary, Qualifiers(), /*isInit*/ true);
95  Address BitCast = Builder.CreateBitCast(Temporary, ConvertType(ArgQT));
96  Args.add(RValue::get(BitCast.getPointer()), ArgQT);
97 
98  // Create char array to store type encoding
99  std::string Str;
100  getContext().getObjCEncodingForType(ValueType, Str);
101  llvm::Constant *GV = CGM.GetAddrOfConstantCString(Str).getPointer();
102 
103  // Cast type encoding to correct type
104  const ParmVarDecl *EncodingDecl = BoxingMethod->parameters()[1];
105  QualType EncodingQT = EncodingDecl->getType().getUnqualifiedType();
106  llvm::Value *Cast = Builder.CreateBitCast(GV, ConvertType(EncodingQT));
107 
108  Args.add(RValue::get(Cast), EncodingQT);
109  } else {
110  Args.add(EmitAnyExpr(SubExpr), ArgQT);
111  }
112 
113  RValue result = Runtime.GenerateMessageSend(
114  *this, ReturnValueSlot(), BoxingMethod->getReturnType(), Sel, Receiver,
115  Args, ClassDecl, BoxingMethod);
116  return Builder.CreateBitCast(result.getScalarVal(),
117  ConvertType(E->getType()));
118 }
119 
121  const ObjCMethodDecl *MethodWithObjects) {
122  ASTContext &Context = CGM.getContext();
123  const ObjCDictionaryLiteral *DLE = nullptr;
124  const ObjCArrayLiteral *ALE = dyn_cast<ObjCArrayLiteral>(E);
125  if (!ALE)
126  DLE = cast<ObjCDictionaryLiteral>(E);
127 
128  // Optimize empty collections by referencing constants, when available.
129  uint64_t NumElements =
130  ALE ? ALE->getNumElements() : DLE->getNumElements();
131  if (NumElements == 0 && CGM.getLangOpts().ObjCRuntime.hasEmptyCollections()) {
132  StringRef ConstantName = ALE ? "__NSArray0__" : "__NSDictionary0__";
134  llvm::Constant *Constant =
135  CGM.CreateRuntimeVariable(ConvertType(IdTy), ConstantName);
136  LValue LV = MakeNaturalAlignAddrLValue(Constant, IdTy);
137  llvm::Value *Ptr = EmitLoadOfScalar(LV, E->getBeginLoc());
138  cast<llvm::LoadInst>(Ptr)->setMetadata(
139  CGM.getModule().getMDKindID("invariant.load"),
140  llvm::MDNode::get(getLLVMContext(), None));
141  return Builder.CreateBitCast(Ptr, ConvertType(E->getType()));
142  }
143 
144  // Compute the type of the array we're initializing.
145  llvm::APInt APNumElements(Context.getTypeSize(Context.getSizeType()),
146  NumElements);
147  QualType ElementType = Context.getObjCIdType().withConst();
148  QualType ElementArrayType
149  = Context.getConstantArrayType(ElementType, APNumElements, nullptr,
150  ArrayType::Normal, /*IndexTypeQuals=*/0);
151 
152  // Allocate the temporary array(s).
153  Address Objects = CreateMemTemp(ElementArrayType, "objects");
154  Address Keys = Address::invalid();
155  if (DLE)
156  Keys = CreateMemTemp(ElementArrayType, "keys");
157 
158  // In ARC, we may need to do extra work to keep all the keys and
159  // values alive until after the call.
160  SmallVector<llvm::Value *, 16> NeededObjects;
161  bool TrackNeededObjects =
162  (getLangOpts().ObjCAutoRefCount &&
163  CGM.getCodeGenOpts().OptimizationLevel != 0);
164 
165  // Perform the actual initialialization of the array(s).
166  for (uint64_t i = 0; i < NumElements; i++) {
167  if (ALE) {
168  // Emit the element and store it to the appropriate array slot.
169  const Expr *Rhs = ALE->getElement(i);
171  ElementType, AlignmentSource::Decl);
172 
173  llvm::Value *value = EmitScalarExpr(Rhs);
174  EmitStoreThroughLValue(RValue::get(value), LV, true);
175  if (TrackNeededObjects) {
176  NeededObjects.push_back(value);
177  }
178  } else {
179  // Emit the key and store it to the appropriate array slot.
180  const Expr *Key = DLE->getKeyValueElement(i).Key;
182  ElementType, AlignmentSource::Decl);
183  llvm::Value *keyValue = EmitScalarExpr(Key);
184  EmitStoreThroughLValue(RValue::get(keyValue), KeyLV, /*isInit=*/true);
185 
186  // Emit the value and store it to the appropriate array slot.
187  const Expr *Value = DLE->getKeyValueElement(i).Value;
188  LValue ValueLV = MakeAddrLValue(Builder.CreateConstArrayGEP(Objects, i),
189  ElementType, AlignmentSource::Decl);
190  llvm::Value *valueValue = EmitScalarExpr(Value);
191  EmitStoreThroughLValue(RValue::get(valueValue), ValueLV, /*isInit=*/true);
192  if (TrackNeededObjects) {
193  NeededObjects.push_back(keyValue);
194  NeededObjects.push_back(valueValue);
195  }
196  }
197  }
198 
199  // Generate the argument list.
200  CallArgList Args;
201  ObjCMethodDecl::param_const_iterator PI = MethodWithObjects->param_begin();
202  const ParmVarDecl *argDecl = *PI++;
203  QualType ArgQT = argDecl->getType().getUnqualifiedType();
204  Args.add(RValue::get(Objects.getPointer()), ArgQT);
205  if (DLE) {
206  argDecl = *PI++;
207  ArgQT = argDecl->getType().getUnqualifiedType();
208  Args.add(RValue::get(Keys.getPointer()), ArgQT);
209  }
210  argDecl = *PI;
211  ArgQT = argDecl->getType().getUnqualifiedType();
212  llvm::Value *Count =
213  llvm::ConstantInt::get(CGM.getTypes().ConvertType(ArgQT), NumElements);
214  Args.add(RValue::get(Count), ArgQT);
215 
216  // Generate a reference to the class pointer, which will be the receiver.
217  Selector Sel = MethodWithObjects->getSelector();
218  QualType ResultType = E->getType();
219  const ObjCObjectPointerType *InterfacePointerType
220  = ResultType->getAsObjCInterfacePointerType();
221  ObjCInterfaceDecl *Class
222  = InterfacePointerType->getObjectType()->getInterface();
223  CGObjCRuntime &Runtime = CGM.getObjCRuntime();
224  llvm::Value *Receiver = Runtime.GetClass(*this, Class);
225 
226  // Generate the message send.
227  RValue result = Runtime.GenerateMessageSend(
228  *this, ReturnValueSlot(), MethodWithObjects->getReturnType(), Sel,
229  Receiver, Args, Class, MethodWithObjects);
230 
231  // The above message send needs these objects, but in ARC they are
232  // passed in a buffer that is essentially __unsafe_unretained.
233  // Therefore we must prevent the optimizer from releasing them until
234  // after the call.
235  if (TrackNeededObjects) {
236  EmitARCIntrinsicUse(NeededObjects);
237  }
238 
239  return Builder.CreateBitCast(result.getScalarVal(),
240  ConvertType(E->getType()));
241 }
242 
245 }
246 
248  const ObjCDictionaryLiteral *E) {
250 }
251 
252 /// Emit a selector.
254  // Untyped selector.
255  // Note that this implementation allows for non-constant strings to be passed
256  // as arguments to @selector(). Currently, the only thing preventing this
257  // behaviour is the type checking in the front end.
258  return CGM.getObjCRuntime().GetSelector(*this, E->getSelector());
259 }
260 
262  // FIXME: This should pass the Decl not the name.
263  return CGM.getObjCRuntime().GenerateProtocolRef(*this, E->getProtocol());
264 }
265 
266 /// Adjust the type of an Objective-C object that doesn't match up due
267 /// to type erasure at various points, e.g., related result types or the use
268 /// of parameterized classes.
270  RValue Result) {
271  if (!ExpT->isObjCRetainableType())
272  return Result;
273 
274  // If the converted types are the same, we're done.
275  llvm::Type *ExpLLVMTy = CGF.ConvertType(ExpT);
276  if (ExpLLVMTy == Result.getScalarVal()->getType())
277  return Result;
278 
279  // We have applied a substitution. Cast the rvalue appropriately.
280  return RValue::get(CGF.Builder.CreateBitCast(Result.getScalarVal(),
281  ExpLLVMTy));
282 }
283 
284 /// Decide whether to extend the lifetime of the receiver of a
285 /// returns-inner-pointer message.
286 static bool
288  switch (message->getReceiverKind()) {
289 
290  // For a normal instance message, we should extend unless the
291  // receiver is loaded from a variable with precise lifetime.
293  const Expr *receiver = message->getInstanceReceiver();
294 
295  // Look through OVEs.
296  if (auto opaque = dyn_cast<OpaqueValueExpr>(receiver)) {
297  if (opaque->getSourceExpr())
298  receiver = opaque->getSourceExpr()->IgnoreParens();
299  }
300 
301  const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(receiver);
302  if (!ice || ice->getCastKind() != CK_LValueToRValue) return true;
303  receiver = ice->getSubExpr()->IgnoreParens();
304 
305  // Look through OVEs.
306  if (auto opaque = dyn_cast<OpaqueValueExpr>(receiver)) {
307  if (opaque->getSourceExpr())
308  receiver = opaque->getSourceExpr()->IgnoreParens();
309  }
310 
311  // Only __strong variables.
312  if (receiver->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
313  return true;
314 
315  // All ivars and fields have precise lifetime.
316  if (isa<MemberExpr>(receiver) || isa<ObjCIvarRefExpr>(receiver))
317  return false;
318 
319  // Otherwise, check for variables.
320  const DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(ice->getSubExpr());
321  if (!declRef) return true;
322  const VarDecl *var = dyn_cast<VarDecl>(declRef->getDecl());
323  if (!var) return true;
324 
325  // All variables have precise lifetime except local variables with
326  // automatic storage duration that aren't specially marked.
327  return (var->hasLocalStorage() &&
328  !var->hasAttr<ObjCPreciseLifetimeAttr>());
329  }
330 
333  // It's never necessary for class objects.
334  return false;
335 
337  // We generally assume that 'self' lives throughout a method call.
338  return false;
339  }
340 
341  llvm_unreachable("invalid receiver kind");
342 }
343 
344 /// Given an expression of ObjC pointer type, check whether it was
345 /// immediately loaded from an ARC __weak l-value.
346 static const Expr *findWeakLValue(const Expr *E) {
347  assert(E->getType()->isObjCRetainableType());
348  E = E->IgnoreParens();
349  if (auto CE = dyn_cast<CastExpr>(E)) {
350  if (CE->getCastKind() == CK_LValueToRValue) {
351  if (CE->getSubExpr()->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
352  return CE->getSubExpr();
353  }
354  }
355 
356  return nullptr;
357 }
358 
359 /// The ObjC runtime may provide entrypoints that are likely to be faster
360 /// than an ordinary message send of the appropriate selector.
361 ///
362 /// The entrypoints are guaranteed to be equivalent to just sending the
363 /// corresponding message. If the entrypoint is implemented naively as just a
364 /// message send, using it is a trade-off: it sacrifices a few cycles of
365 /// overhead to save a small amount of code. However, it's possible for
366 /// runtimes to detect and special-case classes that use "standard"
367 /// behavior; if that's dynamically a large proportion of all objects, using
368 /// the entrypoint will also be faster than using a message send.
369 ///
370 /// If the runtime does support a required entrypoint, then this method will
371 /// generate a call and return the resulting value. Otherwise it will return
372 /// None and the caller can generate a msgSend instead.
375  llvm::Value *Receiver,
376  const CallArgList& Args, Selector Sel,
377  const ObjCMethodDecl *method,
378  bool isClassMessage) {
379  auto &CGM = CGF.CGM;
380  if (!CGM.getCodeGenOpts().ObjCConvertMessagesToRuntimeCalls)
381  return None;
382 
383  auto &Runtime = CGM.getLangOpts().ObjCRuntime;
384  switch (Sel.getMethodFamily()) {
385  case OMF_alloc:
386  if (isClassMessage &&
387  Runtime.shouldUseRuntimeFunctionsForAlloc() &&
388  ResultType->isObjCObjectPointerType()) {
389  // [Foo alloc] -> objc_alloc(Foo) or
390  // [self alloc] -> objc_alloc(self)
391  if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "alloc")
392  return CGF.EmitObjCAlloc(Receiver, CGF.ConvertType(ResultType));
393  // [Foo allocWithZone:nil] -> objc_allocWithZone(Foo) or
394  // [self allocWithZone:nil] -> objc_allocWithZone(self)
395  if (Sel.isKeywordSelector() && Sel.getNumArgs() == 1 &&
396  Args.size() == 1 && Args.front().getType()->isPointerType() &&
397  Sel.getNameForSlot(0) == "allocWithZone") {
398  const llvm::Value* arg = Args.front().getKnownRValue().getScalarVal();
399  if (isa<llvm::ConstantPointerNull>(arg))
400  return CGF.EmitObjCAllocWithZone(Receiver,
401  CGF.ConvertType(ResultType));
402  return None;
403  }
404  }
405  break;
406 
407  case OMF_autorelease:
408  if (ResultType->isObjCObjectPointerType() &&
409  CGM.getLangOpts().getGC() == LangOptions::NonGC &&
410  Runtime.shouldUseARCFunctionsForRetainRelease())
411  return CGF.EmitObjCAutorelease(Receiver, CGF.ConvertType(ResultType));
412  break;
413 
414  case OMF_retain:
415  if (ResultType->isObjCObjectPointerType() &&
416  CGM.getLangOpts().getGC() == LangOptions::NonGC &&
417  Runtime.shouldUseARCFunctionsForRetainRelease())
418  return CGF.EmitObjCRetainNonBlock(Receiver, CGF.ConvertType(ResultType));
419  break;
420 
421  case OMF_release:
422  if (ResultType->isVoidType() &&
423  CGM.getLangOpts().getGC() == LangOptions::NonGC &&
424  Runtime.shouldUseARCFunctionsForRetainRelease()) {
425  CGF.EmitObjCRelease(Receiver, ARCPreciseLifetime);
426  return nullptr;
427  }
428  break;
429 
430  default:
431  break;
432  }
433  return None;
434 }
435 
437  CodeGenFunction &CGF, ReturnValueSlot Return, QualType ResultType,
438  Selector Sel, llvm::Value *Receiver, const CallArgList &Args,
439  const ObjCInterfaceDecl *OID, const ObjCMethodDecl *Method,
440  bool isClassMessage) {
441  if (Optional<llvm::Value *> SpecializedResult =
442  tryGenerateSpecializedMessageSend(CGF, ResultType, Receiver, Args,
443  Sel, Method, isClassMessage)) {
444  return RValue::get(SpecializedResult.getValue());
445  }
446  return GenerateMessageSend(CGF, Return, ResultType, Sel, Receiver, Args, OID,
447  Method);
448 }
449 
451  const ObjCProtocolDecl *PD,
452  llvm::UniqueVector<const ObjCProtocolDecl *> &PDs) {
453  if (!PD->isNonRuntimeProtocol()) {
454  const auto *Can = PD->getCanonicalDecl();
455  PDs.insert(Can);
456  return;
457  }
458 
459  for (const auto *ParentPD : PD->protocols())
460  AppendFirstImpliedRuntimeProtocols(ParentPD, PDs);
461 }
462 
463 std::vector<const ObjCProtocolDecl *>
466  std::vector<const ObjCProtocolDecl *> RuntimePds;
468 
469  for (; begin != end; ++begin) {
470  const auto *It = *begin;
471  const auto *Can = It->getCanonicalDecl();
472  if (Can->isNonRuntimeProtocol())
473  NonRuntimePDs.insert(Can);
474  else
475  RuntimePds.push_back(Can);
476  }
477 
478  // If there are no non-runtime protocols then we can just stop now.
479  if (NonRuntimePDs.empty())
480  return RuntimePds;
481 
482  // Else we have to search through the non-runtime protocol's inheritancy
483  // hierarchy DAG stopping whenever a branch either finds a runtime protocol or
484  // a non-runtime protocol without any parents. These are the "first-implied"
485  // protocols from a non-runtime protocol.
486  llvm::UniqueVector<const ObjCProtocolDecl *> FirstImpliedProtos;
487  for (const auto *PD : NonRuntimePDs)
488  AppendFirstImpliedRuntimeProtocols(PD, FirstImpliedProtos);
489 
490  // Walk the Runtime list to get all protocols implied via the inclusion of
491  // this protocol, e.g. all protocols it inherits from including itself.
492  llvm::DenseSet<const ObjCProtocolDecl *> AllImpliedProtocols;
493  for (const auto *PD : RuntimePds) {
494  const auto *Can = PD->getCanonicalDecl();
495  AllImpliedProtocols.insert(Can);
496  Can->getImpliedProtocols(AllImpliedProtocols);
497  }
498 
499  // Similar to above, walk the list of first-implied protocols to find the set
500  // all the protocols implied excluding the listed protocols themselves since
501  // they are not yet a part of the `RuntimePds` list.
502  for (const auto *PD : FirstImpliedProtos) {
503  PD->getImpliedProtocols(AllImpliedProtocols);
504  }
505 
506  // From the first-implied list we have to finish building the final protocol
507  // list. If a protocol in the first-implied list was already implied via some
508  // inheritance path through some other protocols then it would be redundant to
509  // add it here and so we skip over it.
510  for (const auto *PD : FirstImpliedProtos) {
511  if (!AllImpliedProtocols.contains(PD)) {
512  RuntimePds.push_back(PD);
513  }
514  }
515 
516  return RuntimePds;
517 }
518 
519 /// Instead of '[[MyClass alloc] init]', try to generate
520 /// 'objc_alloc_init(MyClass)'. This provides a code size improvement on the
521 /// caller side, as well as the optimized objc_alloc.
524  auto &Runtime = CGF.getLangOpts().ObjCRuntime;
525  if (!Runtime.shouldUseRuntimeFunctionForCombinedAllocInit())
526  return None;
527 
528  // Match the exact pattern '[[MyClass alloc] init]'.
529  Selector Sel = OME->getSelector();
531  !OME->getType()->isObjCObjectPointerType() || !Sel.isUnarySelector() ||
532  Sel.getNameForSlot(0) != "init")
533  return None;
534 
535  // Okay, this is '[receiver init]', check if 'receiver' is '[cls alloc]'
536  // with 'cls' a Class.
537  auto *SubOME =
538  dyn_cast<ObjCMessageExpr>(OME->getInstanceReceiver()->IgnoreParenCasts());
539  if (!SubOME)
540  return None;
541  Selector SubSel = SubOME->getSelector();
542 
543  if (!SubOME->getType()->isObjCObjectPointerType() ||
544  !SubSel.isUnarySelector() || SubSel.getNameForSlot(0) != "alloc")
545  return None;
546 
547  llvm::Value *Receiver = nullptr;
548  switch (SubOME->getReceiverKind()) {
550  if (!SubOME->getInstanceReceiver()->getType()->isObjCClassType())
551  return None;
552  Receiver = CGF.EmitScalarExpr(SubOME->getInstanceReceiver());
553  break;
554 
555  case ObjCMessageExpr::Class: {
556  QualType ReceiverType = SubOME->getClassReceiver();
557  const ObjCObjectType *ObjTy = ReceiverType->castAs<ObjCObjectType>();
558  const ObjCInterfaceDecl *ID = ObjTy->getInterface();
559  assert(ID && "null interface should be impossible here");
560  Receiver = CGF.CGM.getObjCRuntime().GetClass(CGF, ID);
561  break;
562  }
565  return None;
566  }
567 
568  return CGF.EmitObjCAllocInit(Receiver, CGF.ConvertType(OME->getType()));
569 }
570 
572  ReturnValueSlot Return) {
573  // Only the lookup mechanism and first two arguments of the method
574  // implementation vary between runtimes. We can get the receiver and
575  // arguments in generic code.
576 
577  bool isDelegateInit = E->isDelegateInitCall();
578 
579  const ObjCMethodDecl *method = E->getMethodDecl();
580 
581  // If the method is -retain, and the receiver's being loaded from
582  // a __weak variable, peephole the entire operation to objc_loadWeakRetained.
583  if (method && E->getReceiverKind() == ObjCMessageExpr::Instance &&
584  method->getMethodFamily() == OMF_retain) {
585  if (auto lvalueExpr = findWeakLValue(E->getInstanceReceiver())) {
586  LValue lvalue = EmitLValue(lvalueExpr);
587  llvm::Value *result = EmitARCLoadWeakRetained(lvalue.getAddress(*this));
588  return AdjustObjCObjectType(*this, E->getType(), RValue::get(result));
589  }
590  }
591 
593  return AdjustObjCObjectType(*this, E->getType(), RValue::get(*Val));
594 
595  // We don't retain the receiver in delegate init calls, and this is
596  // safe because the receiver value is always loaded from 'self',
597  // which we zero out. We don't want to Block_copy block receivers,
598  // though.
599  bool retainSelf =
600  (!isDelegateInit &&
601  CGM.getLangOpts().ObjCAutoRefCount &&
602  method &&
603  method->hasAttr<NSConsumesSelfAttr>());
604 
605  CGObjCRuntime &Runtime = CGM.getObjCRuntime();
606  bool isSuperMessage = false;
607  bool isClassMessage = false;
608  ObjCInterfaceDecl *OID = nullptr;
609  // Find the receiver
610  QualType ReceiverType;
611  llvm::Value *Receiver = nullptr;
612  switch (E->getReceiverKind()) {
614  ReceiverType = E->getInstanceReceiver()->getType();
615  isClassMessage = ReceiverType->isObjCClassType();
616  if (retainSelf) {
618  E->getInstanceReceiver());
619  Receiver = ter.getPointer();
620  if (ter.getInt()) retainSelf = false;
621  } else
622  Receiver = EmitScalarExpr(E->getInstanceReceiver());
623  break;
624 
625  case ObjCMessageExpr::Class: {
626  ReceiverType = E->getClassReceiver();
627  OID = ReceiverType->castAs<ObjCObjectType>()->getInterface();
628  assert(OID && "Invalid Objective-C class message send");
629  Receiver = Runtime.GetClass(*this, OID);
630  isClassMessage = true;
631  break;
632  }
633 
635  ReceiverType = E->getSuperType();
636  Receiver = LoadObjCSelf();
637  isSuperMessage = true;
638  break;
639 
641  ReceiverType = E->getSuperType();
642  Receiver = LoadObjCSelf();
643  isSuperMessage = true;
644  isClassMessage = true;
645  break;
646  }
647 
648  if (retainSelf)
649  Receiver = EmitARCRetainNonBlock(Receiver);
650 
651  // In ARC, we sometimes want to "extend the lifetime"
652  // (i.e. retain+autorelease) of receivers of returns-inner-pointer
653  // messages.
654  if (getLangOpts().ObjCAutoRefCount && method &&
655  method->hasAttr<ObjCReturnsInnerPointerAttr>() &&
657  Receiver = EmitARCRetainAutorelease(ReceiverType, Receiver);
658 
659  QualType ResultType = method ? method->getReturnType() : E->getType();
660 
661  CallArgList Args;
662  EmitCallArgs(Args, method, E->arguments(), /*AC*/AbstractCallee(method));
663 
664  // For delegate init calls in ARC, do an unsafe store of null into
665  // self. This represents the call taking direct ownership of that
666  // value. We have to do this after emitting the other call
667  // arguments because they might also reference self, but we don't
668  // have to worry about any of them modifying self because that would
669  // be an undefined read and write of an object in unordered
670  // expressions.
671  if (isDelegateInit) {
672  assert(getLangOpts().ObjCAutoRefCount &&
673  "delegate init calls should only be marked in ARC");
674 
675  // Do an unsafe store of null into self.
676  Address selfAddr =
677  GetAddrOfLocalVar(cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl());
678  Builder.CreateStore(getNullForVariable(selfAddr), selfAddr);
679  }
680 
681  RValue result;
682  if (isSuperMessage) {
683  // super is only valid in an Objective-C method
684  const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
685  bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext());
686  result = Runtime.GenerateMessageSendSuper(*this, Return, ResultType,
687  E->getSelector(),
688  OMD->getClassInterface(),
689  isCategoryImpl,
690  Receiver,
691  isClassMessage,
692  Args,
693  method);
694  } else {
695  // Call runtime methods directly if we can.
697  *this, Return, ResultType, E->getSelector(), Receiver, Args, OID,
698  method, isClassMessage);
699  }
700 
701  // For delegate init calls in ARC, implicitly store the result of
702  // the call back into self. This takes ownership of the value.
703  if (isDelegateInit) {
704  Address selfAddr =
705  GetAddrOfLocalVar(cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl());
706  llvm::Value *newSelf = result.getScalarVal();
707 
708  // The delegate return type isn't necessarily a matching type; in
709  // fact, it's quite likely to be 'id'.
710  llvm::Type *selfTy = selfAddr.getElementType();
711  newSelf = Builder.CreateBitCast(newSelf, selfTy);
712 
713  Builder.CreateStore(newSelf, selfAddr);
714  }
715 
716  return AdjustObjCObjectType(*this, E->getType(), result);
717 }
718 
719 namespace {
720 struct FinishARCDealloc final : EHScopeStack::Cleanup {
721  void Emit(CodeGenFunction &CGF, Flags flags) override {
722  const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CGF.CurCodeDecl);
723 
724  const ObjCImplDecl *impl = cast<ObjCImplDecl>(method->getDeclContext());
725  const ObjCInterfaceDecl *iface = impl->getClassInterface();
726  if (!iface->getSuperClass()) return;
727 
728  bool isCategory = isa<ObjCCategoryImplDecl>(impl);
729 
730  // Call [super dealloc] if we have a superclass.
731  llvm::Value *self = CGF.LoadObjCSelf();
732 
733  CallArgList args;
735  CGF.getContext().VoidTy,
736  method->getSelector(),
737  iface,
738  isCategory,
739  self,
740  /*is class msg*/ false,
741  args,
742  method);
743  }
744 };
745 }
746 
747 /// StartObjCMethod - Begin emission of an ObjCMethod. This generates
748 /// the LLVM function and sets the other context used by
749 /// CodeGenFunction.
751  const ObjCContainerDecl *CD) {
752  SourceLocation StartLoc = OMD->getBeginLoc();
753  FunctionArgList args;
754  // Check if we should generate debug info for this method.
755  if (OMD->hasAttr<NoDebugAttr>())
756  DebugInfo = nullptr; // disable debug info indefinitely for this function
757 
758  llvm::Function *Fn = CGM.getObjCRuntime().GenerateMethod(OMD, CD);
759 
761  if (OMD->isDirectMethod()) {
762  Fn->setVisibility(llvm::Function::HiddenVisibility);
763  CGM.SetLLVMFunctionAttributes(OMD, FI, Fn, /*IsThunk=*/false);
765  } else {
766  CGM.SetInternalFunctionAttributes(OMD, Fn, FI);
767  }
768 
769  args.push_back(OMD->getSelfDecl());
770  args.push_back(OMD->getCmdDecl());
771 
772  args.append(OMD->param_begin(), OMD->param_end());
773 
774  CurGD = OMD;
775  CurEHLocation = OMD->getEndLoc();
776 
777  StartFunction(OMD, OMD->getReturnType(), Fn, FI, args,
778  OMD->getLocation(), StartLoc);
779 
780  if (OMD->isDirectMethod()) {
781  // This function is a direct call, it has to implement a nil check
782  // on entry.
783  //
784  // TODO: possibly have several entry points to elide the check
785  CGM.getObjCRuntime().GenerateDirectMethodPrologue(*this, Fn, OMD, CD);
786  }
787 
788  // In ARC, certain methods get an extra cleanup.
789  if (CGM.getLangOpts().ObjCAutoRefCount &&
790  OMD->isInstanceMethod() &&
791  OMD->getSelector().isUnarySelector()) {
792  const IdentifierInfo *ident =
794  if (ident->isStr("dealloc"))
795  EHStack.pushCleanup<FinishARCDealloc>(getARCCleanupKind());
796  }
797 }
798 
800  LValue lvalue, QualType type);
801 
802 /// Generate an Objective-C method. An Objective-C method is a C function with
803 /// its pointer, name, and types registered in the class structure.
805  StartObjCMethod(OMD, OMD->getClassInterface());
807  assert(isa<CompoundStmt>(OMD->getBody()));
809  EmitCompoundStmtWithoutScope(*cast<CompoundStmt>(OMD->getBody()));
811 }
812 
813 /// emitStructGetterCall - Call the runtime function to load a property
814 /// into the return value slot.
816  bool isAtomic, bool hasStrong) {
817  ASTContext &Context = CGF.getContext();
818 
819  Address src =
820  CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(), ivar, 0)
821  .getAddress(CGF);
822 
823  // objc_copyStruct (ReturnValue, &structIvar,
824  // sizeof (Type of Ivar), isAtomic, false);
825  CallArgList args;
826 
827  Address dest = CGF.Builder.CreateBitCast(CGF.ReturnValue, CGF.VoidPtrTy);
828  args.add(RValue::get(dest.getPointer()), Context.VoidPtrTy);
829 
830  src = CGF.Builder.CreateBitCast(src, CGF.VoidPtrTy);
831  args.add(RValue::get(src.getPointer()), Context.VoidPtrTy);
832 
833  CharUnits size = CGF.getContext().getTypeSizeInChars(ivar->getType());
834  args.add(RValue::get(CGF.CGM.getSize(size)), Context.getSizeType());
835  args.add(RValue::get(CGF.Builder.getInt1(isAtomic)), Context.BoolTy);
836  args.add(RValue::get(CGF.Builder.getInt1(hasStrong)), Context.BoolTy);
837 
838  llvm::FunctionCallee fn = CGF.CGM.getObjCRuntime().GetGetStructFunction();
839  CGCallee callee = CGCallee::forDirect(fn);
840  CGF.EmitCall(CGF.getTypes().arrangeBuiltinFunctionCall(Context.VoidTy, args),
841  callee, ReturnValueSlot(), args);
842 }
843 
844 /// Determine whether the given architecture supports unaligned atomic
845 /// accesses. They don't have to be fast, just faster than a function
846 /// call and a mutex.
847 static bool hasUnalignedAtomics(llvm::Triple::ArchType arch) {
848  // FIXME: Allow unaligned atomic load/store on x86. (It is not
849  // currently supported by the backend.)
850  return 0;
851 }
852 
853 /// Return the maximum size that permits atomic accesses for the given
854 /// architecture.
856  llvm::Triple::ArchType arch) {
857  // ARM has 8-byte atomic accesses, but it's not clear whether we
858  // want to rely on them here.
859 
860  // In the default case, just assume that any size up to a pointer is
861  // fine given adequate alignment.
863 }
864 
865 namespace {
866  class PropertyImplStrategy {
867  public:
868  enum StrategyKind {
869  /// The 'native' strategy is to use the architecture's provided
870  /// reads and writes.
871  Native,
872 
873  /// Use objc_setProperty and objc_getProperty.
874  GetSetProperty,
875 
876  /// Use objc_setProperty for the setter, but use expression
877  /// evaluation for the getter.
878  SetPropertyAndExpressionGet,
879 
880  /// Use objc_copyStruct.
881  CopyStruct,
882 
883  /// The 'expression' strategy is to emit normal assignment or
884  /// lvalue-to-rvalue expressions.
885  Expression
886  };
887 
888  StrategyKind getKind() const { return StrategyKind(Kind); }
889 
890  bool hasStrongMember() const { return HasStrong; }
891  bool isAtomic() const { return IsAtomic; }
892  bool isCopy() const { return IsCopy; }
893 
894  CharUnits getIvarSize() const { return IvarSize; }
895  CharUnits getIvarAlignment() const { return IvarAlignment; }
896 
897  PropertyImplStrategy(CodeGenModule &CGM,
898  const ObjCPropertyImplDecl *propImpl);
899 
900  private:
901  unsigned Kind : 8;
902  unsigned IsAtomic : 1;
903  unsigned IsCopy : 1;
904  unsigned HasStrong : 1;
905 
906  CharUnits IvarSize;
907  CharUnits IvarAlignment;
908  };
909 }
910 
911 /// Pick an implementation strategy for the given property synthesis.
912 PropertyImplStrategy::PropertyImplStrategy(CodeGenModule &CGM,
913  const ObjCPropertyImplDecl *propImpl) {
914  const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
915  ObjCPropertyDecl::SetterKind setterKind = prop->getSetterKind();
916 
917  IsCopy = (setterKind == ObjCPropertyDecl::Copy);
918  IsAtomic = prop->isAtomic();
919  HasStrong = false; // doesn't matter here.
920 
921  // Evaluate the ivar's size and alignment.
922  ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
923  QualType ivarType = ivar->getType();
924  auto TInfo = CGM.getContext().getTypeInfoInChars(ivarType);
925  IvarSize = TInfo.Width;
926  IvarAlignment = TInfo.Align;
927 
928  // If we have a copy property, we always have to use setProperty.
929  // If the property is atomic we need to use getProperty, but in
930  // the nonatomic case we can just use expression.
931  if (IsCopy) {
932  Kind = IsAtomic ? GetSetProperty : SetPropertyAndExpressionGet;
933  return;
934  }
935 
936  // Handle retain.
937  if (setterKind == ObjCPropertyDecl::Retain) {
938  // In GC-only, there's nothing special that needs to be done.
939  if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
940  // fallthrough
941 
942  // In ARC, if the property is non-atomic, use expression emission,
943  // which translates to objc_storeStrong. This isn't required, but
944  // it's slightly nicer.
945  } else if (CGM.getLangOpts().ObjCAutoRefCount && !IsAtomic) {
946  // Using standard expression emission for the setter is only
947  // acceptable if the ivar is __strong, which won't be true if
948  // the property is annotated with __attribute__((NSObject)).
949  // TODO: falling all the way back to objc_setProperty here is
950  // just laziness, though; we could still use objc_storeStrong
951  // if we hacked it right.
952  if (ivarType.getObjCLifetime() == Qualifiers::OCL_Strong)
953  Kind = Expression;
954  else
955  Kind = SetPropertyAndExpressionGet;
956  return;
957 
958  // Otherwise, we need to at least use setProperty. However, if
959  // the property isn't atomic, we can use normal expression
960  // emission for the getter.
961  } else if (!IsAtomic) {
962  Kind = SetPropertyAndExpressionGet;
963  return;
964 
965  // Otherwise, we have to use both setProperty and getProperty.
966  } else {
967  Kind = GetSetProperty;
968  return;
969  }
970  }
971 
972  // If we're not atomic, just use expression accesses.
973  if (!IsAtomic) {
974  Kind = Expression;
975  return;
976  }
977 
978  // Properties on bitfield ivars need to be emitted using expression
979  // accesses even if they're nominally atomic.
980  if (ivar->isBitField()) {
981  Kind = Expression;
982  return;
983  }
984 
985  // GC-qualified or ARC-qualified ivars need to be emitted as
986  // expressions. This actually works out to being atomic anyway,
987  // except for ARC __strong, but that should trigger the above code.
988  if (ivarType.hasNonTrivialObjCLifetime() ||
989  (CGM.getLangOpts().getGC() &&
990  CGM.getContext().getObjCGCAttrKind(ivarType))) {
991  Kind = Expression;
992  return;
993  }
994 
995  // Compute whether the ivar has strong members.
996  if (CGM.getLangOpts().getGC())
997  if (const RecordType *recordType = ivarType->getAs<RecordType>())
998  HasStrong = recordType->getDecl()->hasObjectMember();
999 
1000  // We can never access structs with object members with a native
1001  // access, because we need to use write barriers. This is what
1002  // objc_copyStruct is for.
1003  if (HasStrong) {
1004  Kind = CopyStruct;
1005  return;
1006  }
1007 
1008  // Otherwise, this is target-dependent and based on the size and
1009  // alignment of the ivar.
1010 
1011  // If the size of the ivar is not a power of two, give up. We don't
1012  // want to get into the business of doing compare-and-swaps.
1013  if (!IvarSize.isPowerOfTwo()) {
1014  Kind = CopyStruct;
1015  return;
1016  }
1017 
1018  llvm::Triple::ArchType arch =
1019  CGM.getTarget().getTriple().getArch();
1020 
1021  // Most architectures require memory to fit within a single cache
1022  // line, so the alignment has to be at least the size of the access.
1023  // Otherwise we have to grab a lock.
1024  if (IvarAlignment < IvarSize && !hasUnalignedAtomics(arch)) {
1025  Kind = CopyStruct;
1026  return;
1027  }
1028 
1029  // If the ivar's size exceeds the architecture's maximum atomic
1030  // access size, we have to use CopyStruct.
1031  if (IvarSize > getMaxAtomicAccessSize(CGM, arch)) {
1032  Kind = CopyStruct;
1033  return;
1034  }
1035 
1036  // Otherwise, we can use native loads and stores.
1037  Kind = Native;
1038 }
1039 
1040 /// Generate an Objective-C property getter function.
1041 ///
1042 /// The given Decl must be an ObjCImplementationDecl. \@synthesize
1043 /// is illegal within a category.
1045  const ObjCPropertyImplDecl *PID) {
1046  llvm::Constant *AtomicHelperFn =
1048  ObjCMethodDecl *OMD = PID->getGetterMethodDecl();
1049  assert(OMD && "Invalid call to generate getter (empty method)");
1050  StartObjCMethod(OMD, IMP->getClassInterface());
1051 
1052  generateObjCGetterBody(IMP, PID, OMD, AtomicHelperFn);
1053 
1054  FinishFunction(OMD->getEndLoc());
1055 }
1056 
1057 static bool hasTrivialGetExpr(const ObjCPropertyImplDecl *propImpl) {
1058  const Expr *getter = propImpl->getGetterCXXConstructor();
1059  if (!getter) return true;
1060 
1061  // Sema only makes only of these when the ivar has a C++ class type,
1062  // so the form is pretty constrained.
1063 
1064  // If the property has a reference type, we might just be binding a
1065  // reference, in which case the result will be a gl-value. We should
1066  // treat this as a non-trivial operation.
1067  if (getter->isGLValue())
1068  return false;
1069 
1070  // If we selected a trivial copy-constructor, we're okay.
1071  if (const CXXConstructExpr *construct = dyn_cast<CXXConstructExpr>(getter))
1072  return (construct->getConstructor()->isTrivial());
1073 
1074  // The constructor might require cleanups (in which case it's never
1075  // trivial).
1076  assert(isa<ExprWithCleanups>(getter));
1077  return false;
1078 }
1079 
1080 /// emitCPPObjectAtomicGetterCall - Call the runtime function to
1081 /// copy the ivar into the resturn slot.
1083  llvm::Value *returnAddr,
1084  ObjCIvarDecl *ivar,
1085  llvm::Constant *AtomicHelperFn) {
1086  // objc_copyCppObjectAtomic (&returnSlot, &CppObjectIvar,
1087  // AtomicHelperFn);
1088  CallArgList args;
1089 
1090  // The 1st argument is the return Slot.
1091  args.add(RValue::get(returnAddr), CGF.getContext().VoidPtrTy);
1092 
1093  // The 2nd argument is the address of the ivar.
1094  llvm::Value *ivarAddr =
1095  CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(), ivar, 0)
1096  .getPointer(CGF);
1097  ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
1098  args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
1099 
1100  // Third argument is the helper function.
1101  args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
1102 
1103  llvm::FunctionCallee copyCppAtomicObjectFn =
1105  CGCallee callee = CGCallee::forDirect(copyCppAtomicObjectFn);
1106  CGF.EmitCall(
1108  callee, ReturnValueSlot(), args);
1109 }
1110 
1111 void
1113  const ObjCPropertyImplDecl *propImpl,
1114  const ObjCMethodDecl *GetterMethodDecl,
1115  llvm::Constant *AtomicHelperFn) {
1116  // If there's a non-trivial 'get' expression, we just have to emit that.
1117  if (!hasTrivialGetExpr(propImpl)) {
1118  if (!AtomicHelperFn) {
1119  auto *ret = ReturnStmt::Create(getContext(), SourceLocation(),
1120  propImpl->getGetterCXXConstructor(),
1121  /* NRVOCandidate=*/nullptr);
1122  EmitReturnStmt(*ret);
1123  }
1124  else {
1125  ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
1127  ivar, AtomicHelperFn);
1128  }
1129  return;
1130  }
1131 
1132  const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
1133  QualType propType = prop->getType();
1134  ObjCMethodDecl *getterMethod = propImpl->getGetterMethodDecl();
1135 
1136  ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
1137 
1138  // Pick an implementation strategy.
1139  PropertyImplStrategy strategy(CGM, propImpl);
1140  switch (strategy.getKind()) {
1141  case PropertyImplStrategy::Native: {
1142  // We don't need to do anything for a zero-size struct.
1143  if (strategy.getIvarSize().isZero())
1144  return;
1145 
1147 
1148  // Currently, all atomic accesses have to be through integer
1149  // types, so there's no point in trying to pick a prettier type.
1150  uint64_t ivarSize = getContext().toBits(strategy.getIvarSize());
1151  llvm::Type *bitcastType = llvm::Type::getIntNTy(getLLVMContext(), ivarSize);
1152  bitcastType = bitcastType->getPointerTo(); // addrspace 0 okay
1153 
1154  // Perform an atomic load. This does not impose ordering constraints.
1155  Address ivarAddr = LV.getAddress(*this);
1156  ivarAddr = Builder.CreateBitCast(ivarAddr, bitcastType);
1157  llvm::LoadInst *load = Builder.CreateLoad(ivarAddr, "load");
1158  load->setAtomic(llvm::AtomicOrdering::Unordered);
1159 
1160  // Store that value into the return address. Doing this with a
1161  // bitcast is likely to produce some pretty ugly IR, but it's not
1162  // the *most* terrible thing in the world.
1163  llvm::Type *retTy = ConvertType(getterMethod->getReturnType());
1164  uint64_t retTySize = CGM.getDataLayout().getTypeSizeInBits(retTy);
1165  llvm::Value *ivarVal = load;
1166  if (ivarSize > retTySize) {
1167  llvm::Type *newTy = llvm::Type::getIntNTy(getLLVMContext(), retTySize);
1168  ivarVal = Builder.CreateTrunc(load, newTy);
1169  bitcastType = newTy->getPointerTo();
1170  }
1171  Builder.CreateStore(ivarVal,
1172  Builder.CreateBitCast(ReturnValue, bitcastType));
1173 
1174  // Make sure we don't do an autorelease.
1175  AutoreleaseResult = false;
1176  return;
1177  }
1178 
1179  case PropertyImplStrategy::GetSetProperty: {
1180  llvm::FunctionCallee getPropertyFn =
1182  if (!getPropertyFn) {
1183  CGM.ErrorUnsupported(propImpl, "Obj-C getter requiring atomic copy");
1184  return;
1185  }
1186  CGCallee callee = CGCallee::forDirect(getPropertyFn);
1187 
1188  // Return (ivar-type) objc_getProperty((id) self, _cmd, offset, true).
1189  // FIXME: Can't this be simpler? This might even be worse than the
1190  // corresponding gcc code.
1191  llvm::Value *cmd =
1192  Builder.CreateLoad(GetAddrOfLocalVar(getterMethod->getCmdDecl()), "cmd");
1194  llvm::Value *ivarOffset =
1195  EmitIvarOffset(classImpl->getClassInterface(), ivar);
1196 
1197  CallArgList args;
1198  args.add(RValue::get(self), getContext().getObjCIdType());
1199  args.add(RValue::get(cmd), getContext().getObjCSelType());
1200  args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
1201  args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
1202  getContext().BoolTy);
1203 
1204  // FIXME: We shouldn't need to get the function info here, the
1205  // runtime already should have computed it to build the function.
1206  llvm::CallBase *CallInstruction;
1207  RValue RV = EmitCall(getTypes().arrangeBuiltinFunctionCall(
1208  getContext().getObjCIdType(), args),
1209  callee, ReturnValueSlot(), args, &CallInstruction);
1210  if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(CallInstruction))
1211  call->setTailCall();
1212 
1213  // We need to fix the type here. Ivars with copy & retain are
1214  // always objects so we don't need to worry about complex or
1215  // aggregates.
1217  RV.getScalarVal(),
1218  getTypes().ConvertType(getterMethod->getReturnType())));
1219 
1220  EmitReturnOfRValue(RV, propType);
1221 
1222  // objc_getProperty does an autorelease, so we should suppress ours.
1223  AutoreleaseResult = false;
1224 
1225  return;
1226  }
1227 
1228  case PropertyImplStrategy::CopyStruct:
1229  emitStructGetterCall(*this, ivar, strategy.isAtomic(),
1230  strategy.hasStrongMember());
1231  return;
1232 
1233  case PropertyImplStrategy::Expression:
1234  case PropertyImplStrategy::SetPropertyAndExpressionGet: {
1236 
1237  QualType ivarType = ivar->getType();
1238  switch (getEvaluationKind(ivarType)) {
1239  case TEK_Complex: {
1242  /*init*/ true);
1243  return;
1244  }
1245  case TEK_Aggregate: {
1246  // The return value slot is guaranteed to not be aliased, but
1247  // that's not necessarily the same as "on the stack", so
1248  // we still potentially need objc_memmove_collectable.
1249  EmitAggregateCopy(/* Dest= */ MakeAddrLValue(ReturnValue, ivarType),
1250  /* Src= */ LV, ivarType, getOverlapForReturnValue());
1251  return;
1252  }
1253  case TEK_Scalar: {
1254  llvm::Value *value;
1255  if (propType->isReferenceType()) {
1256  value = LV.getAddress(*this).getPointer();
1257  } else {
1258  // We want to load and autoreleaseReturnValue ARC __weak ivars.
1260  if (getLangOpts().ObjCAutoRefCount) {
1261  value = emitARCRetainLoadOfScalar(*this, LV, ivarType);
1262  } else {
1263  value = EmitARCLoadWeak(LV.getAddress(*this));
1264  }
1265 
1266  // Otherwise we want to do a simple load, suppressing the
1267  // final autorelease.
1268  } else {
1269  value = EmitLoadOfLValue(LV, SourceLocation()).getScalarVal();
1270  AutoreleaseResult = false;
1271  }
1272 
1273  value = Builder.CreateBitCast(
1274  value, ConvertType(GetterMethodDecl->getReturnType()));
1275  }
1276 
1277  EmitReturnOfRValue(RValue::get(value), propType);
1278  return;
1279  }
1280  }
1281  llvm_unreachable("bad evaluation kind");
1282  }
1283 
1284  }
1285  llvm_unreachable("bad @property implementation strategy!");
1286 }
1287 
1288 /// emitStructSetterCall - Call the runtime function to store the value
1289 /// from the first formal parameter into the given ivar.
1291  ObjCIvarDecl *ivar) {
1292  // objc_copyStruct (&structIvar, &Arg,
1293  // sizeof (struct something), true, false);
1294  CallArgList args;
1295 
1296  // The first argument is the address of the ivar.
1297  llvm::Value *ivarAddr =
1298  CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(), ivar, 0)
1299  .getPointer(CGF);
1300  ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
1301  args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
1302 
1303  // The second argument is the address of the parameter variable.
1304  ParmVarDecl *argVar = *OMD->param_begin();
1305  DeclRefExpr argRef(CGF.getContext(), argVar, false,
1306  argVar->getType().getNonReferenceType(), VK_LValue,
1307  SourceLocation());
1308  llvm::Value *argAddr = CGF.EmitLValue(&argRef).getPointer(CGF);
1309  argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
1310  args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
1311 
1312  // The third argument is the sizeof the type.
1313  llvm::Value *size =
1314  CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(ivar->getType()));
1315  args.add(RValue::get(size), CGF.getContext().getSizeType());
1316 
1317  // The fourth argument is the 'isAtomic' flag.
1318  args.add(RValue::get(CGF.Builder.getTrue()), CGF.getContext().BoolTy);
1319 
1320  // The fifth argument is the 'hasStrong' flag.
1321  // FIXME: should this really always be false?
1322  args.add(RValue::get(CGF.Builder.getFalse()), CGF.getContext().BoolTy);
1323 
1324  llvm::FunctionCallee fn = CGF.CGM.getObjCRuntime().GetSetStructFunction();
1325  CGCallee callee = CGCallee::forDirect(fn);
1326  CGF.EmitCall(
1328  callee, ReturnValueSlot(), args);
1329 }
1330 
1331 /// emitCPPObjectAtomicSetterCall - Call the runtime function to store
1332 /// the value from the first formal parameter into the given ivar, using
1333 /// the Cpp API for atomic Cpp objects with non-trivial copy assignment.
1335  ObjCMethodDecl *OMD,
1336  ObjCIvarDecl *ivar,
1337  llvm::Constant *AtomicHelperFn) {
1338  // objc_copyCppObjectAtomic (&CppObjectIvar, &Arg,
1339  // AtomicHelperFn);
1340  CallArgList args;
1341 
1342  // The first argument is the address of the ivar.
1343  llvm::Value *ivarAddr =
1344  CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(), ivar, 0)
1345  .getPointer(CGF);
1346  ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
1347  args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
1348 
1349  // The second argument is the address of the parameter variable.
1350  ParmVarDecl *argVar = *OMD->param_begin();
1351  DeclRefExpr argRef(CGF.getContext(), argVar, false,
1352  argVar->getType().getNonReferenceType(), VK_LValue,
1353  SourceLocation());
1354  llvm::Value *argAddr = CGF.EmitLValue(&argRef).getPointer(CGF);
1355  argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
1356  args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
1357 
1358  // Third argument is the helper function.
1359  args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
1360 
1361  llvm::FunctionCallee fn =
1363  CGCallee callee = CGCallee::forDirect(fn);
1364  CGF.EmitCall(
1366  callee, ReturnValueSlot(), args);
1367 }
1368 
1369 
1370 static bool hasTrivialSetExpr(const ObjCPropertyImplDecl *PID) {
1371  Expr *setter = PID->getSetterCXXAssignment();
1372  if (!setter) return true;
1373 
1374  // Sema only makes only of these when the ivar has a C++ class type,
1375  // so the form is pretty constrained.
1376 
1377  // An operator call is trivial if the function it calls is trivial.
1378  // This also implies that there's nothing non-trivial going on with
1379  // the arguments, because operator= can only be trivial if it's a
1380  // synthesized assignment operator and therefore both parameters are
1381  // references.
1382  if (CallExpr *call = dyn_cast<CallExpr>(setter)) {
1383  if (const FunctionDecl *callee
1384  = dyn_cast_or_null<FunctionDecl>(call->getCalleeDecl()))
1385  if (callee->isTrivial())
1386  return true;
1387  return false;
1388  }
1389 
1390  assert(isa<ExprWithCleanups>(setter));
1391  return false;
1392 }
1393 
1395  if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
1396  return false;
1398 }
1399 
1400 void
1402  const ObjCPropertyImplDecl *propImpl,
1403  llvm::Constant *AtomicHelperFn) {
1404  ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
1405  ObjCMethodDecl *setterMethod = propImpl->getSetterMethodDecl();
1406 
1407  // Just use the setter expression if Sema gave us one and it's
1408  // non-trivial.
1409  if (!hasTrivialSetExpr(propImpl)) {
1410  if (!AtomicHelperFn)
1411  // If non-atomic, assignment is called directly.
1412  EmitStmt(propImpl->getSetterCXXAssignment());
1413  else
1414  // If atomic, assignment is called via a locking api.
1415  emitCPPObjectAtomicSetterCall(*this, setterMethod, ivar,
1416  AtomicHelperFn);
1417  return;
1418  }
1419 
1420  PropertyImplStrategy strategy(CGM, propImpl);
1421  switch (strategy.getKind()) {
1422  case PropertyImplStrategy::Native: {
1423  // We don't need to do anything for a zero-size struct.
1424  if (strategy.getIvarSize().isZero())
1425  return;
1426 
1427  Address argAddr = GetAddrOfLocalVar(*setterMethod->param_begin());
1428 
1429  LValue ivarLValue =
1430  EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, /*quals*/ 0);
1431  Address ivarAddr = ivarLValue.getAddress(*this);
1432 
1433  // Currently, all atomic accesses have to be through integer
1434  // types, so there's no point in trying to pick a prettier type.
1435  llvm::Type *bitcastType =
1436  llvm::Type::getIntNTy(getLLVMContext(),
1437  getContext().toBits(strategy.getIvarSize()));
1438 
1439  // Cast both arguments to the chosen operation type.
1440  argAddr = Builder.CreateElementBitCast(argAddr, bitcastType);
1441  ivarAddr = Builder.CreateElementBitCast(ivarAddr, bitcastType);
1442 
1443  // This bitcast load is likely to cause some nasty IR.
1444  llvm::Value *load = Builder.CreateLoad(argAddr);
1445 
1446  // Perform an atomic store. There are no memory ordering requirements.
1447  llvm::StoreInst *store = Builder.CreateStore(load, ivarAddr);
1448  store->setAtomic(llvm::AtomicOrdering::Unordered);
1449  return;
1450  }
1451 
1452  case PropertyImplStrategy::GetSetProperty:
1453  case PropertyImplStrategy::SetPropertyAndExpressionGet: {
1454 
1455  llvm::FunctionCallee setOptimizedPropertyFn = nullptr;
1456  llvm::FunctionCallee setPropertyFn = nullptr;
1457  if (UseOptimizedSetter(CGM)) {
1458  // 10.8 and iOS 6.0 code and GC is off
1459  setOptimizedPropertyFn =
1461  strategy.isAtomic(), strategy.isCopy());
1462  if (!setOptimizedPropertyFn) {
1463  CGM.ErrorUnsupported(propImpl, "Obj-C optimized setter - NYI");
1464  return;
1465  }
1466  }
1467  else {
1468  setPropertyFn = CGM.getObjCRuntime().GetPropertySetFunction();
1469  if (!setPropertyFn) {
1470  CGM.ErrorUnsupported(propImpl, "Obj-C setter requiring atomic copy");
1471  return;
1472  }
1473  }
1474 
1475  // Emit objc_setProperty((id) self, _cmd, offset, arg,
1476  // <is-atomic>, <is-copy>).
1477  llvm::Value *cmd =
1478  Builder.CreateLoad(GetAddrOfLocalVar(setterMethod->getCmdDecl()));
1479  llvm::Value *self =
1481  llvm::Value *ivarOffset =
1482  EmitIvarOffset(classImpl->getClassInterface(), ivar);
1483  Address argAddr = GetAddrOfLocalVar(*setterMethod->param_begin());
1484  llvm::Value *arg = Builder.CreateLoad(argAddr, "arg");
1486 
1487  CallArgList args;
1488  args.add(RValue::get(self), getContext().getObjCIdType());
1489  args.add(RValue::get(cmd), getContext().getObjCSelType());
1490  if (setOptimizedPropertyFn) {
1491  args.add(RValue::get(arg), getContext().getObjCIdType());
1492  args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
1493  CGCallee callee = CGCallee::forDirect(setOptimizedPropertyFn);
1494  EmitCall(getTypes().arrangeBuiltinFunctionCall(getContext().VoidTy, args),
1495  callee, ReturnValueSlot(), args);
1496  } else {
1497  args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
1498  args.add(RValue::get(arg), getContext().getObjCIdType());
1499  args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
1500  getContext().BoolTy);
1501  args.add(RValue::get(Builder.getInt1(strategy.isCopy())),
1502  getContext().BoolTy);
1503  // FIXME: We shouldn't need to get the function info here, the runtime
1504  // already should have computed it to build the function.
1505  CGCallee callee = CGCallee::forDirect(setPropertyFn);
1506  EmitCall(getTypes().arrangeBuiltinFunctionCall(getContext().VoidTy, args),
1507  callee, ReturnValueSlot(), args);
1508  }
1509 
1510  return;
1511  }
1512 
1513  case PropertyImplStrategy::CopyStruct:
1514  emitStructSetterCall(*this, setterMethod, ivar);
1515  return;
1516 
1517  case PropertyImplStrategy::Expression:
1518  break;
1519  }
1520 
1521  // Otherwise, fake up some ASTs and emit a normal assignment.
1522  ValueDecl *selfDecl = setterMethod->getSelfDecl();
1523  DeclRefExpr self(getContext(), selfDecl, false, selfDecl->getType(),
1525  ImplicitCastExpr selfLoad(ImplicitCastExpr::OnStack, selfDecl->getType(),
1526  CK_LValueToRValue, &self, VK_PRValue,
1527  FPOptionsOverride());
1528  ObjCIvarRefExpr ivarRef(ivar, ivar->getType().getNonReferenceType(),
1530  &selfLoad, true, true);
1531 
1532  ParmVarDecl *argDecl = *setterMethod->param_begin();
1533  QualType argType = argDecl->getType().getNonReferenceType();
1534  DeclRefExpr arg(getContext(), argDecl, false, argType, VK_LValue,
1535  SourceLocation());
1537  argType.getUnqualifiedType(), CK_LValueToRValue,
1539 
1540  // The property type can differ from the ivar type in some situations with
1541  // Objective-C pointer types, we can always bit cast the RHS in these cases.
1542  // The following absurdity is just to ensure well-formed IR.
1543  CastKind argCK = CK_NoOp;
1544  if (ivarRef.getType()->isObjCObjectPointerType()) {
1545  if (argLoad.getType()->isObjCObjectPointerType())
1546  argCK = CK_BitCast;
1547  else if (argLoad.getType()->isBlockPointerType())
1548  argCK = CK_BlockPointerToObjCPointerCast;
1549  else
1550  argCK = CK_CPointerToObjCPointerCast;
1551  } else if (ivarRef.getType()->isBlockPointerType()) {
1552  if (argLoad.getType()->isBlockPointerType())
1553  argCK = CK_BitCast;
1554  else
1555  argCK = CK_AnyPointerToBlockPointerCast;
1556  } else if (ivarRef.getType()->isPointerType()) {
1557  argCK = CK_BitCast;
1558  } else if (argLoad.getType()->isAtomicType() &&
1559  !ivarRef.getType()->isAtomicType()) {
1560  argCK = CK_AtomicToNonAtomic;
1561  } else if (!argLoad.getType()->isAtomicType() &&
1562  ivarRef.getType()->isAtomicType()) {
1563  argCK = CK_NonAtomicToAtomic;
1564  }
1565  ImplicitCastExpr argCast(ImplicitCastExpr::OnStack, ivarRef.getType(), argCK,
1566  &argLoad, VK_PRValue, FPOptionsOverride());
1567  Expr *finalArg = &argLoad;
1568  if (!getContext().hasSameUnqualifiedType(ivarRef.getType(),
1569  argLoad.getType()))
1570  finalArg = &argCast;
1571 
1573  getContext(), &ivarRef, finalArg, BO_Assign, ivarRef.getType(),
1575  EmitStmt(assign);
1576 }
1577 
1578 /// Generate an Objective-C property setter function.
1579 ///
1580 /// The given Decl must be an ObjCImplementationDecl. \@synthesize
1581 /// is illegal within a category.
1583  const ObjCPropertyImplDecl *PID) {
1584  llvm::Constant *AtomicHelperFn =
1586  ObjCMethodDecl *OMD = PID->getSetterMethodDecl();
1587  assert(OMD && "Invalid call to generate setter (empty method)");
1588  StartObjCMethod(OMD, IMP->getClassInterface());
1589 
1590  generateObjCSetterBody(IMP, PID, AtomicHelperFn);
1591 
1592  FinishFunction(OMD->getEndLoc());
1593 }
1594 
1595 namespace {
1596  struct DestroyIvar final : EHScopeStack::Cleanup {
1597  private:
1598  llvm::Value *addr;
1599  const ObjCIvarDecl *ivar;
1600  CodeGenFunction::Destroyer *destroyer;
1601  bool useEHCleanupForArray;
1602  public:
1603  DestroyIvar(llvm::Value *addr, const ObjCIvarDecl *ivar,
1604  CodeGenFunction::Destroyer *destroyer,
1605  bool useEHCleanupForArray)
1606  : addr(addr), ivar(ivar), destroyer(destroyer),
1607  useEHCleanupForArray(useEHCleanupForArray) {}
1608 
1609  void Emit(CodeGenFunction &CGF, Flags flags) override {
1610  LValue lvalue
1611  = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), addr, ivar, /*CVR*/ 0);
1612  CGF.emitDestroy(lvalue.getAddress(CGF), ivar->getType(), destroyer,
1613  flags.isForNormalCleanup() && useEHCleanupForArray);
1614  }
1615  };
1616 }
1617 
1618 /// Like CodeGenFunction::destroyARCStrong, but do it with a call.
1620  Address addr,
1621  QualType type) {
1622  llvm::Value *null = getNullForVariable(addr);
1623  CGF.EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
1624 }
1625 
1627  ObjCImplementationDecl *impl) {
1629 
1630  llvm::Value *self = CGF.LoadObjCSelf();
1631 
1632  const ObjCInterfaceDecl *iface = impl->getClassInterface();
1633  for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
1634  ivar; ivar = ivar->getNextIvar()) {
1635  QualType type = ivar->getType();
1636 
1637  // Check whether the ivar is a destructible type.
1638  QualType::DestructionKind dtorKind = type.isDestructedType();
1639  if (!dtorKind) continue;
1640 
1641  CodeGenFunction::Destroyer *destroyer = nullptr;
1642 
1643  // Use a call to objc_storeStrong to destroy strong ivars, for the
1644  // general benefit of the tools.
1645  if (dtorKind == QualType::DK_objc_strong_lifetime) {
1646  destroyer = destroyARCStrongWithStore;
1647 
1648  // Otherwise use the default for the destruction kind.
1649  } else {
1650  destroyer = CGF.getDestroyer(dtorKind);
1651  }
1652 
1653  CleanupKind cleanupKind = CGF.getCleanupKind(dtorKind);
1654 
1655  CGF.EHStack.pushCleanup<DestroyIvar>(cleanupKind, self, ivar, destroyer,
1656  cleanupKind & EHCleanup);
1657  }
1658 
1659  assert(scope.requiresCleanups() && "nothing to do in .cxx_destruct?");
1660 }
1661 
1663  ObjCMethodDecl *MD,
1664  bool ctor) {
1666  StartObjCMethod(MD, IMP->getClassInterface());
1667 
1668  // Emit .cxx_construct.
1669  if (ctor) {
1670  // Suppress the final autorelease in ARC.
1671  AutoreleaseResult = false;
1672 
1673  for (const auto *IvarInit : IMP->inits()) {
1674  FieldDecl *Field = IvarInit->getAnyMember();
1675  ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
1677  LoadObjCSelf(), Ivar, 0);
1678  EmitAggExpr(IvarInit->getInit(),
1683  }
1684  // constructor returns 'self'.
1685  CodeGenTypes &Types = CGM.getTypes();
1687  llvm::Value *SelfAsId =
1688  Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
1689  EmitReturnOfRValue(RValue::get(SelfAsId), IdTy);
1690 
1691  // Emit .cxx_destruct.
1692  } else {
1693  emitCXXDestructMethod(*this, IMP);
1694  }
1695  FinishFunction();
1696 }
1697 
1699  VarDecl *Self = cast<ObjCMethodDecl>(CurFuncDecl)->getSelfDecl();
1700  DeclRefExpr DRE(getContext(), Self,
1701  /*is enclosing local*/ (CurFuncDecl != CurCodeDecl),
1702  Self->getType(), VK_LValue, SourceLocation());
1704 }
1705 
1707  const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
1708  ImplicitParamDecl *selfDecl = OMD->getSelfDecl();
1709  const ObjCObjectPointerType *PTy = cast<ObjCObjectPointerType>(
1710  getContext().getCanonicalType(selfDecl->getType()));
1711  return PTy->getPointeeType();
1712 }
1713 
1715  llvm::FunctionCallee EnumerationMutationFnPtr =
1717  if (!EnumerationMutationFnPtr) {
1718  CGM.ErrorUnsupported(&S, "Obj-C fast enumeration for this runtime");
1719  return;
1720  }
1721  CGCallee EnumerationMutationFn =
1722  CGCallee::forDirect(EnumerationMutationFnPtr);
1723 
1724  CGDebugInfo *DI = getDebugInfo();
1725  if (DI)
1726  DI->EmitLexicalBlockStart(Builder, S.getSourceRange().getBegin());
1727 
1728  RunCleanupsScope ForScope(*this);
1729 
1730  // The local variable comes into scope immediately.
1732  if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement()))
1733  variable = EmitAutoVarAlloca(*cast<VarDecl>(SD->getSingleDecl()));
1734 
1735  JumpDest LoopEnd = getJumpDestInCurrentScope("forcoll.end");
1736 
1737  // Fast enumeration state.
1739  Address StatePtr = CreateMemTemp(StateTy, "state.ptr");
1740  EmitNullInitialization(StatePtr, StateTy);
1741 
1742  // Number of elements in the items array.
1743  static const unsigned NumItems = 16;
1744 
1745  // Fetch the countByEnumeratingWithState:objects:count: selector.
1746  IdentifierInfo *II[] = {
1747  &CGM.getContext().Idents.get("countByEnumeratingWithState"),
1748  &CGM.getContext().Idents.get("objects"),
1749  &CGM.getContext().Idents.get("count")
1750  };
1751  Selector FastEnumSel =
1752  CGM.getContext().Selectors.getSelector(llvm::array_lengthof(II), &II[0]);
1753 
1754  QualType ItemsTy =
1755  getContext().getConstantArrayType(getContext().getObjCIdType(),
1756  llvm::APInt(32, NumItems), nullptr,
1757  ArrayType::Normal, 0);
1758  Address ItemsPtr = CreateMemTemp(ItemsTy, "items.ptr");
1759 
1760  // Emit the collection pointer. In ARC, we do a retain.
1761  llvm::Value *Collection;
1762  if (getLangOpts().ObjCAutoRefCount) {
1763  Collection = EmitARCRetainScalarExpr(S.getCollection());
1764 
1765  // Enter a cleanup to do the release.
1766  EmitObjCConsumeObject(S.getCollection()->getType(), Collection);
1767  } else {
1768  Collection = EmitScalarExpr(S.getCollection());
1769  }
1770 
1771  // The 'continue' label needs to appear within the cleanup for the
1772  // collection object.
1773  JumpDest AfterBody = getJumpDestInCurrentScope("forcoll.next");
1774 
1775  // Send it our message:
1776  CallArgList Args;
1777 
1778  // The first argument is a temporary of the enumeration-state type.
1779  Args.add(RValue::get(StatePtr.getPointer()),
1780  getContext().getPointerType(StateTy));
1781 
1782  // The second argument is a temporary array with space for NumItems
1783  // pointers. We'll actually be loading elements from the array
1784  // pointer written into the control state; this buffer is so that
1785  // collections that *aren't* backed by arrays can still queue up
1786  // batches of elements.
1787  Args.add(RValue::get(ItemsPtr.getPointer()),
1788  getContext().getPointerType(ItemsTy));
1789 
1790  // The third argument is the capacity of that temporary array.
1791  llvm::Type *NSUIntegerTy = ConvertType(getContext().getNSUIntegerType());
1792  llvm::Constant *Count = llvm::ConstantInt::get(NSUIntegerTy, NumItems);
1793  Args.add(RValue::get(Count), getContext().getNSUIntegerType());
1794 
1795  // Start the enumeration.
1796  RValue CountRV =
1798  getContext().getNSUIntegerType(),
1799  FastEnumSel, Collection, Args);
1800 
1801  // The initial number of objects that were returned in the buffer.
1802  llvm::Value *initialBufferLimit = CountRV.getScalarVal();
1803 
1804  llvm::BasicBlock *EmptyBB = createBasicBlock("forcoll.empty");
1805  llvm::BasicBlock *LoopInitBB = createBasicBlock("forcoll.loopinit");
1806 
1807  llvm::Value *zero = llvm::Constant::getNullValue(NSUIntegerTy);
1808 
1809  // If the limit pointer was zero to begin with, the collection is
1810  // empty; skip all this. Set the branch weight assuming this has the same
1811  // probability of exiting the loop as any other loop exit.
1812  uint64_t EntryCount = getCurrentProfileCount();
1813  Builder.CreateCondBr(
1814  Builder.CreateICmpEQ(initialBufferLimit, zero, "iszero"), EmptyBB,
1815  LoopInitBB,
1816  createProfileWeights(EntryCount, getProfileCount(S.getBody())));
1817 
1818  // Otherwise, initialize the loop.
1819  EmitBlock(LoopInitBB);
1820 
1821  // Save the initial mutations value. This is the value at an
1822  // address that was written into the state object by
1823  // countByEnumeratingWithState:objects:count:.
1824  Address StateMutationsPtrPtr =
1825  Builder.CreateStructGEP(StatePtr, 2, "mutationsptr.ptr");
1826  llvm::Value *StateMutationsPtr
1827  = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
1828 
1829  llvm::Type *UnsignedLongTy = ConvertType(getContext().UnsignedLongTy);
1830  llvm::Value *initialMutations =
1831  Builder.CreateAlignedLoad(UnsignedLongTy, StateMutationsPtr,
1832  getPointerAlign(), "forcoll.initial-mutations");
1833 
1834  // Start looping. This is the point we return to whenever we have a
1835  // fresh, non-empty batch of objects.
1836  llvm::BasicBlock *LoopBodyBB = createBasicBlock("forcoll.loopbody");
1837  EmitBlock(LoopBodyBB);
1838 
1839  // The current index into the buffer.
1840  llvm::PHINode *index = Builder.CreatePHI(NSUIntegerTy, 3, "forcoll.index");
1841  index->addIncoming(zero, LoopInitBB);
1842 
1843  // The current buffer size.
1844  llvm::PHINode *count = Builder.CreatePHI(NSUIntegerTy, 3, "forcoll.count");
1845  count->addIncoming(initialBufferLimit, LoopInitBB);
1846 
1848 
1849  // Check whether the mutations value has changed from where it was
1850  // at start. StateMutationsPtr should actually be invariant between
1851  // refreshes.
1852  StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
1853  llvm::Value *currentMutations
1854  = Builder.CreateAlignedLoad(UnsignedLongTy, StateMutationsPtr,
1855  getPointerAlign(), "statemutations");
1856 
1857  llvm::BasicBlock *WasMutatedBB = createBasicBlock("forcoll.mutated");
1858  llvm::BasicBlock *WasNotMutatedBB = createBasicBlock("forcoll.notmutated");
1859 
1860  Builder.CreateCondBr(Builder.CreateICmpEQ(currentMutations, initialMutations),
1861  WasNotMutatedBB, WasMutatedBB);
1862 
1863  // If so, call the enumeration-mutation function.
1864  EmitBlock(WasMutatedBB);
1865  llvm::Type *ObjCIdType = ConvertType(getContext().getObjCIdType());
1866  llvm::Value *V =
1867  Builder.CreateBitCast(Collection, ObjCIdType);
1868  CallArgList Args2;
1869  Args2.add(RValue::get(V), getContext().getObjCIdType());
1870  // FIXME: We shouldn't need to get the function info here, the runtime already
1871  // should have computed it to build the function.
1872  EmitCall(
1874  EnumerationMutationFn, ReturnValueSlot(), Args2);
1875 
1876  // Otherwise, or if the mutation function returns, just continue.
1877  EmitBlock(WasNotMutatedBB);
1878 
1879  // Initialize the element variable.
1880  RunCleanupsScope elementVariableScope(*this);
1881  bool elementIsVariable;
1882  LValue elementLValue;
1883  QualType elementType;
1884  if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) {
1885  // Initialize the variable, in case it's a __block variable or something.
1886  EmitAutoVarInit(variable);
1887 
1888  const VarDecl *D = cast<VarDecl>(SD->getSingleDecl());
1889  DeclRefExpr tempDRE(getContext(), const_cast<VarDecl *>(D), false,
1890  D->getType(), VK_LValue, SourceLocation());
1891  elementLValue = EmitLValue(&tempDRE);
1892  elementType = D->getType();
1893  elementIsVariable = true;
1894 
1895  if (D->isARCPseudoStrong())
1897  } else {
1898  elementLValue = LValue(); // suppress warning
1899  elementType = cast<Expr>(S.getElement())->getType();
1900  elementIsVariable = false;
1901  }
1902  llvm::Type *convertedElementType = ConvertType(elementType);
1903 
1904  // Fetch the buffer out of the enumeration state.
1905  // TODO: this pointer should actually be invariant between
1906  // refreshes, which would help us do certain loop optimizations.
1907  Address StateItemsPtr =
1908  Builder.CreateStructGEP(StatePtr, 1, "stateitems.ptr");
1909  llvm::Value *EnumStateItems =
1910  Builder.CreateLoad(StateItemsPtr, "stateitems");
1911 
1912  // Fetch the value at the current index from the buffer.
1913  llvm::Value *CurrentItemPtr = Builder.CreateGEP(
1914  EnumStateItems->getType()->getPointerElementType(), EnumStateItems, index,
1915  "currentitem.ptr");
1916  llvm::Value *CurrentItem =
1917  Builder.CreateAlignedLoad(ObjCIdType, CurrentItemPtr, getPointerAlign());
1918 
1919  if (SanOpts.has(SanitizerKind::ObjCCast)) {
1920  // Before using an item from the collection, check that the implicit cast
1921  // from id to the element type is valid. This is done with instrumentation
1922  // roughly corresponding to:
1923  //
1924  // if (![item isKindOfClass:expectedCls]) { /* emit diagnostic */ }
1925  const ObjCObjectPointerType *ObjPtrTy =
1926  elementType->getAsObjCInterfacePointerType();
1927  const ObjCInterfaceType *InterfaceTy =
1928  ObjPtrTy ? ObjPtrTy->getInterfaceType() : nullptr;
1929  if (InterfaceTy) {
1930  SanitizerScope SanScope(this);
1931  auto &C = CGM.getContext();
1932  assert(InterfaceTy->getDecl() && "No decl for ObjC interface type");
1933  Selector IsKindOfClassSel = GetUnarySelector("isKindOfClass", C);
1934  CallArgList IsKindOfClassArgs;
1935  llvm::Value *Cls =
1936  CGM.getObjCRuntime().GetClass(*this, InterfaceTy->getDecl());
1937  IsKindOfClassArgs.add(RValue::get(Cls), C.getObjCClassType());
1938  llvm::Value *IsClass =
1940  .GenerateMessageSend(*this, ReturnValueSlot(), C.BoolTy,
1941  IsKindOfClassSel, CurrentItem,
1942  IsKindOfClassArgs)
1943  .getScalarVal();
1944  llvm::Constant *StaticData[] = {
1945  EmitCheckSourceLocation(S.getBeginLoc()),
1946  EmitCheckTypeDescriptor(QualType(InterfaceTy, 0))};
1947  EmitCheck({{IsClass, SanitizerKind::ObjCCast}},
1948  SanitizerHandler::InvalidObjCCast,
1949  ArrayRef<llvm::Constant *>(StaticData), CurrentItem);
1950  }
1951  }
1952 
1953  // Cast that value to the right type.
1954  CurrentItem = Builder.CreateBitCast(CurrentItem, convertedElementType,
1955  "currentitem");
1956 
1957  // Make sure we have an l-value. Yes, this gets evaluated every
1958  // time through the loop.
1959  if (!elementIsVariable) {
1960  elementLValue = EmitLValue(cast<Expr>(S.getElement()));
1961  EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue);
1962  } else {
1963  EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue,
1964  /*isInit*/ true);
1965  }
1966 
1967  // If we do have an element variable, this assignment is the end of
1968  // its initialization.
1969  if (elementIsVariable)
1970  EmitAutoVarCleanups(variable);
1971 
1972  // Perform the loop body, setting up break and continue labels.
1973  BreakContinueStack.push_back(BreakContinue(LoopEnd, AfterBody));
1974  {
1975  RunCleanupsScope Scope(*this);
1976  EmitStmt(S.getBody());
1977  }
1978  BreakContinueStack.pop_back();
1979 
1980  // Destroy the element variable now.
1981  elementVariableScope.ForceCleanup();
1982 
1983  // Check whether there are more elements.
1984  EmitBlock(AfterBody.getBlock());
1985 
1986  llvm::BasicBlock *FetchMoreBB = createBasicBlock("forcoll.refetch");
1987 
1988  // First we check in the local buffer.
1989  llvm::Value *indexPlusOne =
1990  Builder.CreateAdd(index, llvm::ConstantInt::get(NSUIntegerTy, 1));
1991 
1992  // If we haven't overrun the buffer yet, we can continue.
1993  // Set the branch weights based on the simplifying assumption that this is
1994  // like a while-loop, i.e., ignoring that the false branch fetches more
1995  // elements and then returns to the loop.
1996  Builder.CreateCondBr(
1997  Builder.CreateICmpULT(indexPlusOne, count), LoopBodyBB, FetchMoreBB,
1998  createProfileWeights(getProfileCount(S.getBody()), EntryCount));
1999 
2000  index->addIncoming(indexPlusOne, AfterBody.getBlock());
2001  count->addIncoming(count, AfterBody.getBlock());
2002 
2003  // Otherwise, we have to fetch more elements.
2004  EmitBlock(FetchMoreBB);
2005 
2006  CountRV =
2008  getContext().getNSUIntegerType(),
2009  FastEnumSel, Collection, Args);
2010 
2011  // If we got a zero count, we're done.
2012  llvm::Value *refetchCount = CountRV.getScalarVal();
2013 
2014  // (note that the message send might split FetchMoreBB)
2015  index->addIncoming(zero, Builder.GetInsertBlock());
2016  count->addIncoming(refetchCount, Builder.GetInsertBlock());
2017 
2018  Builder.CreateCondBr(Builder.CreateICmpEQ(refetchCount, zero),
2019  EmptyBB, LoopBodyBB);
2020 
2021  // No more elements.
2022  EmitBlock(EmptyBB);
2023 
2024  if (!elementIsVariable) {
2025  // If the element was not a declaration, set it to be null.
2026 
2027  llvm::Value *null = llvm::Constant::getNullValue(convertedElementType);
2028  elementLValue = EmitLValue(cast<Expr>(S.getElement()));
2029  EmitStoreThroughLValue(RValue::get(null), elementLValue);
2030  }
2031 
2032  if (DI)
2033  DI->EmitLexicalBlockEnd(Builder, S.getSourceRange().getEnd());
2034 
2035  ForScope.ForceCleanup();
2036  EmitBlock(LoopEnd.getBlock());
2037 }
2038 
2040  CGM.getObjCRuntime().EmitTryStmt(*this, S);
2041 }
2042 
2044  CGM.getObjCRuntime().EmitThrowStmt(*this, S);
2045 }
2046 
2048  const ObjCAtSynchronizedStmt &S) {
2050 }
2051 
2052 namespace {
2053  struct CallObjCRelease final : EHScopeStack::Cleanup {
2054  CallObjCRelease(llvm::Value *object) : object(object) {}
2056 
2057  void Emit(CodeGenFunction &CGF, Flags flags) override {
2058  // Releases at the end of the full-expression are imprecise.
2059  CGF.EmitARCRelease(object, ARCImpreciseLifetime);
2060  }
2061  };
2062 }
2063 
2064 /// Produce the code for a CK_ARCConsumeObject. Does a primitive
2065 /// release at the end of the full-expression.
2067  llvm::Value *object) {
2068  // If we're in a conditional branch, we need to make the cleanup
2069  // conditional.
2070  pushFullExprCleanup<CallObjCRelease>(getARCCleanupKind(), object);
2071  return object;
2072 }
2073 
2075  llvm::Value *value) {
2076  return EmitARCRetainAutorelease(type, value);
2077 }
2078 
2079 /// Given a number of pointers, inform the optimizer that they're
2080 /// being intrinsically used up until this point in the program.
2082  llvm::Function *&fn = CGM.getObjCEntrypoints().clang_arc_use;
2083  if (!fn)
2084  fn = CGM.getIntrinsic(llvm::Intrinsic::objc_clang_arc_use);
2085 
2086  // This isn't really a "runtime" function, but as an intrinsic it
2087  // doesn't really matter as long as we align things up.
2088  EmitNounwindRuntimeCall(fn, values);
2089 }
2090 
2091 /// Emit a call to "clang.arc.noop.use", which consumes the result of a call
2092 /// that has operand bundle "clang.arc.attachedcall".
2094  llvm::Function *&fn = CGM.getObjCEntrypoints().clang_arc_noop_use;
2095  if (!fn)
2096  fn = CGM.getIntrinsic(llvm::Intrinsic::objc_clang_arc_noop_use);
2097  EmitNounwindRuntimeCall(fn, values);
2098 }
2099 
2101  if (auto *F = dyn_cast<llvm::Function>(RTF)) {
2102  // If the target runtime doesn't naturally support ARC, emit weak
2103  // references to the runtime support library. We don't really
2104  // permit this to fail, but we need a particular relocation style.
2105  if (!CGM.getLangOpts().ObjCRuntime.hasNativeARC() &&
2106  !CGM.getTriple().isOSBinFormatCOFF()) {
2107  F->setLinkage(llvm::Function::ExternalWeakLinkage);
2108  }
2109  }
2110 }
2111 
2113  llvm::FunctionCallee RTF) {
2114  setARCRuntimeFunctionLinkage(CGM, RTF.getCallee());
2115 }
2116 
2117 static llvm::Function *getARCIntrinsic(llvm::Intrinsic::ID IntID,
2118  CodeGenModule &CGM) {
2119  llvm::Function *fn = CGM.getIntrinsic(IntID);
2121  return fn;
2122 }
2123 
2124 /// Perform an operation having the signature
2125 /// i8* (i8*)
2126 /// where a null input causes a no-op and returns null.
2128  CodeGenFunction &CGF, llvm::Value *value, llvm::Type *returnType,
2129  llvm::Function *&fn, llvm::Intrinsic::ID IntID,
2130  llvm::CallInst::TailCallKind tailKind = llvm::CallInst::TCK_None) {
2131  if (isa<llvm::ConstantPointerNull>(value))
2132  return value;
2133 
2134  if (!fn)
2135  fn = getARCIntrinsic(IntID, CGF.CGM);
2136 
2137  // Cast the argument to 'id'.
2138  llvm::Type *origType = returnType ? returnType : value->getType();
2139  value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
2140 
2141  // Call the function.
2142  llvm::CallInst *call = CGF.EmitNounwindRuntimeCall(fn, value);
2143  call->setTailCallKind(tailKind);
2144 
2145  // Cast the result back to the original type.
2146  return CGF.Builder.CreateBitCast(call, origType);
2147 }
2148 
2149 /// Perform an operation having the following signature:
2150 /// i8* (i8**)
2152  llvm::Function *&fn,
2153  llvm::Intrinsic::ID IntID) {
2154  if (!fn)
2155  fn = getARCIntrinsic(IntID, CGF.CGM);
2156 
2157  // Cast the argument to 'id*'.
2158  llvm::Type *origType = addr.getElementType();
2159  addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy);
2160 
2161  // Call the function.
2162  llvm::Value *result = CGF.EmitNounwindRuntimeCall(fn, addr.getPointer());
2163 
2164  // Cast the result back to a dereference of the original type.
2165  if (origType != CGF.Int8PtrTy)
2166  result = CGF.Builder.CreateBitCast(result, origType);
2167 
2168  return result;
2169 }
2170 
2171 /// Perform an operation having the following signature:
2172 /// i8* (i8**, i8*)
2174  llvm::Value *value,
2175  llvm::Function *&fn,
2176  llvm::Intrinsic::ID IntID,
2177  bool ignored) {
2178  assert(addr.getElementType() == value->getType());
2179 
2180  if (!fn)
2181  fn = getARCIntrinsic(IntID, CGF.CGM);
2182 
2183  llvm::Type *origType = value->getType();
2184 
2185  llvm::Value *args[] = {
2186  CGF.Builder.CreateBitCast(addr.getPointer(), CGF.Int8PtrPtrTy),
2187  CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy)
2188  };
2189  llvm::CallInst *result = CGF.EmitNounwindRuntimeCall(fn, args);
2190 
2191  if (ignored) return nullptr;
2192 
2193  return CGF.Builder.CreateBitCast(result, origType);
2194 }
2195 
2196 /// Perform an operation having the following signature:
2197 /// void (i8**, i8**)
2199  llvm::Function *&fn,
2200  llvm::Intrinsic::ID IntID) {
2201  assert(dst.getType() == src.getType());
2202 
2203  if (!fn)
2204  fn = getARCIntrinsic(IntID, CGF.CGM);
2205 
2206  llvm::Value *args[] = {
2207  CGF.Builder.CreateBitCast(dst.getPointer(), CGF.Int8PtrPtrTy),
2209  };
2210  CGF.EmitNounwindRuntimeCall(fn, args);
2211 }
2212 
2213 /// Perform an operation having the signature
2214 /// i8* (i8*)
2215 /// where a null input causes a no-op and returns null.
2217  llvm::Value *value,
2218  llvm::Type *returnType,
2219  llvm::FunctionCallee &fn,
2220  StringRef fnName) {
2221  if (isa<llvm::ConstantPointerNull>(value))
2222  return value;
2223 
2224  if (!fn) {
2225  llvm::FunctionType *fnType =
2226  llvm::FunctionType::get(CGF.Int8PtrTy, CGF.Int8PtrTy, false);
2227  fn = CGF.CGM.CreateRuntimeFunction(fnType, fnName);
2228 
2229  // We have Native ARC, so set nonlazybind attribute for performance
2230  if (llvm::Function *f = dyn_cast<llvm::Function>(fn.getCallee()))
2231  if (fnName == "objc_retain")
2232  f->addFnAttr(llvm::Attribute::NonLazyBind);
2233  }
2234 
2235  // Cast the argument to 'id'.
2236  llvm::Type *origType = returnType ? returnType : value->getType();
2237  value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
2238 
2239  // Call the function.
2240  llvm::CallBase *Inst = CGF.EmitCallOrInvoke(fn, value);
2241 
2242  // Mark calls to objc_autorelease as tail on the assumption that methods
2243  // overriding autorelease do not touch anything on the stack.
2244  if (fnName == "objc_autorelease")
2245  if (auto *Call = dyn_cast<llvm::CallInst>(Inst))
2246  Call->setTailCall();
2247 
2248  // Cast the result back to the original type.
2249  return CGF.Builder.CreateBitCast(Inst, origType);
2250 }
2251 
2252 /// Produce the code to do a retain. Based on the type, calls one of:
2253 /// call i8* \@objc_retain(i8* %value)
2254 /// call i8* \@objc_retainBlock(i8* %value)
2256  if (type->isBlockPointerType())
2257  return EmitARCRetainBlock(value, /*mandatory*/ false);
2258  else
2259  return EmitARCRetainNonBlock(value);
2260 }
2261 
2262 /// Retain the given object, with normal retain semantics.
2263 /// call i8* \@objc_retain(i8* %value)
2265  return emitARCValueOperation(*this, value, nullptr,
2267  llvm::Intrinsic::objc_retain);
2268 }
2269 
2270 /// Retain the given block, with _Block_copy semantics.
2271 /// call i8* \@objc_retainBlock(i8* %value)
2272 ///
2273 /// \param mandatory - If false, emit the call with metadata
2274 /// indicating that it's okay for the optimizer to eliminate this call
2275 /// if it can prove that the block never escapes except down the stack.
2277  bool mandatory) {
2278  llvm::Value *result
2279  = emitARCValueOperation(*this, value, nullptr,
2281  llvm::Intrinsic::objc_retainBlock);
2282 
2283  // If the copy isn't mandatory, add !clang.arc.copy_on_escape to
2284  // tell the optimizer that it doesn't need to do this copy if the
2285  // block doesn't escape, where being passed as an argument doesn't
2286  // count as escaping.
2287  if (!mandatory && isa<llvm::Instruction>(result)) {
2288  llvm::CallInst *call
2289  = cast<llvm::CallInst>(result->stripPointerCasts());
2290  assert(call->getCalledOperand() ==
2292 
2293  call->setMetadata("clang.arc.copy_on_escape",
2294  llvm::MDNode::get(Builder.getContext(), None));
2295  }
2296 
2297  return result;
2298 }
2299 
2301  // Fetch the void(void) inline asm which marks that we're going to
2302  // do something with the autoreleased return value.
2303  llvm::InlineAsm *&marker
2305  if (!marker) {
2306  StringRef assembly
2307  = CGF.CGM.getTargetCodeGenInfo()
2309 
2310  // If we have an empty assembly string, there's nothing to do.
2311  if (assembly.empty()) {
2312 
2313  // Otherwise, at -O0, build an inline asm that we're going to call
2314  // in a moment.
2315  } else if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0) {
2316  llvm::FunctionType *type =
2317  llvm::FunctionType::get(CGF.VoidTy, /*variadic*/false);
2318 
2319  marker = llvm::InlineAsm::get(type, assembly, "", /*sideeffects*/ true);
2320 
2321  // If we're at -O1 and above, we don't want to litter the code
2322  // with this marker yet, so leave a breadcrumb for the ARC
2323  // optimizer to pick up.
2324  } else {
2325  const char *retainRVMarkerKey = llvm::objcarc::getRVMarkerModuleFlagStr();
2326  if (!CGF.CGM.getModule().getModuleFlag(retainRVMarkerKey)) {
2327  auto *str = llvm::MDString::get(CGF.getLLVMContext(), assembly);
2328  CGF.CGM.getModule().addModuleFlag(llvm::Module::Error,
2329  retainRVMarkerKey, str);
2330  }
2331  }
2332  }
2333 
2334  // Call the marker asm if we made one, which we do only at -O0.
2335  if (marker)
2336  CGF.Builder.CreateCall(marker, None, CGF.getBundlesForFunclet(marker));
2337 }
2338 
2340  bool IsRetainRV,
2341  CodeGenFunction &CGF) {
2343 
2344  // Add operand bundle "clang.arc.attachedcall" to the call instead of emitting
2345  // retainRV or claimRV calls in the IR. We currently do this only when the
2346  // optimization level isn't -O0 since global-isel, which is currently run at
2347  // -O0, doesn't know about the operand bundle.
2348  ObjCEntrypoints &EPs = CGF.CGM.getObjCEntrypoints();
2349  llvm::Function *&EP = IsRetainRV
2352  llvm::Intrinsic::ID IID =
2353  IsRetainRV ? llvm::Intrinsic::objc_retainAutoreleasedReturnValue
2354  : llvm::Intrinsic::objc_unsafeClaimAutoreleasedReturnValue;
2355  EP = getARCIntrinsic(IID, CGF.CGM);
2356 
2357  // FIXME: Do this when the target isn't aarch64.
2358  if (CGF.CGM.getCodeGenOpts().OptimizationLevel > 0 &&
2359  CGF.CGM.getTarget().getTriple().isAArch64()) {
2360  llvm::Value *bundleArgs[] = {EP};
2361  llvm::OperandBundleDef OB("clang.arc.attachedcall", bundleArgs);
2362  auto *oldCall = cast<llvm::CallBase>(value);
2363  llvm::CallBase *newCall = llvm::CallBase::addOperandBundle(
2364  oldCall, llvm::LLVMContext::OB_clang_arc_attachedcall, OB, oldCall);
2365  newCall->copyMetadata(*oldCall);
2366  oldCall->replaceAllUsesWith(newCall);
2367  oldCall->eraseFromParent();
2368  CGF.EmitARCNoopIntrinsicUse(newCall);
2369  return newCall;
2370  }
2371 
2372  bool isNoTail =
2374  llvm::CallInst::TailCallKind tailKind =
2375  isNoTail ? llvm::CallInst::TCK_NoTail : llvm::CallInst::TCK_None;
2376  return emitARCValueOperation(CGF, value, nullptr, EP, IID, tailKind);
2377 }
2378 
2379 /// Retain the given object which is the result of a function call.
2380 /// call i8* \@objc_retainAutoreleasedReturnValue(i8* %value)
2381 ///
2382 /// Yes, this function name is one character away from a different
2383 /// call with completely different semantics.
2384 llvm::Value *
2386  return emitOptimizedARCReturnCall(value, true, *this);
2387 }
2388 
2389 /// Claim a possibly-autoreleased return value at +0. This is only
2390 /// valid to do in contexts which do not rely on the retain to keep
2391 /// the object valid for all of its uses; for example, when
2392 /// the value is ignored, or when it is being assigned to an
2393 /// __unsafe_unretained variable.
2394 ///
2395 /// call i8* \@objc_unsafeClaimAutoreleasedReturnValue(i8* %value)
2396 llvm::Value *
2398  return emitOptimizedARCReturnCall(value, false, *this);
2399 }
2400 
2401 /// Release the given object.
2402 /// call void \@objc_release(i8* %value)
2404  ARCPreciseLifetime_t precise) {
2405  if (isa<llvm::ConstantPointerNull>(value)) return;
2406 
2407  llvm::Function *&fn = CGM.getObjCEntrypoints().objc_release;
2408  if (!fn)
2409  fn = getARCIntrinsic(llvm::Intrinsic::objc_release, CGM);
2410 
2411  // Cast the argument to 'id'.
2412  value = Builder.CreateBitCast(value, Int8PtrTy);
2413 
2414  // Call objc_release.
2415  llvm::CallInst *call = EmitNounwindRuntimeCall(fn, value);
2416 
2417  if (precise == ARCImpreciseLifetime) {
2418  call->setMetadata("clang.imprecise_release",
2419  llvm::MDNode::get(Builder.getContext(), None));
2420  }
2421 }
2422 
2423 /// Destroy a __strong variable.
2424 ///
2425 /// At -O0, emit a call to store 'null' into the address;
2426 /// instrumenting tools prefer this because the address is exposed,
2427 /// but it's relatively cumbersome to optimize.
2428 ///
2429 /// At -O1 and above, just load and call objc_release.
2430 ///
2431 /// call void \@objc_storeStrong(i8** %addr, i8* null)
2433  ARCPreciseLifetime_t precise) {
2434  if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
2435  llvm::Value *null = getNullForVariable(addr);
2436  EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
2437  return;
2438  }
2439 
2440  llvm::Value *value = Builder.CreateLoad(addr);
2441  EmitARCRelease(value, precise);
2442 }
2443 
2444 /// Store into a strong object. Always calls this:
2445 /// call void \@objc_storeStrong(i8** %addr, i8* %value)
2447  llvm::Value *value,
2448  bool ignored) {
2449  assert(addr.getElementType() == value->getType());
2450 
2451  llvm::Function *&fn = CGM.getObjCEntrypoints().objc_storeStrong;
2452  if (!fn)
2453  fn = getARCIntrinsic(llvm::Intrinsic::objc_storeStrong, CGM);
2454 
2455  llvm::Value *args[] = {
2458  };
2459  EmitNounwindRuntimeCall(fn, args);
2460 
2461  if (ignored) return nullptr;
2462  return value;
2463 }
2464 
2465 /// Store into a strong object. Sometimes calls this:
2466 /// call void \@objc_storeStrong(i8** %addr, i8* %value)
2467 /// Other times, breaks it down into components.
2469  llvm::Value *newValue,
2470  bool ignored) {
2471  QualType type = dst.getType();
2472  bool isBlock = type->isBlockPointerType();
2473 
2474  // Use a store barrier at -O0 unless this is a block type or the
2475  // lvalue is inadequately aligned.
2476  if (shouldUseFusedARCCalls() &&
2477  !isBlock &&
2478  (dst.getAlignment().isZero() ||
2480  return EmitARCStoreStrongCall(dst.getAddress(*this), newValue, ignored);
2481  }
2482 
2483  // Otherwise, split it out.
2484 
2485  // Retain the new value.
2486  newValue = EmitARCRetain(type, newValue);
2487 
2488  // Read the old value.
2489  llvm::Value *oldValue = EmitLoadOfScalar(dst, SourceLocation());
2490 
2491  // Store. We do this before the release so that any deallocs won't
2492  // see the old value.
2493  EmitStoreOfScalar(newValue, dst);
2494 
2495  // Finally, release the old value.
2496  EmitARCRelease(oldValue, dst.isARCPreciseLifetime());
2497 
2498  return newValue;
2499 }
2500 
2501 /// Autorelease the given object.
2502 /// call i8* \@objc_autorelease(i8* %value)
2504  return emitARCValueOperation(*this, value, nullptr,
2506  llvm::Intrinsic::objc_autorelease);
2507 }
2508 
2509 /// Autorelease the given object.
2510 /// call i8* \@objc_autoreleaseReturnValue(i8* %value)
2511 llvm::Value *
2513  return emitARCValueOperation(*this, value, nullptr,
2515  llvm::Intrinsic::objc_autoreleaseReturnValue,
2516  llvm::CallInst::TCK_Tail);
2517 }
2518 
2519 /// Do a fused retain/autorelease of the given object.
2520 /// call i8* \@objc_retainAutoreleaseReturnValue(i8* %value)
2521 llvm::Value *
2523  return emitARCValueOperation(*this, value, nullptr,
2525  llvm::Intrinsic::objc_retainAutoreleaseReturnValue,
2526  llvm::CallInst::TCK_Tail);
2527 }
2528 
2529 /// Do a fused retain/autorelease of the given object.
2530 /// call i8* \@objc_retainAutorelease(i8* %value)
2531 /// or
2532 /// %retain = call i8* \@objc_retainBlock(i8* %value)
2533 /// call i8* \@objc_autorelease(i8* %retain)
2535  llvm::Value *value) {
2536  if (!type->isBlockPointerType())
2537  return EmitARCRetainAutoreleaseNonBlock(value);
2538 
2539  if (isa<llvm::ConstantPointerNull>(value)) return value;
2540 
2541  llvm::Type *origType = value->getType();
2542  value = Builder.CreateBitCast(value, Int8PtrTy);
2543  value = EmitARCRetainBlock(value, /*mandatory*/ true);
2544  value = EmitARCAutorelease(value);
2545  return Builder.CreateBitCast(value, origType);
2546 }
2547 
2548 /// Do a fused retain/autorelease of the given object.
2549 /// call i8* \@objc_retainAutorelease(i8* %value)
2550 llvm::Value *
2552  return emitARCValueOperation(*this, value, nullptr,
2554  llvm::Intrinsic::objc_retainAutorelease);
2555 }
2556 
2557 /// i8* \@objc_loadWeak(i8** %addr)
2558 /// Essentially objc_autorelease(objc_loadWeakRetained(addr)).
2560  return emitARCLoadOperation(*this, addr,
2562  llvm::Intrinsic::objc_loadWeak);
2563 }
2564 
2565 /// i8* \@objc_loadWeakRetained(i8** %addr)
2567  return emitARCLoadOperation(*this, addr,
2569  llvm::Intrinsic::objc_loadWeakRetained);
2570 }
2571 
2572 /// i8* \@objc_storeWeak(i8** %addr, i8* %value)
2573 /// Returns %value.
2575  llvm::Value *value,
2576  bool ignored) {
2577  return emitARCStoreOperation(*this, addr, value,
2579  llvm::Intrinsic::objc_storeWeak, ignored);
2580 }
2581 
2582 /// i8* \@objc_initWeak(i8** %addr, i8* %value)
2583 /// Returns %value. %addr is known to not have a current weak entry.
2584 /// Essentially equivalent to:
2585 /// *addr = nil; objc_storeWeak(addr, value);
2587  // If we're initializing to null, just write null to memory; no need
2588  // to get the runtime involved. But don't do this if optimization
2589  // is enabled, because accounting for this would make the optimizer
2590  // much more complicated.
2591  if (isa<llvm::ConstantPointerNull>(value) &&
2592  CGM.getCodeGenOpts().OptimizationLevel == 0) {
2593  Builder.CreateStore(value, addr);
2594  return;
2595  }
2596 
2597  emitARCStoreOperation(*this, addr, value,
2599  llvm::Intrinsic::objc_initWeak, /*ignored*/ true);
2600 }
2601 
2602 /// void \@objc_destroyWeak(i8** %addr)
2603 /// Essentially objc_storeWeak(addr, nil).
2605  llvm::Function *&fn = CGM.getObjCEntrypoints().objc_destroyWeak;
2606  if (!fn)
2607  fn = getARCIntrinsic(llvm::Intrinsic::objc_destroyWeak, CGM);
2608 
2609  // Cast the argument to 'id*'.
2610  addr = Builder.CreateBitCast(addr, Int8PtrPtrTy);
2611 
2612  EmitNounwindRuntimeCall(fn, addr.getPointer());
2613 }
2614 
2615 /// void \@objc_moveWeak(i8** %dest, i8** %src)
2616 /// Disregards the current value in %dest. Leaves %src pointing to nothing.
2617 /// Essentially (objc_copyWeak(dest, src), objc_destroyWeak(src)).
2619  emitARCCopyOperation(*this, dst, src,
2621  llvm::Intrinsic::objc_moveWeak);
2622 }
2623 
2624 /// void \@objc_copyWeak(i8** %dest, i8** %src)
2625 /// Disregards the current value in %dest. Essentially
2626 /// objc_release(objc_initWeak(dest, objc_readWeakRetained(src)))
2628  emitARCCopyOperation(*this, dst, src,
2630  llvm::Intrinsic::objc_copyWeak);
2631 }
2632 
2634  Address SrcAddr) {
2635  llvm::Value *Object = EmitARCLoadWeakRetained(SrcAddr);
2636  Object = EmitObjCConsumeObject(Ty, Object);
2637  EmitARCStoreWeak(DstAddr, Object, false);
2638 }
2639 
2641  Address SrcAddr) {
2642  llvm::Value *Object = EmitARCLoadWeakRetained(SrcAddr);
2643  Object = EmitObjCConsumeObject(Ty, Object);
2644  EmitARCStoreWeak(DstAddr, Object, false);
2645  EmitARCDestroyWeak(SrcAddr);
2646 }
2647 
2648 /// Produce the code to do a objc_autoreleasepool_push.
2649 /// call i8* \@objc_autoreleasePoolPush(void)
2651  llvm::Function *&fn = CGM.getObjCEntrypoints().objc_autoreleasePoolPush;
2652  if (!fn)
2653  fn = getARCIntrinsic(llvm::Intrinsic::objc_autoreleasePoolPush, CGM);
2654 
2655  return EmitNounwindRuntimeCall(fn);
2656 }
2657 
2658 /// Produce the code to do a primitive release.
2659 /// call void \@objc_autoreleasePoolPop(i8* %ptr)
2661  assert(value->getType() == Int8PtrTy);
2662 
2663  if (getInvokeDest()) {
2664  // Call the runtime method not the intrinsic if we are handling exceptions
2665  llvm::FunctionCallee &fn =
2667  if (!fn) {
2668  llvm::FunctionType *fnType =
2669  llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrTy, false);
2670  fn = CGM.CreateRuntimeFunction(fnType, "objc_autoreleasePoolPop");
2672  }
2673 
2674  // objc_autoreleasePoolPop can throw.
2675  EmitRuntimeCallOrInvoke(fn, value);
2676  } else {
2677  llvm::FunctionCallee &fn = CGM.getObjCEntrypoints().objc_autoreleasePoolPop;
2678  if (!fn)
2679  fn = getARCIntrinsic(llvm::Intrinsic::objc_autoreleasePoolPop, CGM);
2680 
2681  EmitRuntimeCall(fn, value);
2682  }
2683 }
2684 
2685 /// Produce the code to do an MRR version objc_autoreleasepool_push.
2686 /// Which is: [[NSAutoreleasePool alloc] init];
2687 /// Where alloc is declared as: + (id) alloc; in NSAutoreleasePool class.
2688 /// init is declared as: - (id) init; in its NSObject super class.
2689 ///
2691  CGObjCRuntime &Runtime = CGM.getObjCRuntime();
2692  llvm::Value *Receiver = Runtime.EmitNSAutoreleasePoolClassRef(*this);
2693  // [NSAutoreleasePool alloc]
2694  IdentifierInfo *II = &CGM.getContext().Idents.get("alloc");
2695  Selector AllocSel = getContext().Selectors.getSelector(0, &II);
2696  CallArgList Args;
2697  RValue AllocRV =
2698  Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2699  getContext().getObjCIdType(),
2700  AllocSel, Receiver, Args);
2701 
2702  // [Receiver init]
2703  Receiver = AllocRV.getScalarVal();
2704  II = &CGM.getContext().Idents.get("init");
2705  Selector InitSel = getContext().Selectors.getSelector(0, &II);
2706  RValue InitRV =
2707  Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2708  getContext().getObjCIdType(),
2709  InitSel, Receiver, Args);
2710  return InitRV.getScalarVal();
2711 }
2712 
2713 /// Allocate the given objc object.
2714 /// call i8* \@objc_alloc(i8* %value)
2716  llvm::Type *resultType) {
2717  return emitObjCValueOperation(*this, value, resultType,
2719  "objc_alloc");
2720 }
2721 
2722 /// Allocate the given objc object.
2723 /// call i8* \@objc_allocWithZone(i8* %value)
2725  llvm::Type *resultType) {
2726  return emitObjCValueOperation(*this, value, resultType,
2728  "objc_allocWithZone");
2729 }
2730 
2732  llvm::Type *resultType) {
2733  return emitObjCValueOperation(*this, value, resultType,
2735  "objc_alloc_init");
2736 }
2737 
2738 /// Produce the code to do a primitive release.
2739 /// [tmp drain];
2741  IdentifierInfo *II = &CGM.getContext().Idents.get("drain");
2742  Selector DrainSel = getContext().Selectors.getSelector(0, &II);
2743  CallArgList Args;
2745  getContext().VoidTy, DrainSel, Arg, Args);
2746 }
2747 
2749  Address addr,
2750  QualType type) {
2752 }
2753 
2755  Address addr,
2756  QualType type) {
2758 }
2759 
2761  Address addr,
2762  QualType type) {
2763  CGF.EmitARCDestroyWeak(addr);
2764 }
2765 
2767  QualType type) {
2768  llvm::Value *value = CGF.Builder.CreateLoad(addr);
2769  CGF.EmitARCIntrinsicUse(value);
2770 }
2771 
2772 /// Autorelease the given object.
2773 /// call i8* \@objc_autorelease(i8* %value)
2775  llvm::Type *returnType) {
2776  return emitObjCValueOperation(
2777  *this, value, returnType,
2779  "objc_autorelease");
2780 }
2781 
2782 /// Retain the given object, with normal retain semantics.
2783 /// call i8* \@objc_retain(i8* %value)
2785  llvm::Type *returnType) {
2786  return emitObjCValueOperation(
2787  *this, value, returnType,
2789 }
2790 
2791 /// Release the given object.
2792 /// call void \@objc_release(i8* %value)
2794  ARCPreciseLifetime_t precise) {
2795  if (isa<llvm::ConstantPointerNull>(value)) return;
2796 
2797  llvm::FunctionCallee &fn =
2799  if (!fn) {
2800  llvm::FunctionType *fnType =
2801  llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrTy, false);
2802  fn = CGM.CreateRuntimeFunction(fnType, "objc_release");
2804  // We have Native ARC, so set nonlazybind attribute for performance
2805  if (llvm::Function *f = dyn_cast<llvm::Function>(fn.getCallee()))
2806  f->addFnAttr(llvm::Attribute::NonLazyBind);
2807  }
2808 
2809  // Cast the argument to 'id'.
2810  value = Builder.CreateBitCast(value, Int8PtrTy);
2811 
2812  // Call objc_release.
2813  llvm::CallBase *call = EmitCallOrInvoke(fn, value);
2814 
2815  if (precise == ARCImpreciseLifetime) {
2816  call->setMetadata("clang.imprecise_release",
2817  llvm::MDNode::get(Builder.getContext(), None));
2818  }
2819 }
2820 
2821 namespace {
2822  struct CallObjCAutoreleasePoolObject final : EHScopeStack::Cleanup {
2823  llvm::Value *Token;
2824 
2825  CallObjCAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2826 
2827  void Emit(CodeGenFunction &CGF, Flags flags) override {
2829  }
2830  };
2831  struct CallObjCMRRAutoreleasePoolObject final : EHScopeStack::Cleanup {
2832  llvm::Value *Token;
2833 
2834  CallObjCMRRAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2835 
2836  void Emit(CodeGenFunction &CGF, Flags flags) override {
2838  }
2839  };
2840 }
2841 
2843  if (CGM.getLangOpts().ObjCAutoRefCount)
2844  EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, Ptr);
2845  else
2846  EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, Ptr);
2847 }
2848 
2850  switch (lifetime) {
2851  case Qualifiers::OCL_None:
2855  return true;
2856 
2857  case Qualifiers::OCL_Weak:
2858  return false;
2859  }
2860 
2861  llvm_unreachable("impossible lifetime!");
2862 }
2863 
2865  LValue lvalue,
2866  QualType type) {
2867  llvm::Value *result;
2868  bool shouldRetain = shouldRetainObjCLifetime(type.getObjCLifetime());
2869  if (shouldRetain) {
2870  result = CGF.EmitLoadOfLValue(lvalue, SourceLocation()).getScalarVal();
2871  } else {
2872  assert(type.getObjCLifetime() == Qualifiers::OCL_Weak);
2873  result = CGF.EmitARCLoadWeakRetained(lvalue.getAddress(CGF));
2874  }
2875  return TryEmitResult(result, !shouldRetain);
2876 }
2877 
2879  const Expr *e) {
2880  e = e->IgnoreParens();
2881  QualType type = e->getType();
2882 
2883  // If we're loading retained from a __strong xvalue, we can avoid
2884  // an extra retain/release pair by zeroing out the source of this
2885  // "move" operation.
2886  if (e->isXValue() &&
2887  !type.isConstQualified() &&
2888  type.getObjCLifetime() == Qualifiers::OCL_Strong) {
2889  // Emit the lvalue.
2890  LValue lv = CGF.EmitLValue(e);
2891 
2892  // Load the object pointer.
2893  llvm::Value *result = CGF.EmitLoadOfLValue(lv,
2895 
2896  // Set the source pointer to NULL.
2898 
2899  return TryEmitResult(result, true);
2900  }
2901 
2902  // As a very special optimization, in ARC++, if the l-value is the
2903  // result of a non-volatile assignment, do a simple retain of the
2904  // result of the call to objc_storeWeak instead of reloading.
2905  if (CGF.getLangOpts().CPlusPlus &&
2906  !type.isVolatileQualified() &&
2907  type.getObjCLifetime() == Qualifiers::OCL_Weak &&
2908  isa<BinaryOperator>(e) &&
2909  cast<BinaryOperator>(e)->getOpcode() == BO_Assign)
2910  return TryEmitResult(CGF.EmitScalarExpr(e), false);
2911 
2912  // Try to emit code for scalar constant instead of emitting LValue and
2913  // loading it because we are not guaranteed to have an l-value. One of such
2914  // cases is DeclRefExpr referencing non-odr-used constant-evaluated variable.
2915  if (const auto *decl_expr = dyn_cast<DeclRefExpr>(e)) {
2916  auto *DRE = const_cast<DeclRefExpr *>(decl_expr);
2917  if (CodeGenFunction::ConstantEmission constant = CGF.tryEmitAsConstant(DRE))
2918  return TryEmitResult(CGF.emitScalarConstant(constant, DRE),
2919  !shouldRetainObjCLifetime(type.getObjCLifetime()));
2920  }
2921 
2922  return tryEmitARCRetainLoadOfScalar(CGF, CGF.EmitLValue(e), type);
2923 }
2924 
2925 typedef llvm::function_ref<llvm::Value *(CodeGenFunction &CGF,
2926  llvm::Value *value)>
2928 
2929 /// Insert code immediately after a call.
2930 
2931 // FIXME: We should find a way to emit the runtime call immediately
2932 // after the call is emitted to eliminate the need for this function.
2934  llvm::Value *value,
2935  ValueTransform doAfterCall,
2936  ValueTransform doFallback) {
2937  CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2938  auto *callBase = dyn_cast<llvm::CallBase>(value);
2939 
2940  if (callBase && llvm::objcarc::hasAttachedCallOpBundle(callBase)) {
2941  // Fall back if the call base has operand bundle "clang.arc.attachedcall".
2942  value = doFallback(CGF, value);
2943  } else if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(value)) {
2944  // Place the retain immediately following the call.
2945  CGF.Builder.SetInsertPoint(call->getParent(),
2946  ++llvm::BasicBlock::iterator(call));
2947  value = doAfterCall(CGF, value);
2948  } else if (llvm::InvokeInst *invoke = dyn_cast<llvm::InvokeInst>(value)) {
2949  // Place the retain at the beginning of the normal destination block.
2950  llvm::BasicBlock *BB = invoke->getNormalDest();
2951  CGF.Builder.SetInsertPoint(BB, BB->begin());
2952  value = doAfterCall(CGF, value);
2953 
2954  // Bitcasts can arise because of related-result returns. Rewrite
2955  // the operand.
2956  } else if (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(value)) {
2957  // Change the insert point to avoid emitting the fall-back call after the
2958  // bitcast.
2959  CGF.Builder.SetInsertPoint(bitcast->getParent(), bitcast->getIterator());
2960  llvm::Value *operand = bitcast->getOperand(0);
2961  operand = emitARCOperationAfterCall(CGF, operand, doAfterCall, doFallback);
2962  bitcast->setOperand(0, operand);
2963  value = bitcast;
2964  } else {
2965  auto *phi = dyn_cast<llvm::PHINode>(value);
2966  if (phi && phi->getNumIncomingValues() == 2 &&
2967  isa<llvm::ConstantPointerNull>(phi->getIncomingValue(1)) &&
2968  isa<llvm::CallBase>(phi->getIncomingValue(0))) {
2969  // Handle phi instructions that are generated when it's necessary to check
2970  // whether the receiver of a message is null.
2971  llvm::Value *inVal = phi->getIncomingValue(0);
2972  inVal = emitARCOperationAfterCall(CGF, inVal, doAfterCall, doFallback);
2973  phi->setIncomingValue(0, inVal);
2974  value = phi;
2975  } else {
2976  // Generic fall-back case.
2977  // Retain using the non-block variant: we never need to do a copy
2978  // of a block that's been returned to us.
2979  value = doFallback(CGF, value);
2980  }
2981  }
2982 
2983  CGF.Builder.restoreIP(ip);
2984  return value;
2985 }
2986 
2987 /// Given that the given expression is some sort of call (which does
2988 /// not return retained), emit a retain following it.
2990  const Expr *e) {
2991  llvm::Value *value = CGF.EmitScalarExpr(e);
2992  return emitARCOperationAfterCall(CGF, value,
2993  [](CodeGenFunction &CGF, llvm::Value *value) {
2994  return CGF.EmitARCRetainAutoreleasedReturnValue(value);
2995  },
2996  [](CodeGenFunction &CGF, llvm::Value *value) {
2997  return CGF.EmitARCRetainNonBlock(value);
2998  });
2999 }
3000 
3001 /// Given that the given expression is some sort of call (which does
3002 /// not return retained), perform an unsafeClaim following it.
3004  const Expr *e) {
3005  llvm::Value *value = CGF.EmitScalarExpr(e);
3006  return emitARCOperationAfterCall(CGF, value,
3007  [](CodeGenFunction &CGF, llvm::Value *value) {
3009  },
3010  [](CodeGenFunction &CGF, llvm::Value *value) {
3011  return value;
3012  });
3013 }
3014 
3016  bool allowUnsafeClaim) {
3017  if (allowUnsafeClaim &&
3019  return emitARCUnsafeClaimCallResult(*this, E);
3020  } else {
3021  llvm::Value *value = emitARCRetainCallResult(*this, E);
3022  return EmitObjCConsumeObject(E->getType(), value);
3023  }
3024 }
3025 
3026 /// Determine whether it might be important to emit a separate
3027 /// objc_retain_block on the result of the given expression, or
3028 /// whether it's okay to just emit it in a +1 context.
3029 static bool shouldEmitSeparateBlockRetain(const Expr *e) {
3030  assert(e->getType()->isBlockPointerType());
3031  e = e->IgnoreParens();
3032 
3033  // For future goodness, emit block expressions directly in +1
3034  // contexts if we can.
3035  if (isa<BlockExpr>(e))
3036  return false;
3037 
3038  if (const CastExpr *cast = dyn_cast<CastExpr>(e)) {
3039  switch (cast->getCastKind()) {
3040  // Emitting these operations in +1 contexts is goodness.
3041  case CK_LValueToRValue:
3042  case CK_ARCReclaimReturnedObject:
3043  case CK_ARCConsumeObject:
3044  case CK_ARCProduceObject:
3045  return false;
3046 
3047  // These operations preserve a block type.
3048  case CK_NoOp:
3049  case CK_BitCast:
3050  return shouldEmitSeparateBlockRetain(cast->getSubExpr());
3051 
3052  // These operations are known to be bad (or haven't been considered).
3053  case CK_AnyPointerToBlockPointerCast:
3054  default:
3055  return true;
3056  }
3057  }
3058 
3059  return true;
3060 }
3061 
3062 namespace {
3063 /// A CRTP base class for emitting expressions of retainable object
3064 /// pointer type in ARC.
3065 template <typename Impl, typename Result> class ARCExprEmitter {
3066 protected:
3067  CodeGenFunction &CGF;
3068  Impl &asImpl() { return *static_cast<Impl*>(this); }
3069 
3070  ARCExprEmitter(CodeGenFunction &CGF) : CGF(CGF) {}
3071 
3072 public:
3073  Result visit(const Expr *e);
3074  Result visitCastExpr(const CastExpr *e);
3075  Result visitPseudoObjectExpr(const PseudoObjectExpr *e);
3076  Result visitBlockExpr(const BlockExpr *e);
3077  Result visitBinaryOperator(const BinaryOperator *e);
3078  Result visitBinAssign(const BinaryOperator *e);
3079  Result visitBinAssignUnsafeUnretained(const BinaryOperator *e);
3080  Result visitBinAssignAutoreleasing(const BinaryOperator *e);
3081  Result visitBinAssignWeak(const BinaryOperator *e);
3082  Result visitBinAssignStrong(const BinaryOperator *e);
3083 
3084  // Minimal implementation:
3085  // Result visitLValueToRValue(const Expr *e)
3086  // Result visitConsumeObject(const Expr *e)
3087  // Result visitExtendBlockObject(const Expr *e)
3088  // Result visitReclaimReturnedObject(const Expr *e)
3089  // Result visitCall(const Expr *e)
3090  // Result visitExpr(const Expr *e)
3091  //
3092  // Result emitBitCast(Result result, llvm::Type *resultType)
3093  // llvm::Value *getValueOfResult(Result result)
3094 };
3095 }
3096 
3097 /// Try to emit a PseudoObjectExpr under special ARC rules.
3098 ///
3099 /// This massively duplicates emitPseudoObjectRValue.
3100 template <typename Impl, typename Result>
3101 Result
3102 ARCExprEmitter<Impl,Result>::visitPseudoObjectExpr(const PseudoObjectExpr *E) {
3104 
3105  // Find the result expression.
3106  const Expr *resultExpr = E->getResultExpr();
3107  assert(resultExpr);
3108  Result result;
3109 
3111  i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
3112  const Expr *semantic = *i;
3113 
3114  // If this semantic expression is an opaque value, bind it
3115  // to the result of its source expression.
3116  if (const OpaqueValueExpr *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
3118  OVMA opaqueData;
3119 
3120  // If this semantic is the result of the pseudo-object
3121  // expression, try to evaluate the source as +1.
3122  if (ov == resultExpr) {
3123  assert(!OVMA::shouldBindAsLValue(ov));
3124  result = asImpl().visit(ov->getSourceExpr());
3125  opaqueData = OVMA::bind(CGF, ov,
3126  RValue::get(asImpl().getValueOfResult(result)));
3127 
3128  // Otherwise, just bind it.
3129  } else {
3130  opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
3131  }
3132  opaques.push_back(opaqueData);
3133 
3134  // Otherwise, if the expression is the result, evaluate it
3135  // and remember the result.
3136  } else if (semantic == resultExpr) {
3137  result = asImpl().visit(semantic);
3138 
3139  // Otherwise, evaluate the expression in an ignored context.
3140  } else {
3141  CGF.EmitIgnoredExpr(semantic);
3142  }
3143  }
3144 
3145  // Unbind all the opaques now.
3146  for (unsigned i = 0, e = opaques.size(); i != e; ++i)
3147  opaques[i].unbind(CGF);
3148 
3149  return result;
3150 }
3151 
3152 template <typename Impl, typename Result>
3153 Result ARCExprEmitter<Impl, Result>::visitBlockExpr(const BlockExpr *e) {
3154  // The default implementation just forwards the expression to visitExpr.
3155  return asImpl().visitExpr(e);
3156 }
3157 
3158 template <typename Impl, typename Result>
3159 Result ARCExprEmitter<Impl,Result>::visitCastExpr(const CastExpr *e) {
3160  switch (e->getCastKind()) {
3161 
3162  // No-op casts don't change the type, so we just ignore them.
3163  case CK_NoOp:
3164  return asImpl().visit(e->getSubExpr());
3165 
3166  // These casts can change the type.
3167  case CK_CPointerToObjCPointerCast:
3168  case CK_BlockPointerToObjCPointerCast:
3169  case CK_AnyPointerToBlockPointerCast:
3170  case CK_BitCast: {
3171  llvm::Type *resultType = CGF.ConvertType(e->getType());
3172  assert(e->getSubExpr()->getType()->hasPointerRepresentation());
3173  Result result = asImpl().visit(e->getSubExpr());
3174  return asImpl().emitBitCast(result, resultType);
3175  }
3176 
3177  // Handle some casts specially.
3178  case CK_LValueToRValue:
3179  return asImpl().visitLValueToRValue(e->getSubExpr());
3180  case CK_ARCConsumeObject:
3181  return asImpl().visitConsumeObject(e->getSubExpr());
3182  case CK_ARCExtendBlockObject:
3183  return asImpl().visitExtendBlockObject(e->getSubExpr());
3184  case CK_ARCReclaimReturnedObject:
3185  return asImpl().visitReclaimReturnedObject(e->getSubExpr());
3186 
3187  // Otherwise, use the default logic.
3188  default:
3189  return asImpl().visitExpr(e);
3190  }
3191 }
3192 
3193 template <typename Impl, typename Result>
3194 Result
3195 ARCExprEmitter<Impl,Result>::visitBinaryOperator(const BinaryOperator *e) {
3196  switch (e->getOpcode()) {
3197  case BO_Comma:
3198  CGF.EmitIgnoredExpr(e->getLHS());
3199  CGF.EnsureInsertPoint();
3200  return asImpl().visit(e->getRHS());
3201 
3202  case BO_Assign:
3203  return asImpl().visitBinAssign(e);
3204 
3205  default:
3206  return asImpl().visitExpr(e);
3207  }
3208 }
3209 
3210 template <typename Impl, typename Result>
3211 Result ARCExprEmitter<Impl,Result>::visitBinAssign(const BinaryOperator *e) {
3212  switch (e->getLHS()->getType().getObjCLifetime()) {
3214  return asImpl().visitBinAssignUnsafeUnretained(e);
3215 
3216  case Qualifiers::OCL_Weak:
3217  return asImpl().visitBinAssignWeak(e);
3218 
3220  return asImpl().visitBinAssignAutoreleasing(e);
3221 
3223  return asImpl().visitBinAssignStrong(e);
3224 
3225  case Qualifiers::OCL_None:
3226  return asImpl().visitExpr(e);
3227  }
3228  llvm_unreachable("bad ObjC ownership qualifier");
3229 }
3230 
3231 /// The default rule for __unsafe_unretained emits the RHS recursively,
3232 /// stores into the unsafe variable, and propagates the result outward.
3233 template <typename Impl, typename Result>
3234 Result ARCExprEmitter<Impl,Result>::
3235  visitBinAssignUnsafeUnretained(const BinaryOperator *e) {
3236  // Recursively emit the RHS.
3237  // For __block safety, do this before emitting the LHS.
3238  Result result = asImpl().visit(e->getRHS());
3239 
3240  // Perform the store.
3241  LValue lvalue =
3242  CGF.EmitCheckedLValue(e->getLHS(), CodeGenFunction::TCK_Store);
3243  CGF.EmitStoreThroughLValue(RValue::get(asImpl().getValueOfResult(result)),
3244  lvalue);
3245 
3246  return result;
3247 }
3248 
3249 template <typename Impl, typename Result>
3250 Result
3251 ARCExprEmitter<Impl,Result>::visitBinAssignAutoreleasing(const BinaryOperator *e) {
3252  return asImpl().visitExpr(e);
3253 }
3254 
3255 template <typename Impl, typename Result>
3256 Result
3257 ARCExprEmitter<Impl,Result>::visitBinAssignWeak(const BinaryOperator *e) {
3258  return asImpl().visitExpr(e);
3259 }
3260 
3261 template <typename Impl, typename Result>
3262 Result
3263 ARCExprEmitter<Impl,Result>::visitBinAssignStrong(const BinaryOperator *e) {
3264  return asImpl().visitExpr(e);
3265 }
3266 
3267 /// The general expression-emission logic.
3268 template <typename Impl, typename Result>
3269 Result ARCExprEmitter<Impl,Result>::visit(const Expr *e) {
3270  // We should *never* see a nested full-expression here, because if
3271  // we fail to emit at +1, our caller must not retain after we close
3272  // out the full-expression. This isn't as important in the unsafe
3273  // emitter.
3274  assert(!isa<ExprWithCleanups>(e));
3275 
3276  // Look through parens, __extension__, generic selection, etc.
3277  e = e->IgnoreParens();
3278 
3279  // Handle certain kinds of casts.
3280  if (const CastExpr *ce = dyn_cast<CastExpr>(e)) {
3281  return asImpl().visitCastExpr(ce);
3282 
3283  // Handle the comma operator.
3284  } else if (auto op = dyn_cast<BinaryOperator>(e)) {
3285  return asImpl().visitBinaryOperator(op);
3286 
3287  // TODO: handle conditional operators here
3288 
3289  // For calls and message sends, use the retained-call logic.
3290  // Delegate inits are a special case in that they're the only
3291  // returns-retained expression that *isn't* surrounded by
3292  // a consume.
3293  } else if (isa<CallExpr>(e) ||
3294  (isa<ObjCMessageExpr>(e) &&
3295  !cast<ObjCMessageExpr>(e)->isDelegateInitCall())) {
3296  return asImpl().visitCall(e);
3297 
3298  // Look through pseudo-object expressions.
3299  } else if (const PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
3300  return asImpl().visitPseudoObjectExpr(pseudo);
3301  } else if (auto *be = dyn_cast<BlockExpr>(e))
3302  return asImpl().visitBlockExpr(be);
3303 
3304  return asImpl().visitExpr(e);
3305 }
3306 
3307 namespace {
3308 
3309 /// An emitter for +1 results.
3310 struct ARCRetainExprEmitter :
3311  public ARCExprEmitter<ARCRetainExprEmitter, TryEmitResult> {
3312 
3313  ARCRetainExprEmitter(CodeGenFunction &CGF) : ARCExprEmitter(CGF) {}
3314 
3315  llvm::Value *getValueOfResult(TryEmitResult result) {
3316  return result.getPointer();
3317  }
3318 
3319  TryEmitResult emitBitCast(TryEmitResult result, llvm::Type *resultType) {
3320  llvm::Value *value = result.getPointer();
3321  value = CGF.Builder.CreateBitCast(value, resultType);
3322  result.setPointer(value);
3323  return result;
3324  }
3325 
3326  TryEmitResult visitLValueToRValue(const Expr *e) {
3327  return tryEmitARCRetainLoadOfScalar(CGF, e);
3328  }
3329 
3330  /// For consumptions, just emit the subexpression and thus elide
3331  /// the retain/release pair.
3332  TryEmitResult visitConsumeObject(const Expr *e) {
3333  llvm::Value *result = CGF.EmitScalarExpr(e);
3334  return TryEmitResult(result, true);
3335  }
3336 
3337  TryEmitResult visitBlockExpr(const BlockExpr *e) {
3338  TryEmitResult result = visitExpr(e);
3339  // Avoid the block-retain if this is a block literal that doesn't need to be
3340  // copied to the heap.
3341  if (CGF.CGM.getCodeGenOpts().ObjCAvoidHeapifyLocalBlocks &&
3343  result.setInt(true);
3344  return result;
3345  }
3346 
3347  /// Block extends are net +0. Naively, we could just recurse on
3348  /// the subexpression, but actually we need to ensure that the
3349  /// value is copied as a block, so there's a little filter here.
3350  TryEmitResult visitExtendBlockObject(const Expr *e) {
3351  llvm::Value *result; // will be a +0 value
3352 
3353  // If we can't safely assume the sub-expression will produce a
3354  // block-copied value, emit the sub-expression at +0.
3356  result = CGF.EmitScalarExpr(e);
3357 
3358  // Otherwise, try to emit the sub-expression at +1 recursively.
3359  } else {
3360  TryEmitResult subresult = asImpl().visit(e);
3361 
3362  // If that produced a retained value, just use that.
3363  if (subresult.getInt()) {
3364  return subresult;
3365  }
3366 
3367  // Otherwise it's +0.
3368  result = subresult.getPointer();
3369  }
3370 
3371  // Retain the object as a block.
3372  result = CGF.EmitARCRetainBlock(result, /*mandatory*/ true);
3373  return TryEmitResult(result, true);
3374  }
3375 
3376  /// For reclaims, emit the subexpression as a retained call and
3377  /// skip the consumption.
3378  TryEmitResult visitReclaimReturnedObject(const Expr *e) {
3379  llvm::Value *result = emitARCRetainCallResult(CGF, e);
3380  return TryEmitResult(result, true);
3381  }
3382 
3383  /// When we have an undecorated call, retroactively do a claim.
3384  TryEmitResult visitCall(const Expr *e) {
3385  llvm::Value *result = emitARCRetainCallResult(CGF, e);
3386  return TryEmitResult(result, true);
3387  }
3388 
3389  // TODO: maybe special-case visitBinAssignWeak?
3390 
3391  TryEmitResult visitExpr(const Expr *e) {
3392  // We didn't find an obvious production, so emit what we've got and
3393  // tell the caller that we didn't manage to retain.
3394  llvm::Value *result = CGF.EmitScalarExpr(e);
3395  return TryEmitResult(result, false);
3396  }
3397 };
3398 }
3399 
3400 static TryEmitResult
3402  return ARCRetainExprEmitter(CGF).visit(e);
3403 }
3404 
3406  LValue lvalue,
3407  QualType type) {
3408  TryEmitResult result = tryEmitARCRetainLoadOfScalar(CGF, lvalue, type);
3409  llvm::Value *value = result.getPointer();
3410  if (!result.getInt())
3411  value = CGF.EmitARCRetain(type, value);
3412  return value;
3413 }
3414 
3415 /// EmitARCRetainScalarExpr - Semantically equivalent to
3416 /// EmitARCRetainObject(e->getType(), EmitScalarExpr(e)), but making a
3417 /// best-effort attempt to peephole expressions that naturally produce
3418 /// retained objects.
3420  // The retain needs to happen within the full-expression.
3421  if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
3422  RunCleanupsScope scope(*this);
3423  return EmitARCRetainScalarExpr(cleanups->getSubExpr());
3424  }
3425 
3426  TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
3427  llvm::Value *value = result.getPointer();
3428  if (!result.getInt())
3429  value = EmitARCRetain(e->getType(), value);
3430  return value;
3431 }
3432 
3433 llvm::Value *
3435  // The retain needs to happen within the full-expression.
3436  if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
3437  RunCleanupsScope scope(*this);
3438  return EmitARCRetainAutoreleaseScalarExpr(cleanups->getSubExpr());
3439  }
3440 
3441  TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
3442  llvm::Value *value = result.getPointer();
3443  if (result.getInt())
3444  value = EmitARCAutorelease(value);
3445  else
3446  value = EmitARCRetainAutorelease(e->getType(), value);
3447  return value;
3448 }
3449 
3451  llvm::Value *result;
3452  bool doRetain;
3453 
3455  result = EmitScalarExpr(e);
3456  doRetain = true;
3457  } else {
3458  TryEmitResult subresult = tryEmitARCRetainScalarExpr(*this, e);
3459  result = subresult.getPointer();
3460  doRetain = !subresult.getInt();
3461  }
3462 
3463  if (doRetain)
3464  result = EmitARCRetainBlock(result, /*mandatory*/ true);
3465  return EmitObjCConsumeObject(e->getType(), result);
3466 }
3467 
3469  // In ARC, retain and autorelease the expression.
3470  if (getLangOpts().ObjCAutoRefCount) {
3471  // Do so before running any cleanups for the full-expression.
3472  // EmitARCRetainAutoreleaseScalarExpr does this for us.
3474  }
3475 
3476  // Otherwise, use the normal scalar-expression emission. The
3477  // exception machinery doesn't do anything special with the
3478  // exception like retaining it, so there's no safety associated with
3479  // only running cleanups after the throw has started, and when it
3480  // matters it tends to be substantially inferior code.
3481  return EmitScalarExpr(expr);
3482 }
3483 
3484 namespace {
3485 
3486 /// An emitter for assigning into an __unsafe_unretained context.
3487 struct ARCUnsafeUnretainedExprEmitter :
3488  public ARCExprEmitter<ARCUnsafeUnretainedExprEmitter, llvm::Value*> {
3489 
3490  ARCUnsafeUnretainedExprEmitter(CodeGenFunction &CGF) : ARCExprEmitter(CGF) {}
3491 
3492  llvm::Value *getValueOfResult(llvm::Value *value) {
3493  return value;
3494  }
3495 
3496  llvm::Value *emitBitCast(llvm::Value *value, llvm::Type *resultType) {
3497  return CGF.Builder.CreateBitCast(value, resultType);
3498  }
3499 
3500  llvm::Value *visitLValueToRValue(const Expr *e) {
3501  return CGF.EmitScalarExpr(e);
3502  }
3503 
3504  /// For consumptions, just emit the subexpression and perform the
3505  /// consumption like normal.
3506  llvm::Value *visitConsumeObject(const Expr *e) {
3507  llvm::Value *value = CGF.EmitScalarExpr(e);
3508  return CGF.EmitObjCConsumeObject(e->getType(), value);
3509  }
3510 
3511  /// No special logic for block extensions. (This probably can't
3512  /// actually happen in this emitter, though.)
3513  llvm::Value *visitExtendBlockObject(const Expr *e) {
3514  return CGF.EmitARCExtendBlockObject(e);
3515  }
3516 
3517  /// For reclaims, perform an unsafeClaim if that's enabled.
3518  llvm::Value *visitReclaimReturnedObject(const Expr *e) {
3519  return CGF.EmitARCReclaimReturnedObject(e, /*unsafe*/ true);
3520  }
3521 
3522  /// When we have an undecorated call, just emit it without adding
3523  /// the unsafeClaim.
3524  llvm::Value *visitCall(const Expr *e) {
3525  return CGF.EmitScalarExpr(e);
3526  }
3527 
3528  /// Just do normal scalar emission in the default case.
3529  llvm::Value *visitExpr(const Expr *e) {
3530  return CGF.EmitScalarExpr(e);
3531  }
3532 };
3533 }
3534 
3536  const Expr *e) {
3537  return ARCUnsafeUnretainedExprEmitter(CGF).visit(e);
3538 }
3539 
3540 /// EmitARCUnsafeUnretainedScalarExpr - Semantically equivalent to
3541 /// immediately releasing the resut of EmitARCRetainScalarExpr, but
3542 /// avoiding any spurious retains, including by performing reclaims
3543 /// with objc_unsafeClaimAutoreleasedReturnValue.
3545  // Look through full-expressions.
3546  if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
3547  RunCleanupsScope scope(*this);
3548  return emitARCUnsafeUnretainedScalarExpr(*this, cleanups->getSubExpr());
3549  }
3550 
3551  return emitARCUnsafeUnretainedScalarExpr(*this, e);
3552 }
3553 
3554 std::pair<LValue,llvm::Value*>
3556  bool ignored) {
3557  // Evaluate the RHS first. If we're ignoring the result, assume
3558  // that we can emit at an unsafe +0.
3559  llvm::Value *value;
3560  if (ignored) {
3562  } else {
3563  value = EmitScalarExpr(e->getRHS());
3564  }
3565 
3566  // Emit the LHS and perform the store.
3567  LValue lvalue = EmitLValue(e->getLHS());
3568  EmitStoreOfScalar(value, lvalue);
3569 
3570  return std::pair<LValue,llvm::Value*>(std::move(lvalue), value);
3571 }
3572 
3573 std::pair<LValue,llvm::Value*>
3575  bool ignored) {
3576  // Evaluate the RHS first.
3577  TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e->getRHS());
3578  llvm::Value *value = result.getPointer();
3579 
3580  bool hasImmediateRetain = result.getInt();
3581 
3582  // If we didn't emit a retained object, and the l-value is of block
3583  // type, then we need to emit the block-retain immediately in case
3584  // it invalidates the l-value.
3585  if (!hasImmediateRetain && e->getType()->isBlockPointerType()) {
3586  value = EmitARCRetainBlock(value, /*mandatory*/ false);
3587  hasImmediateRetain = true;
3588  }
3589 
3590  LValue lvalue = EmitLValue(e->getLHS());
3591 
3592  // If the RHS was emitted retained, expand this.
3593  if (hasImmediateRetain) {
3594  llvm::Value *oldValue = EmitLoadOfScalar(lvalue, SourceLocation());
3595  EmitStoreOfScalar(value, lvalue);
3596  EmitARCRelease(oldValue, lvalue.isARCPreciseLifetime());
3597  } else {
3598  value = EmitARCStoreStrong(lvalue, value, ignored);
3599  }
3600 
3601  return std::pair<LValue,llvm::Value*>(lvalue, value);
3602 }
3603 
3604 std::pair<LValue,llvm::Value*>
3607  LValue lvalue = EmitLValue(e->getLHS());
3608 
3609  EmitStoreOfScalar(value, lvalue);
3610 
3611  return std::pair<LValue,llvm::Value*>(lvalue, value);
3612 }
3613 
3615  const ObjCAutoreleasePoolStmt &ARPS) {
3616  const Stmt *subStmt = ARPS.getSubStmt();
3617  const CompoundStmt &S = cast<CompoundStmt>(*subStmt);
3618 
3619  CGDebugInfo *DI = getDebugInfo();
3620  if (DI)
3621  DI->EmitLexicalBlockStart(Builder, S.getLBracLoc());
3622 
3623  // Keep track of the current cleanup stack depth.
3624  RunCleanupsScope Scope(*this);
3627  EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, token);
3628  } else {
3630  EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, token);
3631  }
3632 
3633  for (const auto *I : S.body())
3634  EmitStmt(I);
3635 
3636  if (DI)
3637  DI->EmitLexicalBlockEnd(Builder, S.getRBracLoc());
3638 }
3639 
3640 /// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
3641 /// make sure it survives garbage collection until this point.
3643  // We just use an inline assembly.
3644  llvm::FunctionType *extenderType
3645  = llvm::FunctionType::get(VoidTy, VoidPtrTy, RequiredArgs::All);
3646  llvm::InlineAsm *extender = llvm::InlineAsm::get(extenderType,
3647  /* assembly */ "",
3648  /* constraints */ "r",
3649  /* side effects */ true);
3650 
3651  object = Builder.CreateBitCast(object, VoidPtrTy);
3652  EmitNounwindRuntimeCall(extender, object);
3653 }
3654 
3655 /// GenerateObjCAtomicSetterCopyHelperFunction - Given a c++ object type with
3656 /// non-trivial copy assignment function, produce following helper function.
3657 /// static void copyHelper(Ty *dest, const Ty *source) { *dest = *source; }
3658 ///
3659 llvm::Constant *
3661  const ObjCPropertyImplDecl *PID) {
3662  if (!getLangOpts().CPlusPlus ||
3664  return nullptr;
3665  QualType Ty = PID->getPropertyIvarDecl()->getType();
3666  if (!Ty->isRecordType())
3667  return nullptr;
3668  const ObjCPropertyDecl *PD = PID->getPropertyDecl();
3670  return nullptr;
3671  llvm::Constant *HelperFn = nullptr;
3672  if (hasTrivialSetExpr(PID))
3673  return nullptr;
3674  assert(PID->getSetterCXXAssignment() && "SetterCXXAssignment - null");
3675  if ((HelperFn = CGM.getAtomicSetterHelperFnMap(Ty)))
3676  return HelperFn;
3677 
3678  ASTContext &C = getContext();
3679  IdentifierInfo *II
3680  = &CGM.getContext().Idents.get("__assign_helper_atomic_property_");
3681 
3682  QualType ReturnTy = C.VoidTy;
3683  QualType DestTy = C.getPointerType(Ty);
3684  QualType SrcTy = Ty;
3685  SrcTy.addConst();
3686  SrcTy = C.getPointerType(SrcTy);
3687 
3688  SmallVector<QualType, 2> ArgTys;
3689  ArgTys.push_back(DestTy);
3690  ArgTys.push_back(SrcTy);
3691  QualType FunctionTy = C.getFunctionType(ReturnTy, ArgTys, {});
3692 
3694  C, C.getTranslationUnitDecl(), SourceLocation(), SourceLocation(), II,
3695  FunctionTy, nullptr, SC_Static, false, false, false);
3696 
3697  FunctionArgList args;
3698  ParmVarDecl *Params[2];
3699  ParmVarDecl *DstDecl = ParmVarDecl::Create(
3700  C, FD, SourceLocation(), SourceLocation(), nullptr, DestTy,
3701  C.getTrivialTypeSourceInfo(DestTy, SourceLocation()), SC_None,
3702  /*DefArg=*/nullptr);
3703  args.push_back(Params[0] = DstDecl);
3704  ParmVarDecl *SrcDecl = ParmVarDecl::Create(
3705  C, FD, SourceLocation(), SourceLocation(), nullptr, SrcTy,
3706  C.getTrivialTypeSourceInfo(SrcTy, SourceLocation()), SC_None,
3707  /*DefArg=*/nullptr);
3708  args.push_back(Params[1] = SrcDecl);
3709  FD->setParams(Params);
3710 
3711  const CGFunctionInfo &FI =
3713 
3714  llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
3715 
3716  llvm::Function *Fn =
3717  llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
3718  "__assign_helper_atomic_property_",
3719  &CGM.getModule());
3720 
3722 
3723  StartFunction(FD, ReturnTy, Fn, FI, args);
3724 
3725  DeclRefExpr DstExpr(C, DstDecl, false, DestTy, VK_PRValue, SourceLocation());
3727  C, &DstExpr, UO_Deref, DestTy->getPointeeType(), VK_LValue, OK_Ordinary,
3728  SourceLocation(), false, FPOptionsOverride());
3729 
3730  DeclRefExpr SrcExpr(C, SrcDecl, false, SrcTy, VK_PRValue, SourceLocation());
3732  C, &SrcExpr, UO_Deref, SrcTy->getPointeeType(), VK_LValue, OK_Ordinary,
3733  SourceLocation(), false, FPOptionsOverride());
3734 
3735  Expr *Args[2] = {DST, SRC};
3736  CallExpr *CalleeExp = cast<CallExpr>(PID->getSetterCXXAssignment());
3738  C, OO_Equal, CalleeExp->getCallee(), Args, DestTy->getPointeeType(),
3740 
3741  EmitStmt(TheCall);
3742 
3743  FinishFunction();
3744  HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
3745  CGM.setAtomicSetterHelperFnMap(Ty, HelperFn);
3746  return HelperFn;
3747 }
3748 
3749 llvm::Constant *
3751  const ObjCPropertyImplDecl *PID) {
3752  if (!getLangOpts().CPlusPlus ||
3754  return nullptr;
3755  const ObjCPropertyDecl *PD = PID->getPropertyDecl();
3756  QualType Ty = PD->getType();
3757  if (!Ty->isRecordType())
3758  return nullptr;
3760  return nullptr;
3761  llvm::Constant *HelperFn = nullptr;
3762  if (hasTrivialGetExpr(PID))
3763  return nullptr;
3764  assert(PID->getGetterCXXConstructor() && "getGetterCXXConstructor - null");
3765  if ((HelperFn = CGM.getAtomicGetterHelperFnMap(Ty)))
3766  return HelperFn;
3767 
3768  ASTContext &C = getContext();
3769  IdentifierInfo *II =
3770  &CGM.getContext().Idents.get("__copy_helper_atomic_property_");
3771 
3772  QualType ReturnTy = C.VoidTy;
3773  QualType DestTy = C.getPointerType(Ty);
3774  QualType SrcTy = Ty;
3775  SrcTy.addConst();
3776  SrcTy = C.getPointerType(SrcTy);
3777 
3778  SmallVector<QualType, 2> ArgTys;
3779  ArgTys.push_back(DestTy);
3780  ArgTys.push_back(SrcTy);
3781  QualType FunctionTy = C.getFunctionType(ReturnTy, ArgTys, {});
3782 
3784  C, C.getTranslationUnitDecl(), SourceLocation(), SourceLocation(), II,
3785  FunctionTy, nullptr, SC_Static, false, false, false);
3786 
3787  FunctionArgList args;
3788  ParmVarDecl *Params[2];
3789  ParmVarDecl *DstDecl = ParmVarDecl::Create(
3790  C, FD, SourceLocation(), SourceLocation(), nullptr, DestTy,
3791  C.getTrivialTypeSourceInfo(DestTy, SourceLocation()), SC_None,
3792  /*DefArg=*/nullptr);
3793  args.push_back(Params[0] = DstDecl);
3794  ParmVarDecl *SrcDecl = ParmVarDecl::Create(
3795  C, FD, SourceLocation(), SourceLocation(), nullptr, SrcTy,
3796  C.getTrivialTypeSourceInfo(SrcTy, SourceLocation()), SC_None,
3797  /*DefArg=*/nullptr);
3798  args.push_back(Params[1] = SrcDecl);
3799  FD->setParams(Params);
3800 
3801  const CGFunctionInfo &FI =
3803 
3804  llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
3805 
3806  llvm::Function *Fn = llvm::Function::Create(
3807  LTy, llvm::GlobalValue::InternalLinkage, "__copy_helper_atomic_property_",
3808  &CGM.getModule());
3809 
3811 
3812  StartFunction(FD, ReturnTy, Fn, FI, args);
3813 
3814  DeclRefExpr SrcExpr(getContext(), SrcDecl, false, SrcTy, VK_PRValue,
3815  SourceLocation());
3816 
3818  C, &SrcExpr, UO_Deref, SrcTy->getPointeeType(), VK_LValue, OK_Ordinary,
3819  SourceLocation(), false, FPOptionsOverride());
3820 
3821  CXXConstructExpr *CXXConstExpr =
3822  cast<CXXConstructExpr>(PID->getGetterCXXConstructor());
3823 
3824  SmallVector<Expr*, 4> ConstructorArgs;
3825  ConstructorArgs.push_back(SRC);
3826  ConstructorArgs.append(std::next(CXXConstExpr->arg_begin()),
3827  CXXConstExpr->arg_end());
3828 
3829  CXXConstructExpr *TheCXXConstructExpr =
3831  CXXConstExpr->getConstructor(),
3832  CXXConstExpr->isElidable(),
3833  ConstructorArgs,
3834  CXXConstExpr->hadMultipleCandidates(),
3835  CXXConstExpr->isListInitialization(),
3836  CXXConstExpr->isStdInitListInitialization(),
3837  CXXConstExpr->requiresZeroInitialization(),
3838  CXXConstExpr->getConstructionKind(),
3839  SourceRange());
3840 
3841  DeclRefExpr DstExpr(getContext(), DstDecl, false, DestTy, VK_PRValue,
3842  SourceLocation());
3843 
3844  RValue DV = EmitAnyExpr(&DstExpr);
3845  CharUnits Alignment
3846  = getContext().getTypeAlignInChars(TheCXXConstructExpr->getType());
3847  EmitAggExpr(TheCXXConstructExpr,
3848  AggValueSlot::forAddr(Address(DV.getScalarVal(), Alignment),
3849  Qualifiers(),
3854 
3855  FinishFunction();
3856  HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
3857  CGM.setAtomicGetterHelperFnMap(Ty, HelperFn);
3858  return HelperFn;
3859 }
3860 
3861 llvm::Value *
3863  // Get selectors for retain/autorelease.
3864  IdentifierInfo *CopyID = &getContext().Idents.get("copy");
3865  Selector CopySelector =
3867  IdentifierInfo *AutoreleaseID = &getContext().Idents.get("autorelease");
3868  Selector AutoreleaseSelector =
3869  getContext().Selectors.getNullarySelector(AutoreleaseID);
3870 
3871  // Emit calls to retain/autorelease.
3872  CGObjCRuntime &Runtime = CGM.getObjCRuntime();
3873  llvm::Value *Val = Block;
3874  RValue Result;
3875  Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
3876  Ty, CopySelector,
3877  Val, CallArgList(), nullptr, nullptr);
3878  Val = Result.getScalarVal();
3879  Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
3880  Ty, AutoreleaseSelector,
3881  Val, CallArgList(), nullptr, nullptr);
3882  Val = Result.getScalarVal();
3883  return Val;
3884 }
3885 
3886 static unsigned getBaseMachOPlatformID(const llvm::Triple &TT) {
3887  switch (TT.getOS()) {
3888  case llvm::Triple::Darwin:
3889  case llvm::Triple::MacOSX:
3890  return llvm::MachO::PLATFORM_MACOS;
3891  case llvm::Triple::IOS:
3892  return llvm::MachO::PLATFORM_IOS;
3893  case llvm::Triple::TvOS:
3894  return llvm::MachO::PLATFORM_TVOS;
3895  case llvm::Triple::WatchOS:
3896  return llvm::MachO::PLATFORM_WATCHOS;
3897  default:
3898  return /*Unknown platform*/ 0;
3899  }
3900 }
3901 
3903  const VersionTuple &Version) {
3904  CodeGenModule &CGM = CGF.CGM;
3905  // Note: we intend to support multi-platform version checks, so reserve
3906  // the room for a dual platform checking invocation that will be
3907  // implemented in the future.
3909 
3910  auto EmitArgs = [&](const VersionTuple &Version, const llvm::Triple &TT) {
3911  Optional<unsigned> Min = Version.getMinor(), SMin = Version.getSubminor();
3912  Args.push_back(
3913  llvm::ConstantInt::get(CGM.Int32Ty, getBaseMachOPlatformID(TT)));
3914  Args.push_back(llvm::ConstantInt::get(CGM.Int32Ty, Version.getMajor()));
3915  Args.push_back(llvm::ConstantInt::get(CGM.Int32Ty, Min ? *Min : 0));
3916  Args.push_back(llvm::ConstantInt::get(CGM.Int32Ty, SMin ? *SMin : 0));
3917  };
3918 
3919  assert(!Version.empty() && "unexpected empty version");
3920  EmitArgs(Version, CGM.getTarget().getTriple());
3921 
3922  if (!CGM.IsPlatformVersionAtLeastFn) {
3923  llvm::FunctionType *FTy = llvm::FunctionType::get(
3924  CGM.Int32Ty, {CGM.Int32Ty, CGM.Int32Ty, CGM.Int32Ty, CGM.Int32Ty},
3925  false);
3927  CGM.CreateRuntimeFunction(FTy, "__isPlatformVersionAtLeast");
3928  }
3929 
3930  llvm::Value *Check =
3932  return CGF.Builder.CreateICmpNE(Check,
3933  llvm::Constant::getNullValue(CGM.Int32Ty));
3934 }
3935 
3936 llvm::Value *
3937 CodeGenFunction::EmitBuiltinAvailable(const VersionTuple &Version) {
3938  // Darwin uses the new __isPlatformVersionAtLeast family of routines.
3939  if (CGM.getTarget().getTriple().isOSDarwin())
3940  return emitIsPlatformVersionAtLeast(*this, Version);
3941 
3942  if (!CGM.IsOSVersionAtLeastFn) {
3943  llvm::FunctionType *FTy =
3944  llvm::FunctionType::get(Int32Ty, {Int32Ty, Int32Ty, Int32Ty}, false);
3946  CGM.CreateRuntimeFunction(FTy, "__isOSVersionAtLeast");
3947  }
3948 
3949  Optional<unsigned> Min = Version.getMinor(), SMin = Version.getSubminor();
3950  llvm::Value *Args[] = {
3951  llvm::ConstantInt::get(CGM.Int32Ty, Version.getMajor()),
3952  llvm::ConstantInt::get(CGM.Int32Ty, Min ? *Min : 0),
3953  llvm::ConstantInt::get(CGM.Int32Ty, SMin ? *SMin : 0),
3954  };
3955 
3956  llvm::Value *CallRes =
3958 
3959  return Builder.CreateICmpNE(CallRes, llvm::Constant::getNullValue(Int32Ty));
3960 }
3961 
3963  const llvm::Triple &TT, const VersionTuple &TargetVersion) {
3964  VersionTuple FoundationDroppedInVersion;
3965  switch (TT.getOS()) {
3966  case llvm::Triple::IOS:
3967  case llvm::Triple::TvOS:
3968  FoundationDroppedInVersion = VersionTuple(/*Major=*/13);
3969  break;
3970  case llvm::Triple::WatchOS:
3971  FoundationDroppedInVersion = VersionTuple(/*Major=*/6);
3972  break;
3973  case llvm::Triple::Darwin:
3974  case llvm::Triple::MacOSX:
3975  FoundationDroppedInVersion = VersionTuple(/*Major=*/10, /*Minor=*/15);
3976  break;
3977  default:
3978  llvm_unreachable("Unexpected OS");
3979  }
3980  return TargetVersion < FoundationDroppedInVersion;
3981 }
3982 
3983 void CodeGenModule::emitAtAvailableLinkGuard() {
3985  return;
3986  // @available requires CoreFoundation only on Darwin.
3987  if (!Target.getTriple().isOSDarwin())
3988  return;
3989  // @available doesn't need Foundation on macOS 10.15+, iOS/tvOS 13+, or
3990  // watchOS 6+.
3992  Target.getTriple(), Target.getPlatformMinVersion()))
3993  return;
3994  // Add -framework CoreFoundation to the linker commands. We still want to
3995  // emit the core foundation reference down below because otherwise if
3996  // CoreFoundation is not used in the code, the linker won't link the
3997  // framework.
3998  auto &Context = getLLVMContext();
3999  llvm::Metadata *Args[2] = {llvm::MDString::get(Context, "-framework"),
4000  llvm::MDString::get(Context, "CoreFoundation")};
4001  LinkerOptionsMetadata.push_back(llvm::MDNode::get(Context, Args));
4002  // Emit a reference to a symbol from CoreFoundation to ensure that
4003  // CoreFoundation is linked into the final binary.
4004  llvm::FunctionType *FTy =
4005  llvm::FunctionType::get(Int32Ty, {VoidPtrTy}, false);
4006  llvm::FunctionCallee CFFunc =
4007  CreateRuntimeFunction(FTy, "CFBundleGetVersionNumber");
4008 
4009  llvm::FunctionType *CheckFTy = llvm::FunctionType::get(VoidTy, {}, false);
4010  llvm::FunctionCallee CFLinkCheckFuncRef = CreateRuntimeFunction(
4011  CheckFTy, "__clang_at_available_requires_core_foundation_framework",
4012  llvm::AttributeList(), /*Local=*/true);
4013  llvm::Function *CFLinkCheckFunc =
4014  cast<llvm::Function>(CFLinkCheckFuncRef.getCallee()->stripPointerCasts());
4015  if (CFLinkCheckFunc->empty()) {
4016  CFLinkCheckFunc->setLinkage(llvm::GlobalValue::LinkOnceAnyLinkage);
4017  CFLinkCheckFunc->setVisibility(llvm::GlobalValue::HiddenVisibility);
4018  CodeGenFunction CGF(*this);
4019  CGF.Builder.SetInsertPoint(CGF.createBasicBlock("", CFLinkCheckFunc));
4020  CGF.EmitNounwindRuntimeCall(CFFunc,
4021  llvm::Constant::getNullValue(VoidPtrTy));
4022  CGF.Builder.CreateUnreachable();
4023  addCompilerUsedGlobal(CFLinkCheckFunc);
4024  }
4025 }
4026 
clang::InternalLinkage
@ InternalLinkage
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
Definition: Linkage.h:31
clang::CodeGen::ObjCEntrypoints::objc_autoreleasePoolPop
llvm::FunctionCallee objc_autoreleasePoolPop
void objc_autoreleasePoolPop(void*);
Definition: CodeGenModule.h:135
clang::ObjCMessageExpr::SuperInstance
@ SuperInstance
The receiver is the instance of the superclass object.
Definition: ExprObjC.h:1097
clang::CodeGen::CodeGenFunction::EmitBuiltinAvailable
llvm::Value * EmitBuiltinAvailable(const VersionTuple &Version)
Definition: CGObjC.cpp:3937
clang::CodeGen::CodeGenFunction::SanitizerScope
RAII object to set/unset CodeGenFunction::IsSanitizerScope.
Definition: CodeGenFunction.h:496
clang::ObjCInterfaceDecl
Represents an ObjC class declaration.
Definition: DeclObjC.h:1151
clang::CodeGen::CodeGenFunction::EmitObjCAutoreleasePoolStmt
void EmitObjCAutoreleasePoolStmt(const ObjCAutoreleasePoolStmt &S)
Definition: CGObjC.cpp:3614
clang::ASTContext::getTypeSizeInChars
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
Definition: ASTContext.cpp:2450
clang::CodeGen::CGObjCRuntime::GetClass
virtual llvm::Value * GetClass(CodeGenFunction &CGF, const ObjCInterfaceDecl *OID)=0
GetClass - Return a reference to the class for the given interface decl.
clang::CodeGen::CodeGenFunction::EmitARCRetainNonBlock
llvm::Value * EmitARCRetainNonBlock(llvm::Value *value)
Retain the given object, with normal retain semantics.
Definition: CGObjC.cpp:2264
emitStructGetterCall
static void emitStructGetterCall(CodeGenFunction &CGF, ObjCIvarDecl *ivar, bool isAtomic, bool hasStrong)
emitStructGetterCall - Call the runtime function to load a property into the return value slot.
Definition: CGObjC.cpp:815
clang::CodeGen::CGDebugInfo::EmitLexicalBlockStart
void EmitLexicalBlockStart(CGBuilderTy &Builder, SourceLocation Loc)
Emit metadata to indicate the beginning of a new lexical block and push the block onto the stack.
Definition: CGDebugInfo.cpp:4220
emitARCStoreOperation
static llvm::Value * emitARCStoreOperation(CodeGenFunction &CGF, Address addr, llvm::Value *value, llvm::Function *&fn, llvm::Intrinsic::ID IntID, bool ignored)
Perform an operation having the following signature: i8* (i8**, i8*)
Definition: CGObjC.cpp:2173
clang::ObjCPropertyImplDecl::getPropertyIvarDecl
ObjCIvarDecl * getPropertyIvarDecl() const
Definition: DeclObjC.h:2824
clang::Type::isRecordType
bool isRecordType() const
Definition: Type.h:6762
clang::CodeGen::CodeGenFunction::EmitObjCAutoreleasePoolCleanup
void EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr)
Definition: CGObjC.cpp:2842
clang::CodeGen::ObjCEntrypoints::objc_allocWithZone
llvm::FunctionCallee objc_allocWithZone
void objc_allocWithZone(id);
Definition: CodeGenModule.h:129
clang::QualType::getObjCLifetime
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:1120
clang::CodeGen::CodeGenFunction::getProfileCount
uint64_t getProfileCount(const Stmt *S)
Get the profiler's count for the given statement.
Definition: CodeGenFunction.h:1498
hasTrivialSetExpr
static bool hasTrivialSetExpr(const ObjCPropertyImplDecl *PID)
Definition: CGObjC.cpp:1370
clang::HiddenVisibility
@ HiddenVisibility
Objects with "hidden" visibility are not seen by the dynamic linker.
Definition: Visibility.h:36
findWeakLValue
static const Expr * findWeakLValue(const Expr *E)
Given an expression of ObjC pointer type, check whether it was immediately loaded from an ARC __weak ...
Definition: CGObjC.cpp:346
clang::CodeGen::CodeGenFunction::RunCleanupsScope::requiresCleanups
bool requiresCleanups() const
Determine whether this scope requires any cleanups.
Definition: CodeGenFunction.h:873
getNullForVariable
static llvm::Constant * getNullForVariable(Address addr)
Given the address of a variable of pointer type, find the correct null to store into it.
Definition: CGObjC.cpp:42
clang::CodeGen::CodeGenTypeCache::Int8PtrTy
llvm::PointerType * Int8PtrTy
Definition: CodeGenTypeCache.h:57
clang::CodeGen::CodeGenFunction::EmitNullInitialization
void EmitNullInitialization(Address DestPtr, QualType Ty)
EmitNullInitialization - Generate code to set a value of the given type to null, If the type contains...
Definition: CodeGenFunction.cpp:1908
clang::ObjCProtocolExpr::getProtocol
ObjCProtocolDecl * getProtocol() const
Definition: ExprObjC.h:521
clang::ObjCBoxedExpr
ObjCBoxedExpr - used for generalized expression boxing.
Definition: ExprObjC.h:128
clang::CodeGen::CodeGenFunction::EmitObjCCollectionLiteral
llvm::Value * EmitObjCCollectionLiteral(const Expr *E, const ObjCMethodDecl *MethodWithObjects)
Definition: CGObjC.cpp:120
clang::OMF_autorelease
@ OMF_autorelease
Definition: IdentifierTable.h:702
clang::ObjCProtocolDecl::protocols
protocol_range protocols() const
Definition: DeclObjC.h:2115
clang::Type::isBlockPointerType
bool isBlockPointerType() const
Definition: Type.h:6680
clang::CodeGen::ObjCEntrypoints::objc_retainAutoreleasedReturnValue
llvm::Function * objc_retainAutoreleasedReturnValue
id objc_retainAutoreleasedReturnValue(id);
Definition: CodeGenModule.h:186
clang::interp::APInt
llvm::APInt APInt
Definition: Integral.h:27
emitARCUnsafeClaimCallResult
static llvm::Value * emitARCUnsafeClaimCallResult(CodeGenFunction &CGF, const Expr *e)
Given that the given expression is some sort of call (which does not return retained),...
Definition: CGObjC.cpp:3003
clang::ObjCObjectPointerType::getInterfaceType
const ObjCInterfaceType * getInterfaceType() const
If this pointer points to an Objective C @interface type, gets the type for that interface.
Definition: Type.cpp:1677
clang::CodeGen::CodeGenFunction::EmitBlockCopyAndAutorelease
llvm::Value * EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty)
Definition: CGObjC.cpp:3862
clang::CodeGen::CodeGenFunction::emitARCCopyAssignWeak
void emitARCCopyAssignWeak(QualType Ty, Address DstAddr, Address SrcAddr)
Definition: CGObjC.cpp:2633
clang::OK_Ordinary
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition: Specifiers.h:136
clang::CodeGen::TEK_Aggregate
@ TEK_Aggregate
Definition: CodeGenFunction.h:115
clang::CodeGen::RValue
RValue - This trivial value class is used to represent the result of an expression that is evaluated.
Definition: CGValue.h:39
clang::CodeGen::CodeGenModule::CreateRuntimeFunction
llvm::FunctionCallee CreateRuntimeFunction(llvm::FunctionType *Ty, StringRef Name, llvm::AttributeList ExtraAttrs=llvm::AttributeList(), bool Local=false, bool AssumeConvergent=false)
Create or return a runtime function declaration with the specified type and name.
Definition: CodeGenModule.cpp:3792
emitARCOperationAfterCall
static llvm::Value * emitARCOperationAfterCall(CodeGenFunction &CGF, llvm::Value *value, ValueTransform doAfterCall, ValueTransform doFallback)
Insert code immediately after a call.
Definition: CGObjC.cpp:2933
clang::CodeGen::CGObjCRuntime::GetPropertyGetFunction
virtual llvm::FunctionCallee GetPropertyGetFunction()=0
Return the runtime function for getting properties.
type
clang::CodeGen::CodeGenFunction::EmitObjCConsumeObject
llvm::Value * EmitObjCConsumeObject(QualType T, llvm::Value *Ptr)
Produce the code for a CK_ARCConsumeObject.
Definition: CGObjC.cpp:2066
clang::CodeGen::CodeGenFunction::EmitARCDestroyWeak
void EmitARCDestroyWeak(Address addr)
void @objc_destroyWeak(i8** addr) Essentially objc_storeWeak(addr, nil).
Definition: CGObjC.cpp:2604
clang::CodeGen::CGObjCRuntime::GenerateMessageSend
virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF, ReturnValueSlot ReturnSlot, QualType ResultType, Selector Sel, llvm::Value *Receiver, const CallArgList &CallArgs, const ObjCInterfaceDecl *Class=nullptr, const ObjCMethodDecl *Method=nullptr)=0
Generate an Objective-C message send operation.
clang::CodeGen::CodeGenFunction::EmitARCRetainAutoreleaseReturnValue
llvm::Value * EmitARCRetainAutoreleaseReturnValue(llvm::Value *value)
Do a fused retain/autorelease of the given object.
Definition: CGObjC.cpp:2522
clang::CodeGen::CodeGenFunction::EmitObjCAtTryStmt
void EmitObjCAtTryStmt(const ObjCAtTryStmt &S)
Definition: CGObjC.cpp:2039
clang::PseudoObjectExpr::semantics_begin
semantics_iterator semantics_begin()
Definition: Expr.h:6163
clang::ObjCDictionaryLiteral::getNumElements
unsigned getNumElements() const
getNumElements - Return number of elements of objective-c dictionary literal.
Definition: ExprObjC.h:360
clang::CodeGen::CodeGenFunction::EmitCheckSourceLocation
llvm::Constant * EmitCheckSourceLocation(SourceLocation Loc)
Emit a description of a source location in a format suitable for passing to a runtime sanitizer handl...
Definition: CGExpr.cpp:3064
clang::CodeGen::CodeGenFunction::AutoreleaseResult
bool AutoreleaseResult
In ARC, whether we should autorelease the return value.
Definition: CodeGenFunction.h:508
clang::Type::isObjCRetainableType
bool isObjCRetainableType() const
Definition: Type.cpp:4284
Error
llvm::Error Error
Definition: ByteCodeEmitter.cpp:20
CodeGenFunction.h
clang::SourceRange
A trivial tuple used to represent a source range.
Definition: SourceLocation.h:212
shouldRetainObjCLifetime
static bool shouldRetainObjCLifetime(Qualifiers::ObjCLifetime lifetime)
Definition: CGObjC.cpp:2849
string
string(SUBSTRING ${CMAKE_CURRENT_BINARY_DIR} 0 ${PATH_LIB_START} PATH_HEAD) string(SUBSTRING $
Definition: CMakeLists.txt:22
clang::CodeGen::CodeGenFunction::EmitCall
RValue EmitCall(const CGFunctionInfo &CallInfo, const CGCallee &Callee, ReturnValueSlot ReturnValue, const CallArgList &Args, llvm::CallBase **callOrInvoke, bool IsMustTail, SourceLocation Loc)
EmitCall - Generate a call of the given function, expecting the given result type,...
Definition: CGCall.cpp:4616
clang::CodeGen::CodeGenFunction::EmitObjCMRRAutoreleasePoolPush
llvm::Value * EmitObjCMRRAutoreleasePoolPush()
Produce the code to do an MRR version objc_autoreleasepool_push.
Definition: CGObjC.cpp:2690
clang::ObjCIvarDecl::getNextIvar
ObjCIvarDecl * getNextIvar()
Definition: DeclObjC.h:1957
clang::ObjCAutoreleasePoolStmt::getSubStmt
const Stmt * getSubStmt() const
Definition: StmtObjC.h:379
clang::ObjCArrayLiteral::getNumElements
unsigned getNumElements() const
getNumElements - Return number of elements of objective-c array literal.
Definition: ExprObjC.h:229
clang::Decl::hasAttr
bool hasAttr() const
Definition: DeclBase.h:547
clang::CodeGen::CodeGenFunction::EmitCompoundStmtWithoutScope
Address EmitCompoundStmtWithoutScope(const CompoundStmt &S, bool GetLast=false, AggValueSlot AVS=AggValueSlot::ignored())
Definition: CGStmt.cpp:455
clang::ObjCPropertyImplDecl::getSetterCXXAssignment
Expr * getSetterCXXAssignment() const
Definition: DeclObjC.h:2860
clang::CodeGen::CodeGenFunction::CurCodeDecl
const Decl * CurCodeDecl
CurCodeDecl - This is the inner-most code context, which includes blocks.
Definition: CodeGenFunction.h:327
clang::ObjCImplementationDecl
ObjCImplementationDecl - Represents a class definition - this is where method definitions are specifi...
Definition: DeclObjC.h:2546
clang::CXXConstructExpr::arg_end
arg_iterator arg_end()
Definition: ExprCXX.h:1598
clang::CodeGen::AggValueSlot::DoesNotNeedGCBarriers
@ DoesNotNeedGCBarriers
Definition: CGValue.h:528
clang::CodeGen::CodeGenFunction::EmitNounwindRuntimeCall
llvm::CallInst * EmitNounwindRuntimeCall(llvm::FunctionCallee callee, const Twine &name="")
clang::ObjCMessageExpr::getSelector
Selector getSelector() const
Definition: ExprObjC.cpp:293
clang::CodeGen::CGObjCRuntime::GetOptimizedPropertySetFunction
virtual llvm::FunctionCallee GetOptimizedPropertySetFunction(bool atomic, bool copy)=0
Return the runtime function for optimized setting properties.
clang::CodeGen::CodeGenFunction::destroyARCStrongPrecise
static Destroyer destroyARCStrongPrecise
Definition: CodeGenFunction.h:4296
clang::CodeGen::ObjCEntrypoints::clang_arc_noop_use
llvm::Function * clang_arc_noop_use
void clang.arc.noop.use(...);
Definition: CodeGenModule.h:215
clang::CodeGen::TargetCodeGenInfo::markARCOptimizedReturnCallsAsNoTail
virtual bool markARCOptimizedReturnCallsAsNoTail() const
Determine whether a call to objc_retainAutoreleasedReturnValue or objc_unsafeClaimAutoreleasedReturnV...
Definition: TargetInfo.h:186
clang::UnaryOperator::Create
static UnaryOperator * Create(const ASTContext &C, Expr *input, Opcode opc, QualType type, ExprValueKind VK, ExprObjectKind OK, SourceLocation l, bool CanOverflow, FPOptionsOverride FPFeatures)
Definition: Expr.cpp:4563
clang::ImplicitCastExpr::OnStack
@ OnStack
Definition: Expr.h:3642
clang::Qualifiers::OCL_Weak
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition: Type.h:176
clang::CodeGen::ObjCEntrypoints::objc_retainAutoreleaseReturnValue
llvm::Function * objc_retainAutoreleaseReturnValue
id objc_retainAutoreleaseReturnValue(id);
Definition: CodeGenModule.h:183
clang::CodeGen::CodeGenModule::setAtomicSetterHelperFnMap
void setAtomicSetterHelperFnMap(QualType Ty, llvm::Constant *Fn)
Definition: CodeGenModule.h:674
clang::ASTContext::VoidTy
CanQualType VoidTy
Definition: ASTContext.h:1075
llvm::SmallVector
Definition: LLVM.h:38
clang::IdentifierTable::get
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
Definition: IdentifierTable.h:592
clang::SourceLocation
Encodes a location in the source.
Definition: SourceLocation.h:88
clang::CodeGen::CodeGenModule::SetInternalFunctionAttributes
void SetInternalFunctionAttributes(GlobalDecl GD, llvm::Function *F, const CGFunctionInfo &FI)
Set the attributes on the LLVM function for the given decl and function info.
Definition: CodeGenModule.cpp:2058
clang::OMF_release
@ OMF_release
Definition: IdentifierTable.h:705
clang::CodeGen::CodeGenFunction::GenerateObjCAtomicSetterCopyHelperFunction
llvm::Constant * GenerateObjCAtomicSetterCopyHelperFunction(const ObjCPropertyImplDecl *PID)
GenerateObjCAtomicSetterCopyHelperFunction - Given a c++ object type with non-trivial copy assignment...
Definition: CGObjC.cpp:3660
clang::CodeGen::LValue::getAddress
Address getAddress(CodeGenFunction &CGF) const
Definition: CGValue.h:329
clang::CodeGen::CGObjCRuntime::GetRuntimeProtocolList
std::vector< const ObjCProtocolDecl * > GetRuntimeProtocolList(ObjCProtocolDecl::protocol_iterator begin, ObjCProtocolDecl::protocol_iterator end)
Walk the list of protocol references from a class, category or protocol to traverse the DAG formed fr...
Definition: CGObjC.cpp:464
clang::ObjCRuntime::hasNativeARC
bool hasNativeARC() const
Does this runtime natively provide the ARC entrypoints?
Definition: ObjCRuntime.h:162
clang::CodeGen::CodeGenFunction::EmitLoadOfComplex
ComplexPairTy EmitLoadOfComplex(LValue src, SourceLocation loc)
EmitLoadOfComplex - Load a complex number from the specified l-value.
Definition: CGExprComplex.cpp:1145
clang::QualType::getNonReferenceType
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition: Type.h:6620
clang::CastExpr::getSubExpr
Expr * getSubExpr()
Definition: Expr.h:3524
clang::CodeGen::CodeGenModule::getSize
llvm::ConstantInt * getSize(CharUnits numChars)
Emit the given number of characters as a value of type size_t.
Definition: CodeGenModule.cpp:981
clang::CodeGen::CodeGenFunction::EmitAnyExpr
RValue EmitAnyExpr(const Expr *E, AggValueSlot aggSlot=AggValueSlot::ignored(), bool ignoreResult=false)
EmitAnyExpr - Emit code to compute the specified expression which can have any type.
Definition: CGExpr.cpp:202
emitAutoreleasedReturnValueMarker
static void emitAutoreleasedReturnValueMarker(CodeGenFunction &CGF)
Definition: CGObjC.cpp:2300
clang::CodeGen::ObjCEntrypoints::objc_autoreleaseReturnValue
llvm::Function * objc_autoreleaseReturnValue
id objc_autoreleaseReturnValue(id);
Definition: CodeGenModule.h:152
clang::CXXConstructExpr::requiresZeroInitialization
bool requiresZeroInitialization() const
Whether this construction first requires zero-initialization before the initializer is called.
Definition: ExprCXX.h:1571
clang::CodeGen::CodeGenTypeCache::getPointerAlign
CharUnits getPointerAlign() const
Definition: CodeGenTypeCache.h:117
clang::QualType
A (possibly-)qualified type.
Definition: Type.h:673
Attr.h
emitCPPObjectAtomicSetterCall
static void emitCPPObjectAtomicSetterCall(CodeGenFunction &CGF, ObjCMethodDecl *OMD, ObjCIvarDecl *ivar, llvm::Constant *AtomicHelperFn)
emitCPPObjectAtomicSetterCall - Call the runtime function to store the value from the first formal pa...
Definition: CGObjC.cpp:1334
clang::Selector::isUnarySelector
bool isUnarySelector() const
Definition: IdentifierTable.h:825
clang::CodeGen::CodeGenTypeCache::PointerAlignInBytes
unsigned char PointerAlignInBytes
Definition: CodeGenTypeCache.h:96
clang::CodeGen::LValue::getQuals
const Qualifiers & getQuals() const
Definition: CGValue.h:313
clang::cast
U cast(CodeGen::Address addr)
Definition: Address.h:108
clang::CodeGen::CodeGenModule::setAtomicGetterHelperFnMap
void setAtomicGetterHelperFnMap(QualType Ty, llvm::Constant *Fn)
Definition: CodeGenModule.h:682
clang::SanitizerSet::has
bool has(SanitizerMask K) const
Check if a certain (single) sanitizer is enabled.
Definition: Sanitizers.h:155
clang::CodeGen::CodeGenModule::getContext
ASTContext & getContext() const
Definition: CodeGenModule.h:702
clang::CodeGen::RequiredArgs::All
@ All
Definition: CGFunctionInfo.h:485
clang::QualType::getCanonicalType
QualType getCanonicalType() const
Definition: Type.h:6463
clang::FieldDecl
Represents a member of a struct/union/class.
Definition: Decl.h:2835
clang::CodeGen::CodeGenFunction::EmitARCDestroyStrong
void EmitARCDestroyStrong(Address addr, ARCPreciseLifetime_t precise)
Destroy a __strong variable.
Definition: CGObjC.cpp:2432
clang::Qualifiers
The collection of all-type qualifiers we support.
Definition: Type.h:145
clang::ParmVarDecl
Represents a parameter to a function.
Definition: Decl.h:1665
clang::ObjCProtocolDecl::getCanonicalDecl
ObjCProtocolDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this Objective-C protocol.
Definition: DeclObjC.h:2244
clang::ObjCPropertyImplDecl::getGetterMethodDecl
ObjCMethodDecl * getGetterMethodDecl() const
Definition: DeclObjC.h:2846
clang::ObjCObjectPointerType::getPointeeType
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition: Type.h:6084
clang::ObjCMethodDecl::getClassInterface
ObjCInterfaceDecl * getClassInterface()
Definition: DeclObjC.cpp:1164
clang::ObjCMessageExpr::arguments
llvm::iterator_range< arg_iterator > arguments()
Definition: ExprObjC.h:1453
clang::CodeGen::CodeGenFunction::createBasicBlock
llvm::BasicBlock * createBasicBlock(const Twine &name="", llvm::Function *parent=nullptr, llvm::BasicBlock *before=nullptr)
createBasicBlock - Create an LLVM basic block.
Definition: CodeGenFunction.h:2394
clang::CodeGen::CodeGenFunction::EmitARCCopyWeak
void EmitARCCopyWeak(Address dst, Address src)
void @objc_copyWeak(i8** dest, i8** src) Disregards the current value in dest.
Definition: CGObjC.cpp:2627
clang::ObjCAtTryStmt
Represents Objective-C's @try ... @catch ... @finally statement.
Definition: StmtObjC.h:165
clang::CodeGen::CGBuilderTy::CreateStore
llvm::StoreInst * CreateStore(llvm::Value *Val, Address Addr, bool IsVolatile=false)
Definition: CGBuilder.h:95
CGObjCRuntime.h
hasUnalignedAtomics
static bool hasUnalignedAtomics(llvm::Triple::ArchType arch)
Determine whether the given architecture supports unaligned atomic accesses.
Definition: CGObjC.cpp:847
clang::ObjCPropertyImplDecl
ObjCPropertyImplDecl - Represents implementation declaration of a property in a class or category imp...
Definition: DeclObjC.h:2751
clang::CodeGen::ARCPreciseLifetime_t
ARCPreciseLifetime_t
Does an ARC strong l-value have precise lifetime?
Definition: CGValue.h:120
TargetInfo.h
clang::ObjCMessageExpr::getInstanceReceiver
Expr * getInstanceReceiver()
Returns the object expression (receiver) for an instance message, or null for a message that is not a...
Definition: ExprObjC.h:1250
clang::Qualifiers::OCL_ExplicitNone
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition: Type.h:166
clang::CodeGen::CodeGenTypes::arrangeBuiltinFunctionDeclaration
const CGFunctionInfo & arrangeBuiltinFunctionDeclaration(QualType resultType, const FunctionArgList &args)
A builtin function is a freestanding function using the default C conventions.
Definition: CGCall.cpp:657
llvm::Optional
Definition: LLVM.h:40
clang::ObjCMethodDecl::param_end
param_const_iterator param_end() const
Definition: DeclObjC.h:361
clang::UnaryOperator
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition: Expr.h:2157
clang::CodeGen::CodeGenModule::SetLLVMFunctionAttributes
void SetLLVMFunctionAttributes(GlobalDecl GD, const CGFunctionInfo &Info, llvm::Function *F, bool IsThunk)
Set the LLVM function attributes (sext, zext, etc).
Definition: CodeGenModule.cpp:1517
clang::CodeGen::CodeGenModule::getLangOpts
const LangOptions & getLangOpts() const
Definition: CodeGenModule.h:703
clang::Type::isVoidType
bool isVoidType() const
Definition: Type.h:6955
clang::CodeGen::CodeGenFunction::EmitARCStoreAutoreleasing
std::pair< LValue, llvm::Value * > EmitARCStoreAutoreleasing(const BinaryOperator *e)
Definition: CGObjC.cpp:3605
clang::CodeGen::LValue::isARCPreciseLifetime
ARCPreciseLifetime_t isARCPreciseLifetime() const
Definition: CGValue.h:287
clang::CodeGen::CodeGenFunction::shouldUseFusedARCCalls
bool shouldUseFusedARCCalls()
Definition: CodeGenFunction.h:1956
emitStructSetterCall
static void emitStructSetterCall(CodeGenFunction &CGF, ObjCMethodDecl *OMD, ObjCIvarDecl *ivar)
emitStructSetterCall - Call the runtime function to store the value from the first formal parameter i...
Definition: CGObjC.cpp:1290
Expression
clang::CodeGen::CodeGenModule::getAtomicGetterHelperFnMap
llvm::Constant * getAtomicGetterHelperFnMap(QualType Ty)
Definition: CodeGenModule.h:679
clang::LangOptions::GCOnly
@ GCOnly
Definition: LangOptions.h:63
clang::CodeGen::CodeGenFunction::EmitObjCThrowOperand
llvm::Value * EmitObjCThrowOperand(const Expr *expr)
Definition: CGObjC.cpp:3468
clang::CodeGen::CodeGenFunction::getDestroyer
Destroyer * getDestroyer(QualType::DestructionKind destructionKind)
Definition: CGDecl.cpp:2079
clang::CodeGen::EHCleanup
@ EHCleanup
Denotes a cleanup that should run when a scope is exited using exceptional control flow (a throw stat...
Definition: EHScopeStack.h:80
clang::ObjCForCollectionStmt
Represents Objective-C's collection statement.
Definition: StmtObjC.h:23
clang::CodeGen::CodeGenFunction::EmitStoreOfScalar
void EmitStoreOfScalar(llvm::Value *Value, Address Addr, bool Volatile, QualType Ty, AlignmentSource Source=AlignmentSource::Type, bool isInit=false, bool isNontemporal=false)
EmitStoreOfScalar - Store a scalar value to an address, taking care to appropriately convert from the...
Definition: CodeGenFunction.h:3802
clang::PseudoObjectExpr::semantics_end
semantics_iterator semantics_end()
Definition: Expr.h:6169
clang::BinaryOperator::getOpcode
Opcode getOpcode() const
Definition: Expr.h:3847
clang::ObjCInterfaceType::getDecl
ObjCInterfaceDecl * getDecl() const
Get the declaration of this interface.
Definition: Type.cpp:824
clang::CodeGen::CodeGenModule::getTargetCodeGenInfo
const TargetCodeGenInfo & getTargetCodeGenInfo()
Definition: TargetInfo.cpp:11083
clang::CodeGen::CodeGenFunction::EmitARCRetainAutoreleasedReturnValue
llvm::Value * EmitARCRetainAutoreleasedReturnValue(llvm::Value *value)
Retain the given object which is the result of a function call.
Definition: CGObjC.cpp:2385
clang::CodeGen::CodeGenFunction::GenerateObjCSetter
void GenerateObjCSetter(ObjCImplementationDecl *IMP, const ObjCPropertyImplDecl *PID)
GenerateObjCSetter - Synthesize an Objective-C property setter function for the given property.
Definition: CGObjC.cpp:1582
clang::CodeGen::CodeGenFunction::TCK_Store
@ TCK_Store
Checking the destination of a store. Must be suitably sized and aligned.
Definition: CodeGenFunction.h:2916
clang::CodeGen::CodeGenFunction::EmitObjCMessageExpr
RValue EmitObjCMessageExpr(const ObjCMessageExpr *E, ReturnValueSlot Return=ReturnValueSlot())
Definition: CGObjC.cpp:571
clang::CodeGen::ObjCEntrypoints::objc_autoreleasePoolPush
llvm::Function * objc_autoreleasePoolPush
void *objc_autoreleasePoolPush(void);
Definition: CodeGenModule.h:142
clang::CodeGen::CGDebugInfo::EmitLexicalBlockEnd
void EmitLexicalBlockEnd(CGBuilderTy &Builder, SourceLocation Loc)
Emit metadata to indicate the end of a new lexical block and pop the current block.
Definition: CGDebugInfo.cpp:4237
setARCRuntimeFunctionLinkage
static void setARCRuntimeFunctionLinkage(CodeGenModule &CGM, llvm::Value *RTF)
Definition: CGObjC.cpp:2100
clang::Token
Token - This structure provides full information about a lexed token.
Definition: Token.h:34
clang::CodeGen::CGBuilderTy::CreateStructGEP
Address CreateStructGEP(Address Addr, unsigned Index, const llvm::Twine &Name="")
Definition: CGBuilder.h:188
clang::ObjCMessageExpr::SuperClass
@ SuperClass
The receiver is a superclass.
Definition: ExprObjC.h:1094
clang::ObjCObjectType::getInterface
ObjCInterfaceDecl * getInterface() const
Gets the interface declaration for this object type, if the base type really is an interface.
Definition: Type.h:6051
clang::CodeGen::CodeGenFunction::EmitStmt
void EmitStmt(const Stmt *S, ArrayRef< const Attr * > Attrs=None)
EmitStmt - Emit the code for the statement.
Definition: CGStmt.cpp:53
ConstantEmitter.h
clang::ASTContext::toBits
int64_t toBits(CharUnits CharSize) const
Convert a size in characters to a size in bits.
Definition: ASTContext.cpp:2444
clang::CodeGen::CodeGenFunction::JumpDest::getBlock
llvm::BasicBlock * getBlock() const
Definition: CodeGenFunction.h:251
emitARCValueOperation
static llvm::Value * emitARCValueOperation(CodeGenFunction &CGF, llvm::Value *value, llvm::Type *returnType, llvm::Function *&fn, llvm::Intrinsic::ID IntID, llvm::CallInst::TailCallKind tailKind=llvm::CallInst::TCK_None)
Perform an operation having the signature i8* (i8*) where a null input causes a no-op and returns nul...
Definition: CGObjC.cpp:2127
clang::ArrayType::Normal
@ Normal
Definition: Type.h:2890
clang::Expr::isXValue
bool isXValue() const
Definition: Expr.h:272
clang::ObjCObjectPointerType::getObjectType
const ObjCObjectType * getObjectType() const
Gets the type pointed to by this ObjC pointer.
Definition: Type.h:6109
clang::Expr::isGLValue
bool isGLValue() const
Definition: Expr.h:273
clang::CodeGen::CallArgList::add
void add(RValue rvalue, QualType type)
Definition: CGCall.h:288
clang::CodeGen::CodeGenFunction::EmitStoreThroughLValue
void EmitStoreThroughLValue(RValue Src, LValue Dst, bool isInit=false)
EmitStoreThroughLValue - Store the specified rvalue into the specified lvalue, where both are guarant...
Definition: CGExpr.cpp:2053
clang::CodeGen::CodeGenFunction::Builder
CGBuilderTy Builder
Definition: CodeGenFunction.h:274
CGDebugInfo.h
clang::ObjCImplDecl::getClassInterface
const ObjCInterfaceDecl * getClassInterface() const
Definition: DeclObjC.h:2434
clang::CodeGen::CodeGenTypes::ConvertType
llvm::Type * ConvertType(QualType T)
ConvertType - Convert type T into a llvm::Type.
Definition: CodeGenTypes.cpp:395
clang::ObjCArrayLiteral::getArrayWithObjectsMethod
ObjCMethodDecl * getArrayWithObjectsMethod() const
Definition: ExprObjC.h:241
clang::CodeGen::CGBuilderTy::CreateBitCast
Address CreateBitCast(Address Addr, llvm::Type *Ty, const llvm::Twine &Name="")
Definition: CGBuilder.h:151
clang::OpaqueValueExpr
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition: Expr.h:1129
tryEmitARCRetainScalarExpr
static TryEmitResult tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e)
Definition: CGObjC.cpp:3401
clang::CodeGen::CodeGenTypeCache::VoidPtrTy
llvm::PointerType * VoidPtrTy
Definition: CodeGenTypeCache.h:56
clang::ObjCMethodDecl::createImplicitParams
void createImplicitParams(ASTContext &Context, const ObjCInterfaceDecl *ID)
createImplicitParams - Used to lazily create the self and cmd implicit parameters.
Definition: DeclObjC.cpp:1143
emitARCLoadOperation
static llvm::Value * emitARCLoadOperation(CodeGenFunction &CGF, Address addr, llvm::Function *&fn, llvm::Intrinsic::ID IntID)
Perform an operation having the following signature: i8* (i8**)
Definition: CGObjC.cpp:2151
clang::CodeGen::CodeGenFunction::GetAddrOfLocalVar
Address GetAddrOfLocalVar(const VarDecl *VD)
GetAddrOfLocalVar - Return the address of a local variable.
Definition: CodeGenFunction.h:2679
clang::CodeGen::CodeGenFunction::EmitObjCStringLiteral
llvm::Value * EmitObjCStringLiteral(const ObjCStringLiteral *E)
Emits an instance of NSConstantString representing the object.
Definition: CGObjC.cpp:48
clang::ObjCObjectType
Represents a class type in Objective C.
Definition: Type.h:5816
clang::ObjCArrayLiteral
ObjCArrayLiteral - used for objective-c array containers; as in: @["Hello", NSApp,...
Definition: ExprObjC.h:190
clang::CodeGen::CodeGenFunction::destroyARCWeak
static Destroyer destroyARCWeak
Definition: CodeGenFunction.h:4297
DeclObjC.h
clang::ObjCMessageExpr::isDelegateInitCall
bool isDelegateInitCall() const
isDelegateInitCall - Answers whether this message send has been tagged as a "delegate init call",...
Definition: ExprObjC.h:1403
clang::CodeGen::ARCImpreciseLifetime
@ ARCImpreciseLifetime
Definition: CGValue.h:121
clang::CodeGen::CodeGenFunction::EmitARCLoadWeak
llvm::Value * EmitARCLoadWeak(Address addr)
i8* @objc_loadWeak(i8** addr) Essentially objc_autorelease(objc_loadWeakRetained(addr)).
Definition: CGObjC.cpp:2559
clang::CodeGen::CGObjCRuntime::GetCppAtomicObjectGetFunction
virtual llvm::FunctionCallee GetCppAtomicObjectGetFunction()=0
API for atomic copying of qualified aggregates with non-trivial copy assignment (c++) in getter.
clang::GlobalDecl
GlobalDecl - represents a global declaration.
Definition: GlobalDecl.h:55
clang::CodeGen::ObjCEntrypoints::clang_arc_use
llvm::Function * clang_arc_use
void clang.arc.use(...);
Definition: CodeGenModule.h:212
clang::CodeGen::AlignmentSource::Decl
@ Decl
The l-value was an access to a declared entity or something equivalently strong, like the address of ...
clang::ASTContext::getTypeAlignInChars
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
Definition: ASTContext.cpp:2459
clang::ObjCMethodDecl::param_const_iterator
const ParmVarDecl *const * param_const_iterator
Definition: DeclObjC.h:352
clang::CodeGen::CodeGenFunction::EmitLoadOfScalar
llvm::Value * EmitLoadOfScalar(Address Addr, bool Volatile, QualType Ty, SourceLocation Loc, AlignmentSource Source=AlignmentSource::Type, bool isNontemporal=false)
EmitLoadOfScalar - Load a scalar value from an address, taking care to appropriately convert from the...
Definition: CodeGenFunction.h:3780
clang::CodeGen::CodeGenFunction::ComplexPairTy
std::pair< llvm::Value *, llvm::Value * > ComplexPairTy
Definition: CodeGenFunction.h:272
clang::CodeGen::ReturnValueSlot
ReturnValueSlot - Contains the address where the return value of a function can be stored,...
Definition: CGCall.h:362
clang::CodeGen::CodeGenFunction::EmitObjCDictionaryLiteral
llvm::Value * EmitObjCDictionaryLiteral(const ObjCDictionaryLiteral *E)
Definition: CGObjC.cpp:247
arch
CudaArch arch
Definition: Cuda.cpp:70
clang::CodeGen::CodeGenFunction::EmitObjCAutoreleasePoolPush
llvm::Value * EmitObjCAutoreleasePoolPush()
Produce the code to do a objc_autoreleasepool_push.
Definition: CGObjC.cpp:2650
clang::CXXConstructExpr::arg_begin
arg_iterator arg_begin()
Definition: ExprCXX.h:1597
clang::CodeGen::ObjCEntrypoints::objc_copyWeak
llvm::Function * objc_copyWeak
void objc_copyWeak(id *dest, id *src);
Definition: CodeGenModule.h:155
clang::IdentifierInfo::isStr
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
Definition: IdentifierTable.h:176
clang::ObjCPropertyAttribute::kind_atomic
@ kind_atomic
Definition: DeclObjCCommon.h:32
clang::ASTContext::getObjCIdType
QualType getObjCIdType() const
Represents the Objective-CC id type.
Definition: ASTContext.h:1993
clang::CodeGen::CGObjCRuntime::EmitThrowStmt
virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF, const ObjCAtThrowStmt &S, bool ClearInsertionPoint=true)=0
clang::ObjCPropertyImplDecl::getSetterMethodDecl
ObjCMethodDecl * getSetterMethodDecl() const
Definition: DeclObjC.h:2849
clang::Type::isReferenceType
bool isReferenceType() const
Definition: Type.h:6684
clang::CallExpr::getCallee
Expr * getCallee()
Definition: Expr.h:2945
clang::Type::isObjCClassType
bool isObjCClassType() const
Definition: Type.h:6833
V
#define V(N, I)
Definition: ASTContext.h:3121
clang::CodeGen::CodeGenTypes::arrangeObjCMethodDeclaration
const CGFunctionInfo & arrangeObjCMethodDeclaration(const ObjCMethodDecl *MD)
Objective-C methods are C functions with some implicit parameters.
Definition: CGCall.cpp:462
clang::CodeGen::CodeGenFunction::emitScalarConstant
llvm::Value * emitScalarConstant(const ConstantEmission &Constant, Expr *E)
Definition: CGExpr.cpp:1576
clang::QualType::hasNonTrivialObjCLifetime
bool hasNonTrivialObjCLifetime() const
Definition: Type.h:1124
clang::CodeGen::CodeGenFunction::GenerateObjCCtorDtorMethod
void GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP, ObjCMethodDecl *MD, bool ctor)
Definition: CGObjC.cpp:1662
clang::ReturnStmt::Create
static ReturnStmt * Create(const ASTContext &Ctx, SourceLocation RL, Expr *E, const VarDecl *NRVOCandidate)
Create a return statement.
Definition: Stmt.cpp:1195
clang::ast_matchers::expr
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
Definition: ASTMatchersInternal.cpp:889
clang::CodeGen::CodeGenFunction::RunCleanupsScope
Enters a new scope for capturing cleanups, all of which will be executed once the scope is exited.
Definition: CodeGenFunction.h:838
clang::CodeGen::CodeGenModule::SetLLVMFunctionAttributesForDefinition
void SetLLVMFunctionAttributesForDefinition(const Decl *D, llvm::Function *F)
Set the LLVM function attributes which only apply to a function definition.
Definition: CodeGenModule.cpp:1761
clang::RecordType
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:4613
clang::CodeGen::ObjCEntrypoints::retainAutoreleasedReturnValueMarker
llvm::InlineAsm * retainAutoreleasedReturnValueMarker
A void(void) inline asm to use to mark that the return value of a call will be immediately retain.
Definition: CodeGenModule.h:209
clang::CodeGen::CodeGenFunction::GenerateObjCMethod
void GenerateObjCMethod(const ObjCMethodDecl *OMD)
Generate an Objective-C method.
Definition: CGObjC.cpp:804
clang::CompoundStmt
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition: Stmt.h:1399
clang::CodeGen::CGObjCRuntime::GetSelector
virtual llvm::Value * GetSelector(CodeGenFunction &CGF, Selector Sel)=0
Get a selector for the specified name and type values.
clang::CodeGen::CodeGenFunction::getCurrentProfileCount
uint64_t getCurrentProfileCount()
Get the profiler's current count.
Definition: CodeGenFunction.h:1512
clang::ObjCSelectorExpr
ObjCSelectorExpr used for @selector in Objective-C.
Definition: ExprObjC.h:454
clang::Type::hasPointerRepresentation
bool hasPointerRepresentation() const
Whether this type is represented natively as a pointer.
Definition: Type.h:7102
clang::ObjCPropertyDecl::isAtomic
bool isAtomic() const
isAtomic - Return true if the property is atomic.
Definition: DeclObjC.h:843
emitARCRetainLoadOfScalar
static llvm::Value * emitARCRetainLoadOfScalar(CodeGenFunction &CGF, LValue lvalue, QualType type)
Definition: CGObjC.cpp:3405
clang::CodeGen::CodeGenFunction::EmitARCAutorelease
llvm::Value * EmitARCAutorelease(llvm::Value *value)
Autorelease the given object.
Definition: CGObjC.cpp:2503
clang::Selector::getNameForSlot
StringRef getNameForSlot(unsigned argIndex) const
Retrieve the name at a given position in the selector.
Definition: IdentifierTable.cpp:502
clang::CodeGen::EHScopeStack::Cleanup
Information for lazily generating a cleanup.
Definition: EHScopeStack.h:141
clang::CodeGen::ObjCEntrypoints::objc_release
llvm::Function * objc_release
void objc_release(id);
Definition: CodeGenModule.h:192
clang::LangOptions::ObjCRuntime
clang::ObjCRuntime ObjCRuntime
Definition: LangOptions.h:323
clang::OMF_retain
@ OMF_retain
Definition: IdentifierTable.h:706
clang::CodeGen::ARCPreciseLifetime
@ ARCPreciseLifetime
Definition: CGValue.h:121
clang::CodeGen::CodeGenFunction::emitDestroy
void emitDestroy(Address addr, QualType type, Destroyer *destroyer, bool useEHCleanupForArray)
emitDestroy - Immediately perform the destruction of the given object.
Definition: CGDecl.cpp:2180
clang::CodeGen::CodeGenModule::getObjCRuntime
CGObjCRuntime & getObjCRuntime()
Return a reference to the configured Objective-C runtime.
Definition: CodeGenModule.h:599
clang::CodeGen::CodeGenFunction::EmitObjCRetainNonBlock
llvm::Value * EmitObjCRetainNonBlock(llvm::Value *value, llvm::Type *returnType)
Retain the given object, with normal retain semantics.
Definition: CGObjC.cpp:2784
clang::CodeGen::CodeGenFunction::generateObjCSetterBody
void generateObjCSetterBody(const ObjCImplementationDecl *classImpl, const ObjCPropertyImplDecl *propImpl, llvm::Constant *AtomicHelperFn)
Definition: CGObjC.cpp:1401
clang::BinaryOperator
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3803
emitOptimizedARCReturnCall
static llvm::Value * emitOptimizedARCReturnCall(llvm::Value *value, bool IsRetainRV, CodeGenFunction &CGF)
Definition: CGObjC.cpp:2339
clang::CodeGen::CGObjCRuntime::EmitNSAutoreleasePoolClassRef
virtual llvm::Value * EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF)
Definition: CGObjCRuntime.h:275
clang::Qualifiers::OCL_Strong
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition: Type.h:173
clang::Scope
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:40
clang::ObjCAtThrowStmt
Represents Objective-C's @throw statement.
Definition: StmtObjC.h:332
clang::CodeGen::CodeGenFunction::AutoVarEmission
Definition: CodeGenFunction.h:3013
clang::SelectorTable::getSelector
Selector getSelector(unsigned NumArgs, IdentifierInfo **IIV)
Can create any sort of selector.
Definition: IdentifierTable.cpp:701
clang::CodeGen::CodeGenFunction::EmitObjCBoxedExpr
llvm::Value * EmitObjCBoxedExpr(const ObjCBoxedExpr *E)
EmitObjCBoxedExpr - This routine generates code to call the appropriate expression boxing method.
Definition: CGObjC.cpp:62
clang::CodeGen::CodeGenFunction::EmitCheck
void EmitCheck(ArrayRef< std::pair< llvm::Value *, SanitizerMask >> Checked, SanitizerHandler Check, ArrayRef< llvm::Constant * > StaticArgs, ArrayRef< llvm::Value * > DynamicArgs)
Create a basic block that will either trap or call a handler function in the UBSan runtime with the p...
Definition: CGExpr.cpp:3198
clang::ASTContext::Selectors
SelectorTable & Selectors
Definition: ASTContext.h:649
clang::CharUnits::fromQuantity
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition: CharUnits.h:63
object
clang::ObjCStringLiteral
ObjCStringLiteral, used for Objective-C string literals i.e.
Definition: ExprObjC.h:52
clang::BlockExpr::getBlockDecl
const BlockDecl * getBlockDecl() const
Definition: Expr.h:5977
clang::CodeGen::CodeGenFunction::EmitARCUnsafeUnretainedScalarExpr
llvm::Value * EmitARCUnsafeUnretainedScalarExpr(const Expr *expr)
EmitARCUnsafeUnretainedScalarExpr - Semantically equivalent to immediately releasing the resut of Emi...
Definition: CGObjC.cpp:3544
clang::CodeGen::CodeGenModule::getCodeGenOpts
const CodeGenOptions & getCodeGenOpts() const
Definition: CodeGenModule.h:708
clang::ObjCDictionaryElement::Key
Expr * Key
The key for the dictionary element.
Definition: ExprObjC.h:265
clang::CodeGen::CodeGenFunction::EmitARCAutoreleaseReturnValue
llvm::Value * EmitARCAutoreleaseReturnValue(llvm::Value *value)
Autorelease the given object.
Definition: CGObjC.cpp:2512
clang::ObjCMethodDecl::getMethodFamily
ObjCMethodFamily getMethodFamily() const
Determines the family of this method.
Definition: DeclObjC.cpp:1006
clang::CodeGen::Address::getType
llvm::PointerType * getType() const
Return the type of the pointer value.
Definition: Address.h:43
clang::Decl::getBodyRBrace
SourceLocation getBodyRBrace() const
getBodyRBrace - Gets the right brace of the body, if a body exists.
Definition: DeclBase.cpp:951
clang::FPOptionsOverride
Represents difference between two FPOptions values.
Definition: LangOptions.h:600
clang::CodeGen::CodeGenFunction::AutoVarEmission::invalid
static AutoVarEmission invalid()
Definition: CodeGenFunction.h:3054
clang::ASTContext
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:212
clang::GetUnarySelector
Selector GetUnarySelector(StringRef name, ASTContext &Ctx)
Utility function for constructing an unary selector.
Definition: ASTContext.h:3267
clang::ASTContext::getSizeType
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
Definition: ASTContext.cpp:5712
CGFunctionInfo.h
clang::CodeGen::CodeGenFunction::EmitObjCExtendObjectLifetime
llvm::Value * EmitObjCExtendObjectLifetime(QualType T, llvm::Value *Ptr)
Definition: CGObjC.cpp:2074
clang::CodeGen::CodeGenFunction::EmitObjCAllocInit
llvm::Value * EmitObjCAllocInit(llvm::Value *value, llvm::Type *resultType)
Definition: CGObjC.cpp:2731
clang::CPlusPlus
@ CPlusPlus
Definition: LangStandard.h:48
clang::CodeGen::CodeGenFunction::EmitARCStoreWeak
llvm::Value * EmitARCStoreWeak(Address addr, llvm::Value *value, bool ignored)
i8* @objc_storeWeak(i8** addr, i8* value) Returns value.
Definition: CGObjC.cpp:2574
clang::ObjCDictionaryLiteral
ObjCDictionaryLiteral - AST node to represent objective-c dictionary literals; as in:"name" : NSUserN...
Definition: ExprObjC.h:306
Diagnostic.h
clang::CodeGen::CodeGenFunction::EmitRuntimeCall
llvm::CallInst * EmitRuntimeCall(llvm::FunctionCallee callee, const Twine &name="")
clang::Selector::getNumArgs
unsigned getNumArgs() const
Definition: IdentifierTable.cpp:480
clang::CodeGen::TEK_Complex
@ TEK_Complex
Definition: CodeGenFunction.h:114
ValueTransform
llvm::function_ref< llvm::Value *(CodeGenFunction &CGF, llvm::Value *value)> ValueTransform
Definition: CGObjC.cpp:2927
clang::PseudoObjectExpr::const_semantics_iterator
const typedef Expr *const * const_semantics_iterator
Definition: Expr.h:6162
clang::Type::getAs
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:7161
clang::CodeGen::CodeGenFunction::getDebugInfo
CGDebugInfo * getDebugInfo()
Definition: CodeGenFunction.h:1948
clang::CodeGen::ObjCEntrypoints::objc_storeStrong
llvm::Function * objc_storeStrong
void objc_storeStrong(id*, id);
Definition: CodeGenModule.h:199
clang::CodeGen::CodeGenFunction::ConstantEmission
Definition: CodeGenFunction.h:3887
clang::ObjCMethodDecl::getSelector
Selector getSelector() const
Definition: DeclObjC.h:330
emitARCCopyOperation
static void emitARCCopyOperation(CodeGenFunction &CGF, Address dst, Address src, llvm::Function *&fn, llvm::Intrinsic::ID IntID)
Perform an operation having the following signature: void (i8**, i8**)
Definition: CGObjC.cpp:2198
tryEmitSpecializedAllocInit
static Optional< llvm::Value * > tryEmitSpecializedAllocInit(CodeGenFunction &CGF, const ObjCMessageExpr *OME)
Instead of '[[MyClass alloc] init]', try to generate 'objc_alloc_init(MyClass)'.
Definition: CGObjC.cpp:523
clang::CodeGen::CodeGenTypeCache::VoidTy
llvm::Type * VoidTy
void
Definition: CodeGenTypeCache.h:34
clang::ObjCRuntime::hasARCUnsafeClaimAutoreleasedReturnValue
bool hasARCUnsafeClaimAutoreleasedReturnValue() const
Is objc_unsafeClaimAutoreleasedReturnValue available?
Definition: ObjCRuntime.h:403
clang::ObjCPropertyImplDecl::getGetterCXXConstructor
Expr * getGetterCXXConstructor() const
Definition: DeclObjC.h:2852
clang::ObjCMethodDecl::isDirectMethod
bool isDirectMethod() const
True if the method is tagged as objc_direct.
Definition: DeclObjC.cpp:824
clang::TargetInfo::getPlatformMinVersion
VersionTuple getPlatformMinVersion() const
Retrieve the minimum desired version of the platform, to which the program should be compiled.
Definition: TargetInfo.h:1439
clang::ObjCMethodDecl::getSelfDecl
ImplicitParamDecl * getSelfDecl() const
Definition: DeclObjC.h:423
clang::PseudoObjectExpr
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition: Expr.h:6095
clang::ObjCAtSynchronizedStmt
Represents Objective-C's @synchronized statement.
Definition: StmtObjC.h:277
clang::ObjCMessageExpr::getReceiverKind
ReceiverKind getReceiverKind() const
Determine the kind of receiver that this message is being sent to.
Definition: ExprObjC.h:1224
clang::CodeGen::CodeGenModule::getModule
llvm::Module & getModule() const
Definition: CodeGenModule.h:709
clang::CodeGen::CGObjCRuntime::EmitTryStmt
virtual void EmitTryStmt(CodeGen::CodeGenFunction &CGF, const ObjCAtTryStmt &S)=0
clang::CodeGen::CodeGenFunction::EmitARCStoreStrongCall
llvm::Value * EmitARCStoreStrongCall(Address addr, llvm::Value *value, bool resultIgnored)
Store into a strong object.
Definition: CGObjC.cpp:2446
clang::ASTContext::getTypeSize
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2245
emitIsPlatformVersionAtLeast
static llvm::Value * emitIsPlatformVersionAtLeast(CodeGenFunction &CGF, const VersionTuple &Version)
Definition: CGObjC.cpp:3902
clang::CodeGen::CGDebugInfo
This class gathers all debug information during compilation and is responsible for emitting to llvm g...
Definition: CGDebugInfo.h:56
clang::DeclRefExpr::getDecl
ValueDecl * getDecl()
Definition: Expr.h:1289
clang::CodeGen::CodeGenFunction::getCleanupKind
CleanupKind getCleanupKind(QualType::DestructionKind kind)
Definition: CodeGenFunction.h:2055
clang::ImplicitParamDecl
Definition: Decl.h:1601
clang::ObjCMessageExpr::Class
@ Class
The receiver is a class.
Definition: ExprObjC.h:1088
clang::CodeGen::LValue::getType
QualType getType() const
Definition: CGValue.h:266
clang::CodeGen::CGObjCRuntime::EnumerationMutationFunction
virtual llvm::FunctionCallee EnumerationMutationFunction()=0
EnumerationMutationFunction - Return the function that's called by the compiler when a mutation is de...
clang::TypeInfoChars::Width
CharUnits Width
Definition: ASTContext.h:197
clang::interp::Cast
bool Cast(InterpState &S, CodePtr OpPC)
Definition: Interp.h:802
ASTContext.h
clang::VarDecl
Represents a variable declaration or definition.
Definition: Decl.h:876
clang::ObjCMethodDecl::getReturnType
QualType getReturnType() const
Definition: DeclObjC.h:332
clang::CodeGen::CGObjCRuntime::GetGetStructFunction
virtual llvm::FunctionCallee GetGetStructFunction()=0
clang::Type::getPointeeType
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:625
clang::CodeGen::CodeGenModule::getTypes
CodeGenTypes & getTypes()
Definition: CodeGenModule.h:726
clang::CXXConstructExpr::getConstructor
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition: ExprCXX.h:1532
clang::CodeGen::CGObjCRuntime::GenerateProtocolRef
virtual llvm::Value * GenerateProtocolRef(CodeGenFunction &CGF, const ObjCProtocolDecl *OPD)=0
Emit the code to return the named protocol as an object, as in a @protocol expression.
clang::ExprWithCleanups
Represents an expression – generally a full-expression – that introduces cleanups to be run at the en...
Definition: ExprCXX.h:3342
clang::CodeGen::CodeGenFunction::EmitAutoVarInit
void EmitAutoVarInit(const AutoVarEmission &emission)
Definition: CGDecl.cpp:1798
clang::ObjCDictionaryLiteral::getDictWithObjectsMethod
ObjCMethodDecl * getDictWithObjectsMethod() const
Definition: ExprObjC.h:376
llvm::DenseSet
Definition: Sema.h:78
clang::CodeGen::AggValueSlot::IsDestructed
@ IsDestructed
Definition: CGValue.h:525
getBaseMachOPlatformID
static unsigned getBaseMachOPlatformID(const llvm::Triple &TT)
Definition: CGObjC.cpp:3886
clang::CodeGen::CodeGenFunction::EmitAutoVarAlloca
AutoVarEmission EmitAutoVarAlloca(const VarDecl &var)
EmitAutoVarAlloca - Emit the alloca and debug information for a local variable.
Definition: CGDecl.cpp:1415
clang::CodeGen::CodeGenFunction::getLLVMContext
llvm::LLVMContext & getLLVMContext()
Definition: CodeGenFunction.h:1990
clang::CodeGen::CodeGenFunction::EmitObjCAutorelease
llvm::Value * EmitObjCAutorelease(llvm::Value *value, llvm::Type *returnType)
Autorelease the given object.
Definition: CGObjC.cpp:2774
clang::Type::isAtomicType
bool isAtomicType() const
Definition: Type.h:6807
clang::CodeGen::CodeGenFunction::getContext
ASTContext & getContext() const
Definition: CodeGenFunction.h:1947
clang::ObjCMethodDecl::getEndLoc
SourceLocation getEndLoc() const LLVM_READONLY
Definition: DeclObjC.cpp:1000
clang::CodeGen::NormalCleanup
@ NormalCleanup
Denotes a cleanup that should run when a scope is exited using normal control flow (falling off the e...
Definition: EHScopeStack.h:84
clang::CodeGen::CodeGenFunction::incrementProfileCounter
void incrementProfileCounter(const Stmt *S, llvm::Value *StepV=nullptr)
Increment the profiler's counter for the given statement by StepV.
Definition: CodeGenFunction.h:1490
clang::CodeGen::CodeGenFunction::FinishFunction
void FinishFunction(SourceLocation EndLoc=SourceLocation())
FinishFunction - Complete IR generation of the current function.
Definition: CodeGenFunction.cpp:324
clang::CodeGen::Address
An aligned address.
Definition: Address.h:24
AppendFirstImpliedRuntimeProtocols
static void AppendFirstImpliedRuntimeProtocols(const ObjCProtocolDecl *PD, llvm::UniqueVector< const ObjCProtocolDecl * > &PDs)
Definition: CGObjC.cpp:450
clang::CodeGen::CodeGenFunction::getJumpDestInCurrentScope
JumpDest getJumpDestInCurrentScope(llvm::BasicBlock *Target)
The given basic block lies in the current EH scope, but may be a target of a potentially scope-crossi...
Definition: CodeGenFunction.h:1112
clang::CodeGen::CodeGenFunction::EmitARCRetainAutoreleaseNonBlock
llvm::Value * EmitARCRetainAutoreleaseNonBlock(llvm::Value *value)
Do a fused retain/autorelease of the given object.
Definition: CGObjC.cpp:2551
CodeGenModule.h
clang::ObjCPropertyDecl::getType
QualType getType() const
Definition: DeclObjC.h:804
clang::CodeGen::CodeGenFunction::EmitObjCForCollectionStmt
void EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S)
Definition: CGObjC.cpp:1714
clang::CodeGen::CodeGenFunction::getARCCleanupKind
CleanupKind getARCCleanupKind()
Retrieves the default cleanup kind for an ARC cleanup.
Definition: CodeGenFunction.h:4230
clang::FunctionDecl::Create
static FunctionDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation NLoc, DeclarationName N, QualType T, TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin=false, bool isInlineSpecified=false, bool hasWrittenPrototype=true, ConstexprSpecKind ConstexprKind=ConstexprSpecKind::Unspecified, Expr *TrailingRequiresClause=nullptr)
Definition: Decl.h:2028
clang::CodeGen::CodeGenFunction::SanOpts
SanitizerSet SanOpts
Sanitizers enabled for this function.
Definition: CodeGenFunction.h:490
clang::CodeGen::CodeGenFunction::getEvaluationKind
static TypeEvaluationKind getEvaluationKind(QualType T)
getEvaluationKind - Return the TypeEvaluationKind of QualType T.
Definition: CodeGenFunction.cpp:215
clang::CodeGen::CGObjCRuntime::GetPropertySetFunction
virtual llvm::FunctionCallee GetPropertySetFunction()=0
Return the runtime function for setting properties.
clang::Selector::getMethodFamily
ObjCMethodFamily getMethodFamily() const
Derive the conventional family of this method.
Definition: IdentifierTable.h:872
clang::CXXConstructExpr::hadMultipleCandidates
bool hadMultipleCandidates() const
Whether the referred constructor was resolved from an overloaded set having size greater than 1.
Definition: ExprCXX.h:1543
clang::CodeGen::CodeGenModule::getAtomicSetterHelperFnMap
llvm::Constant * getAtomicSetterHelperFnMap(QualType Ty)
Definition: CodeGenModule.h:671
clang::CodeGen::CodeGenFunction::EmitObjCArrayLiteral
llvm::Value * EmitObjCArrayLiteral(const ObjCArrayLiteral *E)
Definition: CGObjC.cpp:243
getKind
static Decl::Kind getKind(const Decl *D)
Definition: DeclBase.cpp:998
clang::CodeGen::ObjCEntrypoints::objc_autorelease
llvm::Function * objc_autorelease
id objc_autorelease(id);
Definition: CodeGenModule.h:145
clang::CodeGen::CodeGenFunction::emitARCIntrinsicUse
static Destroyer emitARCIntrinsicUse
Definition: CodeGenFunction.h:4298
clang::ObjCMessageExpr
An expression that sends a message to the given Objective-C object or class.
Definition: ExprObjC.h:940
tryEmitARCRetainLoadOfScalar
static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF, LValue lvalue, QualType type)
Definition: CGObjC.cpp:2864
clang::CodeGen::CodeGenFunction::EmitObjCAllocWithZone
llvm::Value * EmitObjCAllocWithZone(llvm::Value *value, llvm::Type *returnType)
Allocate the given objc object.
Definition: CGObjC.cpp:2724
clang::CodeGen::ObjCEntrypoints::objc_retainAutorelease
llvm::Function * objc_retainAutorelease
id objc_retainAutorelease(id);
Definition: CodeGenModule.h:180
clang::CastExpr::getCastKind
CastKind getCastKind() const
Definition: Expr.h:3518
clang::Qualifiers::OCL_Autoreleasing
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition: Type.h:179
StmtObjC.h
getARCIntrinsic
static llvm::Function * getARCIntrinsic(llvm::Intrinsic::ID IntID, CodeGenModule &CGM)
Definition: CGObjC.cpp:2117
clang::CodeGen::CodeGenFunction::EmitAnyExprToMem
void EmitAnyExprToMem(const Expr *E, Address Location, Qualifiers Quals, bool IsInitializer)
EmitAnyExprToMem - Emits the code necessary to evaluate an arbitrary expression into the given memory...
Definition: CGExpr.cpp:231
clang::Qualifiers::setObjCLifetime
void setObjCLifetime(ObjCLifetime type)
Definition: Type.h:338
clang::CodeGen::CGCallee::forDirect
static CGCallee forDirect(llvm::Constant *functionPtr, const CGCalleeInfo &abstractInfo=CGCalleeInfo())
Definition: CGCall.h:135
clang::CXXOperatorCallExpr::Create
static CXXOperatorCallExpr * Create(const ASTContext &Ctx, OverloadedOperatorKind OpKind, Expr *Fn, ArrayRef< Expr * > Args, QualType Ty, ExprValueKind VK, SourceLocation OperatorLoc, FPOptionsOverride FPFeatures, ADLCallKind UsesADL=NotADL)
Definition: ExprCXX.cpp:558
clang::Qualifiers::ObjCLifetime
ObjCLifetime
Definition: Type.h:160
clang::CodeGen::CodeGenFunction::EmitARCRetainScalarExpr
llvm::Value * EmitARCRetainScalarExpr(const Expr *expr)
EmitARCRetainScalarExpr - Semantically equivalent to EmitARCRetainObject(e->getType(),...
Definition: CGObjC.cpp:3419
clang::SC_Static
@ SC_Static
Definition: Specifiers.h:237
clang::CodeGen::CodeGenModule::getTarget
const TargetInfo & getTarget() const
Definition: CodeGenModule.h:714
clang::QualType::getUnqualifiedType
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:6504
clang::CodeGen::ObjCEntrypoints::objc_alloc_init
llvm::FunctionCallee objc_alloc_init
void objc_alloc_init(id);
Definition: CodeGenModule.h:132
clang::CodeGen::CodeGenFunction::CurGD
GlobalDecl CurGD
CurGD - The GlobalDecl for the current function being compiled.
Definition: CodeGenFunction.h:350
clang::CodeGen::CodeGenTypeCache::Int32Ty
llvm::IntegerType * Int32Ty
Definition: CodeGenTypeCache.h:37
clang::CodeGen::CodeGenFunction::destroyARCStrongImprecise
static Destroyer destroyARCStrongImprecise
Definition: CodeGenFunction.h:4295
clang::Type::isObjCObjectPointerType
bool isObjCObjectPointerType() const
Definition: Type.h:6794
clang::CodeGen::ObjCEntrypoints::objc_retain
llvm::Function * objc_retain
id objc_retain(id);
Definition: CodeGenModule.h:173
clang::ObjCPropertyDecl::getSetterKind
SetterKind getSetterKind() const
getSetterKind - Return the method used for doing assignment in the property setter.
Definition: DeclObjC.h:873
shouldEmitSeparateBlockRetain
static bool shouldEmitSeparateBlockRetain(const Expr *e)
Determine whether it might be important to emit a separate objc_retain_block on the result of the giv...
Definition: CGObjC.cpp:3029
clang::CodeGen::ObjCEntrypoints::objc_initWeak
llvm::Function * objc_initWeak
id objc_initWeak(id*, id);
Definition: CodeGenModule.h:161
clang::CodeGen::CodeGenModule::IsPlatformVersionAtLeastFn
llvm::FunctionCallee IsPlatformVersionAtLeastFn
Definition: CodeGenModule.h:636
clang::CodeGen::CGObjCRuntime::GenerateMessageSendSuper
virtual CodeGen::RValue GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF, ReturnValueSlot ReturnSlot, QualType ResultType, Selector Sel, const ObjCInterfaceDecl *Class, bool isCategoryImpl, llvm::Value *Self, bool IsClassMessage, const CallArgList &CallArgs, const ObjCMethodDecl *Method=nullptr)=0
Generate an Objective-C message send operation to the super class initiated in a method for Class and...
clang::CodeGen::CGObjCRuntime::EmitSynchronizedStmt
virtual void EmitSynchronizedStmt(CodeGen::CodeGenFunction &CGF, const ObjCAtSynchronizedStmt &S)=0
clang::VK_LValue
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:124
clang::ObjCPropertyDecl::Copy
@ Copy
Definition: DeclObjC.h:736
clang::CodeGen::CodeGenTypes::GetFunctionType
llvm::FunctionType * GetFunctionType(const CGFunctionInfo &Info)
GetFunctionType - Get the LLVM function type for.
Definition: CGCall.cpp:1595
clang::CodeGen::CodeGenModule::getDataLayout
const llvm::DataLayout & getDataLayout() const
Definition: CodeGenModule.h:711
clang::Type::castAs
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:7226
clang::ObjCDictionaryLiteral::getKeyValueElement
ObjCDictionaryElement getKeyValueElement(unsigned Index) const
Definition: ExprObjC.h:362
clang::CodeGen::CodeGenFunction::EmitObjCAlloc
llvm::Value * EmitObjCAlloc(llvm::Value *value, llvm::Type *returnType)
Allocate the given objc object.
Definition: CGObjC.cpp:2715
clang::ObjCRuntime::hasAtomicCopyHelper
bool hasAtomicCopyHelper() const
Definition: ObjCRuntime.h:389
clang::Expr::IgnoreParenCasts
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition: Expr.cpp:2924
clang::TargetInfo::getTriple
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1130
clang::CodeGen::CodeGenFunction::OpaqueValueMappingData
A non-RAII class containing all the information about a bound opaque value.
Definition: CodeGenFunction.h:1222
clang::ObjCObjectPointerType
Represents a pointer to an Objective C object.
Definition: Type.h:6072
clang::CodeGen::ObjCEntrypoints::objc_autoreleasePoolPopInvoke
llvm::FunctionCallee objc_autoreleasePoolPopInvoke
void objc_autoreleasePoolPop(void*); Note this method is used when we are using exception handling
Definition: CodeGenModule.h:139
clang::CodeGen::CodeGenFunction::StartFunction
void StartFunction(GlobalDecl GD, QualType RetTy, llvm::Function *Fn, const CGFunctionInfo &FnInfo, const FunctionArgList &Args, SourceLocation Loc=SourceLocation(), SourceLocation StartLoc=SourceLocation())
Emit code for the start of a function.
Definition: CodeGenFunction.cpp:700
clang::ObjCImplementationDecl::inits
init_range inits()
Definition: DeclObjC.h:2608
clang::CodeGen::CGObjCRuntime::GeneratePossiblySpecializedMessageSend
CodeGen::RValue GeneratePossiblySpecializedMessageSend(CodeGenFunction &CGF, ReturnValueSlot Return, QualType ResultType, Selector Sel, llvm::Value *Receiver, const CallArgList &Args, const ObjCInterfaceDecl *OID, const ObjCMethodDecl *Method, bool isClassMessage)
Generate an Objective-C message send operation.
Definition: CGObjC.cpp:436
clang::BinaryOperator::Create
static BinaryOperator * Create(const ASTContext &C, Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy, ExprValueKind VK, ExprObjectKind OK, SourceLocation opLoc, FPOptionsOverride FPFeatures)
Definition: Expr.cpp:4506
clang::CodeGen::LValue
LValue - This represents an lvalue references.
Definition: CGValue.h:167
clang::CodeGen::CodeGenFunction::EHStack
EHScopeStack EHStack
Definition: CodeGenFunction.h:585
clang::CodeGen::CodeGenFunction::getOverlapForReturnValue
AggValueSlot::Overlap_t getOverlapForReturnValue()
Determine whether a return value slot may overlap some other object.
Definition: CodeGenFunction.h:2640
clang::CodeGen::CGObjCRuntime::GenerateMethod
virtual llvm::Function * GenerateMethod(const ObjCMethodDecl *OMD, const ObjCContainerDecl *CD)=0
Generate a function preamble for a method with the specified types.
clang::VK_PRValue
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:120
clang::CodeGen::CodeGenFunction::MakeNaturalAlignAddrLValue
LValue MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T)
Definition: CodeGenFunction.cpp:187
clang::CodeGen::AggValueSlot::forAddr
static AggValueSlot forAddr(Address addr, Qualifiers quals, IsDestructed_t isDestructed, NeedsGCBarriers_t needsGC, IsAliased_t isAliased, Overlap_t mayOverlap, IsZeroed_t isZeroed=IsNotZeroed, IsSanitizerChecked_t isChecked=IsNotSanitizerChecked)
forAddr - Make a slot for an aggregate value.
Definition: CGValue.h:548
clang::CodeGen::CodeGenFunction::EmitDeclRefLValue
LValue EmitDeclRefLValue(const DeclRefExpr *E)
Definition: CGExpr.cpp:2668
clang::ASTContext::VoidPtrTy
CanQualType VoidPtrTy
Definition: ASTContext.h:1102
clang::FieldDecl::isBitField
bool isBitField() const
Determines whether this field is a bitfield.
Definition: Decl.h:2913
clang::Type::isPointerType
bool isPointerType() const
Definition: Type.h:6672
clang::CodeGen::CodeGenFunction::EmitARCStoreUnsafeUnretained
std::pair< LValue, llvm::Value * > EmitARCStoreUnsafeUnretained(const BinaryOperator *e, bool ignored)
Definition: CGObjC.cpp:3555
clang::CodeGen::CodeGenFunction::EmitCallOrInvoke
llvm::CallBase * EmitCallOrInvoke(llvm::FunctionCallee Callee, ArrayRef< llvm::Value * > Args, const Twine &Name="")
Emits a call or invoke instruction to the given function, depending on the current state of the EH st...
Definition: CGCall.cpp:4483
clang::CodeGen::Address::getPointer
llvm::Value * getPointer() const
Definition: Address.h:37
clang::CodeGen::CodeGenModule::ErrorUnsupported
void ErrorUnsupported(const Stmt *S, const char *Type)
Print out an error that codegen doesn't support the specified stmt yet.
Definition: CodeGenModule.cpp:964
clang::CodeGen::CodeGenFunction
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
Definition: CodeGenFunction.h:235
clang::CodeGen::CodeGenModule::getObjCFastEnumerationStateType
QualType getObjCFastEnumerationStateType()