]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/CodeGen/CGBlocks.cpp
Merge clang 3.5.0 release from ^/vendor/clang/dist, resolve conflicts,
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / lib / CodeGen / CGBlocks.cpp
1 //===--- CGBlocks.cpp - Emit LLVM Code for declarations -------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This contains code to emit blocks.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "CGBlocks.h"
15 #include "CGDebugInfo.h"
16 #include "CGObjCRuntime.h"
17 #include "CodeGenFunction.h"
18 #include "CodeGenModule.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "llvm/ADT/SmallSet.h"
21 #include "llvm/IR/CallSite.h"
22 #include "llvm/IR/DataLayout.h"
23 #include "llvm/IR/Module.h"
24 #include <algorithm>
25 #include <cstdio>
26
27 using namespace clang;
28 using namespace CodeGen;
29
30 CGBlockInfo::CGBlockInfo(const BlockDecl *block, StringRef name)
31   : Name(name), CXXThisIndex(0), CanBeGlobal(false), NeedsCopyDispose(false),
32     HasCXXObject(false), UsesStret(false), HasCapturedVariableLayout(false),
33     StructureType(nullptr), Block(block),
34     DominatingIP(nullptr) {
35
36   // Skip asm prefix, if any.  'name' is usually taken directly from
37   // the mangled name of the enclosing function.
38   if (!name.empty() && name[0] == '\01')
39     name = name.substr(1);
40 }
41
42 // Anchor the vtable to this translation unit.
43 CodeGenModule::ByrefHelpers::~ByrefHelpers() {}
44
45 /// Build the given block as a global block.
46 static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
47                                         const CGBlockInfo &blockInfo,
48                                         llvm::Constant *blockFn);
49
50 /// Build the helper function to copy a block.
51 static llvm::Constant *buildCopyHelper(CodeGenModule &CGM,
52                                        const CGBlockInfo &blockInfo) {
53   return CodeGenFunction(CGM).GenerateCopyHelperFunction(blockInfo);
54 }
55
56 /// Build the helper function to dispose of a block.
57 static llvm::Constant *buildDisposeHelper(CodeGenModule &CGM,
58                                           const CGBlockInfo &blockInfo) {
59   return CodeGenFunction(CGM).GenerateDestroyHelperFunction(blockInfo);
60 }
61
62 /// buildBlockDescriptor - Build the block descriptor meta-data for a block.
63 /// buildBlockDescriptor is accessed from 5th field of the Block_literal
64 /// meta-data and contains stationary information about the block literal.
65 /// Its definition will have 4 (or optinally 6) words.
66 /// \code
67 /// struct Block_descriptor {
68 ///   unsigned long reserved;
69 ///   unsigned long size;  // size of Block_literal metadata in bytes.
70 ///   void *copy_func_helper_decl;  // optional copy helper.
71 ///   void *destroy_func_decl; // optioanl destructor helper.
72 ///   void *block_method_encoding_address; // @encode for block literal signature.
73 ///   void *block_layout_info; // encoding of captured block variables.
74 /// };
75 /// \endcode
76 static llvm::Constant *buildBlockDescriptor(CodeGenModule &CGM,
77                                             const CGBlockInfo &blockInfo) {
78   ASTContext &C = CGM.getContext();
79
80   llvm::Type *ulong = CGM.getTypes().ConvertType(C.UnsignedLongTy);
81   llvm::Type *i8p = NULL;
82   if (CGM.getLangOpts().OpenCL)
83     i8p = 
84       llvm::Type::getInt8PtrTy(
85            CGM.getLLVMContext(), C.getTargetAddressSpace(LangAS::opencl_constant));
86   else
87     i8p = CGM.getTypes().ConvertType(C.VoidPtrTy);
88
89   SmallVector<llvm::Constant*, 6> elements;
90
91   // reserved
92   elements.push_back(llvm::ConstantInt::get(ulong, 0));
93
94   // Size
95   // FIXME: What is the right way to say this doesn't fit?  We should give
96   // a user diagnostic in that case.  Better fix would be to change the
97   // API to size_t.
98   elements.push_back(llvm::ConstantInt::get(ulong,
99                                             blockInfo.BlockSize.getQuantity()));
100
101   // Optional copy/dispose helpers.
102   if (blockInfo.NeedsCopyDispose) {
103     // copy_func_helper_decl
104     elements.push_back(buildCopyHelper(CGM, blockInfo));
105
106     // destroy_func_decl
107     elements.push_back(buildDisposeHelper(CGM, blockInfo));
108   }
109
110   // Signature.  Mandatory ObjC-style method descriptor @encode sequence.
111   std::string typeAtEncoding =
112     CGM.getContext().getObjCEncodingForBlock(blockInfo.getBlockExpr());
113   elements.push_back(llvm::ConstantExpr::getBitCast(
114                           CGM.GetAddrOfConstantCString(typeAtEncoding), i8p));
115   
116   // GC layout.
117   if (C.getLangOpts().ObjC1) {
118     if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
119       elements.push_back(CGM.getObjCRuntime().BuildGCBlockLayout(CGM, blockInfo));
120     else
121       elements.push_back(CGM.getObjCRuntime().BuildRCBlockLayout(CGM, blockInfo));
122   }
123   else
124     elements.push_back(llvm::Constant::getNullValue(i8p));
125
126   llvm::Constant *init = llvm::ConstantStruct::getAnon(elements);
127
128   llvm::GlobalVariable *global =
129     new llvm::GlobalVariable(CGM.getModule(), init->getType(), true,
130                              llvm::GlobalValue::InternalLinkage,
131                              init, "__block_descriptor_tmp");
132
133   return llvm::ConstantExpr::getBitCast(global, CGM.getBlockDescriptorType());
134 }
135
136 /*
137   Purely notional variadic template describing the layout of a block.
138
139   template <class _ResultType, class... _ParamTypes, class... _CaptureTypes>
140   struct Block_literal {
141     /// Initialized to one of:
142     ///   extern void *_NSConcreteStackBlock[];
143     ///   extern void *_NSConcreteGlobalBlock[];
144     ///
145     /// In theory, we could start one off malloc'ed by setting
146     /// BLOCK_NEEDS_FREE, giving it a refcount of 1, and using
147     /// this isa:
148     ///   extern void *_NSConcreteMallocBlock[];
149     struct objc_class *isa;
150
151     /// These are the flags (with corresponding bit number) that the
152     /// compiler is actually supposed to know about.
153     ///  25. BLOCK_HAS_COPY_DISPOSE - indicates that the block
154     ///   descriptor provides copy and dispose helper functions
155     ///  26. BLOCK_HAS_CXX_OBJ - indicates that there's a captured
156     ///   object with a nontrivial destructor or copy constructor
157     ///  28. BLOCK_IS_GLOBAL - indicates that the block is allocated
158     ///   as global memory
159     ///  29. BLOCK_USE_STRET - indicates that the block function
160     ///   uses stret, which objc_msgSend needs to know about
161     ///  30. BLOCK_HAS_SIGNATURE - indicates that the block has an
162     ///   @encoded signature string
163     /// And we're not supposed to manipulate these:
164     ///  24. BLOCK_NEEDS_FREE - indicates that the block has been moved
165     ///   to malloc'ed memory
166     ///  27. BLOCK_IS_GC - indicates that the block has been moved to
167     ///   to GC-allocated memory
168     /// Additionally, the bottom 16 bits are a reference count which
169     /// should be zero on the stack.
170     int flags;
171
172     /// Reserved;  should be zero-initialized.
173     int reserved;
174
175     /// Function pointer generated from block literal.
176     _ResultType (*invoke)(Block_literal *, _ParamTypes...);
177
178     /// Block description metadata generated from block literal.
179     struct Block_descriptor *block_descriptor;
180
181     /// Captured values follow.
182     _CapturesTypes captures...;
183   };
184  */
185
186 /// The number of fields in a block header.
187 const unsigned BlockHeaderSize = 5;
188
189 namespace {
190   /// A chunk of data that we actually have to capture in the block.
191   struct BlockLayoutChunk {
192     CharUnits Alignment;
193     CharUnits Size;
194     Qualifiers::ObjCLifetime Lifetime;
195     const BlockDecl::Capture *Capture; // null for 'this'
196     llvm::Type *Type;
197
198     BlockLayoutChunk(CharUnits align, CharUnits size,
199                      Qualifiers::ObjCLifetime lifetime,
200                      const BlockDecl::Capture *capture,
201                      llvm::Type *type)
202       : Alignment(align), Size(size), Lifetime(lifetime),
203         Capture(capture), Type(type) {}
204
205     /// Tell the block info that this chunk has the given field index.
206     void setIndex(CGBlockInfo &info, unsigned index) {
207       if (!Capture)
208         info.CXXThisIndex = index;
209       else
210         info.Captures[Capture->getVariable()]
211           = CGBlockInfo::Capture::makeIndex(index);
212     }
213   };
214
215   /// Order by 1) all __strong together 2) next, all byfref together 3) next,
216   /// all __weak together. Preserve descending alignment in all situations.
217   bool operator<(const BlockLayoutChunk &left, const BlockLayoutChunk &right) {
218     CharUnits LeftValue, RightValue;
219     bool LeftByref = left.Capture ? left.Capture->isByRef() : false;
220     bool RightByref = right.Capture ? right.Capture->isByRef() : false;
221     
222     if (left.Lifetime == Qualifiers::OCL_Strong &&
223         left.Alignment >= right.Alignment)
224       LeftValue = CharUnits::fromQuantity(64);
225     else if (LeftByref && left.Alignment >= right.Alignment)
226       LeftValue = CharUnits::fromQuantity(32);
227     else if (left.Lifetime == Qualifiers::OCL_Weak &&
228              left.Alignment >= right.Alignment)
229       LeftValue = CharUnits::fromQuantity(16);
230     else
231       LeftValue = left.Alignment;
232     if (right.Lifetime == Qualifiers::OCL_Strong &&
233         right.Alignment >= left.Alignment)
234       RightValue = CharUnits::fromQuantity(64);
235     else if (RightByref && right.Alignment >= left.Alignment)
236       RightValue = CharUnits::fromQuantity(32);
237     else if (right.Lifetime == Qualifiers::OCL_Weak &&
238              right.Alignment >= left.Alignment)
239       RightValue = CharUnits::fromQuantity(16);
240     else
241       RightValue = right.Alignment;
242     
243       return LeftValue > RightValue;
244   }
245 }
246
247 /// Determines if the given type is safe for constant capture in C++.
248 static bool isSafeForCXXConstantCapture(QualType type) {
249   const RecordType *recordType =
250     type->getBaseElementTypeUnsafe()->getAs<RecordType>();
251
252   // Only records can be unsafe.
253   if (!recordType) return true;
254
255   const auto *record = cast<CXXRecordDecl>(recordType->getDecl());
256
257   // Maintain semantics for classes with non-trivial dtors or copy ctors.
258   if (!record->hasTrivialDestructor()) return false;
259   if (record->hasNonTrivialCopyConstructor()) return false;
260
261   // Otherwise, we just have to make sure there aren't any mutable
262   // fields that might have changed since initialization.
263   return !record->hasMutableFields();
264 }
265
266 /// It is illegal to modify a const object after initialization.
267 /// Therefore, if a const object has a constant initializer, we don't
268 /// actually need to keep storage for it in the block; we'll just
269 /// rematerialize it at the start of the block function.  This is
270 /// acceptable because we make no promises about address stability of
271 /// captured variables.
272 static llvm::Constant *tryCaptureAsConstant(CodeGenModule &CGM,
273                                             CodeGenFunction *CGF,
274                                             const VarDecl *var) {
275   QualType type = var->getType();
276
277   // We can only do this if the variable is const.
278   if (!type.isConstQualified()) return nullptr;
279
280   // Furthermore, in C++ we have to worry about mutable fields:
281   // C++ [dcl.type.cv]p4:
282   //   Except that any class member declared mutable can be
283   //   modified, any attempt to modify a const object during its
284   //   lifetime results in undefined behavior.
285   if (CGM.getLangOpts().CPlusPlus && !isSafeForCXXConstantCapture(type))
286     return nullptr;
287
288   // If the variable doesn't have any initializer (shouldn't this be
289   // invalid?), it's not clear what we should do.  Maybe capture as
290   // zero?
291   const Expr *init = var->getInit();
292   if (!init) return nullptr;
293
294   return CGM.EmitConstantInit(*var, CGF);
295 }
296
297 /// Get the low bit of a nonzero character count.  This is the
298 /// alignment of the nth byte if the 0th byte is universally aligned.
299 static CharUnits getLowBit(CharUnits v) {
300   return CharUnits::fromQuantity(v.getQuantity() & (~v.getQuantity() + 1));
301 }
302
303 static void initializeForBlockHeader(CodeGenModule &CGM, CGBlockInfo &info,
304                              SmallVectorImpl<llvm::Type*> &elementTypes) {
305   ASTContext &C = CGM.getContext();
306
307   // The header is basically a 'struct { void *; int; int; void *; void *; }'.
308   CharUnits ptrSize, ptrAlign, intSize, intAlign;
309   std::tie(ptrSize, ptrAlign) = C.getTypeInfoInChars(C.VoidPtrTy);
310   std::tie(intSize, intAlign) = C.getTypeInfoInChars(C.IntTy);
311
312   // Are there crazy embedded platforms where this isn't true?
313   assert(intSize <= ptrSize && "layout assumptions horribly violated");
314
315   CharUnits headerSize = ptrSize;
316   if (2 * intSize < ptrAlign) headerSize += ptrSize;
317   else headerSize += 2 * intSize;
318   headerSize += 2 * ptrSize;
319
320   info.BlockAlign = ptrAlign;
321   info.BlockSize = headerSize;
322
323   assert(elementTypes.empty());
324   llvm::Type *i8p = CGM.getTypes().ConvertType(C.VoidPtrTy);
325   llvm::Type *intTy = CGM.getTypes().ConvertType(C.IntTy);
326   elementTypes.push_back(i8p);
327   elementTypes.push_back(intTy);
328   elementTypes.push_back(intTy);
329   elementTypes.push_back(i8p);
330   elementTypes.push_back(CGM.getBlockDescriptorType());
331
332   assert(elementTypes.size() == BlockHeaderSize);
333 }
334
335 /// Compute the layout of the given block.  Attempts to lay the block
336 /// out with minimal space requirements.
337 static void computeBlockInfo(CodeGenModule &CGM, CodeGenFunction *CGF,
338                              CGBlockInfo &info) {
339   ASTContext &C = CGM.getContext();
340   const BlockDecl *block = info.getBlockDecl();
341
342   SmallVector<llvm::Type*, 8> elementTypes;
343   initializeForBlockHeader(CGM, info, elementTypes);
344
345   if (!block->hasCaptures()) {
346     info.StructureType =
347       llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
348     info.CanBeGlobal = true;
349     return;
350   }
351   else if (C.getLangOpts().ObjC1 &&
352            CGM.getLangOpts().getGC() == LangOptions::NonGC)
353     info.HasCapturedVariableLayout = true;
354   
355   // Collect the layout chunks.
356   SmallVector<BlockLayoutChunk, 16> layout;
357   layout.reserve(block->capturesCXXThis() +
358                  (block->capture_end() - block->capture_begin()));
359
360   CharUnits maxFieldAlign;
361
362   // First, 'this'.
363   if (block->capturesCXXThis()) {
364     assert(CGF && CGF->CurFuncDecl && isa<CXXMethodDecl>(CGF->CurFuncDecl) &&
365            "Can't capture 'this' outside a method");
366     QualType thisType = cast<CXXMethodDecl>(CGF->CurFuncDecl)->getThisType(C);
367
368     llvm::Type *llvmType = CGM.getTypes().ConvertType(thisType);
369     std::pair<CharUnits,CharUnits> tinfo
370       = CGM.getContext().getTypeInfoInChars(thisType);
371     maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
372
373     layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first,
374                                       Qualifiers::OCL_None,
375                                       nullptr, llvmType));
376   }
377
378   // Next, all the block captures.
379   for (const auto &CI : block->captures()) {
380     const VarDecl *variable = CI.getVariable();
381
382     if (CI.isByRef()) {
383       // We have to copy/dispose of the __block reference.
384       info.NeedsCopyDispose = true;
385
386       // Just use void* instead of a pointer to the byref type.
387       QualType byRefPtrTy = C.VoidPtrTy;
388
389       llvm::Type *llvmType = CGM.getTypes().ConvertType(byRefPtrTy);
390       std::pair<CharUnits,CharUnits> tinfo
391         = CGM.getContext().getTypeInfoInChars(byRefPtrTy);
392       maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
393
394       layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first,
395                                         Qualifiers::OCL_None, &CI, llvmType));
396       continue;
397     }
398
399     // Otherwise, build a layout chunk with the size and alignment of
400     // the declaration.
401     if (llvm::Constant *constant = tryCaptureAsConstant(CGM, CGF, variable)) {
402       info.Captures[variable] = CGBlockInfo::Capture::makeConstant(constant);
403       continue;
404     }
405
406     // If we have a lifetime qualifier, honor it for capture purposes.
407     // That includes *not* copying it if it's __unsafe_unretained.
408     Qualifiers::ObjCLifetime lifetime =
409       variable->getType().getObjCLifetime();
410     if (lifetime) {
411       switch (lifetime) {
412       case Qualifiers::OCL_None: llvm_unreachable("impossible");
413       case Qualifiers::OCL_ExplicitNone:
414       case Qualifiers::OCL_Autoreleasing:
415         break;
416
417       case Qualifiers::OCL_Strong:
418       case Qualifiers::OCL_Weak:
419         info.NeedsCopyDispose = true;
420       }
421
422     // Block pointers require copy/dispose.  So do Objective-C pointers.
423     } else if (variable->getType()->isObjCRetainableType()) {
424       info.NeedsCopyDispose = true;
425       // used for mrr below.
426       lifetime = Qualifiers::OCL_Strong;
427
428     // So do types that require non-trivial copy construction.
429     } else if (CI.hasCopyExpr()) {
430       info.NeedsCopyDispose = true;
431       info.HasCXXObject = true;
432
433     // And so do types with destructors.
434     } else if (CGM.getLangOpts().CPlusPlus) {
435       if (const CXXRecordDecl *record =
436             variable->getType()->getAsCXXRecordDecl()) {
437         if (!record->hasTrivialDestructor()) {
438           info.HasCXXObject = true;
439           info.NeedsCopyDispose = true;
440         }
441       }
442     }
443
444     QualType VT = variable->getType();
445     CharUnits size = C.getTypeSizeInChars(VT);
446     CharUnits align = C.getDeclAlign(variable);
447     
448     maxFieldAlign = std::max(maxFieldAlign, align);
449
450     llvm::Type *llvmType =
451       CGM.getTypes().ConvertTypeForMem(VT);
452     
453     layout.push_back(BlockLayoutChunk(align, size, lifetime, &CI, llvmType));
454   }
455
456   // If that was everything, we're done here.
457   if (layout.empty()) {
458     info.StructureType =
459       llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
460     info.CanBeGlobal = true;
461     return;
462   }
463
464   // Sort the layout by alignment.  We have to use a stable sort here
465   // to get reproducible results.  There should probably be an
466   // llvm::array_pod_stable_sort.
467   std::stable_sort(layout.begin(), layout.end());
468   
469   // Needed for blocks layout info.
470   info.BlockHeaderForcedGapOffset = info.BlockSize;
471   info.BlockHeaderForcedGapSize = CharUnits::Zero();
472   
473   CharUnits &blockSize = info.BlockSize;
474   info.BlockAlign = std::max(maxFieldAlign, info.BlockAlign);
475
476   // Assuming that the first byte in the header is maximally aligned,
477   // get the alignment of the first byte following the header.
478   CharUnits endAlign = getLowBit(blockSize);
479
480   // If the end of the header isn't satisfactorily aligned for the
481   // maximum thing, look for things that are okay with the header-end
482   // alignment, and keep appending them until we get something that's
483   // aligned right.  This algorithm is only guaranteed optimal if
484   // that condition is satisfied at some point; otherwise we can get
485   // things like:
486   //   header                 // next byte has alignment 4
487   //   something_with_size_5; // next byte has alignment 1
488   //   something_with_alignment_8;
489   // which has 7 bytes of padding, as opposed to the naive solution
490   // which might have less (?).
491   if (endAlign < maxFieldAlign) {
492     SmallVectorImpl<BlockLayoutChunk>::iterator
493       li = layout.begin() + 1, le = layout.end();
494
495     // Look for something that the header end is already
496     // satisfactorily aligned for.
497     for (; li != le && endAlign < li->Alignment; ++li)
498       ;
499
500     // If we found something that's naturally aligned for the end of
501     // the header, keep adding things...
502     if (li != le) {
503       SmallVectorImpl<BlockLayoutChunk>::iterator first = li;
504       for (; li != le; ++li) {
505         assert(endAlign >= li->Alignment);
506
507         li->setIndex(info, elementTypes.size());
508         elementTypes.push_back(li->Type);
509         blockSize += li->Size;
510         endAlign = getLowBit(blockSize);
511
512         // ...until we get to the alignment of the maximum field.
513         if (endAlign >= maxFieldAlign) {
514           if (li == first) {
515             // No user field was appended. So, a gap was added.
516             // Save total gap size for use in block layout bit map.
517             info.BlockHeaderForcedGapSize = li->Size;
518           }
519           break;
520         }
521       }
522       // Don't re-append everything we just appended.
523       layout.erase(first, li);
524     }
525   }
526
527   assert(endAlign == getLowBit(blockSize));
528   
529   // At this point, we just have to add padding if the end align still
530   // isn't aligned right.
531   if (endAlign < maxFieldAlign) {
532     CharUnits newBlockSize = blockSize.RoundUpToAlignment(maxFieldAlign);
533     CharUnits padding = newBlockSize - blockSize;
534
535     elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
536                                                 padding.getQuantity()));
537     blockSize = newBlockSize;
538     endAlign = getLowBit(blockSize); // might be > maxFieldAlign
539   }
540
541   assert(endAlign >= maxFieldAlign);
542   assert(endAlign == getLowBit(blockSize));
543   // Slam everything else on now.  This works because they have
544   // strictly decreasing alignment and we expect that size is always a
545   // multiple of alignment.
546   for (SmallVectorImpl<BlockLayoutChunk>::iterator
547          li = layout.begin(), le = layout.end(); li != le; ++li) {
548     assert(endAlign >= li->Alignment);
549     li->setIndex(info, elementTypes.size());
550     elementTypes.push_back(li->Type);
551     blockSize += li->Size;
552     endAlign = getLowBit(blockSize);
553   }
554
555   info.StructureType =
556     llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
557 }
558
559 /// Enter the scope of a block.  This should be run at the entrance to
560 /// a full-expression so that the block's cleanups are pushed at the
561 /// right place in the stack.
562 static void enterBlockScope(CodeGenFunction &CGF, BlockDecl *block) {
563   assert(CGF.HaveInsertPoint());
564
565   // Allocate the block info and place it at the head of the list.
566   CGBlockInfo &blockInfo =
567     *new CGBlockInfo(block, CGF.CurFn->getName());
568   blockInfo.NextBlockInfo = CGF.FirstBlockInfo;
569   CGF.FirstBlockInfo = &blockInfo;
570
571   // Compute information about the layout, etc., of this block,
572   // pushing cleanups as necessary.
573   computeBlockInfo(CGF.CGM, &CGF, blockInfo);
574
575   // Nothing else to do if it can be global.
576   if (blockInfo.CanBeGlobal) return;
577
578   // Make the allocation for the block.
579   blockInfo.Address =
580     CGF.CreateTempAlloca(blockInfo.StructureType, "block");
581   blockInfo.Address->setAlignment(blockInfo.BlockAlign.getQuantity());
582
583   // If there are cleanups to emit, enter them (but inactive).
584   if (!blockInfo.NeedsCopyDispose) return;
585
586   // Walk through the captures (in order) and find the ones not
587   // captured by constant.
588   for (const auto &CI : block->captures()) {
589     // Ignore __block captures; there's nothing special in the
590     // on-stack block that we need to do for them.
591     if (CI.isByRef()) continue;
592
593     // Ignore variables that are constant-captured.
594     const VarDecl *variable = CI.getVariable();
595     CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
596     if (capture.isConstant()) continue;
597
598     // Ignore objects that aren't destructed.
599     QualType::DestructionKind dtorKind =
600       variable->getType().isDestructedType();
601     if (dtorKind == QualType::DK_none) continue;
602
603     CodeGenFunction::Destroyer *destroyer;
604
605     // Block captures count as local values and have imprecise semantics.
606     // They also can't be arrays, so need to worry about that.
607     if (dtorKind == QualType::DK_objc_strong_lifetime) {
608       destroyer = CodeGenFunction::destroyARCStrongImprecise;
609     } else {
610       destroyer = CGF.getDestroyer(dtorKind);
611     }
612
613     // GEP down to the address.
614     llvm::Value *addr = CGF.Builder.CreateStructGEP(blockInfo.Address,
615                                                     capture.getIndex());
616
617     // We can use that GEP as the dominating IP.
618     if (!blockInfo.DominatingIP)
619       blockInfo.DominatingIP = cast<llvm::Instruction>(addr);
620
621     CleanupKind cleanupKind = InactiveNormalCleanup;
622     bool useArrayEHCleanup = CGF.needsEHCleanup(dtorKind);
623     if (useArrayEHCleanup) 
624       cleanupKind = InactiveNormalAndEHCleanup;
625
626     CGF.pushDestroy(cleanupKind, addr, variable->getType(),
627                     destroyer, useArrayEHCleanup);
628
629     // Remember where that cleanup was.
630     capture.setCleanup(CGF.EHStack.stable_begin());
631   }
632 }
633
634 /// Enter a full-expression with a non-trivial number of objects to
635 /// clean up.  This is in this file because, at the moment, the only
636 /// kind of cleanup object is a BlockDecl*.
637 void CodeGenFunction::enterNonTrivialFullExpression(const ExprWithCleanups *E) {
638   assert(E->getNumObjects() != 0);
639   ArrayRef<ExprWithCleanups::CleanupObject> cleanups = E->getObjects();
640   for (ArrayRef<ExprWithCleanups::CleanupObject>::iterator
641          i = cleanups.begin(), e = cleanups.end(); i != e; ++i) {
642     enterBlockScope(*this, *i);
643   }
644 }
645
646 /// Find the layout for the given block in a linked list and remove it.
647 static CGBlockInfo *findAndRemoveBlockInfo(CGBlockInfo **head,
648                                            const BlockDecl *block) {
649   while (true) {
650     assert(head && *head);
651     CGBlockInfo *cur = *head;
652
653     // If this is the block we're looking for, splice it out of the list.
654     if (cur->getBlockDecl() == block) {
655       *head = cur->NextBlockInfo;
656       return cur;
657     }
658
659     head = &cur->NextBlockInfo;
660   }
661 }
662
663 /// Destroy a chain of block layouts.
664 void CodeGenFunction::destroyBlockInfos(CGBlockInfo *head) {
665   assert(head && "destroying an empty chain");
666   do {
667     CGBlockInfo *cur = head;
668     head = cur->NextBlockInfo;
669     delete cur;
670   } while (head != nullptr);
671 }
672
673 /// Emit a block literal expression in the current function.
674 llvm::Value *CodeGenFunction::EmitBlockLiteral(const BlockExpr *blockExpr) {
675   // If the block has no captures, we won't have a pre-computed
676   // layout for it.
677   if (!blockExpr->getBlockDecl()->hasCaptures()) {
678     CGBlockInfo blockInfo(blockExpr->getBlockDecl(), CurFn->getName());
679     computeBlockInfo(CGM, this, blockInfo);
680     blockInfo.BlockExpression = blockExpr;
681     return EmitBlockLiteral(blockInfo);
682   }
683
684   // Find the block info for this block and take ownership of it.
685   std::unique_ptr<CGBlockInfo> blockInfo;
686   blockInfo.reset(findAndRemoveBlockInfo(&FirstBlockInfo,
687                                          blockExpr->getBlockDecl()));
688
689   blockInfo->BlockExpression = blockExpr;
690   return EmitBlockLiteral(*blockInfo);
691 }
692
693 llvm::Value *CodeGenFunction::EmitBlockLiteral(const CGBlockInfo &blockInfo) {
694   // Using the computed layout, generate the actual block function.
695   bool isLambdaConv = blockInfo.getBlockDecl()->isConversionFromLambda();
696   llvm::Constant *blockFn
697     = CodeGenFunction(CGM, true).GenerateBlockFunction(CurGD, blockInfo,
698                                                        LocalDeclMap,
699                                                        isLambdaConv);
700   blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
701
702   // If there is nothing to capture, we can emit this as a global block.
703   if (blockInfo.CanBeGlobal)
704     return buildGlobalBlock(CGM, blockInfo, blockFn);
705
706   // Otherwise, we have to emit this as a local block.
707
708   llvm::Constant *isa = CGM.getNSConcreteStackBlock();
709   isa = llvm::ConstantExpr::getBitCast(isa, VoidPtrTy);
710
711   // Build the block descriptor.
712   llvm::Constant *descriptor = buildBlockDescriptor(CGM, blockInfo);
713
714   llvm::AllocaInst *blockAddr = blockInfo.Address;
715   assert(blockAddr && "block has no address!");
716
717   // Compute the initial on-stack block flags.
718   BlockFlags flags = BLOCK_HAS_SIGNATURE;
719   if (blockInfo.HasCapturedVariableLayout) flags |= BLOCK_HAS_EXTENDED_LAYOUT;
720   if (blockInfo.NeedsCopyDispose) flags |= BLOCK_HAS_COPY_DISPOSE;
721   if (blockInfo.HasCXXObject) flags |= BLOCK_HAS_CXX_OBJ;
722   if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
723
724   // Initialize the block literal.
725   Builder.CreateStore(isa, Builder.CreateStructGEP(blockAddr, 0, "block.isa"));
726   Builder.CreateStore(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
727                       Builder.CreateStructGEP(blockAddr, 1, "block.flags"));
728   Builder.CreateStore(llvm::ConstantInt::get(IntTy, 0),
729                       Builder.CreateStructGEP(blockAddr, 2, "block.reserved"));
730   Builder.CreateStore(blockFn, Builder.CreateStructGEP(blockAddr, 3,
731                                                        "block.invoke"));
732   Builder.CreateStore(descriptor, Builder.CreateStructGEP(blockAddr, 4,
733                                                           "block.descriptor"));
734
735   // Finally, capture all the values into the block.
736   const BlockDecl *blockDecl = blockInfo.getBlockDecl();
737
738   // First, 'this'.
739   if (blockDecl->capturesCXXThis()) {
740     llvm::Value *addr = Builder.CreateStructGEP(blockAddr,
741                                                 blockInfo.CXXThisIndex,
742                                                 "block.captured-this.addr");
743     Builder.CreateStore(LoadCXXThis(), addr);
744   }
745
746   // Next, captured variables.
747   for (const auto &CI : blockDecl->captures()) {
748     const VarDecl *variable = CI.getVariable();
749     const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
750
751     // Ignore constant captures.
752     if (capture.isConstant()) continue;
753
754     QualType type = variable->getType();
755     CharUnits align = getContext().getDeclAlign(variable);
756
757     // This will be a [[type]]*, except that a byref entry will just be
758     // an i8**.
759     llvm::Value *blockField =
760       Builder.CreateStructGEP(blockAddr, capture.getIndex(),
761                               "block.captured");
762
763     // Compute the address of the thing we're going to move into the
764     // block literal.
765     llvm::Value *src;
766     if (BlockInfo && CI.isNested()) {
767       // We need to use the capture from the enclosing block.
768       const CGBlockInfo::Capture &enclosingCapture =
769         BlockInfo->getCapture(variable);
770
771       // This is a [[type]]*, except that a byref entry wil just be an i8**.
772       src = Builder.CreateStructGEP(LoadBlockStruct(),
773                                     enclosingCapture.getIndex(),
774                                     "block.capture.addr");
775     } else if (blockDecl->isConversionFromLambda()) {
776       // The lambda capture in a lambda's conversion-to-block-pointer is
777       // special; we'll simply emit it directly.
778       src = nullptr;
779     } else {
780       // Just look it up in the locals map, which will give us back a
781       // [[type]]*.  If that doesn't work, do the more elaborate DRE
782       // emission.
783       src = LocalDeclMap.lookup(variable);
784       if (!src) {
785         DeclRefExpr declRef(const_cast<VarDecl *>(variable),
786                             /*refersToEnclosing*/ CI.isNested(), type,
787                             VK_LValue, SourceLocation());
788         src = EmitDeclRefLValue(&declRef).getAddress();
789       }
790     }
791
792     // For byrefs, we just write the pointer to the byref struct into
793     // the block field.  There's no need to chase the forwarding
794     // pointer at this point, since we're building something that will
795     // live a shorter life than the stack byref anyway.
796     if (CI.isByRef()) {
797       // Get a void* that points to the byref struct.
798       if (CI.isNested())
799         src = Builder.CreateAlignedLoad(src, align.getQuantity(),
800                                         "byref.capture");
801       else
802         src = Builder.CreateBitCast(src, VoidPtrTy);
803
804       // Write that void* into the capture field.
805       Builder.CreateAlignedStore(src, blockField, align.getQuantity());
806
807     // If we have a copy constructor, evaluate that into the block field.
808     } else if (const Expr *copyExpr = CI.getCopyExpr()) {
809       if (blockDecl->isConversionFromLambda()) {
810         // If we have a lambda conversion, emit the expression
811         // directly into the block instead.
812         AggValueSlot Slot =
813             AggValueSlot::forAddr(blockField, align, Qualifiers(),
814                                   AggValueSlot::IsDestructed,
815                                   AggValueSlot::DoesNotNeedGCBarriers,
816                                   AggValueSlot::IsNotAliased);
817         EmitAggExpr(copyExpr, Slot);
818       } else {
819         EmitSynthesizedCXXCopyCtor(blockField, src, copyExpr);
820       }
821
822     // If it's a reference variable, copy the reference into the block field.
823     } else if (type->isReferenceType()) {
824       llvm::Value *ref =
825         Builder.CreateAlignedLoad(src, align.getQuantity(), "ref.val");
826       Builder.CreateAlignedStore(ref, blockField, align.getQuantity());
827
828     // If this is an ARC __strong block-pointer variable, don't do a
829     // block copy.
830     //
831     // TODO: this can be generalized into the normal initialization logic:
832     // we should never need to do a block-copy when initializing a local
833     // variable, because the local variable's lifetime should be strictly
834     // contained within the stack block's.
835     } else if (type.getObjCLifetime() == Qualifiers::OCL_Strong &&
836                type->isBlockPointerType()) {
837       // Load the block and do a simple retain.
838       LValue srcLV = MakeAddrLValue(src, type, align);
839       llvm::Value *value = EmitLoadOfScalar(srcLV, SourceLocation());
840       value = EmitARCRetainNonBlock(value);
841
842       // Do a primitive store to the block field.
843       LValue destLV = MakeAddrLValue(blockField, type, align);
844       EmitStoreOfScalar(value, destLV, /*init*/ true);
845
846     // Otherwise, fake up a POD copy into the block field.
847     } else {
848       // Fake up a new variable so that EmitScalarInit doesn't think
849       // we're referring to the variable in its own initializer.
850       ImplicitParamDecl blockFieldPseudoVar(getContext(), /*DC*/ nullptr,
851                                             SourceLocation(), /*name*/ nullptr,
852                                             type);
853
854       // We use one of these or the other depending on whether the
855       // reference is nested.
856       DeclRefExpr declRef(const_cast<VarDecl*>(variable),
857                           /*refersToEnclosing*/ CI.isNested(), type,
858                           VK_LValue, SourceLocation());
859
860       ImplicitCastExpr l2r(ImplicitCastExpr::OnStack, type, CK_LValueToRValue,
861                            &declRef, VK_RValue);
862       EmitExprAsInit(&l2r, &blockFieldPseudoVar,
863                      MakeAddrLValue(blockField, type, align),
864                      /*captured by init*/ false);
865     }
866
867     // Activate the cleanup if layout pushed one.
868     if (!CI.isByRef()) {
869       EHScopeStack::stable_iterator cleanup = capture.getCleanup();
870       if (cleanup.isValid())
871         ActivateCleanupBlock(cleanup, blockInfo.DominatingIP);
872     }
873   }
874
875   // Cast to the converted block-pointer type, which happens (somewhat
876   // unfortunately) to be a pointer to function type.
877   llvm::Value *result =
878     Builder.CreateBitCast(blockAddr,
879                           ConvertType(blockInfo.getBlockExpr()->getType()));
880
881   return result;
882 }
883
884
885 llvm::Type *CodeGenModule::getBlockDescriptorType() {
886   if (BlockDescriptorType)
887     return BlockDescriptorType;
888
889   llvm::Type *UnsignedLongTy =
890     getTypes().ConvertType(getContext().UnsignedLongTy);
891
892   // struct __block_descriptor {
893   //   unsigned long reserved;
894   //   unsigned long block_size;
895   //
896   //   // later, the following will be added
897   //
898   //   struct {
899   //     void (*copyHelper)();
900   //     void (*copyHelper)();
901   //   } helpers;                // !!! optional
902   //
903   //   const char *signature;   // the block signature
904   //   const char *layout;      // reserved
905   // };
906   BlockDescriptorType =
907     llvm::StructType::create("struct.__block_descriptor",
908                              UnsignedLongTy, UnsignedLongTy, NULL);
909
910   // Now form a pointer to that.
911   BlockDescriptorType = llvm::PointerType::getUnqual(BlockDescriptorType);
912   return BlockDescriptorType;
913 }
914
915 llvm::Type *CodeGenModule::getGenericBlockLiteralType() {
916   if (GenericBlockLiteralType)
917     return GenericBlockLiteralType;
918
919   llvm::Type *BlockDescPtrTy = getBlockDescriptorType();
920
921   // struct __block_literal_generic {
922   //   void *__isa;
923   //   int __flags;
924   //   int __reserved;
925   //   void (*__invoke)(void *);
926   //   struct __block_descriptor *__descriptor;
927   // };
928   GenericBlockLiteralType =
929     llvm::StructType::create("struct.__block_literal_generic",
930                              VoidPtrTy, IntTy, IntTy, VoidPtrTy,
931                              BlockDescPtrTy, NULL);
932
933   return GenericBlockLiteralType;
934 }
935
936
937 RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr *E, 
938                                           ReturnValueSlot ReturnValue) {
939   const BlockPointerType *BPT =
940     E->getCallee()->getType()->getAs<BlockPointerType>();
941
942   llvm::Value *Callee = EmitScalarExpr(E->getCallee());
943
944   // Get a pointer to the generic block literal.
945   llvm::Type *BlockLiteralTy =
946     llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
947
948   // Bitcast the callee to a block literal.
949   llvm::Value *BlockLiteral =
950     Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal");
951
952   // Get the function pointer from the literal.
953   llvm::Value *FuncPtr = Builder.CreateStructGEP(BlockLiteral, 3);
954
955   BlockLiteral = Builder.CreateBitCast(BlockLiteral, VoidPtrTy);
956
957   // Add the block literal.
958   CallArgList Args;
959   Args.add(RValue::get(BlockLiteral), getContext().VoidPtrTy);
960
961   QualType FnType = BPT->getPointeeType();
962
963   // And the rest of the arguments.
964   EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(),
965                E->arg_begin(), E->arg_end());
966
967   // Load the function.
968   llvm::Value *Func = Builder.CreateLoad(FuncPtr);
969
970   const FunctionType *FuncTy = FnType->castAs<FunctionType>();
971   const CGFunctionInfo &FnInfo =
972     CGM.getTypes().arrangeBlockFunctionCall(Args, FuncTy);
973
974   // Cast the function pointer to the right type.
975   llvm::Type *BlockFTy = CGM.getTypes().GetFunctionType(FnInfo);
976
977   llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
978   Func = Builder.CreateBitCast(Func, BlockFTyPtr);
979
980   // And call the block.
981   return EmitCall(FnInfo, Func, ReturnValue, Args);
982 }
983
984 llvm::Value *CodeGenFunction::GetAddrOfBlockDecl(const VarDecl *variable,
985                                                  bool isByRef) {
986   assert(BlockInfo && "evaluating block ref without block information?");
987   const CGBlockInfo::Capture &capture = BlockInfo->getCapture(variable);
988
989   // Handle constant captures.
990   if (capture.isConstant()) return LocalDeclMap[variable];
991
992   llvm::Value *addr =
993     Builder.CreateStructGEP(LoadBlockStruct(), capture.getIndex(),
994                             "block.capture.addr");
995
996   if (isByRef) {
997     // addr should be a void** right now.  Load, then cast the result
998     // to byref*.
999
1000     addr = Builder.CreateLoad(addr);
1001     llvm::PointerType *byrefPointerType
1002       = llvm::PointerType::get(BuildByRefType(variable), 0);
1003     addr = Builder.CreateBitCast(addr, byrefPointerType,
1004                                  "byref.addr");
1005
1006     // Follow the forwarding pointer.
1007     addr = Builder.CreateStructGEP(addr, 1, "byref.forwarding");
1008     addr = Builder.CreateLoad(addr, "byref.addr.forwarded");
1009
1010     // Cast back to byref* and GEP over to the actual object.
1011     addr = Builder.CreateBitCast(addr, byrefPointerType);
1012     addr = Builder.CreateStructGEP(addr, getByRefValueLLVMField(variable), 
1013                                    variable->getNameAsString());
1014   }
1015
1016   if (variable->getType()->isReferenceType())
1017     addr = Builder.CreateLoad(addr, "ref.tmp");
1018
1019   return addr;
1020 }
1021
1022 llvm::Constant *
1023 CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *blockExpr,
1024                                     const char *name) {
1025   CGBlockInfo blockInfo(blockExpr->getBlockDecl(), name);
1026   blockInfo.BlockExpression = blockExpr;
1027
1028   // Compute information about the layout, etc., of this block.
1029   computeBlockInfo(*this, nullptr, blockInfo);
1030
1031   // Using that metadata, generate the actual block function.
1032   llvm::Constant *blockFn;
1033   {
1034     llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap;
1035     blockFn = CodeGenFunction(*this).GenerateBlockFunction(GlobalDecl(),
1036                                                            blockInfo,
1037                                                            LocalDeclMap,
1038                                                            false);
1039   }
1040   blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
1041
1042   return buildGlobalBlock(*this, blockInfo, blockFn);
1043 }
1044
1045 static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
1046                                         const CGBlockInfo &blockInfo,
1047                                         llvm::Constant *blockFn) {
1048   assert(blockInfo.CanBeGlobal);
1049
1050   // Generate the constants for the block literal initializer.
1051   llvm::Constant *fields[BlockHeaderSize];
1052
1053   // isa
1054   fields[0] = CGM.getNSConcreteGlobalBlock();
1055
1056   // __flags
1057   BlockFlags flags = BLOCK_IS_GLOBAL | BLOCK_HAS_SIGNATURE;
1058   if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
1059                                       
1060   fields[1] = llvm::ConstantInt::get(CGM.IntTy, flags.getBitMask());
1061
1062   // Reserved
1063   fields[2] = llvm::Constant::getNullValue(CGM.IntTy);
1064
1065   // Function
1066   fields[3] = blockFn;
1067
1068   // Descriptor
1069   fields[4] = buildBlockDescriptor(CGM, blockInfo);
1070
1071   llvm::Constant *init = llvm::ConstantStruct::getAnon(fields);
1072
1073   llvm::GlobalVariable *literal =
1074     new llvm::GlobalVariable(CGM.getModule(),
1075                              init->getType(),
1076                              /*constant*/ true,
1077                              llvm::GlobalVariable::InternalLinkage,
1078                              init,
1079                              "__block_literal_global");
1080   literal->setAlignment(blockInfo.BlockAlign.getQuantity());
1081
1082   // Return a constant of the appropriately-casted type.
1083   llvm::Type *requiredType =
1084     CGM.getTypes().ConvertType(blockInfo.getBlockExpr()->getType());
1085   return llvm::ConstantExpr::getBitCast(literal, requiredType);
1086 }
1087
1088 llvm::Function *
1089 CodeGenFunction::GenerateBlockFunction(GlobalDecl GD,
1090                                        const CGBlockInfo &blockInfo,
1091                                        const DeclMapTy &ldm,
1092                                        bool IsLambdaConversionToBlock) {
1093   const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1094
1095   CurGD = GD;
1096   
1097   BlockInfo = &blockInfo;
1098
1099   // Arrange for local static and local extern declarations to appear
1100   // to be local to this function as well, in case they're directly
1101   // referenced in a block.
1102   for (DeclMapTy::const_iterator i = ldm.begin(), e = ldm.end(); i != e; ++i) {
1103     const auto *var = dyn_cast<VarDecl>(i->first);
1104     if (var && !var->hasLocalStorage())
1105       LocalDeclMap[var] = i->second;
1106   }
1107
1108   // Begin building the function declaration.
1109
1110   // Build the argument list.
1111   FunctionArgList args;
1112
1113   // The first argument is the block pointer.  Just take it as a void*
1114   // and cast it later.
1115   QualType selfTy = getContext().VoidPtrTy;
1116   IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
1117
1118   ImplicitParamDecl selfDecl(getContext(), const_cast<BlockDecl*>(blockDecl),
1119                              SourceLocation(), II, selfTy);
1120   args.push_back(&selfDecl);
1121
1122   // Now add the rest of the parameters.
1123   for (auto i : blockDecl->params())
1124     args.push_back(i);
1125
1126   // Create the function declaration.
1127   const FunctionProtoType *fnType = blockInfo.getBlockExpr()->getFunctionType();
1128   const CGFunctionInfo &fnInfo = CGM.getTypes().arrangeFreeFunctionDeclaration(
1129       fnType->getReturnType(), args, fnType->getExtInfo(),
1130       fnType->isVariadic());
1131   if (CGM.ReturnSlotInterferesWithArgs(fnInfo))
1132     blockInfo.UsesStret = true;
1133
1134   llvm::FunctionType *fnLLVMType = CGM.getTypes().GetFunctionType(fnInfo);
1135
1136   StringRef name = CGM.getBlockMangledName(GD, blockDecl);
1137   llvm::Function *fn = llvm::Function::Create(
1138       fnLLVMType, llvm::GlobalValue::InternalLinkage, name, &CGM.getModule());
1139   CGM.SetInternalFunctionAttributes(blockDecl, fn, fnInfo);
1140
1141   // Begin generating the function.
1142   StartFunction(blockDecl, fnType->getReturnType(), fn, fnInfo, args,
1143                 blockDecl->getLocation(),
1144                 blockInfo.getBlockExpr()->getBody()->getLocStart());
1145
1146   // Okay.  Undo some of what StartFunction did.
1147   
1148   // Pull the 'self' reference out of the local decl map.
1149   llvm::Value *blockAddr = LocalDeclMap[&selfDecl];
1150   LocalDeclMap.erase(&selfDecl);
1151   BlockPointer = Builder.CreateBitCast(blockAddr,
1152                                        blockInfo.StructureType->getPointerTo(),
1153                                        "block");
1154   // At -O0 we generate an explicit alloca for the BlockPointer, so the RA
1155   // won't delete the dbg.declare intrinsics for captured variables.
1156   llvm::Value *BlockPointerDbgLoc = BlockPointer;
1157   if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1158     // Allocate a stack slot for it, so we can point the debugger to it
1159     llvm::AllocaInst *Alloca = CreateTempAlloca(BlockPointer->getType(),
1160                                                 "block.addr");
1161     unsigned Align = getContext().getDeclAlign(&selfDecl).getQuantity();
1162     Alloca->setAlignment(Align);
1163     // Set the DebugLocation to empty, so the store is recognized as a
1164     // frame setup instruction by llvm::DwarfDebug::beginFunction().
1165     NoLocation NL(*this, Builder);
1166     Builder.CreateAlignedStore(BlockPointer, Alloca, Align);
1167     BlockPointerDbgLoc = Alloca;
1168   }
1169
1170   // If we have a C++ 'this' reference, go ahead and force it into
1171   // existence now.
1172   if (blockDecl->capturesCXXThis()) {
1173     llvm::Value *addr = Builder.CreateStructGEP(BlockPointer,
1174                                                 blockInfo.CXXThisIndex,
1175                                                 "block.captured-this");
1176     CXXThisValue = Builder.CreateLoad(addr, "this");
1177   }
1178
1179   // Also force all the constant captures.
1180   for (const auto &CI : blockDecl->captures()) {
1181     const VarDecl *variable = CI.getVariable();
1182     const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1183     if (!capture.isConstant()) continue;
1184
1185     unsigned align = getContext().getDeclAlign(variable).getQuantity();
1186
1187     llvm::AllocaInst *alloca =
1188       CreateMemTemp(variable->getType(), "block.captured-const");
1189     alloca->setAlignment(align);
1190
1191     Builder.CreateAlignedStore(capture.getConstant(), alloca, align);
1192
1193     LocalDeclMap[variable] = alloca;
1194   }
1195
1196   // Save a spot to insert the debug information for all the DeclRefExprs.
1197   llvm::BasicBlock *entry = Builder.GetInsertBlock();
1198   llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
1199   --entry_ptr;
1200
1201   if (IsLambdaConversionToBlock)
1202     EmitLambdaBlockInvokeBody();
1203   else {
1204     PGO.assignRegionCounters(blockDecl, fn);
1205     RegionCounter Cnt = getPGORegionCounter(blockDecl->getBody());
1206     Cnt.beginRegion(Builder);
1207     EmitStmt(blockDecl->getBody());
1208     PGO.emitInstrumentationData();
1209     PGO.destroyRegionCounters();
1210   }
1211
1212   // Remember where we were...
1213   llvm::BasicBlock *resume = Builder.GetInsertBlock();
1214
1215   // Go back to the entry.
1216   ++entry_ptr;
1217   Builder.SetInsertPoint(entry, entry_ptr);
1218
1219   // Emit debug information for all the DeclRefExprs.
1220   // FIXME: also for 'this'
1221   if (CGDebugInfo *DI = getDebugInfo()) {
1222     for (const auto &CI : blockDecl->captures()) {
1223       const VarDecl *variable = CI.getVariable();
1224       DI->EmitLocation(Builder, variable->getLocation());
1225
1226       if (CGM.getCodeGenOpts().getDebugInfo()
1227             >= CodeGenOptions::LimitedDebugInfo) {
1228         const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1229         if (capture.isConstant()) {
1230           DI->EmitDeclareOfAutoVariable(variable, LocalDeclMap[variable],
1231                                         Builder);
1232           continue;
1233         }
1234
1235         DI->EmitDeclareOfBlockDeclRefVariable(variable, BlockPointerDbgLoc,
1236                                               Builder, blockInfo);
1237       }
1238     }
1239     // Recover location if it was changed in the above loop.
1240     DI->EmitLocation(Builder,
1241                      cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
1242   }
1243
1244   // And resume where we left off.
1245   if (resume == nullptr)
1246     Builder.ClearInsertionPoint();
1247   else
1248     Builder.SetInsertPoint(resume);
1249
1250   FinishFunction(cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
1251
1252   return fn;
1253 }
1254
1255 /*
1256     notes.push_back(HelperInfo());
1257     HelperInfo &note = notes.back();
1258     note.index = capture.getIndex();
1259     note.RequiresCopying = (ci->hasCopyExpr() || BlockRequiresCopying(type));
1260     note.cxxbar_import = ci->getCopyExpr();
1261
1262     if (ci->isByRef()) {
1263       note.flag = BLOCK_FIELD_IS_BYREF;
1264       if (type.isObjCGCWeak())
1265         note.flag |= BLOCK_FIELD_IS_WEAK;
1266     } else if (type->isBlockPointerType()) {
1267       note.flag = BLOCK_FIELD_IS_BLOCK;
1268     } else {
1269       note.flag = BLOCK_FIELD_IS_OBJECT;
1270     }
1271  */
1272
1273
1274 /// Generate the copy-helper function for a block closure object:
1275 ///   static void block_copy_helper(block_t *dst, block_t *src);
1276 /// The runtime will have previously initialized 'dst' by doing a
1277 /// bit-copy of 'src'.
1278 ///
1279 /// Note that this copies an entire block closure object to the heap;
1280 /// it should not be confused with a 'byref copy helper', which moves
1281 /// the contents of an individual __block variable to the heap.
1282 llvm::Constant *
1283 CodeGenFunction::GenerateCopyHelperFunction(const CGBlockInfo &blockInfo) {
1284   ASTContext &C = getContext();
1285
1286   FunctionArgList args;
1287   ImplicitParamDecl dstDecl(getContext(), nullptr, SourceLocation(), nullptr,
1288                             C.VoidPtrTy);
1289   args.push_back(&dstDecl);
1290   ImplicitParamDecl srcDecl(getContext(), nullptr, SourceLocation(), nullptr,
1291                             C.VoidPtrTy);
1292   args.push_back(&srcDecl);
1293
1294   const CGFunctionInfo &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
1295       C.VoidTy, args, FunctionType::ExtInfo(), /*variadic=*/false);
1296
1297   // FIXME: it would be nice if these were mergeable with things with
1298   // identical semantics.
1299   llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
1300
1301   llvm::Function *Fn =
1302     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
1303                            "__copy_helper_block_", &CGM.getModule());
1304
1305   IdentifierInfo *II
1306     = &CGM.getContext().Idents.get("__copy_helper_block_");
1307
1308   FunctionDecl *FD = FunctionDecl::Create(C,
1309                                           C.getTranslationUnitDecl(),
1310                                           SourceLocation(),
1311                                           SourceLocation(), II, C.VoidTy,
1312                                           nullptr, SC_Static,
1313                                           false,
1314                                           false);
1315   // Create a scope with an artificial location for the body of this function.
1316   ArtificialLocation AL(*this, Builder);
1317   StartFunction(FD, C.VoidTy, Fn, FI, args);
1318   AL.Emit();
1319
1320   llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
1321
1322   llvm::Value *src = GetAddrOfLocalVar(&srcDecl);
1323   src = Builder.CreateLoad(src);
1324   src = Builder.CreateBitCast(src, structPtrTy, "block.source");
1325
1326   llvm::Value *dst = GetAddrOfLocalVar(&dstDecl);
1327   dst = Builder.CreateLoad(dst);
1328   dst = Builder.CreateBitCast(dst, structPtrTy, "block.dest");
1329
1330   const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1331
1332   for (const auto &CI : blockDecl->captures()) {
1333     const VarDecl *variable = CI.getVariable();
1334     QualType type = variable->getType();
1335
1336     const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1337     if (capture.isConstant()) continue;
1338
1339     const Expr *copyExpr = CI.getCopyExpr();
1340     BlockFieldFlags flags;
1341
1342     bool useARCWeakCopy = false;
1343     bool useARCStrongCopy = false;
1344
1345     if (copyExpr) {
1346       assert(!CI.isByRef());
1347       // don't bother computing flags
1348
1349     } else if (CI.isByRef()) {
1350       flags = BLOCK_FIELD_IS_BYREF;
1351       if (type.isObjCGCWeak())
1352         flags |= BLOCK_FIELD_IS_WEAK;
1353
1354     } else if (type->isObjCRetainableType()) {
1355       flags = BLOCK_FIELD_IS_OBJECT;
1356       bool isBlockPointer = type->isBlockPointerType();
1357       if (isBlockPointer)
1358         flags = BLOCK_FIELD_IS_BLOCK;
1359
1360       // Special rules for ARC captures:
1361       if (getLangOpts().ObjCAutoRefCount) {
1362         Qualifiers qs = type.getQualifiers();
1363
1364         // We need to register __weak direct captures with the runtime.
1365         if (qs.getObjCLifetime() == Qualifiers::OCL_Weak) {
1366           useARCWeakCopy = true;
1367
1368         // We need to retain the copied value for __strong direct captures.
1369         } else if (qs.getObjCLifetime() == Qualifiers::OCL_Strong) {
1370           // If it's a block pointer, we have to copy the block and
1371           // assign that to the destination pointer, so we might as
1372           // well use _Block_object_assign.  Otherwise we can avoid that.
1373           if (!isBlockPointer)
1374             useARCStrongCopy = true;
1375
1376         // Otherwise the memcpy is fine.
1377         } else {
1378           continue;
1379         }
1380
1381       // Non-ARC captures of retainable pointers are strong and
1382       // therefore require a call to _Block_object_assign.
1383       } else {
1384         // fall through
1385       }
1386     } else {
1387       continue;
1388     }
1389
1390     unsigned index = capture.getIndex();
1391     llvm::Value *srcField = Builder.CreateStructGEP(src, index);
1392     llvm::Value *dstField = Builder.CreateStructGEP(dst, index);
1393
1394     // If there's an explicit copy expression, we do that.
1395     if (copyExpr) {
1396       EmitSynthesizedCXXCopyCtor(dstField, srcField, copyExpr);
1397     } else if (useARCWeakCopy) {
1398       EmitARCCopyWeak(dstField, srcField);
1399     } else {
1400       llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
1401       if (useARCStrongCopy) {
1402         // At -O0, store null into the destination field (so that the
1403         // storeStrong doesn't over-release) and then call storeStrong.
1404         // This is a workaround to not having an initStrong call.
1405         if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1406           auto *ty = cast<llvm::PointerType>(srcValue->getType());
1407           llvm::Value *null = llvm::ConstantPointerNull::get(ty);
1408           Builder.CreateStore(null, dstField);
1409           EmitARCStoreStrongCall(dstField, srcValue, true);
1410
1411         // With optimization enabled, take advantage of the fact that
1412         // the blocks runtime guarantees a memcpy of the block data, and
1413         // just emit a retain of the src field.
1414         } else {
1415           EmitARCRetainNonBlock(srcValue);
1416
1417           // We don't need this anymore, so kill it.  It's not quite
1418           // worth the annoyance to avoid creating it in the first place.
1419           cast<llvm::Instruction>(dstField)->eraseFromParent();
1420         }
1421       } else {
1422         srcValue = Builder.CreateBitCast(srcValue, VoidPtrTy);
1423         llvm::Value *dstAddr = Builder.CreateBitCast(dstField, VoidPtrTy);
1424         llvm::Value *args[] = {
1425           dstAddr, srcValue, llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
1426         };
1427
1428         bool copyCanThrow = false;
1429         if (CI.isByRef() && variable->getType()->getAsCXXRecordDecl()) {
1430           const Expr *copyExpr =
1431             CGM.getContext().getBlockVarCopyInits(variable);
1432           if (copyExpr) {
1433             copyCanThrow = true; // FIXME: reuse the noexcept logic
1434           }
1435         }
1436
1437         if (copyCanThrow) {
1438           EmitRuntimeCallOrInvoke(CGM.getBlockObjectAssign(), args);
1439         } else {
1440           EmitNounwindRuntimeCall(CGM.getBlockObjectAssign(), args);
1441         }
1442       }
1443     }
1444   }
1445
1446   FinishFunction();
1447
1448   return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
1449 }
1450
1451 /// Generate the destroy-helper function for a block closure object:
1452 ///   static void block_destroy_helper(block_t *theBlock);
1453 ///
1454 /// Note that this destroys a heap-allocated block closure object;
1455 /// it should not be confused with a 'byref destroy helper', which
1456 /// destroys the heap-allocated contents of an individual __block
1457 /// variable.
1458 llvm::Constant *
1459 CodeGenFunction::GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo) {
1460   ASTContext &C = getContext();
1461
1462   FunctionArgList args;
1463   ImplicitParamDecl srcDecl(getContext(), nullptr, SourceLocation(), nullptr,
1464                             C.VoidPtrTy);
1465   args.push_back(&srcDecl);
1466
1467   const CGFunctionInfo &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
1468       C.VoidTy, args, FunctionType::ExtInfo(), /*variadic=*/false);
1469
1470   // FIXME: We'd like to put these into a mergable by content, with
1471   // internal linkage.
1472   llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
1473
1474   llvm::Function *Fn =
1475     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
1476                            "__destroy_helper_block_", &CGM.getModule());
1477
1478   IdentifierInfo *II
1479     = &CGM.getContext().Idents.get("__destroy_helper_block_");
1480
1481   FunctionDecl *FD = FunctionDecl::Create(C, C.getTranslationUnitDecl(),
1482                                           SourceLocation(),
1483                                           SourceLocation(), II, C.VoidTy,
1484                                           nullptr, SC_Static,
1485                                           false, false);
1486   // Create a scope with an artificial location for the body of this function.
1487   ArtificialLocation AL(*this, Builder);
1488   StartFunction(FD, C.VoidTy, Fn, FI, args);
1489   AL.Emit();
1490
1491   llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
1492
1493   llvm::Value *src = GetAddrOfLocalVar(&srcDecl);
1494   src = Builder.CreateLoad(src);
1495   src = Builder.CreateBitCast(src, structPtrTy, "block");
1496
1497   const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1498
1499   CodeGenFunction::RunCleanupsScope cleanups(*this);
1500
1501   for (const auto &CI : blockDecl->captures()) {
1502     const VarDecl *variable = CI.getVariable();
1503     QualType type = variable->getType();
1504
1505     const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1506     if (capture.isConstant()) continue;
1507
1508     BlockFieldFlags flags;
1509     const CXXDestructorDecl *dtor = nullptr;
1510
1511     bool useARCWeakDestroy = false;
1512     bool useARCStrongDestroy = false;
1513
1514     if (CI.isByRef()) {
1515       flags = BLOCK_FIELD_IS_BYREF;
1516       if (type.isObjCGCWeak())
1517         flags |= BLOCK_FIELD_IS_WEAK;
1518     } else if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1519       if (record->hasTrivialDestructor())
1520         continue;
1521       dtor = record->getDestructor();
1522     } else if (type->isObjCRetainableType()) {
1523       flags = BLOCK_FIELD_IS_OBJECT;
1524       if (type->isBlockPointerType())
1525         flags = BLOCK_FIELD_IS_BLOCK;
1526
1527       // Special rules for ARC captures.
1528       if (getLangOpts().ObjCAutoRefCount) {
1529         Qualifiers qs = type.getQualifiers();
1530
1531         // Don't generate special dispose logic for a captured object
1532         // unless it's __strong or __weak.
1533         if (!qs.hasStrongOrWeakObjCLifetime())
1534           continue;
1535
1536         // Support __weak direct captures.
1537         if (qs.getObjCLifetime() == Qualifiers::OCL_Weak)
1538           useARCWeakDestroy = true;
1539
1540         // Tools really want us to use objc_storeStrong here.
1541         else
1542           useARCStrongDestroy = true;
1543       }
1544     } else {
1545       continue;
1546     }
1547
1548     unsigned index = capture.getIndex();
1549     llvm::Value *srcField = Builder.CreateStructGEP(src, index);
1550
1551     // If there's an explicit copy expression, we do that.
1552     if (dtor) {
1553       PushDestructorCleanup(dtor, srcField);
1554
1555     // If this is a __weak capture, emit the release directly.
1556     } else if (useARCWeakDestroy) {
1557       EmitARCDestroyWeak(srcField);
1558
1559     // Destroy strong objects with a call if requested.
1560     } else if (useARCStrongDestroy) {
1561       EmitARCDestroyStrong(srcField, ARCImpreciseLifetime);
1562
1563     // Otherwise we call _Block_object_dispose.  It wouldn't be too
1564     // hard to just emit this as a cleanup if we wanted to make sure
1565     // that things were done in reverse.
1566     } else {
1567       llvm::Value *value = Builder.CreateLoad(srcField);
1568       value = Builder.CreateBitCast(value, VoidPtrTy);
1569       BuildBlockRelease(value, flags);
1570     }
1571   }
1572
1573   cleanups.ForceCleanup();
1574
1575   FinishFunction();
1576
1577   return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
1578 }
1579
1580 namespace {
1581
1582 /// Emits the copy/dispose helper functions for a __block object of id type.
1583 class ObjectByrefHelpers : public CodeGenModule::ByrefHelpers {
1584   BlockFieldFlags Flags;
1585
1586 public:
1587   ObjectByrefHelpers(CharUnits alignment, BlockFieldFlags flags)
1588     : ByrefHelpers(alignment), Flags(flags) {}
1589
1590   void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1591                 llvm::Value *srcField) override {
1592     destField = CGF.Builder.CreateBitCast(destField, CGF.VoidPtrTy);
1593
1594     srcField = CGF.Builder.CreateBitCast(srcField, CGF.VoidPtrPtrTy);
1595     llvm::Value *srcValue = CGF.Builder.CreateLoad(srcField);
1596
1597     unsigned flags = (Flags | BLOCK_BYREF_CALLER).getBitMask();
1598
1599     llvm::Value *flagsVal = llvm::ConstantInt::get(CGF.Int32Ty, flags);
1600     llvm::Value *fn = CGF.CGM.getBlockObjectAssign();
1601
1602     llvm::Value *args[] = { destField, srcValue, flagsVal };
1603     CGF.EmitNounwindRuntimeCall(fn, args);
1604   }
1605
1606   void emitDispose(CodeGenFunction &CGF, llvm::Value *field) override {
1607     field = CGF.Builder.CreateBitCast(field, CGF.Int8PtrTy->getPointerTo(0));
1608     llvm::Value *value = CGF.Builder.CreateLoad(field);
1609
1610     CGF.BuildBlockRelease(value, Flags | BLOCK_BYREF_CALLER);
1611   }
1612
1613   void profileImpl(llvm::FoldingSetNodeID &id) const override {
1614     id.AddInteger(Flags.getBitMask());
1615   }
1616 };
1617
1618 /// Emits the copy/dispose helpers for an ARC __block __weak variable.
1619 class ARCWeakByrefHelpers : public CodeGenModule::ByrefHelpers {
1620 public:
1621   ARCWeakByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
1622
1623   void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1624                 llvm::Value *srcField) override {
1625     CGF.EmitARCMoveWeak(destField, srcField);
1626   }
1627
1628   void emitDispose(CodeGenFunction &CGF, llvm::Value *field) override {
1629     CGF.EmitARCDestroyWeak(field);
1630   }
1631
1632   void profileImpl(llvm::FoldingSetNodeID &id) const override {
1633     // 0 is distinguishable from all pointers and byref flags
1634     id.AddInteger(0);
1635   }
1636 };
1637
1638 /// Emits the copy/dispose helpers for an ARC __block __strong variable
1639 /// that's not of block-pointer type.
1640 class ARCStrongByrefHelpers : public CodeGenModule::ByrefHelpers {
1641 public:
1642   ARCStrongByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
1643
1644   void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1645                 llvm::Value *srcField) override {
1646     // Do a "move" by copying the value and then zeroing out the old
1647     // variable.
1648
1649     llvm::LoadInst *value = CGF.Builder.CreateLoad(srcField);
1650     value->setAlignment(Alignment.getQuantity());
1651     
1652     llvm::Value *null =
1653       llvm::ConstantPointerNull::get(cast<llvm::PointerType>(value->getType()));
1654
1655     if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0) {
1656       llvm::StoreInst *store = CGF.Builder.CreateStore(null, destField);
1657       store->setAlignment(Alignment.getQuantity());
1658       CGF.EmitARCStoreStrongCall(destField, value, /*ignored*/ true);
1659       CGF.EmitARCStoreStrongCall(srcField, null, /*ignored*/ true);
1660       return;
1661     }
1662     llvm::StoreInst *store = CGF.Builder.CreateStore(value, destField);
1663     store->setAlignment(Alignment.getQuantity());
1664
1665     store = CGF.Builder.CreateStore(null, srcField);
1666     store->setAlignment(Alignment.getQuantity());
1667   }
1668
1669   void emitDispose(CodeGenFunction &CGF, llvm::Value *field) override {
1670     CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
1671   }
1672
1673   void profileImpl(llvm::FoldingSetNodeID &id) const override {
1674     // 1 is distinguishable from all pointers and byref flags
1675     id.AddInteger(1);
1676   }
1677 };
1678
1679 /// Emits the copy/dispose helpers for an ARC __block __strong
1680 /// variable that's of block-pointer type.
1681 class ARCStrongBlockByrefHelpers : public CodeGenModule::ByrefHelpers {
1682 public:
1683   ARCStrongBlockByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
1684
1685   void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1686                 llvm::Value *srcField) override {
1687     // Do the copy with objc_retainBlock; that's all that
1688     // _Block_object_assign would do anyway, and we'd have to pass the
1689     // right arguments to make sure it doesn't get no-op'ed.
1690     llvm::LoadInst *oldValue = CGF.Builder.CreateLoad(srcField);
1691     oldValue->setAlignment(Alignment.getQuantity());
1692
1693     llvm::Value *copy = CGF.EmitARCRetainBlock(oldValue, /*mandatory*/ true);
1694
1695     llvm::StoreInst *store = CGF.Builder.CreateStore(copy, destField);
1696     store->setAlignment(Alignment.getQuantity());
1697   }
1698
1699   void emitDispose(CodeGenFunction &CGF, llvm::Value *field) override {
1700     CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
1701   }
1702
1703   void profileImpl(llvm::FoldingSetNodeID &id) const override {
1704     // 2 is distinguishable from all pointers and byref flags
1705     id.AddInteger(2);
1706   }
1707 };
1708
1709 /// Emits the copy/dispose helpers for a __block variable with a
1710 /// nontrivial copy constructor or destructor.
1711 class CXXByrefHelpers : public CodeGenModule::ByrefHelpers {
1712   QualType VarType;
1713   const Expr *CopyExpr;
1714
1715 public:
1716   CXXByrefHelpers(CharUnits alignment, QualType type,
1717                   const Expr *copyExpr)
1718     : ByrefHelpers(alignment), VarType(type), CopyExpr(copyExpr) {}
1719
1720   bool needsCopy() const override { return CopyExpr != nullptr; }
1721   void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1722                 llvm::Value *srcField) override {
1723     if (!CopyExpr) return;
1724     CGF.EmitSynthesizedCXXCopyCtor(destField, srcField, CopyExpr);
1725   }
1726
1727   void emitDispose(CodeGenFunction &CGF, llvm::Value *field) override {
1728     EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin();
1729     CGF.PushDestructorCleanup(VarType, field);
1730     CGF.PopCleanupBlocks(cleanupDepth);
1731   }
1732
1733   void profileImpl(llvm::FoldingSetNodeID &id) const override {
1734     id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr());
1735   }
1736 };
1737 } // end anonymous namespace
1738
1739 static llvm::Constant *
1740 generateByrefCopyHelper(CodeGenFunction &CGF,
1741                         llvm::StructType &byrefType,
1742                         unsigned valueFieldIndex,
1743                         CodeGenModule::ByrefHelpers &byrefInfo) {
1744   ASTContext &Context = CGF.getContext();
1745
1746   QualType R = Context.VoidTy;
1747
1748   FunctionArgList args;
1749   ImplicitParamDecl dst(CGF.getContext(), nullptr, SourceLocation(), nullptr,
1750                         Context.VoidPtrTy);
1751   args.push_back(&dst);
1752
1753   ImplicitParamDecl src(CGF.getContext(), nullptr, SourceLocation(), nullptr,
1754                         Context.VoidPtrTy);
1755   args.push_back(&src);
1756
1757   const CGFunctionInfo &FI = CGF.CGM.getTypes().arrangeFreeFunctionDeclaration(
1758       R, args, FunctionType::ExtInfo(), /*variadic=*/false);
1759
1760   CodeGenTypes &Types = CGF.CGM.getTypes();
1761   llvm::FunctionType *LTy = Types.GetFunctionType(FI);
1762
1763   // FIXME: We'd like to put these into a mergable by content, with
1764   // internal linkage.
1765   llvm::Function *Fn =
1766     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
1767                            "__Block_byref_object_copy_", &CGF.CGM.getModule());
1768
1769   IdentifierInfo *II
1770     = &Context.Idents.get("__Block_byref_object_copy_");
1771
1772   FunctionDecl *FD = FunctionDecl::Create(Context,
1773                                           Context.getTranslationUnitDecl(),
1774                                           SourceLocation(),
1775                                           SourceLocation(), II, R, nullptr,
1776                                           SC_Static,
1777                                           false, false);
1778
1779   CGF.StartFunction(FD, R, Fn, FI, args);
1780
1781   if (byrefInfo.needsCopy()) {
1782     llvm::Type *byrefPtrType = byrefType.getPointerTo(0);
1783
1784     // dst->x
1785     llvm::Value *destField = CGF.GetAddrOfLocalVar(&dst);
1786     destField = CGF.Builder.CreateLoad(destField);
1787     destField = CGF.Builder.CreateBitCast(destField, byrefPtrType);
1788     destField = CGF.Builder.CreateStructGEP(destField, valueFieldIndex, "x");
1789
1790     // src->x
1791     llvm::Value *srcField = CGF.GetAddrOfLocalVar(&src);
1792     srcField = CGF.Builder.CreateLoad(srcField);
1793     srcField = CGF.Builder.CreateBitCast(srcField, byrefPtrType);
1794     srcField = CGF.Builder.CreateStructGEP(srcField, valueFieldIndex, "x");
1795
1796     byrefInfo.emitCopy(CGF, destField, srcField);
1797   }  
1798
1799   CGF.FinishFunction();
1800
1801   return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
1802 }
1803
1804 /// Build the copy helper for a __block variable.
1805 static llvm::Constant *buildByrefCopyHelper(CodeGenModule &CGM,
1806                                             llvm::StructType &byrefType,
1807                                             unsigned byrefValueIndex,
1808                                             CodeGenModule::ByrefHelpers &info) {
1809   CodeGenFunction CGF(CGM);
1810   return generateByrefCopyHelper(CGF, byrefType, byrefValueIndex, info);
1811 }
1812
1813 /// Generate code for a __block variable's dispose helper.
1814 static llvm::Constant *
1815 generateByrefDisposeHelper(CodeGenFunction &CGF,
1816                            llvm::StructType &byrefType,
1817                            unsigned byrefValueIndex,
1818                            CodeGenModule::ByrefHelpers &byrefInfo) {
1819   ASTContext &Context = CGF.getContext();
1820   QualType R = Context.VoidTy;
1821
1822   FunctionArgList args;
1823   ImplicitParamDecl src(CGF.getContext(), nullptr, SourceLocation(), nullptr,
1824                         Context.VoidPtrTy);
1825   args.push_back(&src);
1826
1827   const CGFunctionInfo &FI = CGF.CGM.getTypes().arrangeFreeFunctionDeclaration(
1828       R, args, FunctionType::ExtInfo(), /*variadic=*/false);
1829
1830   CodeGenTypes &Types = CGF.CGM.getTypes();
1831   llvm::FunctionType *LTy = Types.GetFunctionType(FI);
1832
1833   // FIXME: We'd like to put these into a mergable by content, with
1834   // internal linkage.
1835   llvm::Function *Fn =
1836     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
1837                            "__Block_byref_object_dispose_",
1838                            &CGF.CGM.getModule());
1839
1840   IdentifierInfo *II
1841     = &Context.Idents.get("__Block_byref_object_dispose_");
1842
1843   FunctionDecl *FD = FunctionDecl::Create(Context,
1844                                           Context.getTranslationUnitDecl(),
1845                                           SourceLocation(),
1846                                           SourceLocation(), II, R, nullptr,
1847                                           SC_Static,
1848                                           false, false);
1849   CGF.StartFunction(FD, R, Fn, FI, args);
1850
1851   if (byrefInfo.needsDispose()) {
1852     llvm::Value *V = CGF.GetAddrOfLocalVar(&src);
1853     V = CGF.Builder.CreateLoad(V);
1854     V = CGF.Builder.CreateBitCast(V, byrefType.getPointerTo(0));
1855     V = CGF.Builder.CreateStructGEP(V, byrefValueIndex, "x");
1856
1857     byrefInfo.emitDispose(CGF, V);
1858   }
1859
1860   CGF.FinishFunction();
1861
1862   return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
1863 }
1864
1865 /// Build the dispose helper for a __block variable.
1866 static llvm::Constant *buildByrefDisposeHelper(CodeGenModule &CGM,
1867                                               llvm::StructType &byrefType,
1868                                                unsigned byrefValueIndex,
1869                                             CodeGenModule::ByrefHelpers &info) {
1870   CodeGenFunction CGF(CGM);
1871   return generateByrefDisposeHelper(CGF, byrefType, byrefValueIndex, info);
1872 }
1873
1874 /// Lazily build the copy and dispose helpers for a __block variable
1875 /// with the given information.
1876 template <class T> static T *buildByrefHelpers(CodeGenModule &CGM,
1877                                                llvm::StructType &byrefTy,
1878                                                unsigned byrefValueIndex,
1879                                                T &byrefInfo) {
1880   // Increase the field's alignment to be at least pointer alignment,
1881   // since the layout of the byref struct will guarantee at least that.
1882   byrefInfo.Alignment = std::max(byrefInfo.Alignment,
1883                               CharUnits::fromQuantity(CGM.PointerAlignInBytes));
1884
1885   llvm::FoldingSetNodeID id;
1886   byrefInfo.Profile(id);
1887
1888   void *insertPos;
1889   CodeGenModule::ByrefHelpers *node
1890     = CGM.ByrefHelpersCache.FindNodeOrInsertPos(id, insertPos);
1891   if (node) return static_cast<T*>(node);
1892
1893   byrefInfo.CopyHelper =
1894     buildByrefCopyHelper(CGM, byrefTy, byrefValueIndex, byrefInfo);
1895   byrefInfo.DisposeHelper =
1896     buildByrefDisposeHelper(CGM, byrefTy, byrefValueIndex,byrefInfo);
1897
1898   T *copy = new (CGM.getContext()) T(byrefInfo);
1899   CGM.ByrefHelpersCache.InsertNode(copy, insertPos);
1900   return copy;
1901 }
1902
1903 /// Build the copy and dispose helpers for the given __block variable
1904 /// emission.  Places the helpers in the global cache.  Returns null
1905 /// if no helpers are required.
1906 CodeGenModule::ByrefHelpers *
1907 CodeGenFunction::buildByrefHelpers(llvm::StructType &byrefType,
1908                                    const AutoVarEmission &emission) {
1909   const VarDecl &var = *emission.Variable;
1910   QualType type = var.getType();
1911
1912   unsigned byrefValueIndex = getByRefValueLLVMField(&var);
1913
1914   if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1915     const Expr *copyExpr = CGM.getContext().getBlockVarCopyInits(&var);
1916     if (!copyExpr && record->hasTrivialDestructor()) return nullptr;
1917
1918     CXXByrefHelpers byrefInfo(emission.Alignment, type, copyExpr);
1919     return ::buildByrefHelpers(CGM, byrefType, byrefValueIndex, byrefInfo);
1920   }
1921
1922   // Otherwise, if we don't have a retainable type, there's nothing to do.
1923   // that the runtime does extra copies.
1924   if (!type->isObjCRetainableType()) return nullptr;
1925
1926   Qualifiers qs = type.getQualifiers();
1927
1928   // If we have lifetime, that dominates.
1929   if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
1930     assert(getLangOpts().ObjCAutoRefCount);
1931
1932     switch (lifetime) {
1933     case Qualifiers::OCL_None: llvm_unreachable("impossible");
1934
1935     // These are just bits as far as the runtime is concerned.
1936     case Qualifiers::OCL_ExplicitNone:
1937     case Qualifiers::OCL_Autoreleasing:
1938       return nullptr;
1939
1940     // Tell the runtime that this is ARC __weak, called by the
1941     // byref routines.
1942     case Qualifiers::OCL_Weak: {
1943       ARCWeakByrefHelpers byrefInfo(emission.Alignment);
1944       return ::buildByrefHelpers(CGM, byrefType, byrefValueIndex, byrefInfo);
1945     }
1946
1947     // ARC __strong __block variables need to be retained.
1948     case Qualifiers::OCL_Strong:
1949       // Block pointers need to be copied, and there's no direct
1950       // transfer possible.
1951       if (type->isBlockPointerType()) {
1952         ARCStrongBlockByrefHelpers byrefInfo(emission.Alignment);
1953         return ::buildByrefHelpers(CGM, byrefType, byrefValueIndex, byrefInfo);
1954
1955       // Otherwise, we transfer ownership of the retain from the stack
1956       // to the heap.
1957       } else {
1958         ARCStrongByrefHelpers byrefInfo(emission.Alignment);
1959         return ::buildByrefHelpers(CGM, byrefType, byrefValueIndex, byrefInfo);
1960       }
1961     }
1962     llvm_unreachable("fell out of lifetime switch!");
1963   }
1964
1965   BlockFieldFlags flags;
1966   if (type->isBlockPointerType()) {
1967     flags |= BLOCK_FIELD_IS_BLOCK;
1968   } else if (CGM.getContext().isObjCNSObjectType(type) || 
1969              type->isObjCObjectPointerType()) {
1970     flags |= BLOCK_FIELD_IS_OBJECT;
1971   } else {
1972     return nullptr;
1973   }
1974
1975   if (type.isObjCGCWeak())
1976     flags |= BLOCK_FIELD_IS_WEAK;
1977
1978   ObjectByrefHelpers byrefInfo(emission.Alignment, flags);
1979   return ::buildByrefHelpers(CGM, byrefType, byrefValueIndex, byrefInfo);
1980 }
1981
1982 unsigned CodeGenFunction::getByRefValueLLVMField(const ValueDecl *VD) const {
1983   assert(ByRefValueInfo.count(VD) && "Did not find value!");
1984   
1985   return ByRefValueInfo.find(VD)->second.second;
1986 }
1987
1988 llvm::Value *CodeGenFunction::BuildBlockByrefAddress(llvm::Value *BaseAddr,
1989                                                      const VarDecl *V) {
1990   llvm::Value *Loc = Builder.CreateStructGEP(BaseAddr, 1, "forwarding");
1991   Loc = Builder.CreateLoad(Loc);
1992   Loc = Builder.CreateStructGEP(Loc, getByRefValueLLVMField(V),
1993                                 V->getNameAsString());
1994   return Loc;
1995 }
1996
1997 /// BuildByRefType - This routine changes a __block variable declared as T x
1998 ///   into:
1999 ///
2000 ///      struct {
2001 ///        void *__isa;
2002 ///        void *__forwarding;
2003 ///        int32_t __flags;
2004 ///        int32_t __size;
2005 ///        void *__copy_helper;       // only if needed
2006 ///        void *__destroy_helper;    // only if needed
2007 ///        void *__byref_variable_layout;// only if needed
2008 ///        char padding[X];           // only if needed
2009 ///        T x;
2010 ///      } x
2011 ///
2012 llvm::Type *CodeGenFunction::BuildByRefType(const VarDecl *D) {
2013   std::pair<llvm::Type *, unsigned> &Info = ByRefValueInfo[D];
2014   if (Info.first)
2015     return Info.first;
2016   
2017   QualType Ty = D->getType();
2018
2019   SmallVector<llvm::Type *, 8> types;
2020   
2021   llvm::StructType *ByRefType =
2022     llvm::StructType::create(getLLVMContext(),
2023                              "struct.__block_byref_" + D->getNameAsString());
2024   
2025   // void *__isa;
2026   types.push_back(Int8PtrTy);
2027   
2028   // void *__forwarding;
2029   types.push_back(llvm::PointerType::getUnqual(ByRefType));
2030   
2031   // int32_t __flags;
2032   types.push_back(Int32Ty);
2033     
2034   // int32_t __size;
2035   types.push_back(Int32Ty);
2036   // Note that this must match *exactly* the logic in buildByrefHelpers.
2037   bool HasCopyAndDispose = getContext().BlockRequiresCopying(Ty, D);
2038   if (HasCopyAndDispose) {
2039     /// void *__copy_helper;
2040     types.push_back(Int8PtrTy);
2041     
2042     /// void *__destroy_helper;
2043     types.push_back(Int8PtrTy);
2044   }
2045   bool HasByrefExtendedLayout = false;
2046   Qualifiers::ObjCLifetime Lifetime;
2047   if (getContext().getByrefLifetime(Ty, Lifetime, HasByrefExtendedLayout) &&
2048       HasByrefExtendedLayout)
2049     /// void *__byref_variable_layout;
2050     types.push_back(Int8PtrTy);
2051
2052   bool Packed = false;
2053   CharUnits Align = getContext().getDeclAlign(D);
2054   if (Align >
2055       getContext().toCharUnitsFromBits(getTarget().getPointerAlign(0))) {
2056     // We have to insert padding.
2057     
2058     // The struct above has 2 32-bit integers.
2059     unsigned CurrentOffsetInBytes = 4 * 2;
2060     
2061     // And either 2, 3, 4 or 5 pointers.
2062     unsigned noPointers = 2;
2063     if (HasCopyAndDispose)
2064       noPointers += 2;
2065     if (HasByrefExtendedLayout)
2066       noPointers += 1;
2067     
2068     CurrentOffsetInBytes += noPointers * CGM.getDataLayout().getTypeAllocSize(Int8PtrTy);
2069     
2070     // Align the offset.
2071     unsigned AlignedOffsetInBytes = 
2072       llvm::RoundUpToAlignment(CurrentOffsetInBytes, Align.getQuantity());
2073     
2074     unsigned NumPaddingBytes = AlignedOffsetInBytes - CurrentOffsetInBytes;
2075     if (NumPaddingBytes > 0) {
2076       llvm::Type *Ty = Int8Ty;
2077       // FIXME: We need a sema error for alignment larger than the minimum of
2078       // the maximal stack alignment and the alignment of malloc on the system.
2079       if (NumPaddingBytes > 1)
2080         Ty = llvm::ArrayType::get(Ty, NumPaddingBytes);
2081     
2082       types.push_back(Ty);
2083
2084       // We want a packed struct.
2085       Packed = true;
2086     }
2087   }
2088
2089   // T x;
2090   types.push_back(ConvertTypeForMem(Ty));
2091   
2092   ByRefType->setBody(types, Packed);
2093   
2094   Info.first = ByRefType;
2095   
2096   Info.second = types.size() - 1;
2097   
2098   return Info.first;
2099 }
2100
2101 /// Initialize the structural components of a __block variable, i.e.
2102 /// everything but the actual object.
2103 void CodeGenFunction::emitByrefStructureInit(const AutoVarEmission &emission) {
2104   // Find the address of the local.
2105   llvm::Value *addr = emission.Address;
2106
2107   // That's an alloca of the byref structure type.
2108   llvm::StructType *byrefType = cast<llvm::StructType>(
2109                  cast<llvm::PointerType>(addr->getType())->getElementType());
2110
2111   // Build the byref helpers if necessary.  This is null if we don't need any.
2112   CodeGenModule::ByrefHelpers *helpers =
2113     buildByrefHelpers(*byrefType, emission);
2114
2115   const VarDecl &D = *emission.Variable;
2116   QualType type = D.getType();
2117
2118   bool HasByrefExtendedLayout;
2119   Qualifiers::ObjCLifetime ByrefLifetime;
2120   bool ByRefHasLifetime =
2121     getContext().getByrefLifetime(type, ByrefLifetime, HasByrefExtendedLayout);
2122   
2123   llvm::Value *V;
2124
2125   // Initialize the 'isa', which is just 0 or 1.
2126   int isa = 0;
2127   if (type.isObjCGCWeak())
2128     isa = 1;
2129   V = Builder.CreateIntToPtr(Builder.getInt32(isa), Int8PtrTy, "isa");
2130   Builder.CreateStore(V, Builder.CreateStructGEP(addr, 0, "byref.isa"));
2131
2132   // Store the address of the variable into its own forwarding pointer.
2133   Builder.CreateStore(addr,
2134                       Builder.CreateStructGEP(addr, 1, "byref.forwarding"));
2135
2136   // Blocks ABI:
2137   //   c) the flags field is set to either 0 if no helper functions are
2138   //      needed or BLOCK_BYREF_HAS_COPY_DISPOSE if they are,
2139   BlockFlags flags;
2140   if (helpers) flags |= BLOCK_BYREF_HAS_COPY_DISPOSE;
2141   if (ByRefHasLifetime) {
2142     if (HasByrefExtendedLayout) flags |= BLOCK_BYREF_LAYOUT_EXTENDED;
2143       else switch (ByrefLifetime) {
2144         case Qualifiers::OCL_Strong:
2145           flags |= BLOCK_BYREF_LAYOUT_STRONG;
2146           break;
2147         case Qualifiers::OCL_Weak:
2148           flags |= BLOCK_BYREF_LAYOUT_WEAK;
2149           break;
2150         case Qualifiers::OCL_ExplicitNone:
2151           flags |= BLOCK_BYREF_LAYOUT_UNRETAINED;
2152           break;
2153         case Qualifiers::OCL_None:
2154           if (!type->isObjCObjectPointerType() && !type->isBlockPointerType())
2155             flags |= BLOCK_BYREF_LAYOUT_NON_OBJECT;
2156           break;
2157         default:
2158           break;
2159       }
2160     if (CGM.getLangOpts().ObjCGCBitmapPrint) {
2161       printf("\n Inline flag for BYREF variable layout (%d):", flags.getBitMask());
2162       if (flags & BLOCK_BYREF_HAS_COPY_DISPOSE)
2163         printf(" BLOCK_BYREF_HAS_COPY_DISPOSE");
2164       if (flags & BLOCK_BYREF_LAYOUT_MASK) {
2165         BlockFlags ThisFlag(flags.getBitMask() & BLOCK_BYREF_LAYOUT_MASK);
2166         if (ThisFlag ==  BLOCK_BYREF_LAYOUT_EXTENDED)
2167           printf(" BLOCK_BYREF_LAYOUT_EXTENDED");
2168         if (ThisFlag ==  BLOCK_BYREF_LAYOUT_STRONG)
2169           printf(" BLOCK_BYREF_LAYOUT_STRONG");
2170         if (ThisFlag == BLOCK_BYREF_LAYOUT_WEAK)
2171           printf(" BLOCK_BYREF_LAYOUT_WEAK");
2172         if (ThisFlag == BLOCK_BYREF_LAYOUT_UNRETAINED)
2173           printf(" BLOCK_BYREF_LAYOUT_UNRETAINED");
2174         if (ThisFlag == BLOCK_BYREF_LAYOUT_NON_OBJECT)
2175           printf(" BLOCK_BYREF_LAYOUT_NON_OBJECT");
2176       }
2177       printf("\n");
2178     }
2179   }
2180   
2181   Builder.CreateStore(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
2182                       Builder.CreateStructGEP(addr, 2, "byref.flags"));
2183
2184   CharUnits byrefSize = CGM.GetTargetTypeStoreSize(byrefType);
2185   V = llvm::ConstantInt::get(IntTy, byrefSize.getQuantity());
2186   Builder.CreateStore(V, Builder.CreateStructGEP(addr, 3, "byref.size"));
2187
2188   if (helpers) {
2189     llvm::Value *copy_helper = Builder.CreateStructGEP(addr, 4);
2190     Builder.CreateStore(helpers->CopyHelper, copy_helper);
2191
2192     llvm::Value *destroy_helper = Builder.CreateStructGEP(addr, 5);
2193     Builder.CreateStore(helpers->DisposeHelper, destroy_helper);
2194   }
2195   if (ByRefHasLifetime && HasByrefExtendedLayout) {
2196     llvm::Constant* ByrefLayoutInfo = CGM.getObjCRuntime().BuildByrefLayout(CGM, type);
2197     llvm::Value *ByrefInfoAddr = Builder.CreateStructGEP(addr, helpers ? 6 : 4,
2198                                                          "byref.layout");
2199     // cast destination to pointer to source type.
2200     llvm::Type *DesTy = ByrefLayoutInfo->getType();
2201     DesTy = DesTy->getPointerTo();
2202     llvm::Value *BC = Builder.CreatePointerCast(ByrefInfoAddr, DesTy);
2203     Builder.CreateStore(ByrefLayoutInfo, BC);
2204   }
2205 }
2206
2207 void CodeGenFunction::BuildBlockRelease(llvm::Value *V, BlockFieldFlags flags) {
2208   llvm::Value *F = CGM.getBlockObjectDispose();
2209   llvm::Value *args[] = {
2210     Builder.CreateBitCast(V, Int8PtrTy),
2211     llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
2212   };
2213   EmitNounwindRuntimeCall(F, args); // FIXME: throwing destructors?
2214 }
2215
2216 namespace {
2217   struct CallBlockRelease : EHScopeStack::Cleanup {
2218     llvm::Value *Addr;
2219     CallBlockRelease(llvm::Value *Addr) : Addr(Addr) {}
2220
2221     void Emit(CodeGenFunction &CGF, Flags flags) override {
2222       // Should we be passing FIELD_IS_WEAK here?
2223       CGF.BuildBlockRelease(Addr, BLOCK_FIELD_IS_BYREF);
2224     }
2225   };
2226 }
2227
2228 /// Enter a cleanup to destroy a __block variable.  Note that this
2229 /// cleanup should be a no-op if the variable hasn't left the stack
2230 /// yet; if a cleanup is required for the variable itself, that needs
2231 /// to be done externally.
2232 void CodeGenFunction::enterByrefCleanup(const AutoVarEmission &emission) {
2233   // We don't enter this cleanup if we're in pure-GC mode.
2234   if (CGM.getLangOpts().getGC() == LangOptions::GCOnly)
2235     return;
2236
2237   EHStack.pushCleanup<CallBlockRelease>(NormalAndEHCleanup, emission.Address);
2238 }
2239
2240 /// Adjust the declaration of something from the blocks API.
2241 static void configureBlocksRuntimeObject(CodeGenModule &CGM,
2242                                          llvm::Constant *C) {
2243   if (!CGM.getLangOpts().BlocksRuntimeOptional) return;
2244
2245   auto *GV = cast<llvm::GlobalValue>(C->stripPointerCasts());
2246   if (GV->isDeclaration() && GV->hasExternalLinkage())
2247     GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
2248 }
2249
2250 llvm::Constant *CodeGenModule::getBlockObjectDispose() {
2251   if (BlockObjectDispose)
2252     return BlockObjectDispose;
2253
2254   llvm::Type *args[] = { Int8PtrTy, Int32Ty };
2255   llvm::FunctionType *fty
2256     = llvm::FunctionType::get(VoidTy, args, false);
2257   BlockObjectDispose = CreateRuntimeFunction(fty, "_Block_object_dispose");
2258   configureBlocksRuntimeObject(*this, BlockObjectDispose);
2259   return BlockObjectDispose;
2260 }
2261
2262 llvm::Constant *CodeGenModule::getBlockObjectAssign() {
2263   if (BlockObjectAssign)
2264     return BlockObjectAssign;
2265
2266   llvm::Type *args[] = { Int8PtrTy, Int8PtrTy, Int32Ty };
2267   llvm::FunctionType *fty
2268     = llvm::FunctionType::get(VoidTy, args, false);
2269   BlockObjectAssign = CreateRuntimeFunction(fty, "_Block_object_assign");
2270   configureBlocksRuntimeObject(*this, BlockObjectAssign);
2271   return BlockObjectAssign;
2272 }
2273
2274 llvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() {
2275   if (NSConcreteGlobalBlock)
2276     return NSConcreteGlobalBlock;
2277
2278   NSConcreteGlobalBlock = GetOrCreateLLVMGlobal("_NSConcreteGlobalBlock",
2279                                                 Int8PtrTy->getPointerTo(),
2280                                                 nullptr);
2281   configureBlocksRuntimeObject(*this, NSConcreteGlobalBlock);
2282   return NSConcreteGlobalBlock;
2283 }
2284
2285 llvm::Constant *CodeGenModule::getNSConcreteStackBlock() {
2286   if (NSConcreteStackBlock)
2287     return NSConcreteStackBlock;
2288
2289   NSConcreteStackBlock = GetOrCreateLLVMGlobal("_NSConcreteStackBlock",
2290                                                Int8PtrTy->getPointerTo(),
2291                                                nullptr);
2292   configureBlocksRuntimeObject(*this, NSConcreteStackBlock);
2293   return NSConcreteStackBlock;  
2294 }