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