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