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"
24 #include "clang/CodeGen/CGFunctionInfo.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
35 tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e);
36 static RValue AdjustObjCObjectType(CodeGenFunction &CGF,
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.
48 llvm::Value *CodeGenFunction::EmitObjCStringLiteral(const ObjCStringLiteral *E)
49 {
50   llvm::Constant *C =
51       CGM.getObjCRuntime().GenerateConstantString(E->getString()).getPointer();
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 ///
61 llvm::Value *
62 CodeGenFunction::EmitObjCBoxedExpr(const ObjCBoxedExpr *E) {
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 
68   if (E->isExpressibleAsConstantInitializer()) {
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 
120 llvm::Value *CodeGenFunction::EmitObjCCollectionLiteral(const Expr *E,
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__";
133     QualType IdTy(CGM.getContext().getObjCIdType());
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);
170       LValue LV = MakeAddrLValue(Builder.CreateConstArrayGEP(Objects, 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;
181       LValue KeyLV = MakeAddrLValue(Builder.CreateConstArrayGEP(Keys, i),
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 
243 llvm::Value *CodeGenFunction::EmitObjCArrayLiteral(const ObjCArrayLiteral *E) {
244   return EmitObjCCollectionLiteral(E, E->getArrayWithObjectsMethod());
245 }
246 
247 llvm::Value *CodeGenFunction::EmitObjCDictionaryLiteral(
248                                             const ObjCDictionaryLiteral *E) {
249   return EmitObjCCollectionLiteral(E, E->getDictWithObjectsMethod());
250 }
251 
252 /// Emit a selector.
253 llvm::Value *CodeGenFunction::EmitObjCSelectorExpr(const ObjCSelectorExpr *E) {
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 
261 llvm::Value *CodeGenFunction::EmitObjCProtocolExpr(const ObjCProtocolExpr *E) {
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.
269 static RValue AdjustObjCObjectType(CodeGenFunction &CGF, QualType ExpT,
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
287 shouldExtendReceiverForInnerPointerMessage(const ObjCMessageExpr *message) {
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.
292   case ObjCMessageExpr::Instance: {
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 
331   case ObjCMessageExpr::Class:
332   case ObjCMessageExpr::SuperClass:
333     // It's never necessary for class objects.
334     return false;
335 
336   case ObjCMessageExpr::SuperInstance:
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.
373 static Optional<llvm::Value *>
374 tryGenerateSpecializedMessageSend(CodeGenFunction &CGF, QualType ResultType,
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 
436 CodeGen::RValue CGObjCRuntime::GeneratePossiblySpecializedMessageSend(
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 
450 static void AppendFirstImpliedRuntimeProtocols(
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 *>
464 CGObjCRuntime::GetRuntimeProtocolList(ObjCProtocolDecl::protocol_iterator begin,
465                                       ObjCProtocolDecl::protocol_iterator end) {
466   std::vector<const ObjCProtocolDecl *> RuntimePds;
467   llvm::DenseSet<const ObjCProtocolDecl *> NonRuntimePDs;
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.
522 static Optional<llvm::Value *>
523 tryEmitSpecializedAllocInit(CodeGenFunction &CGF, const ObjCMessageExpr *OME) {
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();
530   if (OME->getReceiverKind() != ObjCMessageExpr::Instance ||
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()) {
549   case ObjCMessageExpr::Instance:
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   }
563   case ObjCMessageExpr::SuperInstance:
564   case ObjCMessageExpr::SuperClass:
565     return None;
566   }
567 
568   return CGF.EmitObjCAllocInit(Receiver, CGF.ConvertType(OME->getType()));
569 }
570 
571 RValue CodeGenFunction::EmitObjCMessageExpr(const ObjCMessageExpr *E,
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 
592   if (Optional<llvm::Value *> Val = tryEmitSpecializedAllocInit(*this, E))
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()) {
613   case ObjCMessageExpr::Instance:
614     ReceiverType = E->getInstanceReceiver()->getType();
615     isClassMessage = ReceiverType->isObjCClassType();
616     if (retainSelf) {
617       TryEmitResult ter = tryEmitARCRetainScalarExpr(*this,
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 
634   case ObjCMessageExpr::SuperInstance:
635     ReceiverType = E->getSuperType();
636     Receiver = LoadObjCSelf();
637     isSuperMessage = true;
638     break;
639 
640   case ObjCMessageExpr::SuperClass:
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>() &&
656       shouldExtendReceiverForInnerPointerMessage(E))
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.
696     result = Runtime.GeneratePossiblySpecializedMessageSend(
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;
734     CGF.CGM.getObjCRuntime().GenerateMessageSendSuper(CGF, ReturnValueSlot(),
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.
750 void CodeGenFunction::StartObjCMethod(const ObjCMethodDecl *OMD,
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 
760   const CGFunctionInfo &FI = CGM.getTypes().arrangeObjCMethodDeclaration(OMD);
761   if (OMD->isDirectMethod()) {
762     Fn->setVisibility(llvm::Function::HiddenVisibility);
763     CGM.SetLLVMFunctionAttributes(OMD, FI, Fn);
764     CGM.SetLLVMFunctionAttributesForDefinition(OMD, Fn);
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 =
793       OMD->getSelector().getIdentifierInfoForSlot(0);
794     if (ident->isStr("dealloc"))
795       EHStack.pushCleanup<FinishARCDealloc>(getARCCleanupKind());
796   }
797 }
798 
799 static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
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.
804 void CodeGenFunction::GenerateObjCMethod(const ObjCMethodDecl *OMD) {
805   StartObjCMethod(OMD, OMD->getClassInterface());
806   PGO.assignRegionCounters(GlobalDecl(OMD), CurFn);
807   assert(isa<CompoundStmt>(OMD->getBody()));
808   incrementProfileCounter(OMD->getBody());
809   EmitCompoundStmtWithoutScope(*cast<CompoundStmt>(OMD->getBody()));
810   FinishFunction(OMD->getBodyRBrace());
811 }
812 
813 /// emitStructGetterCall - Call the runtime function to load a property
814 /// into the return value slot.
815 static void emitStructGetterCall(CodeGenFunction &CGF, ObjCIvarDecl *ivar,
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.
855 static CharUnits getMaxAtomicAccessSize(CodeGenModule &CGM,
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.
862   return CharUnits::fromQuantity(CGM.PointerSizeInBytes);
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 getProperty/setProperty.
929   // TODO: we could actually use setProperty and an expression for non-atomics.
930   if (IsCopy) {
931     Kind = GetSetProperty;
932     return;
933   }
934 
935   // Handle retain.
936   if (setterKind == ObjCPropertyDecl::Retain) {
937     // In GC-only, there's nothing special that needs to be done.
938     if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
939       // fallthrough
940 
941     // In ARC, if the property is non-atomic, use expression emission,
942     // which translates to objc_storeStrong.  This isn't required, but
943     // it's slightly nicer.
944     } else if (CGM.getLangOpts().ObjCAutoRefCount && !IsAtomic) {
945       // Using standard expression emission for the setter is only
946       // acceptable if the ivar is __strong, which won't be true if
947       // the property is annotated with __attribute__((NSObject)).
948       // TODO: falling all the way back to objc_setProperty here is
949       // just laziness, though;  we could still use objc_storeStrong
950       // if we hacked it right.
951       if (ivarType.getObjCLifetime() == Qualifiers::OCL_Strong)
952         Kind = Expression;
953       else
954         Kind = SetPropertyAndExpressionGet;
955       return;
956 
957     // Otherwise, we need to at least use setProperty.  However, if
958     // the property isn't atomic, we can use normal expression
959     // emission for the getter.
960     } else if (!IsAtomic) {
961       Kind = SetPropertyAndExpressionGet;
962       return;
963 
964     // Otherwise, we have to use both setProperty and getProperty.
965     } else {
966       Kind = GetSetProperty;
967       return;
968     }
969   }
970 
971   // If we're not atomic, just use expression accesses.
972   if (!IsAtomic) {
973     Kind = Expression;
974     return;
975   }
976 
977   // Properties on bitfield ivars need to be emitted using expression
978   // accesses even if they're nominally atomic.
979   if (ivar->isBitField()) {
980     Kind = Expression;
981     return;
982   }
983 
984   // GC-qualified or ARC-qualified ivars need to be emitted as
985   // expressions.  This actually works out to being atomic anyway,
986   // except for ARC __strong, but that should trigger the above code.
987   if (ivarType.hasNonTrivialObjCLifetime() ||
988       (CGM.getLangOpts().getGC() &&
989        CGM.getContext().getObjCGCAttrKind(ivarType))) {
990     Kind = Expression;
991     return;
992   }
993 
994   // Compute whether the ivar has strong members.
995   if (CGM.getLangOpts().getGC())
996     if (const RecordType *recordType = ivarType->getAs<RecordType>())
997       HasStrong = recordType->getDecl()->hasObjectMember();
998 
999   // We can never access structs with object members with a native
1000   // access, because we need to use write barriers.  This is what
1001   // objc_copyStruct is for.
1002   if (HasStrong) {
1003     Kind = CopyStruct;
1004     return;
1005   }
1006 
1007   // Otherwise, this is target-dependent and based on the size and
1008   // alignment of the ivar.
1009 
1010   // If the size of the ivar is not a power of two, give up.  We don't
1011   // want to get into the business of doing compare-and-swaps.
1012   if (!IvarSize.isPowerOfTwo()) {
1013     Kind = CopyStruct;
1014     return;
1015   }
1016 
1017   llvm::Triple::ArchType arch =
1018     CGM.getTarget().getTriple().getArch();
1019 
1020   // Most architectures require memory to fit within a single cache
1021   // line, so the alignment has to be at least the size of the access.
1022   // Otherwise we have to grab a lock.
1023   if (IvarAlignment < IvarSize && !hasUnalignedAtomics(arch)) {
1024     Kind = CopyStruct;
1025     return;
1026   }
1027 
1028   // If the ivar's size exceeds the architecture's maximum atomic
1029   // access size, we have to use CopyStruct.
1030   if (IvarSize > getMaxAtomicAccessSize(CGM, arch)) {
1031     Kind = CopyStruct;
1032     return;
1033   }
1034 
1035   // Otherwise, we can use native loads and stores.
1036   Kind = Native;
1037 }
1038 
1039 /// Generate an Objective-C property getter function.
1040 ///
1041 /// The given Decl must be an ObjCImplementationDecl. \@synthesize
1042 /// is illegal within a category.
1043 void CodeGenFunction::GenerateObjCGetter(ObjCImplementationDecl *IMP,
1044                                          const ObjCPropertyImplDecl *PID) {
1045   llvm::Constant *AtomicHelperFn =
1046       CodeGenFunction(CGM).GenerateObjCAtomicGetterCopyHelperFunction(PID);
1047   ObjCMethodDecl *OMD = PID->getGetterMethodDecl();
1048   assert(OMD && "Invalid call to generate getter (empty method)");
1049   StartObjCMethod(OMD, IMP->getClassInterface());
1050 
1051   generateObjCGetterBody(IMP, PID, OMD, AtomicHelperFn);
1052 
1053   FinishFunction(OMD->getEndLoc());
1054 }
1055 
1056 static bool hasTrivialGetExpr(const ObjCPropertyImplDecl *propImpl) {
1057   const Expr *getter = propImpl->getGetterCXXConstructor();
1058   if (!getter) return true;
1059 
1060   // Sema only makes only of these when the ivar has a C++ class type,
1061   // so the form is pretty constrained.
1062 
1063   // If the property has a reference type, we might just be binding a
1064   // reference, in which case the result will be a gl-value.  We should
1065   // treat this as a non-trivial operation.
1066   if (getter->isGLValue())
1067     return false;
1068 
1069   // If we selected a trivial copy-constructor, we're okay.
1070   if (const CXXConstructExpr *construct = dyn_cast<CXXConstructExpr>(getter))
1071     return (construct->getConstructor()->isTrivial());
1072 
1073   // The constructor might require cleanups (in which case it's never
1074   // trivial).
1075   assert(isa<ExprWithCleanups>(getter));
1076   return false;
1077 }
1078 
1079 /// emitCPPObjectAtomicGetterCall - Call the runtime function to
1080 /// copy the ivar into the resturn slot.
1081 static void emitCPPObjectAtomicGetterCall(CodeGenFunction &CGF,
1082                                           llvm::Value *returnAddr,
1083                                           ObjCIvarDecl *ivar,
1084                                           llvm::Constant *AtomicHelperFn) {
1085   // objc_copyCppObjectAtomic (&returnSlot, &CppObjectIvar,
1086   //                           AtomicHelperFn);
1087   CallArgList args;
1088 
1089   // The 1st argument is the return Slot.
1090   args.add(RValue::get(returnAddr), CGF.getContext().VoidPtrTy);
1091 
1092   // The 2nd argument is the address of the ivar.
1093   llvm::Value *ivarAddr =
1094       CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(), ivar, 0)
1095           .getPointer(CGF);
1096   ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
1097   args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
1098 
1099   // Third argument is the helper function.
1100   args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
1101 
1102   llvm::FunctionCallee copyCppAtomicObjectFn =
1103       CGF.CGM.getObjCRuntime().GetCppAtomicObjectGetFunction();
1104   CGCallee callee = CGCallee::forDirect(copyCppAtomicObjectFn);
1105   CGF.EmitCall(
1106       CGF.getTypes().arrangeBuiltinFunctionCall(CGF.getContext().VoidTy, args),
1107                callee, ReturnValueSlot(), args);
1108 }
1109 
1110 void
1111 CodeGenFunction::generateObjCGetterBody(const ObjCImplementationDecl *classImpl,
1112                                         const ObjCPropertyImplDecl *propImpl,
1113                                         const ObjCMethodDecl *GetterMethodDecl,
1114                                         llvm::Constant *AtomicHelperFn) {
1115   // If there's a non-trivial 'get' expression, we just have to emit that.
1116   if (!hasTrivialGetExpr(propImpl)) {
1117     if (!AtomicHelperFn) {
1118       auto *ret = ReturnStmt::Create(getContext(), SourceLocation(),
1119                                      propImpl->getGetterCXXConstructor(),
1120                                      /* NRVOCandidate=*/nullptr);
1121       EmitReturnStmt(*ret);
1122     }
1123     else {
1124       ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
1125       emitCPPObjectAtomicGetterCall(*this, ReturnValue.getPointer(),
1126                                     ivar, AtomicHelperFn);
1127     }
1128     return;
1129   }
1130 
1131   const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
1132   QualType propType = prop->getType();
1133   ObjCMethodDecl *getterMethod = propImpl->getGetterMethodDecl();
1134 
1135   ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
1136 
1137   // Pick an implementation strategy.
1138   PropertyImplStrategy strategy(CGM, propImpl);
1139   switch (strategy.getKind()) {
1140   case PropertyImplStrategy::Native: {
1141     // We don't need to do anything for a zero-size struct.
1142     if (strategy.getIvarSize().isZero())
1143       return;
1144 
1145     LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
1146 
1147     // Currently, all atomic accesses have to be through integer
1148     // types, so there's no point in trying to pick a prettier type.
1149     uint64_t ivarSize = getContext().toBits(strategy.getIvarSize());
1150     llvm::Type *bitcastType = llvm::Type::getIntNTy(getLLVMContext(), ivarSize);
1151     bitcastType = bitcastType->getPointerTo(); // addrspace 0 okay
1152 
1153     // Perform an atomic load.  This does not impose ordering constraints.
1154     Address ivarAddr = LV.getAddress(*this);
1155     ivarAddr = Builder.CreateBitCast(ivarAddr, bitcastType);
1156     llvm::LoadInst *load = Builder.CreateLoad(ivarAddr, "load");
1157     load->setAtomic(llvm::AtomicOrdering::Unordered);
1158 
1159     // Store that value into the return address.  Doing this with a
1160     // bitcast is likely to produce some pretty ugly IR, but it's not
1161     // the *most* terrible thing in the world.
1162     llvm::Type *retTy = ConvertType(getterMethod->getReturnType());
1163     uint64_t retTySize = CGM.getDataLayout().getTypeSizeInBits(retTy);
1164     llvm::Value *ivarVal = load;
1165     if (ivarSize > retTySize) {
1166       llvm::Type *newTy = llvm::Type::getIntNTy(getLLVMContext(), retTySize);
1167       ivarVal = Builder.CreateTrunc(load, newTy);
1168       bitcastType = newTy->getPointerTo();
1169     }
1170     Builder.CreateStore(ivarVal,
1171                         Builder.CreateBitCast(ReturnValue, bitcastType));
1172 
1173     // Make sure we don't do an autorelease.
1174     AutoreleaseResult = false;
1175     return;
1176   }
1177 
1178   case PropertyImplStrategy::GetSetProperty: {
1179     llvm::FunctionCallee getPropertyFn =
1180         CGM.getObjCRuntime().GetPropertyGetFunction();
1181     if (!getPropertyFn) {
1182       CGM.ErrorUnsupported(propImpl, "Obj-C getter requiring atomic copy");
1183       return;
1184     }
1185     CGCallee callee = CGCallee::forDirect(getPropertyFn);
1186 
1187     // Return (ivar-type) objc_getProperty((id) self, _cmd, offset, true).
1188     // FIXME: Can't this be simpler? This might even be worse than the
1189     // corresponding gcc code.
1190     llvm::Value *cmd =
1191       Builder.CreateLoad(GetAddrOfLocalVar(getterMethod->getCmdDecl()), "cmd");
1192     llvm::Value *self = Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
1193     llvm::Value *ivarOffset =
1194       EmitIvarOffset(classImpl->getClassInterface(), ivar);
1195 
1196     CallArgList args;
1197     args.add(RValue::get(self), getContext().getObjCIdType());
1198     args.add(RValue::get(cmd), getContext().getObjCSelType());
1199     args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
1200     args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
1201              getContext().BoolTy);
1202 
1203     // FIXME: We shouldn't need to get the function info here, the
1204     // runtime already should have computed it to build the function.
1205     llvm::CallBase *CallInstruction;
1206     RValue RV = EmitCall(getTypes().arrangeBuiltinFunctionCall(
1207                              getContext().getObjCIdType(), args),
1208                          callee, ReturnValueSlot(), args, &CallInstruction);
1209     if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(CallInstruction))
1210       call->setTailCall();
1211 
1212     // We need to fix the type here. Ivars with copy & retain are
1213     // always objects so we don't need to worry about complex or
1214     // aggregates.
1215     RV = RValue::get(Builder.CreateBitCast(
1216         RV.getScalarVal(),
1217         getTypes().ConvertType(getterMethod->getReturnType())));
1218 
1219     EmitReturnOfRValue(RV, propType);
1220 
1221     // objc_getProperty does an autorelease, so we should suppress ours.
1222     AutoreleaseResult = false;
1223 
1224     return;
1225   }
1226 
1227   case PropertyImplStrategy::CopyStruct:
1228     emitStructGetterCall(*this, ivar, strategy.isAtomic(),
1229                          strategy.hasStrongMember());
1230     return;
1231 
1232   case PropertyImplStrategy::Expression:
1233   case PropertyImplStrategy::SetPropertyAndExpressionGet: {
1234     LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
1235 
1236     QualType ivarType = ivar->getType();
1237     switch (getEvaluationKind(ivarType)) {
1238     case TEK_Complex: {
1239       ComplexPairTy pair = EmitLoadOfComplex(LV, SourceLocation());
1240       EmitStoreOfComplex(pair, MakeAddrLValue(ReturnValue, ivarType),
1241                          /*init*/ true);
1242       return;
1243     }
1244     case TEK_Aggregate: {
1245       // The return value slot is guaranteed to not be aliased, but
1246       // that's not necessarily the same as "on the stack", so
1247       // we still potentially need objc_memmove_collectable.
1248       EmitAggregateCopy(/* Dest= */ MakeAddrLValue(ReturnValue, ivarType),
1249                         /* Src= */ LV, ivarType, getOverlapForReturnValue());
1250       return;
1251     }
1252     case TEK_Scalar: {
1253       llvm::Value *value;
1254       if (propType->isReferenceType()) {
1255         value = LV.getAddress(*this).getPointer();
1256       } else {
1257         // We want to load and autoreleaseReturnValue ARC __weak ivars.
1258         if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
1259           if (getLangOpts().ObjCAutoRefCount) {
1260             value = emitARCRetainLoadOfScalar(*this, LV, ivarType);
1261           } else {
1262             value = EmitARCLoadWeak(LV.getAddress(*this));
1263           }
1264 
1265         // Otherwise we want to do a simple load, suppressing the
1266         // final autorelease.
1267         } else {
1268           value = EmitLoadOfLValue(LV, SourceLocation()).getScalarVal();
1269           AutoreleaseResult = false;
1270         }
1271 
1272         value = Builder.CreateBitCast(
1273             value, ConvertType(GetterMethodDecl->getReturnType()));
1274       }
1275 
1276       EmitReturnOfRValue(RValue::get(value), propType);
1277       return;
1278     }
1279     }
1280     llvm_unreachable("bad evaluation kind");
1281   }
1282 
1283   }
1284   llvm_unreachable("bad @property implementation strategy!");
1285 }
1286 
1287 /// emitStructSetterCall - Call the runtime function to store the value
1288 /// from the first formal parameter into the given ivar.
1289 static void emitStructSetterCall(CodeGenFunction &CGF, ObjCMethodDecl *OMD,
1290                                  ObjCIvarDecl *ivar) {
1291   // objc_copyStruct (&structIvar, &Arg,
1292   //                  sizeof (struct something), true, false);
1293   CallArgList args;
1294 
1295   // The first argument is the address of the ivar.
1296   llvm::Value *ivarAddr =
1297       CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(), ivar, 0)
1298           .getPointer(CGF);
1299   ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
1300   args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
1301 
1302   // The second argument is the address of the parameter variable.
1303   ParmVarDecl *argVar = *OMD->param_begin();
1304   DeclRefExpr argRef(CGF.getContext(), argVar, false,
1305                      argVar->getType().getNonReferenceType(), VK_LValue,
1306                      SourceLocation());
1307   llvm::Value *argAddr = CGF.EmitLValue(&argRef).getPointer(CGF);
1308   argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
1309   args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
1310 
1311   // The third argument is the sizeof the type.
1312   llvm::Value *size =
1313     CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(ivar->getType()));
1314   args.add(RValue::get(size), CGF.getContext().getSizeType());
1315 
1316   // The fourth argument is the 'isAtomic' flag.
1317   args.add(RValue::get(CGF.Builder.getTrue()), CGF.getContext().BoolTy);
1318 
1319   // The fifth argument is the 'hasStrong' flag.
1320   // FIXME: should this really always be false?
1321   args.add(RValue::get(CGF.Builder.getFalse()), CGF.getContext().BoolTy);
1322 
1323   llvm::FunctionCallee fn = CGF.CGM.getObjCRuntime().GetSetStructFunction();
1324   CGCallee callee = CGCallee::forDirect(fn);
1325   CGF.EmitCall(
1326       CGF.getTypes().arrangeBuiltinFunctionCall(CGF.getContext().VoidTy, args),
1327                callee, ReturnValueSlot(), args);
1328 }
1329 
1330 /// emitCPPObjectAtomicSetterCall - Call the runtime function to store
1331 /// the value from the first formal parameter into the given ivar, using
1332 /// the Cpp API for atomic Cpp objects with non-trivial copy assignment.
1333 static void emitCPPObjectAtomicSetterCall(CodeGenFunction &CGF,
1334                                           ObjCMethodDecl *OMD,
1335                                           ObjCIvarDecl *ivar,
1336                                           llvm::Constant *AtomicHelperFn) {
1337   // objc_copyCppObjectAtomic (&CppObjectIvar, &Arg,
1338   //                           AtomicHelperFn);
1339   CallArgList args;
1340 
1341   // The first argument is the address of the ivar.
1342   llvm::Value *ivarAddr =
1343       CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(), ivar, 0)
1344           .getPointer(CGF);
1345   ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
1346   args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
1347 
1348   // The second argument is the address of the parameter variable.
1349   ParmVarDecl *argVar = *OMD->param_begin();
1350   DeclRefExpr argRef(CGF.getContext(), argVar, false,
1351                      argVar->getType().getNonReferenceType(), VK_LValue,
1352                      SourceLocation());
1353   llvm::Value *argAddr = CGF.EmitLValue(&argRef).getPointer(CGF);
1354   argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
1355   args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
1356 
1357   // Third argument is the helper function.
1358   args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
1359 
1360   llvm::FunctionCallee fn =
1361       CGF.CGM.getObjCRuntime().GetCppAtomicObjectSetFunction();
1362   CGCallee callee = CGCallee::forDirect(fn);
1363   CGF.EmitCall(
1364       CGF.getTypes().arrangeBuiltinFunctionCall(CGF.getContext().VoidTy, args),
1365                callee, ReturnValueSlot(), args);
1366 }
1367 
1368 
1369 static bool hasTrivialSetExpr(const ObjCPropertyImplDecl *PID) {
1370   Expr *setter = PID->getSetterCXXAssignment();
1371   if (!setter) return true;
1372 
1373   // Sema only makes only of these when the ivar has a C++ class type,
1374   // so the form is pretty constrained.
1375 
1376   // An operator call is trivial if the function it calls is trivial.
1377   // This also implies that there's nothing non-trivial going on with
1378   // the arguments, because operator= can only be trivial if it's a
1379   // synthesized assignment operator and therefore both parameters are
1380   // references.
1381   if (CallExpr *call = dyn_cast<CallExpr>(setter)) {
1382     if (const FunctionDecl *callee
1383           = dyn_cast_or_null<FunctionDecl>(call->getCalleeDecl()))
1384       if (callee->isTrivial())
1385         return true;
1386     return false;
1387   }
1388 
1389   assert(isa<ExprWithCleanups>(setter));
1390   return false;
1391 }
1392 
1393 static bool UseOptimizedSetter(CodeGenModule &CGM) {
1394   if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
1395     return false;
1396   return CGM.getLangOpts().ObjCRuntime.hasOptimizedSetter();
1397 }
1398 
1399 void
1400 CodeGenFunction::generateObjCSetterBody(const ObjCImplementationDecl *classImpl,
1401                                         const ObjCPropertyImplDecl *propImpl,
1402                                         llvm::Constant *AtomicHelperFn) {
1403   ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
1404   ObjCMethodDecl *setterMethod = propImpl->getSetterMethodDecl();
1405 
1406   // Just use the setter expression if Sema gave us one and it's
1407   // non-trivial.
1408   if (!hasTrivialSetExpr(propImpl)) {
1409     if (!AtomicHelperFn)
1410       // If non-atomic, assignment is called directly.
1411       EmitStmt(propImpl->getSetterCXXAssignment());
1412     else
1413       // If atomic, assignment is called via a locking api.
1414       emitCPPObjectAtomicSetterCall(*this, setterMethod, ivar,
1415                                     AtomicHelperFn);
1416     return;
1417   }
1418 
1419   PropertyImplStrategy strategy(CGM, propImpl);
1420   switch (strategy.getKind()) {
1421   case PropertyImplStrategy::Native: {
1422     // We don't need to do anything for a zero-size struct.
1423     if (strategy.getIvarSize().isZero())
1424       return;
1425 
1426     Address argAddr = GetAddrOfLocalVar(*setterMethod->param_begin());
1427 
1428     LValue ivarLValue =
1429       EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, /*quals*/ 0);
1430     Address ivarAddr = ivarLValue.getAddress(*this);
1431 
1432     // Currently, all atomic accesses have to be through integer
1433     // types, so there's no point in trying to pick a prettier type.
1434     llvm::Type *bitcastType =
1435       llvm::Type::getIntNTy(getLLVMContext(),
1436                             getContext().toBits(strategy.getIvarSize()));
1437 
1438     // Cast both arguments to the chosen operation type.
1439     argAddr = Builder.CreateElementBitCast(argAddr, bitcastType);
1440     ivarAddr = Builder.CreateElementBitCast(ivarAddr, bitcastType);
1441 
1442     // This bitcast load is likely to cause some nasty IR.
1443     llvm::Value *load = Builder.CreateLoad(argAddr);
1444 
1445     // Perform an atomic store.  There are no memory ordering requirements.
1446     llvm::StoreInst *store = Builder.CreateStore(load, ivarAddr);
1447     store->setAtomic(llvm::AtomicOrdering::Unordered);
1448     return;
1449   }
1450 
1451   case PropertyImplStrategy::GetSetProperty:
1452   case PropertyImplStrategy::SetPropertyAndExpressionGet: {
1453 
1454     llvm::FunctionCallee setOptimizedPropertyFn = nullptr;
1455     llvm::FunctionCallee setPropertyFn = nullptr;
1456     if (UseOptimizedSetter(CGM)) {
1457       // 10.8 and iOS 6.0 code and GC is off
1458       setOptimizedPropertyFn =
1459           CGM.getObjCRuntime().GetOptimizedPropertySetFunction(
1460               strategy.isAtomic(), strategy.isCopy());
1461       if (!setOptimizedPropertyFn) {
1462         CGM.ErrorUnsupported(propImpl, "Obj-C optimized setter - NYI");
1463         return;
1464       }
1465     }
1466     else {
1467       setPropertyFn = CGM.getObjCRuntime().GetPropertySetFunction();
1468       if (!setPropertyFn) {
1469         CGM.ErrorUnsupported(propImpl, "Obj-C setter requiring atomic copy");
1470         return;
1471       }
1472     }
1473 
1474     // Emit objc_setProperty((id) self, _cmd, offset, arg,
1475     //                       <is-atomic>, <is-copy>).
1476     llvm::Value *cmd =
1477       Builder.CreateLoad(GetAddrOfLocalVar(setterMethod->getCmdDecl()));
1478     llvm::Value *self =
1479       Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
1480     llvm::Value *ivarOffset =
1481       EmitIvarOffset(classImpl->getClassInterface(), ivar);
1482     Address argAddr = GetAddrOfLocalVar(*setterMethod->param_begin());
1483     llvm::Value *arg = Builder.CreateLoad(argAddr, "arg");
1484     arg = Builder.CreateBitCast(arg, VoidPtrTy);
1485 
1486     CallArgList args;
1487     args.add(RValue::get(self), getContext().getObjCIdType());
1488     args.add(RValue::get(cmd), getContext().getObjCSelType());
1489     if (setOptimizedPropertyFn) {
1490       args.add(RValue::get(arg), getContext().getObjCIdType());
1491       args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
1492       CGCallee callee = CGCallee::forDirect(setOptimizedPropertyFn);
1493       EmitCall(getTypes().arrangeBuiltinFunctionCall(getContext().VoidTy, args),
1494                callee, ReturnValueSlot(), args);
1495     } else {
1496       args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
1497       args.add(RValue::get(arg), getContext().getObjCIdType());
1498       args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
1499                getContext().BoolTy);
1500       args.add(RValue::get(Builder.getInt1(strategy.isCopy())),
1501                getContext().BoolTy);
1502       // FIXME: We shouldn't need to get the function info here, the runtime
1503       // already should have computed it to build the function.
1504       CGCallee callee = CGCallee::forDirect(setPropertyFn);
1505       EmitCall(getTypes().arrangeBuiltinFunctionCall(getContext().VoidTy, args),
1506                callee, ReturnValueSlot(), args);
1507     }
1508 
1509     return;
1510   }
1511 
1512   case PropertyImplStrategy::CopyStruct:
1513     emitStructSetterCall(*this, setterMethod, ivar);
1514     return;
1515 
1516   case PropertyImplStrategy::Expression:
1517     break;
1518   }
1519 
1520   // Otherwise, fake up some ASTs and emit a normal assignment.
1521   ValueDecl *selfDecl = setterMethod->getSelfDecl();
1522   DeclRefExpr self(getContext(), selfDecl, false, selfDecl->getType(),
1523                    VK_LValue, SourceLocation());
1524   ImplicitCastExpr selfLoad(ImplicitCastExpr::OnStack, selfDecl->getType(),
1525                             CK_LValueToRValue, &self, VK_RValue,
1526                             FPOptionsOverride());
1527   ObjCIvarRefExpr ivarRef(ivar, ivar->getType().getNonReferenceType(),
1528                           SourceLocation(), SourceLocation(),
1529                           &selfLoad, true, true);
1530 
1531   ParmVarDecl *argDecl = *setterMethod->param_begin();
1532   QualType argType = argDecl->getType().getNonReferenceType();
1533   DeclRefExpr arg(getContext(), argDecl, false, argType, VK_LValue,
1534                   SourceLocation());
1535   ImplicitCastExpr argLoad(ImplicitCastExpr::OnStack,
1536                            argType.getUnqualifiedType(), CK_LValueToRValue,
1537                            &arg, VK_RValue, FPOptionsOverride());
1538 
1539   // The property type can differ from the ivar type in some situations with
1540   // Objective-C pointer types, we can always bit cast the RHS in these cases.
1541   // The following absurdity is just to ensure well-formed IR.
1542   CastKind argCK = CK_NoOp;
1543   if (ivarRef.getType()->isObjCObjectPointerType()) {
1544     if (argLoad.getType()->isObjCObjectPointerType())
1545       argCK = CK_BitCast;
1546     else if (argLoad.getType()->isBlockPointerType())
1547       argCK = CK_BlockPointerToObjCPointerCast;
1548     else
1549       argCK = CK_CPointerToObjCPointerCast;
1550   } else if (ivarRef.getType()->isBlockPointerType()) {
1551      if (argLoad.getType()->isBlockPointerType())
1552       argCK = CK_BitCast;
1553     else
1554       argCK = CK_AnyPointerToBlockPointerCast;
1555   } else if (ivarRef.getType()->isPointerType()) {
1556     argCK = CK_BitCast;
1557   }
1558   ImplicitCastExpr argCast(ImplicitCastExpr::OnStack, ivarRef.getType(), argCK,
1559                            &argLoad, VK_RValue, FPOptionsOverride());
1560   Expr *finalArg = &argLoad;
1561   if (!getContext().hasSameUnqualifiedType(ivarRef.getType(),
1562                                            argLoad.getType()))
1563     finalArg = &argCast;
1564 
1565   BinaryOperator *assign = BinaryOperator::Create(
1566       getContext(), &ivarRef, finalArg, BO_Assign, ivarRef.getType(), VK_RValue,
1567       OK_Ordinary, SourceLocation(), FPOptionsOverride());
1568   EmitStmt(assign);
1569 }
1570 
1571 /// Generate an Objective-C property setter function.
1572 ///
1573 /// The given Decl must be an ObjCImplementationDecl. \@synthesize
1574 /// is illegal within a category.
1575 void CodeGenFunction::GenerateObjCSetter(ObjCImplementationDecl *IMP,
1576                                          const ObjCPropertyImplDecl *PID) {
1577   llvm::Constant *AtomicHelperFn =
1578       CodeGenFunction(CGM).GenerateObjCAtomicSetterCopyHelperFunction(PID);
1579   ObjCMethodDecl *OMD = PID->getSetterMethodDecl();
1580   assert(OMD && "Invalid call to generate setter (empty method)");
1581   StartObjCMethod(OMD, IMP->getClassInterface());
1582 
1583   generateObjCSetterBody(IMP, PID, AtomicHelperFn);
1584 
1585   FinishFunction(OMD->getEndLoc());
1586 }
1587 
1588 namespace {
1589   struct DestroyIvar final : EHScopeStack::Cleanup {
1590   private:
1591     llvm::Value *addr;
1592     const ObjCIvarDecl *ivar;
1593     CodeGenFunction::Destroyer *destroyer;
1594     bool useEHCleanupForArray;
1595   public:
1596     DestroyIvar(llvm::Value *addr, const ObjCIvarDecl *ivar,
1597                 CodeGenFunction::Destroyer *destroyer,
1598                 bool useEHCleanupForArray)
1599       : addr(addr), ivar(ivar), destroyer(destroyer),
1600         useEHCleanupForArray(useEHCleanupForArray) {}
1601 
1602     void Emit(CodeGenFunction &CGF, Flags flags) override {
1603       LValue lvalue
1604         = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), addr, ivar, /*CVR*/ 0);
1605       CGF.emitDestroy(lvalue.getAddress(CGF), ivar->getType(), destroyer,
1606                       flags.isForNormalCleanup() && useEHCleanupForArray);
1607     }
1608   };
1609 }
1610 
1611 /// Like CodeGenFunction::destroyARCStrong, but do it with a call.
1612 static void destroyARCStrongWithStore(CodeGenFunction &CGF,
1613                                       Address addr,
1614                                       QualType type) {
1615   llvm::Value *null = getNullForVariable(addr);
1616   CGF.EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
1617 }
1618 
1619 static void emitCXXDestructMethod(CodeGenFunction &CGF,
1620                                   ObjCImplementationDecl *impl) {
1621   CodeGenFunction::RunCleanupsScope scope(CGF);
1622 
1623   llvm::Value *self = CGF.LoadObjCSelf();
1624 
1625   const ObjCInterfaceDecl *iface = impl->getClassInterface();
1626   for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
1627        ivar; ivar = ivar->getNextIvar()) {
1628     QualType type = ivar->getType();
1629 
1630     // Check whether the ivar is a destructible type.
1631     QualType::DestructionKind dtorKind = type.isDestructedType();
1632     if (!dtorKind) continue;
1633 
1634     CodeGenFunction::Destroyer *destroyer = nullptr;
1635 
1636     // Use a call to objc_storeStrong to destroy strong ivars, for the
1637     // general benefit of the tools.
1638     if (dtorKind == QualType::DK_objc_strong_lifetime) {
1639       destroyer = destroyARCStrongWithStore;
1640 
1641     // Otherwise use the default for the destruction kind.
1642     } else {
1643       destroyer = CGF.getDestroyer(dtorKind);
1644     }
1645 
1646     CleanupKind cleanupKind = CGF.getCleanupKind(dtorKind);
1647 
1648     CGF.EHStack.pushCleanup<DestroyIvar>(cleanupKind, self, ivar, destroyer,
1649                                          cleanupKind & EHCleanup);
1650   }
1651 
1652   assert(scope.requiresCleanups() && "nothing to do in .cxx_destruct?");
1653 }
1654 
1655 void CodeGenFunction::GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
1656                                                  ObjCMethodDecl *MD,
1657                                                  bool ctor) {
1658   MD->createImplicitParams(CGM.getContext(), IMP->getClassInterface());
1659   StartObjCMethod(MD, IMP->getClassInterface());
1660 
1661   // Emit .cxx_construct.
1662   if (ctor) {
1663     // Suppress the final autorelease in ARC.
1664     AutoreleaseResult = false;
1665 
1666     for (const auto *IvarInit : IMP->inits()) {
1667       FieldDecl *Field = IvarInit->getAnyMember();
1668       ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
1669       LValue LV = EmitLValueForIvar(TypeOfSelfObject(),
1670                                     LoadObjCSelf(), Ivar, 0);
1671       EmitAggExpr(IvarInit->getInit(),
1672                   AggValueSlot::forLValue(LV, *this, AggValueSlot::IsDestructed,
1673                                           AggValueSlot::DoesNotNeedGCBarriers,
1674                                           AggValueSlot::IsNotAliased,
1675                                           AggValueSlot::DoesNotOverlap));
1676     }
1677     // constructor returns 'self'.
1678     CodeGenTypes &Types = CGM.getTypes();
1679     QualType IdTy(CGM.getContext().getObjCIdType());
1680     llvm::Value *SelfAsId =
1681       Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
1682     EmitReturnOfRValue(RValue::get(SelfAsId), IdTy);
1683 
1684   // Emit .cxx_destruct.
1685   } else {
1686     emitCXXDestructMethod(*this, IMP);
1687   }
1688   FinishFunction();
1689 }
1690 
1691 llvm::Value *CodeGenFunction::LoadObjCSelf() {
1692   VarDecl *Self = cast<ObjCMethodDecl>(CurFuncDecl)->getSelfDecl();
1693   DeclRefExpr DRE(getContext(), Self,
1694                   /*is enclosing local*/ (CurFuncDecl != CurCodeDecl),
1695                   Self->getType(), VK_LValue, SourceLocation());
1696   return EmitLoadOfScalar(EmitDeclRefLValue(&DRE), SourceLocation());
1697 }
1698 
1699 QualType CodeGenFunction::TypeOfSelfObject() {
1700   const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
1701   ImplicitParamDecl *selfDecl = OMD->getSelfDecl();
1702   const ObjCObjectPointerType *PTy = cast<ObjCObjectPointerType>(
1703     getContext().getCanonicalType(selfDecl->getType()));
1704   return PTy->getPointeeType();
1705 }
1706 
1707 void CodeGenFunction::EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S){
1708   llvm::FunctionCallee EnumerationMutationFnPtr =
1709       CGM.getObjCRuntime().EnumerationMutationFunction();
1710   if (!EnumerationMutationFnPtr) {
1711     CGM.ErrorUnsupported(&S, "Obj-C fast enumeration for this runtime");
1712     return;
1713   }
1714   CGCallee EnumerationMutationFn =
1715     CGCallee::forDirect(EnumerationMutationFnPtr);
1716 
1717   CGDebugInfo *DI = getDebugInfo();
1718   if (DI)
1719     DI->EmitLexicalBlockStart(Builder, S.getSourceRange().getBegin());
1720 
1721   RunCleanupsScope ForScope(*this);
1722 
1723   // The local variable comes into scope immediately.
1724   AutoVarEmission variable = AutoVarEmission::invalid();
1725   if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement()))
1726     variable = EmitAutoVarAlloca(*cast<VarDecl>(SD->getSingleDecl()));
1727 
1728   JumpDest LoopEnd = getJumpDestInCurrentScope("forcoll.end");
1729 
1730   // Fast enumeration state.
1731   QualType StateTy = CGM.getObjCFastEnumerationStateType();
1732   Address StatePtr = CreateMemTemp(StateTy, "state.ptr");
1733   EmitNullInitialization(StatePtr, StateTy);
1734 
1735   // Number of elements in the items array.
1736   static const unsigned NumItems = 16;
1737 
1738   // Fetch the countByEnumeratingWithState:objects:count: selector.
1739   IdentifierInfo *II[] = {
1740     &CGM.getContext().Idents.get("countByEnumeratingWithState"),
1741     &CGM.getContext().Idents.get("objects"),
1742     &CGM.getContext().Idents.get("count")
1743   };
1744   Selector FastEnumSel =
1745     CGM.getContext().Selectors.getSelector(llvm::array_lengthof(II), &II[0]);
1746 
1747   QualType ItemsTy =
1748     getContext().getConstantArrayType(getContext().getObjCIdType(),
1749                                       llvm::APInt(32, NumItems), nullptr,
1750                                       ArrayType::Normal, 0);
1751   Address ItemsPtr = CreateMemTemp(ItemsTy, "items.ptr");
1752 
1753   // Emit the collection pointer.  In ARC, we do a retain.
1754   llvm::Value *Collection;
1755   if (getLangOpts().ObjCAutoRefCount) {
1756     Collection = EmitARCRetainScalarExpr(S.getCollection());
1757 
1758     // Enter a cleanup to do the release.
1759     EmitObjCConsumeObject(S.getCollection()->getType(), Collection);
1760   } else {
1761     Collection = EmitScalarExpr(S.getCollection());
1762   }
1763 
1764   // The 'continue' label needs to appear within the cleanup for the
1765   // collection object.
1766   JumpDest AfterBody = getJumpDestInCurrentScope("forcoll.next");
1767 
1768   // Send it our message:
1769   CallArgList Args;
1770 
1771   // The first argument is a temporary of the enumeration-state type.
1772   Args.add(RValue::get(StatePtr.getPointer()),
1773            getContext().getPointerType(StateTy));
1774 
1775   // The second argument is a temporary array with space for NumItems
1776   // pointers.  We'll actually be loading elements from the array
1777   // pointer written into the control state; this buffer is so that
1778   // collections that *aren't* backed by arrays can still queue up
1779   // batches of elements.
1780   Args.add(RValue::get(ItemsPtr.getPointer()),
1781            getContext().getPointerType(ItemsTy));
1782 
1783   // The third argument is the capacity of that temporary array.
1784   llvm::Type *NSUIntegerTy = ConvertType(getContext().getNSUIntegerType());
1785   llvm::Constant *Count = llvm::ConstantInt::get(NSUIntegerTy, NumItems);
1786   Args.add(RValue::get(Count), getContext().getNSUIntegerType());
1787 
1788   // Start the enumeration.
1789   RValue CountRV =
1790       CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
1791                                                getContext().getNSUIntegerType(),
1792                                                FastEnumSel, Collection, Args);
1793 
1794   // The initial number of objects that were returned in the buffer.
1795   llvm::Value *initialBufferLimit = CountRV.getScalarVal();
1796 
1797   llvm::BasicBlock *EmptyBB = createBasicBlock("forcoll.empty");
1798   llvm::BasicBlock *LoopInitBB = createBasicBlock("forcoll.loopinit");
1799 
1800   llvm::Value *zero = llvm::Constant::getNullValue(NSUIntegerTy);
1801 
1802   // If the limit pointer was zero to begin with, the collection is
1803   // empty; skip all this. Set the branch weight assuming this has the same
1804   // probability of exiting the loop as any other loop exit.
1805   uint64_t EntryCount = getCurrentProfileCount();
1806   Builder.CreateCondBr(
1807       Builder.CreateICmpEQ(initialBufferLimit, zero, "iszero"), EmptyBB,
1808       LoopInitBB,
1809       createProfileWeights(EntryCount, getProfileCount(S.getBody())));
1810 
1811   // Otherwise, initialize the loop.
1812   EmitBlock(LoopInitBB);
1813 
1814   // Save the initial mutations value.  This is the value at an
1815   // address that was written into the state object by
1816   // countByEnumeratingWithState:objects:count:.
1817   Address StateMutationsPtrPtr =
1818       Builder.CreateStructGEP(StatePtr, 2, "mutationsptr.ptr");
1819   llvm::Value *StateMutationsPtr
1820     = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
1821 
1822   llvm::Value *initialMutations =
1823     Builder.CreateAlignedLoad(StateMutationsPtr, getPointerAlign(),
1824                               "forcoll.initial-mutations");
1825 
1826   // Start looping.  This is the point we return to whenever we have a
1827   // fresh, non-empty batch of objects.
1828   llvm::BasicBlock *LoopBodyBB = createBasicBlock("forcoll.loopbody");
1829   EmitBlock(LoopBodyBB);
1830 
1831   // The current index into the buffer.
1832   llvm::PHINode *index = Builder.CreatePHI(NSUIntegerTy, 3, "forcoll.index");
1833   index->addIncoming(zero, LoopInitBB);
1834 
1835   // The current buffer size.
1836   llvm::PHINode *count = Builder.CreatePHI(NSUIntegerTy, 3, "forcoll.count");
1837   count->addIncoming(initialBufferLimit, LoopInitBB);
1838 
1839   incrementProfileCounter(&S);
1840 
1841   // Check whether the mutations value has changed from where it was
1842   // at start.  StateMutationsPtr should actually be invariant between
1843   // refreshes.
1844   StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
1845   llvm::Value *currentMutations
1846     = Builder.CreateAlignedLoad(StateMutationsPtr, getPointerAlign(),
1847                                 "statemutations");
1848 
1849   llvm::BasicBlock *WasMutatedBB = createBasicBlock("forcoll.mutated");
1850   llvm::BasicBlock *WasNotMutatedBB = createBasicBlock("forcoll.notmutated");
1851 
1852   Builder.CreateCondBr(Builder.CreateICmpEQ(currentMutations, initialMutations),
1853                        WasNotMutatedBB, WasMutatedBB);
1854 
1855   // If so, call the enumeration-mutation function.
1856   EmitBlock(WasMutatedBB);
1857   llvm::Value *V =
1858     Builder.CreateBitCast(Collection,
1859                           ConvertType(getContext().getObjCIdType()));
1860   CallArgList Args2;
1861   Args2.add(RValue::get(V), getContext().getObjCIdType());
1862   // FIXME: We shouldn't need to get the function info here, the runtime already
1863   // should have computed it to build the function.
1864   EmitCall(
1865           CGM.getTypes().arrangeBuiltinFunctionCall(getContext().VoidTy, Args2),
1866            EnumerationMutationFn, ReturnValueSlot(), Args2);
1867 
1868   // Otherwise, or if the mutation function returns, just continue.
1869   EmitBlock(WasNotMutatedBB);
1870 
1871   // Initialize the element variable.
1872   RunCleanupsScope elementVariableScope(*this);
1873   bool elementIsVariable;
1874   LValue elementLValue;
1875   QualType elementType;
1876   if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) {
1877     // Initialize the variable, in case it's a __block variable or something.
1878     EmitAutoVarInit(variable);
1879 
1880     const VarDecl *D = cast<VarDecl>(SD->getSingleDecl());
1881     DeclRefExpr tempDRE(getContext(), const_cast<VarDecl *>(D), false,
1882                         D->getType(), VK_LValue, SourceLocation());
1883     elementLValue = EmitLValue(&tempDRE);
1884     elementType = D->getType();
1885     elementIsVariable = true;
1886 
1887     if (D->isARCPseudoStrong())
1888       elementLValue.getQuals().setObjCLifetime(Qualifiers::OCL_ExplicitNone);
1889   } else {
1890     elementLValue = LValue(); // suppress warning
1891     elementType = cast<Expr>(S.getElement())->getType();
1892     elementIsVariable = false;
1893   }
1894   llvm::Type *convertedElementType = ConvertType(elementType);
1895 
1896   // Fetch the buffer out of the enumeration state.
1897   // TODO: this pointer should actually be invariant between
1898   // refreshes, which would help us do certain loop optimizations.
1899   Address StateItemsPtr =
1900       Builder.CreateStructGEP(StatePtr, 1, "stateitems.ptr");
1901   llvm::Value *EnumStateItems =
1902     Builder.CreateLoad(StateItemsPtr, "stateitems");
1903 
1904   // Fetch the value at the current index from the buffer.
1905   llvm::Value *CurrentItemPtr =
1906     Builder.CreateGEP(EnumStateItems, index, "currentitem.ptr");
1907   llvm::Value *CurrentItem =
1908     Builder.CreateAlignedLoad(CurrentItemPtr, getPointerAlign());
1909 
1910   if (SanOpts.has(SanitizerKind::ObjCCast)) {
1911     // Before using an item from the collection, check that the implicit cast
1912     // from id to the element type is valid. This is done with instrumentation
1913     // roughly corresponding to:
1914     //
1915     //   if (![item isKindOfClass:expectedCls]) { /* emit diagnostic */ }
1916     const ObjCObjectPointerType *ObjPtrTy =
1917         elementType->getAsObjCInterfacePointerType();
1918     const ObjCInterfaceType *InterfaceTy =
1919         ObjPtrTy ? ObjPtrTy->getInterfaceType() : nullptr;
1920     if (InterfaceTy) {
1921       SanitizerScope SanScope(this);
1922       auto &C = CGM.getContext();
1923       assert(InterfaceTy->getDecl() && "No decl for ObjC interface type");
1924       Selector IsKindOfClassSel = GetUnarySelector("isKindOfClass", C);
1925       CallArgList IsKindOfClassArgs;
1926       llvm::Value *Cls =
1927           CGM.getObjCRuntime().GetClass(*this, InterfaceTy->getDecl());
1928       IsKindOfClassArgs.add(RValue::get(Cls), C.getObjCClassType());
1929       llvm::Value *IsClass =
1930           CGM.getObjCRuntime()
1931               .GenerateMessageSend(*this, ReturnValueSlot(), C.BoolTy,
1932                                    IsKindOfClassSel, CurrentItem,
1933                                    IsKindOfClassArgs)
1934               .getScalarVal();
1935       llvm::Constant *StaticData[] = {
1936           EmitCheckSourceLocation(S.getBeginLoc()),
1937           EmitCheckTypeDescriptor(QualType(InterfaceTy, 0))};
1938       EmitCheck({{IsClass, SanitizerKind::ObjCCast}},
1939                 SanitizerHandler::InvalidObjCCast,
1940                 ArrayRef<llvm::Constant *>(StaticData), CurrentItem);
1941     }
1942   }
1943 
1944   // Cast that value to the right type.
1945   CurrentItem = Builder.CreateBitCast(CurrentItem, convertedElementType,
1946                                       "currentitem");
1947 
1948   // Make sure we have an l-value.  Yes, this gets evaluated every
1949   // time through the loop.
1950   if (!elementIsVariable) {
1951     elementLValue = EmitLValue(cast<Expr>(S.getElement()));
1952     EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue);
1953   } else {
1954     EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue,
1955                            /*isInit*/ true);
1956   }
1957 
1958   // If we do have an element variable, this assignment is the end of
1959   // its initialization.
1960   if (elementIsVariable)
1961     EmitAutoVarCleanups(variable);
1962 
1963   // Perform the loop body, setting up break and continue labels.
1964   BreakContinueStack.push_back(BreakContinue(LoopEnd, AfterBody));
1965   {
1966     RunCleanupsScope Scope(*this);
1967     EmitStmt(S.getBody());
1968   }
1969   BreakContinueStack.pop_back();
1970 
1971   // Destroy the element variable now.
1972   elementVariableScope.ForceCleanup();
1973 
1974   // Check whether there are more elements.
1975   EmitBlock(AfterBody.getBlock());
1976 
1977   llvm::BasicBlock *FetchMoreBB = createBasicBlock("forcoll.refetch");
1978 
1979   // First we check in the local buffer.
1980   llvm::Value *indexPlusOne =
1981       Builder.CreateAdd(index, llvm::ConstantInt::get(NSUIntegerTy, 1));
1982 
1983   // If we haven't overrun the buffer yet, we can continue.
1984   // Set the branch weights based on the simplifying assumption that this is
1985   // like a while-loop, i.e., ignoring that the false branch fetches more
1986   // elements and then returns to the loop.
1987   Builder.CreateCondBr(
1988       Builder.CreateICmpULT(indexPlusOne, count), LoopBodyBB, FetchMoreBB,
1989       createProfileWeights(getProfileCount(S.getBody()), EntryCount));
1990 
1991   index->addIncoming(indexPlusOne, AfterBody.getBlock());
1992   count->addIncoming(count, AfterBody.getBlock());
1993 
1994   // Otherwise, we have to fetch more elements.
1995   EmitBlock(FetchMoreBB);
1996 
1997   CountRV =
1998       CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
1999                                                getContext().getNSUIntegerType(),
2000                                                FastEnumSel, Collection, Args);
2001 
2002   // If we got a zero count, we're done.
2003   llvm::Value *refetchCount = CountRV.getScalarVal();
2004 
2005   // (note that the message send might split FetchMoreBB)
2006   index->addIncoming(zero, Builder.GetInsertBlock());
2007   count->addIncoming(refetchCount, Builder.GetInsertBlock());
2008 
2009   Builder.CreateCondBr(Builder.CreateICmpEQ(refetchCount, zero),
2010                        EmptyBB, LoopBodyBB);
2011 
2012   // No more elements.
2013   EmitBlock(EmptyBB);
2014 
2015   if (!elementIsVariable) {
2016     // If the element was not a declaration, set it to be null.
2017 
2018     llvm::Value *null = llvm::Constant::getNullValue(convertedElementType);
2019     elementLValue = EmitLValue(cast<Expr>(S.getElement()));
2020     EmitStoreThroughLValue(RValue::get(null), elementLValue);
2021   }
2022 
2023   if (DI)
2024     DI->EmitLexicalBlockEnd(Builder, S.getSourceRange().getEnd());
2025 
2026   ForScope.ForceCleanup();
2027   EmitBlock(LoopEnd.getBlock());
2028 }
2029 
2030 void CodeGenFunction::EmitObjCAtTryStmt(const ObjCAtTryStmt &S) {
2031   CGM.getObjCRuntime().EmitTryStmt(*this, S);
2032 }
2033 
2034 void CodeGenFunction::EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S) {
2035   CGM.getObjCRuntime().EmitThrowStmt(*this, S);
2036 }
2037 
2038 void CodeGenFunction::EmitObjCAtSynchronizedStmt(
2039                                               const ObjCAtSynchronizedStmt &S) {
2040   CGM.getObjCRuntime().EmitSynchronizedStmt(*this, S);
2041 }
2042 
2043 namespace {
2044   struct CallObjCRelease final : EHScopeStack::Cleanup {
2045     CallObjCRelease(llvm::Value *object) : object(object) {}
2046     llvm::Value *object;
2047 
2048     void Emit(CodeGenFunction &CGF, Flags flags) override {
2049       // Releases at the end of the full-expression are imprecise.
2050       CGF.EmitARCRelease(object, ARCImpreciseLifetime);
2051     }
2052   };
2053 }
2054 
2055 /// Produce the code for a CK_ARCConsumeObject.  Does a primitive
2056 /// release at the end of the full-expression.
2057 llvm::Value *CodeGenFunction::EmitObjCConsumeObject(QualType type,
2058                                                     llvm::Value *object) {
2059   // If we're in a conditional branch, we need to make the cleanup
2060   // conditional.
2061   pushFullExprCleanup<CallObjCRelease>(getARCCleanupKind(), object);
2062   return object;
2063 }
2064 
2065 llvm::Value *CodeGenFunction::EmitObjCExtendObjectLifetime(QualType type,
2066                                                            llvm::Value *value) {
2067   return EmitARCRetainAutorelease(type, value);
2068 }
2069 
2070 /// Given a number of pointers, inform the optimizer that they're
2071 /// being intrinsically used up until this point in the program.
2072 void CodeGenFunction::EmitARCIntrinsicUse(ArrayRef<llvm::Value*> values) {
2073   llvm::Function *&fn = CGM.getObjCEntrypoints().clang_arc_use;
2074   if (!fn)
2075     fn = CGM.getIntrinsic(llvm::Intrinsic::objc_clang_arc_use);
2076 
2077   // This isn't really a "runtime" function, but as an intrinsic it
2078   // doesn't really matter as long as we align things up.
2079   EmitNounwindRuntimeCall(fn, values);
2080 }
2081 
2082 /// Emit a call to "clang.arc.noop.use", which consumes the result of a call
2083 /// that has operand bundle "clang.arc.attachedcall".
2084 void CodeGenFunction::EmitARCNoopIntrinsicUse(ArrayRef<llvm::Value *> values) {
2085   llvm::Function *&fn = CGM.getObjCEntrypoints().clang_arc_noop_use;
2086   if (!fn)
2087     fn = CGM.getIntrinsic(llvm::Intrinsic::objc_clang_arc_noop_use);
2088   EmitNounwindRuntimeCall(fn, values);
2089 }
2090 
2091 static void setARCRuntimeFunctionLinkage(CodeGenModule &CGM, llvm::Value *RTF) {
2092   if (auto *F = dyn_cast<llvm::Function>(RTF)) {
2093     // If the target runtime doesn't naturally support ARC, emit weak
2094     // references to the runtime support library.  We don't really
2095     // permit this to fail, but we need a particular relocation style.
2096     if (!CGM.getLangOpts().ObjCRuntime.hasNativeARC() &&
2097         !CGM.getTriple().isOSBinFormatCOFF()) {
2098       F->setLinkage(llvm::Function::ExternalWeakLinkage);
2099     }
2100   }
2101 }
2102 
2103 static void setARCRuntimeFunctionLinkage(CodeGenModule &CGM,
2104                                          llvm::FunctionCallee RTF) {
2105   setARCRuntimeFunctionLinkage(CGM, RTF.getCallee());
2106 }
2107 
2108 /// Perform an operation having the signature
2109 ///   i8* (i8*)
2110 /// where a null input causes a no-op and returns null.
2111 static llvm::Value *emitARCValueOperation(
2112     CodeGenFunction &CGF, llvm::Value *value, llvm::Type *returnType,
2113     llvm::Function *&fn, llvm::Intrinsic::ID IntID,
2114     llvm::CallInst::TailCallKind tailKind = llvm::CallInst::TCK_None) {
2115   if (isa<llvm::ConstantPointerNull>(value))
2116     return value;
2117 
2118   if (!fn) {
2119     fn = CGF.CGM.getIntrinsic(IntID);
2120     setARCRuntimeFunctionLinkage(CGF.CGM, fn);
2121   }
2122 
2123   // Cast the argument to 'id'.
2124   llvm::Type *origType = returnType ? returnType : value->getType();
2125   value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
2126 
2127   // Call the function.
2128   llvm::CallInst *call = CGF.EmitNounwindRuntimeCall(fn, value);
2129   call->setTailCallKind(tailKind);
2130 
2131   // Cast the result back to the original type.
2132   return CGF.Builder.CreateBitCast(call, origType);
2133 }
2134 
2135 /// Perform an operation having the following signature:
2136 ///   i8* (i8**)
2137 static llvm::Value *emitARCLoadOperation(CodeGenFunction &CGF, Address addr,
2138                                          llvm::Function *&fn,
2139                                          llvm::Intrinsic::ID IntID) {
2140   if (!fn) {
2141     fn = CGF.CGM.getIntrinsic(IntID);
2142     setARCRuntimeFunctionLinkage(CGF.CGM, fn);
2143   }
2144 
2145   // Cast the argument to 'id*'.
2146   llvm::Type *origType = addr.getElementType();
2147   addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy);
2148 
2149   // Call the function.
2150   llvm::Value *result = CGF.EmitNounwindRuntimeCall(fn, addr.getPointer());
2151 
2152   // Cast the result back to a dereference of the original type.
2153   if (origType != CGF.Int8PtrTy)
2154     result = CGF.Builder.CreateBitCast(result, origType);
2155 
2156   return result;
2157 }
2158 
2159 /// Perform an operation having the following signature:
2160 ///   i8* (i8**, i8*)
2161 static llvm::Value *emitARCStoreOperation(CodeGenFunction &CGF, Address addr,
2162                                           llvm::Value *value,
2163                                           llvm::Function *&fn,
2164                                           llvm::Intrinsic::ID IntID,
2165                                           bool ignored) {
2166   assert(addr.getElementType() == value->getType());
2167 
2168   if (!fn) {
2169     fn = CGF.CGM.getIntrinsic(IntID);
2170     setARCRuntimeFunctionLinkage(CGF.CGM, fn);
2171   }
2172 
2173   llvm::Type *origType = value->getType();
2174 
2175   llvm::Value *args[] = {
2176     CGF.Builder.CreateBitCast(addr.getPointer(), CGF.Int8PtrPtrTy),
2177     CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy)
2178   };
2179   llvm::CallInst *result = CGF.EmitNounwindRuntimeCall(fn, args);
2180 
2181   if (ignored) return nullptr;
2182 
2183   return CGF.Builder.CreateBitCast(result, origType);
2184 }
2185 
2186 /// Perform an operation having the following signature:
2187 ///   void (i8**, i8**)
2188 static void emitARCCopyOperation(CodeGenFunction &CGF, Address dst, Address src,
2189                                  llvm::Function *&fn,
2190                                  llvm::Intrinsic::ID IntID) {
2191   assert(dst.getType() == src.getType());
2192 
2193   if (!fn) {
2194     fn = CGF.CGM.getIntrinsic(IntID);
2195     setARCRuntimeFunctionLinkage(CGF.CGM, fn);
2196   }
2197 
2198   llvm::Value *args[] = {
2199     CGF.Builder.CreateBitCast(dst.getPointer(), CGF.Int8PtrPtrTy),
2200     CGF.Builder.CreateBitCast(src.getPointer(), CGF.Int8PtrPtrTy)
2201   };
2202   CGF.EmitNounwindRuntimeCall(fn, args);
2203 }
2204 
2205 /// Perform an operation having the signature
2206 ///   i8* (i8*)
2207 /// where a null input causes a no-op and returns null.
2208 static llvm::Value *emitObjCValueOperation(CodeGenFunction &CGF,
2209                                            llvm::Value *value,
2210                                            llvm::Type *returnType,
2211                                            llvm::FunctionCallee &fn,
2212                                            StringRef fnName) {
2213   if (isa<llvm::ConstantPointerNull>(value))
2214     return value;
2215 
2216   if (!fn) {
2217     llvm::FunctionType *fnType =
2218       llvm::FunctionType::get(CGF.Int8PtrTy, CGF.Int8PtrTy, false);
2219     fn = CGF.CGM.CreateRuntimeFunction(fnType, fnName);
2220 
2221     // We have Native ARC, so set nonlazybind attribute for performance
2222     if (llvm::Function *f = dyn_cast<llvm::Function>(fn.getCallee()))
2223       if (fnName == "objc_retain")
2224         f->addFnAttr(llvm::Attribute::NonLazyBind);
2225   }
2226 
2227   // Cast the argument to 'id'.
2228   llvm::Type *origType = returnType ? returnType : value->getType();
2229   value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
2230 
2231   // Call the function.
2232   llvm::CallBase *Inst = CGF.EmitCallOrInvoke(fn, value);
2233 
2234   // Mark calls to objc_autorelease as tail on the assumption that methods
2235   // overriding autorelease do not touch anything on the stack.
2236   if (fnName == "objc_autorelease")
2237     if (auto *Call = dyn_cast<llvm::CallInst>(Inst))
2238       Call->setTailCall();
2239 
2240   // Cast the result back to the original type.
2241   return CGF.Builder.CreateBitCast(Inst, origType);
2242 }
2243 
2244 /// Produce the code to do a retain.  Based on the type, calls one of:
2245 ///   call i8* \@objc_retain(i8* %value)
2246 ///   call i8* \@objc_retainBlock(i8* %value)
2247 llvm::Value *CodeGenFunction::EmitARCRetain(QualType type, llvm::Value *value) {
2248   if (type->isBlockPointerType())
2249     return EmitARCRetainBlock(value, /*mandatory*/ false);
2250   else
2251     return EmitARCRetainNonBlock(value);
2252 }
2253 
2254 /// Retain the given object, with normal retain semantics.
2255 ///   call i8* \@objc_retain(i8* %value)
2256 llvm::Value *CodeGenFunction::EmitARCRetainNonBlock(llvm::Value *value) {
2257   return emitARCValueOperation(*this, value, nullptr,
2258                                CGM.getObjCEntrypoints().objc_retain,
2259                                llvm::Intrinsic::objc_retain);
2260 }
2261 
2262 /// Retain the given block, with _Block_copy semantics.
2263 ///   call i8* \@objc_retainBlock(i8* %value)
2264 ///
2265 /// \param mandatory - If false, emit the call with metadata
2266 /// indicating that it's okay for the optimizer to eliminate this call
2267 /// if it can prove that the block never escapes except down the stack.
2268 llvm::Value *CodeGenFunction::EmitARCRetainBlock(llvm::Value *value,
2269                                                  bool mandatory) {
2270   llvm::Value *result
2271     = emitARCValueOperation(*this, value, nullptr,
2272                             CGM.getObjCEntrypoints().objc_retainBlock,
2273                             llvm::Intrinsic::objc_retainBlock);
2274 
2275   // If the copy isn't mandatory, add !clang.arc.copy_on_escape to
2276   // tell the optimizer that it doesn't need to do this copy if the
2277   // block doesn't escape, where being passed as an argument doesn't
2278   // count as escaping.
2279   if (!mandatory && isa<llvm::Instruction>(result)) {
2280     llvm::CallInst *call
2281       = cast<llvm::CallInst>(result->stripPointerCasts());
2282     assert(call->getCalledOperand() ==
2283            CGM.getObjCEntrypoints().objc_retainBlock);
2284 
2285     call->setMetadata("clang.arc.copy_on_escape",
2286                       llvm::MDNode::get(Builder.getContext(), None));
2287   }
2288 
2289   return result;
2290 }
2291 
2292 static void emitAutoreleasedReturnValueMarker(CodeGenFunction &CGF) {
2293   // Fetch the void(void) inline asm which marks that we're going to
2294   // do something with the autoreleased return value.
2295   llvm::InlineAsm *&marker
2296     = CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker;
2297   if (!marker) {
2298     StringRef assembly
2299       = CGF.CGM.getTargetCodeGenInfo()
2300            .getARCRetainAutoreleasedReturnValueMarker();
2301 
2302     // If we have an empty assembly string, there's nothing to do.
2303     if (assembly.empty()) {
2304 
2305     // Otherwise, at -O0, build an inline asm that we're going to call
2306     // in a moment.
2307     } else if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0) {
2308       llvm::FunctionType *type =
2309         llvm::FunctionType::get(CGF.VoidTy, /*variadic*/false);
2310 
2311       marker = llvm::InlineAsm::get(type, assembly, "", /*sideeffects*/ true);
2312 
2313     // If we're at -O1 and above, we don't want to litter the code
2314     // with this marker yet, so leave a breadcrumb for the ARC
2315     // optimizer to pick up.
2316     } else {
2317       const char *retainRVMarkerKey = llvm::objcarc::getRVMarkerModuleFlagStr();
2318       if (!CGF.CGM.getModule().getModuleFlag(retainRVMarkerKey)) {
2319         auto *str = llvm::MDString::get(CGF.getLLVMContext(), assembly);
2320         CGF.CGM.getModule().addModuleFlag(llvm::Module::Error,
2321                                           retainRVMarkerKey, str);
2322       }
2323     }
2324   }
2325 
2326   // Call the marker asm if we made one, which we do only at -O0.
2327   if (marker)
2328     CGF.Builder.CreateCall(marker, None, CGF.getBundlesForFunclet(marker));
2329 }
2330 
2331 static llvm::Value *emitOptimizedARCReturnCall(llvm::Value *value,
2332                                                bool IsRetainRV,
2333                                                CodeGenFunction &CGF) {
2334   emitAutoreleasedReturnValueMarker(CGF);
2335 
2336   // Add operand bundle "clang.arc.attachedcall" to the call instead of emitting
2337   // retainRV or claimRV calls in the IR. We currently do this only when the
2338   // optimization level isn't -O0 since global-isel, which is currently run at
2339   // -O0, doesn't know about the operand bundle.
2340 
2341   // FIXME: Do this when the target isn't aarch64.
2342   if (CGF.CGM.getCodeGenOpts().OptimizationLevel > 0 &&
2343       CGF.CGM.getTarget().getTriple().isAArch64()) {
2344     llvm::Value *bundleArgs[] = {llvm::ConstantInt::get(
2345         CGF.Int64Ty,
2346         llvm::objcarc::getAttachedCallOperandBundleEnum(IsRetainRV))};
2347     llvm::OperandBundleDef OB("clang.arc.attachedcall", bundleArgs);
2348     auto *oldCall = cast<llvm::CallBase>(value);
2349     llvm::CallBase *newCall = llvm::CallBase::addOperandBundle(
2350         oldCall, llvm::LLVMContext::OB_clang_arc_attachedcall, OB, oldCall);
2351     newCall->copyMetadata(*oldCall);
2352     oldCall->replaceAllUsesWith(newCall);
2353     oldCall->eraseFromParent();
2354     CGF.EmitARCNoopIntrinsicUse(newCall);
2355     return newCall;
2356   }
2357 
2358   bool isNoTail =
2359       CGF.CGM.getTargetCodeGenInfo().markARCOptimizedReturnCallsAsNoTail();
2360   llvm::CallInst::TailCallKind tailKind =
2361       isNoTail ? llvm::CallInst::TCK_NoTail : llvm::CallInst::TCK_None;
2362   ObjCEntrypoints &EPs = CGF.CGM.getObjCEntrypoints();
2363   llvm::Function *&EP = IsRetainRV
2364                             ? EPs.objc_retainAutoreleasedReturnValue
2365                             : EPs.objc_unsafeClaimAutoreleasedReturnValue;
2366   llvm::Intrinsic::ID IID =
2367       IsRetainRV ? llvm::Intrinsic::objc_retainAutoreleasedReturnValue
2368                  : llvm::Intrinsic::objc_unsafeClaimAutoreleasedReturnValue;
2369   return emitARCValueOperation(CGF, value, nullptr, EP, IID, tailKind);
2370 }
2371 
2372 /// Retain the given object which is the result of a function call.
2373 ///   call i8* \@objc_retainAutoreleasedReturnValue(i8* %value)
2374 ///
2375 /// Yes, this function name is one character away from a different
2376 /// call with completely different semantics.
2377 llvm::Value *
2378 CodeGenFunction::EmitARCRetainAutoreleasedReturnValue(llvm::Value *value) {
2379   return emitOptimizedARCReturnCall(value, true, *this);
2380 }
2381 
2382 /// Claim a possibly-autoreleased return value at +0.  This is only
2383 /// valid to do in contexts which do not rely on the retain to keep
2384 /// the object valid for all of its uses; for example, when
2385 /// the value is ignored, or when it is being assigned to an
2386 /// __unsafe_unretained variable.
2387 ///
2388 ///   call i8* \@objc_unsafeClaimAutoreleasedReturnValue(i8* %value)
2389 llvm::Value *
2390 CodeGenFunction::EmitARCUnsafeClaimAutoreleasedReturnValue(llvm::Value *value) {
2391   return emitOptimizedARCReturnCall(value, false, *this);
2392 }
2393 
2394 /// Release the given object.
2395 ///   call void \@objc_release(i8* %value)
2396 void CodeGenFunction::EmitARCRelease(llvm::Value *value,
2397                                      ARCPreciseLifetime_t precise) {
2398   if (isa<llvm::ConstantPointerNull>(value)) return;
2399 
2400   llvm::Function *&fn = CGM.getObjCEntrypoints().objc_release;
2401   if (!fn) {
2402     fn = CGM.getIntrinsic(llvm::Intrinsic::objc_release);
2403     setARCRuntimeFunctionLinkage(CGM, fn);
2404   }
2405 
2406   // Cast the argument to 'id'.
2407   value = Builder.CreateBitCast(value, Int8PtrTy);
2408 
2409   // Call objc_release.
2410   llvm::CallInst *call = EmitNounwindRuntimeCall(fn, value);
2411 
2412   if (precise == ARCImpreciseLifetime) {
2413     call->setMetadata("clang.imprecise_release",
2414                       llvm::MDNode::get(Builder.getContext(), None));
2415   }
2416 }
2417 
2418 /// Destroy a __strong variable.
2419 ///
2420 /// At -O0, emit a call to store 'null' into the address;
2421 /// instrumenting tools prefer this because the address is exposed,
2422 /// but it's relatively cumbersome to optimize.
2423 ///
2424 /// At -O1 and above, just load and call objc_release.
2425 ///
2426 ///   call void \@objc_storeStrong(i8** %addr, i8* null)
2427 void CodeGenFunction::EmitARCDestroyStrong(Address addr,
2428                                            ARCPreciseLifetime_t precise) {
2429   if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
2430     llvm::Value *null = getNullForVariable(addr);
2431     EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
2432     return;
2433   }
2434 
2435   llvm::Value *value = Builder.CreateLoad(addr);
2436   EmitARCRelease(value, precise);
2437 }
2438 
2439 /// Store into a strong object.  Always calls this:
2440 ///   call void \@objc_storeStrong(i8** %addr, i8* %value)
2441 llvm::Value *CodeGenFunction::EmitARCStoreStrongCall(Address addr,
2442                                                      llvm::Value *value,
2443                                                      bool ignored) {
2444   assert(addr.getElementType() == value->getType());
2445 
2446   llvm::Function *&fn = CGM.getObjCEntrypoints().objc_storeStrong;
2447   if (!fn) {
2448     fn = CGM.getIntrinsic(llvm::Intrinsic::objc_storeStrong);
2449     setARCRuntimeFunctionLinkage(CGM, fn);
2450   }
2451 
2452   llvm::Value *args[] = {
2453     Builder.CreateBitCast(addr.getPointer(), Int8PtrPtrTy),
2454     Builder.CreateBitCast(value, Int8PtrTy)
2455   };
2456   EmitNounwindRuntimeCall(fn, args);
2457 
2458   if (ignored) return nullptr;
2459   return value;
2460 }
2461 
2462 /// Store into a strong object.  Sometimes calls this:
2463 ///   call void \@objc_storeStrong(i8** %addr, i8* %value)
2464 /// Other times, breaks it down into components.
2465 llvm::Value *CodeGenFunction::EmitARCStoreStrong(LValue dst,
2466                                                  llvm::Value *newValue,
2467                                                  bool ignored) {
2468   QualType type = dst.getType();
2469   bool isBlock = type->isBlockPointerType();
2470 
2471   // Use a store barrier at -O0 unless this is a block type or the
2472   // lvalue is inadequately aligned.
2473   if (shouldUseFusedARCCalls() &&
2474       !isBlock &&
2475       (dst.getAlignment().isZero() ||
2476        dst.getAlignment() >= CharUnits::fromQuantity(PointerAlignInBytes))) {
2477     return EmitARCStoreStrongCall(dst.getAddress(*this), newValue, ignored);
2478   }
2479 
2480   // Otherwise, split it out.
2481 
2482   // Retain the new value.
2483   newValue = EmitARCRetain(type, newValue);
2484 
2485   // Read the old value.
2486   llvm::Value *oldValue = EmitLoadOfScalar(dst, SourceLocation());
2487 
2488   // Store.  We do this before the release so that any deallocs won't
2489   // see the old value.
2490   EmitStoreOfScalar(newValue, dst);
2491 
2492   // Finally, release the old value.
2493   EmitARCRelease(oldValue, dst.isARCPreciseLifetime());
2494 
2495   return newValue;
2496 }
2497 
2498 /// Autorelease the given object.
2499 ///   call i8* \@objc_autorelease(i8* %value)
2500 llvm::Value *CodeGenFunction::EmitARCAutorelease(llvm::Value *value) {
2501   return emitARCValueOperation(*this, value, nullptr,
2502                                CGM.getObjCEntrypoints().objc_autorelease,
2503                                llvm::Intrinsic::objc_autorelease);
2504 }
2505 
2506 /// Autorelease the given object.
2507 ///   call i8* \@objc_autoreleaseReturnValue(i8* %value)
2508 llvm::Value *
2509 CodeGenFunction::EmitARCAutoreleaseReturnValue(llvm::Value *value) {
2510   return emitARCValueOperation(*this, value, nullptr,
2511                             CGM.getObjCEntrypoints().objc_autoreleaseReturnValue,
2512                                llvm::Intrinsic::objc_autoreleaseReturnValue,
2513                                llvm::CallInst::TCK_Tail);
2514 }
2515 
2516 /// Do a fused retain/autorelease of the given object.
2517 ///   call i8* \@objc_retainAutoreleaseReturnValue(i8* %value)
2518 llvm::Value *
2519 CodeGenFunction::EmitARCRetainAutoreleaseReturnValue(llvm::Value *value) {
2520   return emitARCValueOperation(*this, value, nullptr,
2521                      CGM.getObjCEntrypoints().objc_retainAutoreleaseReturnValue,
2522                              llvm::Intrinsic::objc_retainAutoreleaseReturnValue,
2523                                llvm::CallInst::TCK_Tail);
2524 }
2525 
2526 /// Do a fused retain/autorelease of the given object.
2527 ///   call i8* \@objc_retainAutorelease(i8* %value)
2528 /// or
2529 ///   %retain = call i8* \@objc_retainBlock(i8* %value)
2530 ///   call i8* \@objc_autorelease(i8* %retain)
2531 llvm::Value *CodeGenFunction::EmitARCRetainAutorelease(QualType type,
2532                                                        llvm::Value *value) {
2533   if (!type->isBlockPointerType())
2534     return EmitARCRetainAutoreleaseNonBlock(value);
2535 
2536   if (isa<llvm::ConstantPointerNull>(value)) return value;
2537 
2538   llvm::Type *origType = value->getType();
2539   value = Builder.CreateBitCast(value, Int8PtrTy);
2540   value = EmitARCRetainBlock(value, /*mandatory*/ true);
2541   value = EmitARCAutorelease(value);
2542   return Builder.CreateBitCast(value, origType);
2543 }
2544 
2545 /// Do a fused retain/autorelease of the given object.
2546 ///   call i8* \@objc_retainAutorelease(i8* %value)
2547 llvm::Value *
2548 CodeGenFunction::EmitARCRetainAutoreleaseNonBlock(llvm::Value *value) {
2549   return emitARCValueOperation(*this, value, nullptr,
2550                                CGM.getObjCEntrypoints().objc_retainAutorelease,
2551                                llvm::Intrinsic::objc_retainAutorelease);
2552 }
2553 
2554 /// i8* \@objc_loadWeak(i8** %addr)
2555 /// Essentially objc_autorelease(objc_loadWeakRetained(addr)).
2556 llvm::Value *CodeGenFunction::EmitARCLoadWeak(Address addr) {
2557   return emitARCLoadOperation(*this, addr,
2558                               CGM.getObjCEntrypoints().objc_loadWeak,
2559                               llvm::Intrinsic::objc_loadWeak);
2560 }
2561 
2562 /// i8* \@objc_loadWeakRetained(i8** %addr)
2563 llvm::Value *CodeGenFunction::EmitARCLoadWeakRetained(Address addr) {
2564   return emitARCLoadOperation(*this, addr,
2565                               CGM.getObjCEntrypoints().objc_loadWeakRetained,
2566                               llvm::Intrinsic::objc_loadWeakRetained);
2567 }
2568 
2569 /// i8* \@objc_storeWeak(i8** %addr, i8* %value)
2570 /// Returns %value.
2571 llvm::Value *CodeGenFunction::EmitARCStoreWeak(Address addr,
2572                                                llvm::Value *value,
2573                                                bool ignored) {
2574   return emitARCStoreOperation(*this, addr, value,
2575                                CGM.getObjCEntrypoints().objc_storeWeak,
2576                                llvm::Intrinsic::objc_storeWeak, ignored);
2577 }
2578 
2579 /// i8* \@objc_initWeak(i8** %addr, i8* %value)
2580 /// Returns %value.  %addr is known to not have a current weak entry.
2581 /// Essentially equivalent to:
2582 ///   *addr = nil; objc_storeWeak(addr, value);
2583 void CodeGenFunction::EmitARCInitWeak(Address addr, llvm::Value *value) {
2584   // If we're initializing to null, just write null to memory; no need
2585   // to get the runtime involved.  But don't do this if optimization
2586   // is enabled, because accounting for this would make the optimizer
2587   // much more complicated.
2588   if (isa<llvm::ConstantPointerNull>(value) &&
2589       CGM.getCodeGenOpts().OptimizationLevel == 0) {
2590     Builder.CreateStore(value, addr);
2591     return;
2592   }
2593 
2594   emitARCStoreOperation(*this, addr, value,
2595                         CGM.getObjCEntrypoints().objc_initWeak,
2596                         llvm::Intrinsic::objc_initWeak, /*ignored*/ true);
2597 }
2598 
2599 /// void \@objc_destroyWeak(i8** %addr)
2600 /// Essentially objc_storeWeak(addr, nil).
2601 void CodeGenFunction::EmitARCDestroyWeak(Address addr) {
2602   llvm::Function *&fn = CGM.getObjCEntrypoints().objc_destroyWeak;
2603   if (!fn) {
2604     fn = CGM.getIntrinsic(llvm::Intrinsic::objc_destroyWeak);
2605     setARCRuntimeFunctionLinkage(CGM, fn);
2606   }
2607 
2608   // Cast the argument to 'id*'.
2609   addr = Builder.CreateBitCast(addr, Int8PtrPtrTy);
2610 
2611   EmitNounwindRuntimeCall(fn, addr.getPointer());
2612 }
2613 
2614 /// void \@objc_moveWeak(i8** %dest, i8** %src)
2615 /// Disregards the current value in %dest.  Leaves %src pointing to nothing.
2616 /// Essentially (objc_copyWeak(dest, src), objc_destroyWeak(src)).
2617 void CodeGenFunction::EmitARCMoveWeak(Address dst, Address src) {
2618   emitARCCopyOperation(*this, dst, src,
2619                        CGM.getObjCEntrypoints().objc_moveWeak,
2620                        llvm::Intrinsic::objc_moveWeak);
2621 }
2622 
2623 /// void \@objc_copyWeak(i8** %dest, i8** %src)
2624 /// Disregards the current value in %dest.  Essentially
2625 ///   objc_release(objc_initWeak(dest, objc_readWeakRetained(src)))
2626 void CodeGenFunction::EmitARCCopyWeak(Address dst, Address src) {
2627   emitARCCopyOperation(*this, dst, src,
2628                        CGM.getObjCEntrypoints().objc_copyWeak,
2629                        llvm::Intrinsic::objc_copyWeak);
2630 }
2631 
2632 void CodeGenFunction::emitARCCopyAssignWeak(QualType Ty, Address DstAddr,
2633                                             Address SrcAddr) {
2634   llvm::Value *Object = EmitARCLoadWeakRetained(SrcAddr);
2635   Object = EmitObjCConsumeObject(Ty, Object);
2636   EmitARCStoreWeak(DstAddr, Object, false);
2637 }
2638 
2639 void CodeGenFunction::emitARCMoveAssignWeak(QualType Ty, Address DstAddr,
2640                                             Address SrcAddr) {
2641   llvm::Value *Object = EmitARCLoadWeakRetained(SrcAddr);
2642   Object = EmitObjCConsumeObject(Ty, Object);
2643   EmitARCStoreWeak(DstAddr, Object, false);
2644   EmitARCDestroyWeak(SrcAddr);
2645 }
2646 
2647 /// Produce the code to do a objc_autoreleasepool_push.
2648 ///   call i8* \@objc_autoreleasePoolPush(void)
2649 llvm::Value *CodeGenFunction::EmitObjCAutoreleasePoolPush() {
2650   llvm::Function *&fn = CGM.getObjCEntrypoints().objc_autoreleasePoolPush;
2651   if (!fn) {
2652     fn = CGM.getIntrinsic(llvm::Intrinsic::objc_autoreleasePoolPush);
2653     setARCRuntimeFunctionLinkage(CGM, fn);
2654   }
2655 
2656   return EmitNounwindRuntimeCall(fn);
2657 }
2658 
2659 /// Produce the code to do a primitive release.
2660 ///   call void \@objc_autoreleasePoolPop(i8* %ptr)
2661 void CodeGenFunction::EmitObjCAutoreleasePoolPop(llvm::Value *value) {
2662   assert(value->getType() == Int8PtrTy);
2663 
2664   if (getInvokeDest()) {
2665     // Call the runtime method not the intrinsic if we are handling exceptions
2666     llvm::FunctionCallee &fn =
2667         CGM.getObjCEntrypoints().objc_autoreleasePoolPopInvoke;
2668     if (!fn) {
2669       llvm::FunctionType *fnType =
2670         llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrTy, false);
2671       fn = CGM.CreateRuntimeFunction(fnType, "objc_autoreleasePoolPop");
2672       setARCRuntimeFunctionLinkage(CGM, fn);
2673     }
2674 
2675     // objc_autoreleasePoolPop can throw.
2676     EmitRuntimeCallOrInvoke(fn, value);
2677   } else {
2678     llvm::FunctionCallee &fn = CGM.getObjCEntrypoints().objc_autoreleasePoolPop;
2679     if (!fn) {
2680       fn = CGM.getIntrinsic(llvm::Intrinsic::objc_autoreleasePoolPop);
2681       setARCRuntimeFunctionLinkage(CGM, fn);
2682     }
2683 
2684     EmitRuntimeCall(fn, value);
2685   }
2686 }
2687 
2688 /// Produce the code to do an MRR version objc_autoreleasepool_push.
2689 /// Which is: [[NSAutoreleasePool alloc] init];
2690 /// Where alloc is declared as: + (id) alloc; in NSAutoreleasePool class.
2691 /// init is declared as: - (id) init; in its NSObject super class.
2692 ///
2693 llvm::Value *CodeGenFunction::EmitObjCMRRAutoreleasePoolPush() {
2694   CGObjCRuntime &Runtime = CGM.getObjCRuntime();
2695   llvm::Value *Receiver = Runtime.EmitNSAutoreleasePoolClassRef(*this);
2696   // [NSAutoreleasePool alloc]
2697   IdentifierInfo *II = &CGM.getContext().Idents.get("alloc");
2698   Selector AllocSel = getContext().Selectors.getSelector(0, &II);
2699   CallArgList Args;
2700   RValue AllocRV =
2701     Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2702                                 getContext().getObjCIdType(),
2703                                 AllocSel, Receiver, Args);
2704 
2705   // [Receiver init]
2706   Receiver = AllocRV.getScalarVal();
2707   II = &CGM.getContext().Idents.get("init");
2708   Selector InitSel = getContext().Selectors.getSelector(0, &II);
2709   RValue InitRV =
2710     Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2711                                 getContext().getObjCIdType(),
2712                                 InitSel, Receiver, Args);
2713   return InitRV.getScalarVal();
2714 }
2715 
2716 /// Allocate the given objc object.
2717 ///   call i8* \@objc_alloc(i8* %value)
2718 llvm::Value *CodeGenFunction::EmitObjCAlloc(llvm::Value *value,
2719                                             llvm::Type *resultType) {
2720   return emitObjCValueOperation(*this, value, resultType,
2721                                 CGM.getObjCEntrypoints().objc_alloc,
2722                                 "objc_alloc");
2723 }
2724 
2725 /// Allocate the given objc object.
2726 ///   call i8* \@objc_allocWithZone(i8* %value)
2727 llvm::Value *CodeGenFunction::EmitObjCAllocWithZone(llvm::Value *value,
2728                                                     llvm::Type *resultType) {
2729   return emitObjCValueOperation(*this, value, resultType,
2730                                 CGM.getObjCEntrypoints().objc_allocWithZone,
2731                                 "objc_allocWithZone");
2732 }
2733 
2734 llvm::Value *CodeGenFunction::EmitObjCAllocInit(llvm::Value *value,
2735                                                 llvm::Type *resultType) {
2736   return emitObjCValueOperation(*this, value, resultType,
2737                                 CGM.getObjCEntrypoints().objc_alloc_init,
2738                                 "objc_alloc_init");
2739 }
2740 
2741 /// Produce the code to do a primitive release.
2742 /// [tmp drain];
2743 void CodeGenFunction::EmitObjCMRRAutoreleasePoolPop(llvm::Value *Arg) {
2744   IdentifierInfo *II = &CGM.getContext().Idents.get("drain");
2745   Selector DrainSel = getContext().Selectors.getSelector(0, &II);
2746   CallArgList Args;
2747   CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
2748                               getContext().VoidTy, DrainSel, Arg, Args);
2749 }
2750 
2751 void CodeGenFunction::destroyARCStrongPrecise(CodeGenFunction &CGF,
2752                                               Address addr,
2753                                               QualType type) {
2754   CGF.EmitARCDestroyStrong(addr, ARCPreciseLifetime);
2755 }
2756 
2757 void CodeGenFunction::destroyARCStrongImprecise(CodeGenFunction &CGF,
2758                                                 Address addr,
2759                                                 QualType type) {
2760   CGF.EmitARCDestroyStrong(addr, ARCImpreciseLifetime);
2761 }
2762 
2763 void CodeGenFunction::destroyARCWeak(CodeGenFunction &CGF,
2764                                      Address addr,
2765                                      QualType type) {
2766   CGF.EmitARCDestroyWeak(addr);
2767 }
2768 
2769 void CodeGenFunction::emitARCIntrinsicUse(CodeGenFunction &CGF, Address addr,
2770                                           QualType type) {
2771   llvm::Value *value = CGF.Builder.CreateLoad(addr);
2772   CGF.EmitARCIntrinsicUse(value);
2773 }
2774 
2775 /// Autorelease the given object.
2776 ///   call i8* \@objc_autorelease(i8* %value)
2777 llvm::Value *CodeGenFunction::EmitObjCAutorelease(llvm::Value *value,
2778                                                   llvm::Type *returnType) {
2779   return emitObjCValueOperation(
2780       *this, value, returnType,
2781       CGM.getObjCEntrypoints().objc_autoreleaseRuntimeFunction,
2782       "objc_autorelease");
2783 }
2784 
2785 /// Retain the given object, with normal retain semantics.
2786 ///   call i8* \@objc_retain(i8* %value)
2787 llvm::Value *CodeGenFunction::EmitObjCRetainNonBlock(llvm::Value *value,
2788                                                      llvm::Type *returnType) {
2789   return emitObjCValueOperation(
2790       *this, value, returnType,
2791       CGM.getObjCEntrypoints().objc_retainRuntimeFunction, "objc_retain");
2792 }
2793 
2794 /// Release the given object.
2795 ///   call void \@objc_release(i8* %value)
2796 void CodeGenFunction::EmitObjCRelease(llvm::Value *value,
2797                                       ARCPreciseLifetime_t precise) {
2798   if (isa<llvm::ConstantPointerNull>(value)) return;
2799 
2800   llvm::FunctionCallee &fn =
2801       CGM.getObjCEntrypoints().objc_releaseRuntimeFunction;
2802   if (!fn) {
2803     llvm::FunctionType *fnType =
2804         llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrTy, false);
2805     fn = CGM.CreateRuntimeFunction(fnType, "objc_release");
2806     setARCRuntimeFunctionLinkage(CGM, fn);
2807     // We have Native ARC, so set nonlazybind attribute for performance
2808     if (llvm::Function *f = dyn_cast<llvm::Function>(fn.getCallee()))
2809       f->addFnAttr(llvm::Attribute::NonLazyBind);
2810   }
2811 
2812   // Cast the argument to 'id'.
2813   value = Builder.CreateBitCast(value, Int8PtrTy);
2814 
2815   // Call objc_release.
2816   llvm::CallBase *call = EmitCallOrInvoke(fn, value);
2817 
2818   if (precise == ARCImpreciseLifetime) {
2819     call->setMetadata("clang.imprecise_release",
2820                       llvm::MDNode::get(Builder.getContext(), None));
2821   }
2822 }
2823 
2824 namespace {
2825   struct CallObjCAutoreleasePoolObject final : EHScopeStack::Cleanup {
2826     llvm::Value *Token;
2827 
2828     CallObjCAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2829 
2830     void Emit(CodeGenFunction &CGF, Flags flags) override {
2831       CGF.EmitObjCAutoreleasePoolPop(Token);
2832     }
2833   };
2834   struct CallObjCMRRAutoreleasePoolObject final : EHScopeStack::Cleanup {
2835     llvm::Value *Token;
2836 
2837     CallObjCMRRAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2838 
2839     void Emit(CodeGenFunction &CGF, Flags flags) override {
2840       CGF.EmitObjCMRRAutoreleasePoolPop(Token);
2841     }
2842   };
2843 }
2844 
2845 void CodeGenFunction::EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr) {
2846   if (CGM.getLangOpts().ObjCAutoRefCount)
2847     EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, Ptr);
2848   else
2849     EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, Ptr);
2850 }
2851 
2852 static bool shouldRetainObjCLifetime(Qualifiers::ObjCLifetime lifetime) {
2853   switch (lifetime) {
2854   case Qualifiers::OCL_None:
2855   case Qualifiers::OCL_ExplicitNone:
2856   case Qualifiers::OCL_Strong:
2857   case Qualifiers::OCL_Autoreleasing:
2858     return true;
2859 
2860   case Qualifiers::OCL_Weak:
2861     return false;
2862   }
2863 
2864   llvm_unreachable("impossible lifetime!");
2865 }
2866 
2867 static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2868                                                   LValue lvalue,
2869                                                   QualType type) {
2870   llvm::Value *result;
2871   bool shouldRetain = shouldRetainObjCLifetime(type.getObjCLifetime());
2872   if (shouldRetain) {
2873     result = CGF.EmitLoadOfLValue(lvalue, SourceLocation()).getScalarVal();
2874   } else {
2875     assert(type.getObjCLifetime() == Qualifiers::OCL_Weak);
2876     result = CGF.EmitARCLoadWeakRetained(lvalue.getAddress(CGF));
2877   }
2878   return TryEmitResult(result, !shouldRetain);
2879 }
2880 
2881 static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2882                                                   const Expr *e) {
2883   e = e->IgnoreParens();
2884   QualType type = e->getType();
2885 
2886   // If we're loading retained from a __strong xvalue, we can avoid
2887   // an extra retain/release pair by zeroing out the source of this
2888   // "move" operation.
2889   if (e->isXValue() &&
2890       !type.isConstQualified() &&
2891       type.getObjCLifetime() == Qualifiers::OCL_Strong) {
2892     // Emit the lvalue.
2893     LValue lv = CGF.EmitLValue(e);
2894 
2895     // Load the object pointer.
2896     llvm::Value *result = CGF.EmitLoadOfLValue(lv,
2897                                                SourceLocation()).getScalarVal();
2898 
2899     // Set the source pointer to NULL.
2900     CGF.EmitStoreOfScalar(getNullForVariable(lv.getAddress(CGF)), lv);
2901 
2902     return TryEmitResult(result, true);
2903   }
2904 
2905   // As a very special optimization, in ARC++, if the l-value is the
2906   // result of a non-volatile assignment, do a simple retain of the
2907   // result of the call to objc_storeWeak instead of reloading.
2908   if (CGF.getLangOpts().CPlusPlus &&
2909       !type.isVolatileQualified() &&
2910       type.getObjCLifetime() == Qualifiers::OCL_Weak &&
2911       isa<BinaryOperator>(e) &&
2912       cast<BinaryOperator>(e)->getOpcode() == BO_Assign)
2913     return TryEmitResult(CGF.EmitScalarExpr(e), false);
2914 
2915   // Try to emit code for scalar constant instead of emitting LValue and
2916   // loading it because we are not guaranteed to have an l-value. One of such
2917   // cases is DeclRefExpr referencing non-odr-used constant-evaluated variable.
2918   if (const auto *decl_expr = dyn_cast<DeclRefExpr>(e)) {
2919     auto *DRE = const_cast<DeclRefExpr *>(decl_expr);
2920     if (CodeGenFunction::ConstantEmission constant = CGF.tryEmitAsConstant(DRE))
2921       return TryEmitResult(CGF.emitScalarConstant(constant, DRE),
2922                            !shouldRetainObjCLifetime(type.getObjCLifetime()));
2923   }
2924 
2925   return tryEmitARCRetainLoadOfScalar(CGF, CGF.EmitLValue(e), type);
2926 }
2927 
2928 typedef llvm::function_ref<llvm::Value *(CodeGenFunction &CGF,
2929                                          llvm::Value *value)>
2930   ValueTransform;
2931 
2932 /// Insert code immediately after a call.
2933 
2934 // FIXME: We should find a way to emit the runtime call immediately
2935 // after the call is emitted to eliminate the need for this function.
2936 static llvm::Value *emitARCOperationAfterCall(CodeGenFunction &CGF,
2937                                               llvm::Value *value,
2938                                               ValueTransform doAfterCall,
2939                                               ValueTransform doFallback) {
2940   CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2941 
2942   if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(value)) {
2943     // Place the retain immediately following the call.
2944     CGF.Builder.SetInsertPoint(call->getParent(),
2945                                ++llvm::BasicBlock::iterator(call));
2946     value = doAfterCall(CGF, value);
2947   } else if (llvm::InvokeInst *invoke = dyn_cast<llvm::InvokeInst>(value)) {
2948     // Place the retain at the beginning of the normal destination block.
2949     llvm::BasicBlock *BB = invoke->getNormalDest();
2950     CGF.Builder.SetInsertPoint(BB, BB->begin());
2951     value = doAfterCall(CGF, value);
2952 
2953   // Bitcasts can arise because of related-result returns.  Rewrite
2954   // the operand.
2955   } else if (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(value)) {
2956     // Change the insert point to avoid emitting the fall-back call after the
2957     // bitcast.
2958     CGF.Builder.SetInsertPoint(bitcast->getParent(), bitcast->getIterator());
2959     llvm::Value *operand = bitcast->getOperand(0);
2960     operand = emitARCOperationAfterCall(CGF, operand, doAfterCall, doFallback);
2961     bitcast->setOperand(0, operand);
2962     value = bitcast;
2963   } else {
2964     auto *phi = dyn_cast<llvm::PHINode>(value);
2965     if (phi && phi->getNumIncomingValues() == 2 &&
2966         isa<llvm::ConstantPointerNull>(phi->getIncomingValue(1)) &&
2967         isa<llvm::CallBase>(phi->getIncomingValue(0))) {
2968       // Handle phi instructions that are generated when it's necessary to check
2969       // whether the receiver of a message is null.
2970       llvm::Value *inVal = phi->getIncomingValue(0);
2971       inVal = emitARCOperationAfterCall(CGF, inVal, doAfterCall, doFallback);
2972       phi->setIncomingValue(0, inVal);
2973       value = phi;
2974     } else {
2975       // Generic fall-back case.
2976       // Retain using the non-block variant: we never need to do a copy
2977       // of a block that's been returned to us.
2978       value = doFallback(CGF, value);
2979     }
2980   }
2981 
2982   CGF.Builder.restoreIP(ip);
2983   return value;
2984 }
2985 
2986 /// Given that the given expression is some sort of call (which does
2987 /// not return retained), emit a retain following it.
2988 static llvm::Value *emitARCRetainCallResult(CodeGenFunction &CGF,
2989                                             const Expr *e) {
2990   llvm::Value *value = CGF.EmitScalarExpr(e);
2991   return emitARCOperationAfterCall(CGF, value,
2992            [](CodeGenFunction &CGF, llvm::Value *value) {
2993              return CGF.EmitARCRetainAutoreleasedReturnValue(value);
2994            },
2995            [](CodeGenFunction &CGF, llvm::Value *value) {
2996              return CGF.EmitARCRetainNonBlock(value);
2997            });
2998 }
2999 
3000 /// Given that the given expression is some sort of call (which does
3001 /// not return retained), perform an unsafeClaim following it.
3002 static llvm::Value *emitARCUnsafeClaimCallResult(CodeGenFunction &CGF,
3003                                                  const Expr *e) {
3004   llvm::Value *value = CGF.EmitScalarExpr(e);
3005   return emitARCOperationAfterCall(CGF, value,
3006            [](CodeGenFunction &CGF, llvm::Value *value) {
3007              return CGF.EmitARCUnsafeClaimAutoreleasedReturnValue(value);
3008            },
3009            [](CodeGenFunction &CGF, llvm::Value *value) {
3010              return value;
3011            });
3012 }
3013 
3014 llvm::Value *CodeGenFunction::EmitARCReclaimReturnedObject(const Expr *E,
3015                                                       bool allowUnsafeClaim) {
3016   if (allowUnsafeClaim &&
3017       CGM.getLangOpts().ObjCRuntime.hasARCUnsafeClaimAutoreleasedReturnValue()) {
3018     return emitARCUnsafeClaimCallResult(*this, E);
3019   } else {
3020     llvm::Value *value = emitARCRetainCallResult(*this, E);
3021     return EmitObjCConsumeObject(E->getType(), value);
3022   }
3023 }
3024 
3025 /// Determine whether it might be important to emit a separate
3026 /// objc_retain_block on the result of the given expression, or
3027 /// whether it's okay to just emit it in a +1 context.
3028 static bool shouldEmitSeparateBlockRetain(const Expr *e) {
3029   assert(e->getType()->isBlockPointerType());
3030   e = e->IgnoreParens();
3031 
3032   // For future goodness, emit block expressions directly in +1
3033   // contexts if we can.
3034   if (isa<BlockExpr>(e))
3035     return false;
3036 
3037   if (const CastExpr *cast = dyn_cast<CastExpr>(e)) {
3038     switch (cast->getCastKind()) {
3039     // Emitting these operations in +1 contexts is goodness.
3040     case CK_LValueToRValue:
3041     case CK_ARCReclaimReturnedObject:
3042     case CK_ARCConsumeObject:
3043     case CK_ARCProduceObject:
3044       return false;
3045 
3046     // These operations preserve a block type.
3047     case CK_NoOp:
3048     case CK_BitCast:
3049       return shouldEmitSeparateBlockRetain(cast->getSubExpr());
3050 
3051     // These operations are known to be bad (or haven't been considered).
3052     case CK_AnyPointerToBlockPointerCast:
3053     default:
3054       return true;
3055     }
3056   }
3057 
3058   return true;
3059 }
3060 
3061 namespace {
3062 /// A CRTP base class for emitting expressions of retainable object
3063 /// pointer type in ARC.
3064 template <typename Impl, typename Result> class ARCExprEmitter {
3065 protected:
3066   CodeGenFunction &CGF;
3067   Impl &asImpl() { return *static_cast<Impl*>(this); }
3068 
3069   ARCExprEmitter(CodeGenFunction &CGF) : CGF(CGF) {}
3070 
3071 public:
3072   Result visit(const Expr *e);
3073   Result visitCastExpr(const CastExpr *e);
3074   Result visitPseudoObjectExpr(const PseudoObjectExpr *e);
3075   Result visitBlockExpr(const BlockExpr *e);
3076   Result visitBinaryOperator(const BinaryOperator *e);
3077   Result visitBinAssign(const BinaryOperator *e);
3078   Result visitBinAssignUnsafeUnretained(const BinaryOperator *e);
3079   Result visitBinAssignAutoreleasing(const BinaryOperator *e);
3080   Result visitBinAssignWeak(const BinaryOperator *e);
3081   Result visitBinAssignStrong(const BinaryOperator *e);
3082 
3083   // Minimal implementation:
3084   //   Result visitLValueToRValue(const Expr *e)
3085   //   Result visitConsumeObject(const Expr *e)
3086   //   Result visitExtendBlockObject(const Expr *e)
3087   //   Result visitReclaimReturnedObject(const Expr *e)
3088   //   Result visitCall(const Expr *e)
3089   //   Result visitExpr(const Expr *e)
3090   //
3091   //   Result emitBitCast(Result result, llvm::Type *resultType)
3092   //   llvm::Value *getValueOfResult(Result result)
3093 };
3094 }
3095 
3096 /// Try to emit a PseudoObjectExpr under special ARC rules.
3097 ///
3098 /// This massively duplicates emitPseudoObjectRValue.
3099 template <typename Impl, typename Result>
3100 Result
3101 ARCExprEmitter<Impl,Result>::visitPseudoObjectExpr(const PseudoObjectExpr *E) {
3102   SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
3103 
3104   // Find the result expression.
3105   const Expr *resultExpr = E->getResultExpr();
3106   assert(resultExpr);
3107   Result result;
3108 
3109   for (PseudoObjectExpr::const_semantics_iterator
3110          i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
3111     const Expr *semantic = *i;
3112 
3113     // If this semantic expression is an opaque value, bind it
3114     // to the result of its source expression.
3115     if (const OpaqueValueExpr *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
3116       typedef CodeGenFunction::OpaqueValueMappingData OVMA;
3117       OVMA opaqueData;
3118 
3119       // If this semantic is the result of the pseudo-object
3120       // expression, try to evaluate the source as +1.
3121       if (ov == resultExpr) {
3122         assert(!OVMA::shouldBindAsLValue(ov));
3123         result = asImpl().visit(ov->getSourceExpr());
3124         opaqueData = OVMA::bind(CGF, ov,
3125                             RValue::get(asImpl().getValueOfResult(result)));
3126 
3127       // Otherwise, just bind it.
3128       } else {
3129         opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
3130       }
3131       opaques.push_back(opaqueData);
3132 
3133     // Otherwise, if the expression is the result, evaluate it
3134     // and remember the result.
3135     } else if (semantic == resultExpr) {
3136       result = asImpl().visit(semantic);
3137 
3138     // Otherwise, evaluate the expression in an ignored context.
3139     } else {
3140       CGF.EmitIgnoredExpr(semantic);
3141     }
3142   }
3143 
3144   // Unbind all the opaques now.
3145   for (unsigned i = 0, e = opaques.size(); i != e; ++i)
3146     opaques[i].unbind(CGF);
3147 
3148   return result;
3149 }
3150 
3151 template <typename Impl, typename Result>
3152 Result ARCExprEmitter<Impl, Result>::visitBlockExpr(const BlockExpr *e) {
3153   // The default implementation just forwards the expression to visitExpr.
3154   return asImpl().visitExpr(e);
3155 }
3156 
3157 template <typename Impl, typename Result>
3158 Result ARCExprEmitter<Impl,Result>::visitCastExpr(const CastExpr *e) {
3159   switch (e->getCastKind()) {
3160 
3161   // No-op casts don't change the type, so we just ignore them.
3162   case CK_NoOp:
3163     return asImpl().visit(e->getSubExpr());
3164 
3165   // These casts can change the type.
3166   case CK_CPointerToObjCPointerCast:
3167   case CK_BlockPointerToObjCPointerCast:
3168   case CK_AnyPointerToBlockPointerCast:
3169   case CK_BitCast: {
3170     llvm::Type *resultType = CGF.ConvertType(e->getType());
3171     assert(e->getSubExpr()->getType()->hasPointerRepresentation());
3172     Result result = asImpl().visit(e->getSubExpr());
3173     return asImpl().emitBitCast(result, resultType);
3174   }
3175 
3176   // Handle some casts specially.
3177   case CK_LValueToRValue:
3178     return asImpl().visitLValueToRValue(e->getSubExpr());
3179   case CK_ARCConsumeObject:
3180     return asImpl().visitConsumeObject(e->getSubExpr());
3181   case CK_ARCExtendBlockObject:
3182     return asImpl().visitExtendBlockObject(e->getSubExpr());
3183   case CK_ARCReclaimReturnedObject:
3184     return asImpl().visitReclaimReturnedObject(e->getSubExpr());
3185 
3186   // Otherwise, use the default logic.
3187   default:
3188     return asImpl().visitExpr(e);
3189   }
3190 }
3191 
3192 template <typename Impl, typename Result>
3193 Result
3194 ARCExprEmitter<Impl,Result>::visitBinaryOperator(const BinaryOperator *e) {
3195   switch (e->getOpcode()) {
3196   case BO_Comma:
3197     CGF.EmitIgnoredExpr(e->getLHS());
3198     CGF.EnsureInsertPoint();
3199     return asImpl().visit(e->getRHS());
3200 
3201   case BO_Assign:
3202     return asImpl().visitBinAssign(e);
3203 
3204   default:
3205     return asImpl().visitExpr(e);
3206   }
3207 }
3208 
3209 template <typename Impl, typename Result>
3210 Result ARCExprEmitter<Impl,Result>::visitBinAssign(const BinaryOperator *e) {
3211   switch (e->getLHS()->getType().getObjCLifetime()) {
3212   case Qualifiers::OCL_ExplicitNone:
3213     return asImpl().visitBinAssignUnsafeUnretained(e);
3214 
3215   case Qualifiers::OCL_Weak:
3216     return asImpl().visitBinAssignWeak(e);
3217 
3218   case Qualifiers::OCL_Autoreleasing:
3219     return asImpl().visitBinAssignAutoreleasing(e);
3220 
3221   case Qualifiers::OCL_Strong:
3222     return asImpl().visitBinAssignStrong(e);
3223 
3224   case Qualifiers::OCL_None:
3225     return asImpl().visitExpr(e);
3226   }
3227   llvm_unreachable("bad ObjC ownership qualifier");
3228 }
3229 
3230 /// The default rule for __unsafe_unretained emits the RHS recursively,
3231 /// stores into the unsafe variable, and propagates the result outward.
3232 template <typename Impl, typename Result>
3233 Result ARCExprEmitter<Impl,Result>::
3234                     visitBinAssignUnsafeUnretained(const BinaryOperator *e) {
3235   // Recursively emit the RHS.
3236   // For __block safety, do this before emitting the LHS.
3237   Result result = asImpl().visit(e->getRHS());
3238 
3239   // Perform the store.
3240   LValue lvalue =
3241     CGF.EmitCheckedLValue(e->getLHS(), CodeGenFunction::TCK_Store);
3242   CGF.EmitStoreThroughLValue(RValue::get(asImpl().getValueOfResult(result)),
3243                              lvalue);
3244 
3245   return result;
3246 }
3247 
3248 template <typename Impl, typename Result>
3249 Result
3250 ARCExprEmitter<Impl,Result>::visitBinAssignAutoreleasing(const BinaryOperator *e) {
3251   return asImpl().visitExpr(e);
3252 }
3253 
3254 template <typename Impl, typename Result>
3255 Result
3256 ARCExprEmitter<Impl,Result>::visitBinAssignWeak(const BinaryOperator *e) {
3257   return asImpl().visitExpr(e);
3258 }
3259 
3260 template <typename Impl, typename Result>
3261 Result
3262 ARCExprEmitter<Impl,Result>::visitBinAssignStrong(const BinaryOperator *e) {
3263   return asImpl().visitExpr(e);
3264 }
3265 
3266 /// The general expression-emission logic.
3267 template <typename Impl, typename Result>
3268 Result ARCExprEmitter<Impl,Result>::visit(const Expr *e) {
3269   // We should *never* see a nested full-expression here, because if
3270   // we fail to emit at +1, our caller must not retain after we close
3271   // out the full-expression.  This isn't as important in the unsafe
3272   // emitter.
3273   assert(!isa<ExprWithCleanups>(e));
3274 
3275   // Look through parens, __extension__, generic selection, etc.
3276   e = e->IgnoreParens();
3277 
3278   // Handle certain kinds of casts.
3279   if (const CastExpr *ce = dyn_cast<CastExpr>(e)) {
3280     return asImpl().visitCastExpr(ce);
3281 
3282   // Handle the comma operator.
3283   } else if (auto op = dyn_cast<BinaryOperator>(e)) {
3284     return asImpl().visitBinaryOperator(op);
3285 
3286   // TODO: handle conditional operators here
3287 
3288   // For calls and message sends, use the retained-call logic.
3289   // Delegate inits are a special case in that they're the only
3290   // returns-retained expression that *isn't* surrounded by
3291   // a consume.
3292   } else if (isa<CallExpr>(e) ||
3293              (isa<ObjCMessageExpr>(e) &&
3294               !cast<ObjCMessageExpr>(e)->isDelegateInitCall())) {
3295     return asImpl().visitCall(e);
3296 
3297   // Look through pseudo-object expressions.
3298   } else if (const PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
3299     return asImpl().visitPseudoObjectExpr(pseudo);
3300   } else if (auto *be = dyn_cast<BlockExpr>(e))
3301     return asImpl().visitBlockExpr(be);
3302 
3303   return asImpl().visitExpr(e);
3304 }
3305 
3306 namespace {
3307 
3308 /// An emitter for +1 results.
3309 struct ARCRetainExprEmitter :
3310   public ARCExprEmitter<ARCRetainExprEmitter, TryEmitResult> {
3311 
3312   ARCRetainExprEmitter(CodeGenFunction &CGF) : ARCExprEmitter(CGF) {}
3313 
3314   llvm::Value *getValueOfResult(TryEmitResult result) {
3315     return result.getPointer();
3316   }
3317 
3318   TryEmitResult emitBitCast(TryEmitResult result, llvm::Type *resultType) {
3319     llvm::Value *value = result.getPointer();
3320     value = CGF.Builder.CreateBitCast(value, resultType);
3321     result.setPointer(value);
3322     return result;
3323   }
3324 
3325   TryEmitResult visitLValueToRValue(const Expr *e) {
3326     return tryEmitARCRetainLoadOfScalar(CGF, e);
3327   }
3328 
3329   /// For consumptions, just emit the subexpression and thus elide
3330   /// the retain/release pair.
3331   TryEmitResult visitConsumeObject(const Expr *e) {
3332     llvm::Value *result = CGF.EmitScalarExpr(e);
3333     return TryEmitResult(result, true);
3334   }
3335 
3336   TryEmitResult visitBlockExpr(const BlockExpr *e) {
3337     TryEmitResult result = visitExpr(e);
3338     // Avoid the block-retain if this is a block literal that doesn't need to be
3339     // copied to the heap.
3340     if (e->getBlockDecl()->canAvoidCopyToHeap())
3341       result.setInt(true);
3342     return result;
3343   }
3344 
3345   /// Block extends are net +0.  Naively, we could just recurse on
3346   /// the subexpression, but actually we need to ensure that the
3347   /// value is copied as a block, so there's a little filter here.
3348   TryEmitResult visitExtendBlockObject(const Expr *e) {
3349     llvm::Value *result; // will be a +0 value
3350 
3351     // If we can't safely assume the sub-expression will produce a
3352     // block-copied value, emit the sub-expression at +0.
3353     if (shouldEmitSeparateBlockRetain(e)) {
3354       result = CGF.EmitScalarExpr(e);
3355 
3356     // Otherwise, try to emit the sub-expression at +1 recursively.
3357     } else {
3358       TryEmitResult subresult = asImpl().visit(e);
3359 
3360       // If that produced a retained value, just use that.
3361       if (subresult.getInt()) {
3362         return subresult;
3363       }
3364 
3365       // Otherwise it's +0.
3366       result = subresult.getPointer();
3367     }
3368 
3369     // Retain the object as a block.
3370     result = CGF.EmitARCRetainBlock(result, /*mandatory*/ true);
3371     return TryEmitResult(result, true);
3372   }
3373 
3374   /// For reclaims, emit the subexpression as a retained call and
3375   /// skip the consumption.
3376   TryEmitResult visitReclaimReturnedObject(const Expr *e) {
3377     llvm::Value *result = emitARCRetainCallResult(CGF, e);
3378     return TryEmitResult(result, true);
3379   }
3380 
3381   /// When we have an undecorated call, retroactively do a claim.
3382   TryEmitResult visitCall(const Expr *e) {
3383     llvm::Value *result = emitARCRetainCallResult(CGF, e);
3384     return TryEmitResult(result, true);
3385   }
3386 
3387   // TODO: maybe special-case visitBinAssignWeak?
3388 
3389   TryEmitResult visitExpr(const Expr *e) {
3390     // We didn't find an obvious production, so emit what we've got and
3391     // tell the caller that we didn't manage to retain.
3392     llvm::Value *result = CGF.EmitScalarExpr(e);
3393     return TryEmitResult(result, false);
3394   }
3395 };
3396 }
3397 
3398 static TryEmitResult
3399 tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e) {
3400   return ARCRetainExprEmitter(CGF).visit(e);
3401 }
3402 
3403 static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
3404                                                 LValue lvalue,
3405                                                 QualType type) {
3406   TryEmitResult result = tryEmitARCRetainLoadOfScalar(CGF, lvalue, type);
3407   llvm::Value *value = result.getPointer();
3408   if (!result.getInt())
3409     value = CGF.EmitARCRetain(type, value);
3410   return value;
3411 }
3412 
3413 /// EmitARCRetainScalarExpr - Semantically equivalent to
3414 /// EmitARCRetainObject(e->getType(), EmitScalarExpr(e)), but making a
3415 /// best-effort attempt to peephole expressions that naturally produce
3416 /// retained objects.
3417 llvm::Value *CodeGenFunction::EmitARCRetainScalarExpr(const Expr *e) {
3418   // The retain needs to happen within the full-expression.
3419   if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
3420     RunCleanupsScope scope(*this);
3421     return EmitARCRetainScalarExpr(cleanups->getSubExpr());
3422   }
3423 
3424   TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
3425   llvm::Value *value = result.getPointer();
3426   if (!result.getInt())
3427     value = EmitARCRetain(e->getType(), value);
3428   return value;
3429 }
3430 
3431 llvm::Value *
3432 CodeGenFunction::EmitARCRetainAutoreleaseScalarExpr(const Expr *e) {
3433   // The retain needs to happen within the full-expression.
3434   if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
3435     RunCleanupsScope scope(*this);
3436     return EmitARCRetainAutoreleaseScalarExpr(cleanups->getSubExpr());
3437   }
3438 
3439   TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
3440   llvm::Value *value = result.getPointer();
3441   if (result.getInt())
3442     value = EmitARCAutorelease(value);
3443   else
3444     value = EmitARCRetainAutorelease(e->getType(), value);
3445   return value;
3446 }
3447 
3448 llvm::Value *CodeGenFunction::EmitARCExtendBlockObject(const Expr *e) {
3449   llvm::Value *result;
3450   bool doRetain;
3451 
3452   if (shouldEmitSeparateBlockRetain(e)) {
3453     result = EmitScalarExpr(e);
3454     doRetain = true;
3455   } else {
3456     TryEmitResult subresult = tryEmitARCRetainScalarExpr(*this, e);
3457     result = subresult.getPointer();
3458     doRetain = !subresult.getInt();
3459   }
3460 
3461   if (doRetain)
3462     result = EmitARCRetainBlock(result, /*mandatory*/ true);
3463   return EmitObjCConsumeObject(e->getType(), result);
3464 }
3465 
3466 llvm::Value *CodeGenFunction::EmitObjCThrowOperand(const Expr *expr) {
3467   // In ARC, retain and autorelease the expression.
3468   if (getLangOpts().ObjCAutoRefCount) {
3469     // Do so before running any cleanups for the full-expression.
3470     // EmitARCRetainAutoreleaseScalarExpr does this for us.
3471     return EmitARCRetainAutoreleaseScalarExpr(expr);
3472   }
3473 
3474   // Otherwise, use the normal scalar-expression emission.  The
3475   // exception machinery doesn't do anything special with the
3476   // exception like retaining it, so there's no safety associated with
3477   // only running cleanups after the throw has started, and when it
3478   // matters it tends to be substantially inferior code.
3479   return EmitScalarExpr(expr);
3480 }
3481 
3482 namespace {
3483 
3484 /// An emitter for assigning into an __unsafe_unretained context.
3485 struct ARCUnsafeUnretainedExprEmitter :
3486   public ARCExprEmitter<ARCUnsafeUnretainedExprEmitter, llvm::Value*> {
3487 
3488   ARCUnsafeUnretainedExprEmitter(CodeGenFunction &CGF) : ARCExprEmitter(CGF) {}
3489 
3490   llvm::Value *getValueOfResult(llvm::Value *value) {
3491     return value;
3492   }
3493 
3494   llvm::Value *emitBitCast(llvm::Value *value, llvm::Type *resultType) {
3495     return CGF.Builder.CreateBitCast(value, resultType);
3496   }
3497 
3498   llvm::Value *visitLValueToRValue(const Expr *e) {
3499     return CGF.EmitScalarExpr(e);
3500   }
3501 
3502   /// For consumptions, just emit the subexpression and perform the
3503   /// consumption like normal.
3504   llvm::Value *visitConsumeObject(const Expr *e) {
3505     llvm::Value *value = CGF.EmitScalarExpr(e);
3506     return CGF.EmitObjCConsumeObject(e->getType(), value);
3507   }
3508 
3509   /// No special logic for block extensions.  (This probably can't
3510   /// actually happen in this emitter, though.)
3511   llvm::Value *visitExtendBlockObject(const Expr *e) {
3512     return CGF.EmitARCExtendBlockObject(e);
3513   }
3514 
3515   /// For reclaims, perform an unsafeClaim if that's enabled.
3516   llvm::Value *visitReclaimReturnedObject(const Expr *e) {
3517     return CGF.EmitARCReclaimReturnedObject(e, /*unsafe*/ true);
3518   }
3519 
3520   /// When we have an undecorated call, just emit it without adding
3521   /// the unsafeClaim.
3522   llvm::Value *visitCall(const Expr *e) {
3523     return CGF.EmitScalarExpr(e);
3524   }
3525 
3526   /// Just do normal scalar emission in the default case.
3527   llvm::Value *visitExpr(const Expr *e) {
3528     return CGF.EmitScalarExpr(e);
3529   }
3530 };
3531 }
3532 
3533 static llvm::Value *emitARCUnsafeUnretainedScalarExpr(CodeGenFunction &CGF,
3534                                                       const Expr *e) {
3535   return ARCUnsafeUnretainedExprEmitter(CGF).visit(e);
3536 }
3537 
3538 /// EmitARCUnsafeUnretainedScalarExpr - Semantically equivalent to
3539 /// immediately releasing the resut of EmitARCRetainScalarExpr, but
3540 /// avoiding any spurious retains, including by performing reclaims
3541 /// with objc_unsafeClaimAutoreleasedReturnValue.
3542 llvm::Value *CodeGenFunction::EmitARCUnsafeUnretainedScalarExpr(const Expr *e) {
3543   // Look through full-expressions.
3544   if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
3545     RunCleanupsScope scope(*this);
3546     return emitARCUnsafeUnretainedScalarExpr(*this, cleanups->getSubExpr());
3547   }
3548 
3549   return emitARCUnsafeUnretainedScalarExpr(*this, e);
3550 }
3551 
3552 std::pair<LValue,llvm::Value*>
3553 CodeGenFunction::EmitARCStoreUnsafeUnretained(const BinaryOperator *e,
3554                                               bool ignored) {
3555   // Evaluate the RHS first.  If we're ignoring the result, assume
3556   // that we can emit at an unsafe +0.
3557   llvm::Value *value;
3558   if (ignored) {
3559     value = EmitARCUnsafeUnretainedScalarExpr(e->getRHS());
3560   } else {
3561     value = EmitScalarExpr(e->getRHS());
3562   }
3563 
3564   // Emit the LHS and perform the store.
3565   LValue lvalue = EmitLValue(e->getLHS());
3566   EmitStoreOfScalar(value, lvalue);
3567 
3568   return std::pair<LValue,llvm::Value*>(std::move(lvalue), value);
3569 }
3570 
3571 std::pair<LValue,llvm::Value*>
3572 CodeGenFunction::EmitARCStoreStrong(const BinaryOperator *e,
3573                                     bool ignored) {
3574   // Evaluate the RHS first.
3575   TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e->getRHS());
3576   llvm::Value *value = result.getPointer();
3577 
3578   bool hasImmediateRetain = result.getInt();
3579 
3580   // If we didn't emit a retained object, and the l-value is of block
3581   // type, then we need to emit the block-retain immediately in case
3582   // it invalidates the l-value.
3583   if (!hasImmediateRetain && e->getType()->isBlockPointerType()) {
3584     value = EmitARCRetainBlock(value, /*mandatory*/ false);
3585     hasImmediateRetain = true;
3586   }
3587 
3588   LValue lvalue = EmitLValue(e->getLHS());
3589 
3590   // If the RHS was emitted retained, expand this.
3591   if (hasImmediateRetain) {
3592     llvm::Value *oldValue = EmitLoadOfScalar(lvalue, SourceLocation());
3593     EmitStoreOfScalar(value, lvalue);
3594     EmitARCRelease(oldValue, lvalue.isARCPreciseLifetime());
3595   } else {
3596     value = EmitARCStoreStrong(lvalue, value, ignored);
3597   }
3598 
3599   return std::pair<LValue,llvm::Value*>(lvalue, value);
3600 }
3601 
3602 std::pair<LValue,llvm::Value*>
3603 CodeGenFunction::EmitARCStoreAutoreleasing(const BinaryOperator *e) {
3604   llvm::Value *value = EmitARCRetainAutoreleaseScalarExpr(e->getRHS());
3605   LValue lvalue = EmitLValue(e->getLHS());
3606 
3607   EmitStoreOfScalar(value, lvalue);
3608 
3609   return std::pair<LValue,llvm::Value*>(lvalue, value);
3610 }
3611 
3612 void CodeGenFunction::EmitObjCAutoreleasePoolStmt(
3613                                           const ObjCAutoreleasePoolStmt &ARPS) {
3614   const Stmt *subStmt = ARPS.getSubStmt();
3615   const CompoundStmt &S = cast<CompoundStmt>(*subStmt);
3616 
3617   CGDebugInfo *DI = getDebugInfo();
3618   if (DI)
3619     DI->EmitLexicalBlockStart(Builder, S.getLBracLoc());
3620 
3621   // Keep track of the current cleanup stack depth.
3622   RunCleanupsScope Scope(*this);
3623   if (CGM.getLangOpts().ObjCRuntime.hasNativeARC()) {
3624     llvm::Value *token = EmitObjCAutoreleasePoolPush();
3625     EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, token);
3626   } else {
3627     llvm::Value *token = EmitObjCMRRAutoreleasePoolPush();
3628     EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, token);
3629   }
3630 
3631   for (const auto *I : S.body())
3632     EmitStmt(I);
3633 
3634   if (DI)
3635     DI->EmitLexicalBlockEnd(Builder, S.getRBracLoc());
3636 }
3637 
3638 /// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
3639 /// make sure it survives garbage collection until this point.
3640 void CodeGenFunction::EmitExtendGCLifetime(llvm::Value *object) {
3641   // We just use an inline assembly.
3642   llvm::FunctionType *extenderType
3643     = llvm::FunctionType::get(VoidTy, VoidPtrTy, RequiredArgs::All);
3644   llvm::InlineAsm *extender = llvm::InlineAsm::get(extenderType,
3645                                                    /* assembly */ "",
3646                                                    /* constraints */ "r",
3647                                                    /* side effects */ true);
3648 
3649   object = Builder.CreateBitCast(object, VoidPtrTy);
3650   EmitNounwindRuntimeCall(extender, object);
3651 }
3652 
3653 /// GenerateObjCAtomicSetterCopyHelperFunction - Given a c++ object type with
3654 /// non-trivial copy assignment function, produce following helper function.
3655 /// static void copyHelper(Ty *dest, const Ty *source) { *dest = *source; }
3656 ///
3657 llvm::Constant *
3658 CodeGenFunction::GenerateObjCAtomicSetterCopyHelperFunction(
3659                                         const ObjCPropertyImplDecl *PID) {
3660   if (!getLangOpts().CPlusPlus ||
3661       !getLangOpts().ObjCRuntime.hasAtomicCopyHelper())
3662     return nullptr;
3663   QualType Ty = PID->getPropertyIvarDecl()->getType();
3664   if (!Ty->isRecordType())
3665     return nullptr;
3666   const ObjCPropertyDecl *PD = PID->getPropertyDecl();
3667   if ((!(PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_atomic)))
3668     return nullptr;
3669   llvm::Constant *HelperFn = nullptr;
3670   if (hasTrivialSetExpr(PID))
3671     return nullptr;
3672   assert(PID->getSetterCXXAssignment() && "SetterCXXAssignment - null");
3673   if ((HelperFn = CGM.getAtomicSetterHelperFnMap(Ty)))
3674     return HelperFn;
3675 
3676   ASTContext &C = getContext();
3677   IdentifierInfo *II
3678     = &CGM.getContext().Idents.get("__assign_helper_atomic_property_");
3679 
3680   QualType ReturnTy = C.VoidTy;
3681   QualType DestTy = C.getPointerType(Ty);
3682   QualType SrcTy = Ty;
3683   SrcTy.addConst();
3684   SrcTy = C.getPointerType(SrcTy);
3685 
3686   SmallVector<QualType, 2> ArgTys;
3687   ArgTys.push_back(DestTy);
3688   ArgTys.push_back(SrcTy);
3689   QualType FunctionTy = C.getFunctionType(ReturnTy, ArgTys, {});
3690 
3691   FunctionDecl *FD = FunctionDecl::Create(
3692       C, C.getTranslationUnitDecl(), SourceLocation(), SourceLocation(), II,
3693       FunctionTy, nullptr, SC_Static, false, false);
3694 
3695   FunctionArgList args;
3696   ImplicitParamDecl DstDecl(C, FD, SourceLocation(), /*Id=*/nullptr, DestTy,
3697                             ImplicitParamDecl::Other);
3698   args.push_back(&DstDecl);
3699   ImplicitParamDecl SrcDecl(C, FD, SourceLocation(), /*Id=*/nullptr, SrcTy,
3700                             ImplicitParamDecl::Other);
3701   args.push_back(&SrcDecl);
3702 
3703   const CGFunctionInfo &FI =
3704       CGM.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy, args);
3705 
3706   llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
3707 
3708   llvm::Function *Fn =
3709     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
3710                            "__assign_helper_atomic_property_",
3711                            &CGM.getModule());
3712 
3713   CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
3714 
3715   StartFunction(FD, ReturnTy, Fn, FI, args);
3716 
3717   DeclRefExpr DstExpr(C, &DstDecl, false, DestTy, VK_RValue, SourceLocation());
3718   UnaryOperator *DST = UnaryOperator::Create(
3719       C, &DstExpr, UO_Deref, DestTy->getPointeeType(), VK_LValue, OK_Ordinary,
3720       SourceLocation(), false, FPOptionsOverride());
3721 
3722   DeclRefExpr SrcExpr(C, &SrcDecl, false, SrcTy, VK_RValue, SourceLocation());
3723   UnaryOperator *SRC = UnaryOperator::Create(
3724       C, &SrcExpr, UO_Deref, SrcTy->getPointeeType(), VK_LValue, OK_Ordinary,
3725       SourceLocation(), false, FPOptionsOverride());
3726 
3727   Expr *Args[2] = {DST, SRC};
3728   CallExpr *CalleeExp = cast<CallExpr>(PID->getSetterCXXAssignment());
3729   CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
3730       C, OO_Equal, CalleeExp->getCallee(), Args, DestTy->getPointeeType(),
3731       VK_LValue, SourceLocation(), FPOptionsOverride());
3732 
3733   EmitStmt(TheCall);
3734 
3735   FinishFunction();
3736   HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
3737   CGM.setAtomicSetterHelperFnMap(Ty, HelperFn);
3738   return HelperFn;
3739 }
3740 
3741 llvm::Constant *
3742 CodeGenFunction::GenerateObjCAtomicGetterCopyHelperFunction(
3743                                             const ObjCPropertyImplDecl *PID) {
3744   if (!getLangOpts().CPlusPlus ||
3745       !getLangOpts().ObjCRuntime.hasAtomicCopyHelper())
3746     return nullptr;
3747   const ObjCPropertyDecl *PD = PID->getPropertyDecl();
3748   QualType Ty = PD->getType();
3749   if (!Ty->isRecordType())
3750     return nullptr;
3751   if ((!(PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_atomic)))
3752     return nullptr;
3753   llvm::Constant *HelperFn = nullptr;
3754   if (hasTrivialGetExpr(PID))
3755     return nullptr;
3756   assert(PID->getGetterCXXConstructor() && "getGetterCXXConstructor - null");
3757   if ((HelperFn = CGM.getAtomicGetterHelperFnMap(Ty)))
3758     return HelperFn;
3759 
3760   ASTContext &C = getContext();
3761   IdentifierInfo *II =
3762       &CGM.getContext().Idents.get("__copy_helper_atomic_property_");
3763 
3764   QualType ReturnTy = C.VoidTy;
3765   QualType DestTy = C.getPointerType(Ty);
3766   QualType SrcTy = Ty;
3767   SrcTy.addConst();
3768   SrcTy = C.getPointerType(SrcTy);
3769 
3770   SmallVector<QualType, 2> ArgTys;
3771   ArgTys.push_back(DestTy);
3772   ArgTys.push_back(SrcTy);
3773   QualType FunctionTy = C.getFunctionType(ReturnTy, ArgTys, {});
3774 
3775   FunctionDecl *FD = FunctionDecl::Create(
3776       C, C.getTranslationUnitDecl(), SourceLocation(), SourceLocation(), II,
3777       FunctionTy, nullptr, SC_Static, false, false);
3778 
3779   FunctionArgList args;
3780   ImplicitParamDecl DstDecl(C, FD, SourceLocation(), /*Id=*/nullptr, DestTy,
3781                             ImplicitParamDecl::Other);
3782   args.push_back(&DstDecl);
3783   ImplicitParamDecl SrcDecl(C, FD, SourceLocation(), /*Id=*/nullptr, SrcTy,
3784                             ImplicitParamDecl::Other);
3785   args.push_back(&SrcDecl);
3786 
3787   const CGFunctionInfo &FI =
3788       CGM.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy, args);
3789 
3790   llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
3791 
3792   llvm::Function *Fn = llvm::Function::Create(
3793       LTy, llvm::GlobalValue::InternalLinkage, "__copy_helper_atomic_property_",
3794       &CGM.getModule());
3795 
3796   CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
3797 
3798   StartFunction(FD, ReturnTy, Fn, FI, args);
3799 
3800   DeclRefExpr SrcExpr(getContext(), &SrcDecl, false, SrcTy, VK_RValue,
3801                       SourceLocation());
3802 
3803   UnaryOperator *SRC = UnaryOperator::Create(
3804       C, &SrcExpr, UO_Deref, SrcTy->getPointeeType(), VK_LValue, OK_Ordinary,
3805       SourceLocation(), false, FPOptionsOverride());
3806 
3807   CXXConstructExpr *CXXConstExpr =
3808     cast<CXXConstructExpr>(PID->getGetterCXXConstructor());
3809 
3810   SmallVector<Expr*, 4> ConstructorArgs;
3811   ConstructorArgs.push_back(SRC);
3812   ConstructorArgs.append(std::next(CXXConstExpr->arg_begin()),
3813                          CXXConstExpr->arg_end());
3814 
3815   CXXConstructExpr *TheCXXConstructExpr =
3816     CXXConstructExpr::Create(C, Ty, SourceLocation(),
3817                              CXXConstExpr->getConstructor(),
3818                              CXXConstExpr->isElidable(),
3819                              ConstructorArgs,
3820                              CXXConstExpr->hadMultipleCandidates(),
3821                              CXXConstExpr->isListInitialization(),
3822                              CXXConstExpr->isStdInitListInitialization(),
3823                              CXXConstExpr->requiresZeroInitialization(),
3824                              CXXConstExpr->getConstructionKind(),
3825                              SourceRange());
3826 
3827   DeclRefExpr DstExpr(getContext(), &DstDecl, false, DestTy, VK_RValue,
3828                       SourceLocation());
3829 
3830   RValue DV = EmitAnyExpr(&DstExpr);
3831   CharUnits Alignment
3832     = getContext().getTypeAlignInChars(TheCXXConstructExpr->getType());
3833   EmitAggExpr(TheCXXConstructExpr,
3834               AggValueSlot::forAddr(Address(DV.getScalarVal(), Alignment),
3835                                     Qualifiers(),
3836                                     AggValueSlot::IsDestructed,
3837                                     AggValueSlot::DoesNotNeedGCBarriers,
3838                                     AggValueSlot::IsNotAliased,
3839                                     AggValueSlot::DoesNotOverlap));
3840 
3841   FinishFunction();
3842   HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
3843   CGM.setAtomicGetterHelperFnMap(Ty, HelperFn);
3844   return HelperFn;
3845 }
3846 
3847 llvm::Value *
3848 CodeGenFunction::EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty) {
3849   // Get selectors for retain/autorelease.
3850   IdentifierInfo *CopyID = &getContext().Idents.get("copy");
3851   Selector CopySelector =
3852       getContext().Selectors.getNullarySelector(CopyID);
3853   IdentifierInfo *AutoreleaseID = &getContext().Idents.get("autorelease");
3854   Selector AutoreleaseSelector =
3855       getContext().Selectors.getNullarySelector(AutoreleaseID);
3856 
3857   // Emit calls to retain/autorelease.
3858   CGObjCRuntime &Runtime = CGM.getObjCRuntime();
3859   llvm::Value *Val = Block;
3860   RValue Result;
3861   Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
3862                                        Ty, CopySelector,
3863                                        Val, CallArgList(), nullptr, nullptr);
3864   Val = Result.getScalarVal();
3865   Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
3866                                        Ty, AutoreleaseSelector,
3867                                        Val, CallArgList(), nullptr, nullptr);
3868   Val = Result.getScalarVal();
3869   return Val;
3870 }
3871 
3872 static unsigned getBaseMachOPlatformID(const llvm::Triple &TT) {
3873   switch (TT.getOS()) {
3874   case llvm::Triple::Darwin:
3875   case llvm::Triple::MacOSX:
3876     return llvm::MachO::PLATFORM_MACOS;
3877   case llvm::Triple::IOS:
3878     return llvm::MachO::PLATFORM_IOS;
3879   case llvm::Triple::TvOS:
3880     return llvm::MachO::PLATFORM_TVOS;
3881   case llvm::Triple::WatchOS:
3882     return llvm::MachO::PLATFORM_WATCHOS;
3883   default:
3884     return /*Unknown platform*/ 0;
3885   }
3886 }
3887 
3888 static llvm::Value *emitIsPlatformVersionAtLeast(CodeGenFunction &CGF,
3889                                                  const VersionTuple &Version) {
3890   CodeGenModule &CGM = CGF.CGM;
3891   // Note: we intend to support multi-platform version checks, so reserve
3892   // the room for a dual platform checking invocation that will be
3893   // implemented in the future.
3894   llvm::SmallVector<llvm::Value *, 8> Args;
3895 
3896   auto EmitArgs = [&](const VersionTuple &Version, const llvm::Triple &TT) {
3897     Optional<unsigned> Min = Version.getMinor(), SMin = Version.getSubminor();
3898     Args.push_back(
3899         llvm::ConstantInt::get(CGM.Int32Ty, getBaseMachOPlatformID(TT)));
3900     Args.push_back(llvm::ConstantInt::get(CGM.Int32Ty, Version.getMajor()));
3901     Args.push_back(llvm::ConstantInt::get(CGM.Int32Ty, Min ? *Min : 0));
3902     Args.push_back(llvm::ConstantInt::get(CGM.Int32Ty, SMin ? *SMin : 0));
3903   };
3904 
3905   assert(!Version.empty() && "unexpected empty version");
3906   EmitArgs(Version, CGM.getTarget().getTriple());
3907 
3908   if (!CGM.IsPlatformVersionAtLeastFn) {
3909     llvm::FunctionType *FTy = llvm::FunctionType::get(
3910         CGM.Int32Ty, {CGM.Int32Ty, CGM.Int32Ty, CGM.Int32Ty, CGM.Int32Ty},
3911         false);
3912     CGM.IsPlatformVersionAtLeastFn =
3913         CGM.CreateRuntimeFunction(FTy, "__isPlatformVersionAtLeast");
3914   }
3915 
3916   llvm::Value *Check =
3917       CGF.EmitNounwindRuntimeCall(CGM.IsPlatformVersionAtLeastFn, Args);
3918   return CGF.Builder.CreateICmpNE(Check,
3919                                   llvm::Constant::getNullValue(CGM.Int32Ty));
3920 }
3921 
3922 llvm::Value *
3923 CodeGenFunction::EmitBuiltinAvailable(const VersionTuple &Version) {
3924   // Darwin uses the new __isPlatformVersionAtLeast family of routines.
3925   if (CGM.getTarget().getTriple().isOSDarwin())
3926     return emitIsPlatformVersionAtLeast(*this, Version);
3927 
3928   if (!CGM.IsOSVersionAtLeastFn) {
3929     llvm::FunctionType *FTy =
3930         llvm::FunctionType::get(Int32Ty, {Int32Ty, Int32Ty, Int32Ty}, false);
3931     CGM.IsOSVersionAtLeastFn =
3932         CGM.CreateRuntimeFunction(FTy, "__isOSVersionAtLeast");
3933   }
3934 
3935   Optional<unsigned> Min = Version.getMinor(), SMin = Version.getSubminor();
3936   llvm::Value *Args[] = {
3937       llvm::ConstantInt::get(CGM.Int32Ty, Version.getMajor()),
3938       llvm::ConstantInt::get(CGM.Int32Ty, Min ? *Min : 0),
3939       llvm::ConstantInt::get(CGM.Int32Ty, SMin ? *SMin : 0),
3940   };
3941 
3942   llvm::Value *CallRes =
3943       EmitNounwindRuntimeCall(CGM.IsOSVersionAtLeastFn, Args);
3944 
3945   return Builder.CreateICmpNE(CallRes, llvm::Constant::getNullValue(Int32Ty));
3946 }
3947 
3948 static bool isFoundationNeededForDarwinAvailabilityCheck(
3949     const llvm::Triple &TT, const VersionTuple &TargetVersion) {
3950   VersionTuple FoundationDroppedInVersion;
3951   switch (TT.getOS()) {
3952   case llvm::Triple::IOS:
3953   case llvm::Triple::TvOS:
3954     FoundationDroppedInVersion = VersionTuple(/*Major=*/13);
3955     break;
3956   case llvm::Triple::WatchOS:
3957     FoundationDroppedInVersion = VersionTuple(/*Major=*/6);
3958     break;
3959   case llvm::Triple::Darwin:
3960   case llvm::Triple::MacOSX:
3961     FoundationDroppedInVersion = VersionTuple(/*Major=*/10, /*Minor=*/15);
3962     break;
3963   default:
3964     llvm_unreachable("Unexpected OS");
3965   }
3966   return TargetVersion < FoundationDroppedInVersion;
3967 }
3968 
3969 void CodeGenModule::emitAtAvailableLinkGuard() {
3970   if (!IsPlatformVersionAtLeastFn)
3971     return;
3972   // @available requires CoreFoundation only on Darwin.
3973   if (!Target.getTriple().isOSDarwin())
3974     return;
3975   // @available doesn't need Foundation on macOS 10.15+, iOS/tvOS 13+, or
3976   // watchOS 6+.
3977   if (!isFoundationNeededForDarwinAvailabilityCheck(
3978           Target.getTriple(), Target.getPlatformMinVersion()))
3979     return;
3980   // Add -framework CoreFoundation to the linker commands. We still want to
3981   // emit the core foundation reference down below because otherwise if
3982   // CoreFoundation is not used in the code, the linker won't link the
3983   // framework.
3984   auto &Context = getLLVMContext();
3985   llvm::Metadata *Args[2] = {llvm::MDString::get(Context, "-framework"),
3986                              llvm::MDString::get(Context, "CoreFoundation")};
3987   LinkerOptionsMetadata.push_back(llvm::MDNode::get(Context, Args));
3988   // Emit a reference to a symbol from CoreFoundation to ensure that
3989   // CoreFoundation is linked into the final binary.
3990   llvm::FunctionType *FTy =
3991       llvm::FunctionType::get(Int32Ty, {VoidPtrTy}, false);
3992   llvm::FunctionCallee CFFunc =
3993       CreateRuntimeFunction(FTy, "CFBundleGetVersionNumber");
3994 
3995   llvm::FunctionType *CheckFTy = llvm::FunctionType::get(VoidTy, {}, false);
3996   llvm::FunctionCallee CFLinkCheckFuncRef = CreateRuntimeFunction(
3997       CheckFTy, "__clang_at_available_requires_core_foundation_framework",
3998       llvm::AttributeList(), /*Local=*/true);
3999   llvm::Function *CFLinkCheckFunc =
4000       cast<llvm::Function>(CFLinkCheckFuncRef.getCallee()->stripPointerCasts());
4001   if (CFLinkCheckFunc->empty()) {
4002     CFLinkCheckFunc->setLinkage(llvm::GlobalValue::LinkOnceAnyLinkage);
4003     CFLinkCheckFunc->setVisibility(llvm::GlobalValue::HiddenVisibility);
4004     CodeGenFunction CGF(*this);
4005     CGF.Builder.SetInsertPoint(CGF.createBasicBlock("", CFLinkCheckFunc));
4006     CGF.EmitNounwindRuntimeCall(CFFunc,
4007                                 llvm::Constant::getNullValue(VoidPtrTy));
4008     CGF.Builder.CreateUnreachable();
4009     addCompilerUsedGlobal(CFLinkCheckFunc);
4010   }
4011 }
4012 
4013 CGObjCRuntime::~CGObjCRuntime() {}
4014