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