CGBlocks.cpp 64 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811
  1. //===--- CGBlocks.cpp - Emit LLVM Code for declarations -------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This contains code to emit blocks.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "CGDebugInfo.h"
  14. #include "CodeGenFunction.h"
  15. #include "CGObjCRuntime.h"
  16. #include "CodeGenModule.h"
  17. #include "CGBlocks.h"
  18. #include "clang/AST/DeclObjC.h"
  19. #include "llvm/Module.h"
  20. #include "llvm/ADT/SmallSet.h"
  21. #include "llvm/Target/TargetData.h"
  22. #include <algorithm>
  23. using namespace clang;
  24. using namespace CodeGen;
  25. CGBlockInfo::CGBlockInfo(const BlockExpr *blockExpr, const char *N)
  26. : Name(N), CXXThisIndex(0), CanBeGlobal(false), NeedsCopyDispose(false),
  27. HasCXXObject(false), UsesStret(false), StructureType(0), Block(blockExpr) {
  28. // Skip asm prefix, if any.
  29. if (Name && Name[0] == '\01')
  30. ++Name;
  31. }
  32. // Anchor the vtable to this translation unit.
  33. CodeGenModule::ByrefHelpers::~ByrefHelpers() {}
  34. /// Build the given block as a global block.
  35. static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
  36. const CGBlockInfo &blockInfo,
  37. llvm::Constant *blockFn);
  38. /// Build the helper function to copy a block.
  39. static llvm::Constant *buildCopyHelper(CodeGenModule &CGM,
  40. const CGBlockInfo &blockInfo) {
  41. return CodeGenFunction(CGM).GenerateCopyHelperFunction(blockInfo);
  42. }
  43. /// Build the helper function to dipose of a block.
  44. static llvm::Constant *buildDisposeHelper(CodeGenModule &CGM,
  45. const CGBlockInfo &blockInfo) {
  46. return CodeGenFunction(CGM).GenerateDestroyHelperFunction(blockInfo);
  47. }
  48. /// Build the block descriptor constant for a block.
  49. static llvm::Constant *buildBlockDescriptor(CodeGenModule &CGM,
  50. const CGBlockInfo &blockInfo) {
  51. ASTContext &C = CGM.getContext();
  52. llvm::Type *ulong = CGM.getTypes().ConvertType(C.UnsignedLongTy);
  53. llvm::Type *i8p = CGM.getTypes().ConvertType(C.VoidPtrTy);
  54. SmallVector<llvm::Constant*, 6> elements;
  55. // reserved
  56. elements.push_back(llvm::ConstantInt::get(ulong, 0));
  57. // Size
  58. // FIXME: What is the right way to say this doesn't fit? We should give
  59. // a user diagnostic in that case. Better fix would be to change the
  60. // API to size_t.
  61. elements.push_back(llvm::ConstantInt::get(ulong,
  62. blockInfo.BlockSize.getQuantity()));
  63. // Optional copy/dispose helpers.
  64. if (blockInfo.NeedsCopyDispose) {
  65. // copy_func_helper_decl
  66. elements.push_back(buildCopyHelper(CGM, blockInfo));
  67. // destroy_func_decl
  68. elements.push_back(buildDisposeHelper(CGM, blockInfo));
  69. }
  70. // Signature. Mandatory ObjC-style method descriptor @encode sequence.
  71. std::string typeAtEncoding =
  72. CGM.getContext().getObjCEncodingForBlock(blockInfo.getBlockExpr());
  73. elements.push_back(llvm::ConstantExpr::getBitCast(
  74. CGM.GetAddrOfConstantCString(typeAtEncoding), i8p));
  75. // GC layout.
  76. if (C.getLangOptions().ObjC1)
  77. elements.push_back(CGM.getObjCRuntime().BuildGCBlockLayout(CGM, blockInfo));
  78. else
  79. elements.push_back(llvm::Constant::getNullValue(i8p));
  80. llvm::Constant *init = llvm::ConstantStruct::getAnon(elements);
  81. llvm::GlobalVariable *global =
  82. new llvm::GlobalVariable(CGM.getModule(), init->getType(), true,
  83. llvm::GlobalValue::InternalLinkage,
  84. init, "__block_descriptor_tmp");
  85. return llvm::ConstantExpr::getBitCast(global, CGM.getBlockDescriptorType());
  86. }
  87. /*
  88. Purely notional variadic template describing the layout of a block.
  89. template <class _ResultType, class... _ParamTypes, class... _CaptureTypes>
  90. struct Block_literal {
  91. /// Initialized to one of:
  92. /// extern void *_NSConcreteStackBlock[];
  93. /// extern void *_NSConcreteGlobalBlock[];
  94. ///
  95. /// In theory, we could start one off malloc'ed by setting
  96. /// BLOCK_NEEDS_FREE, giving it a refcount of 1, and using
  97. /// this isa:
  98. /// extern void *_NSConcreteMallocBlock[];
  99. struct objc_class *isa;
  100. /// These are the flags (with corresponding bit number) that the
  101. /// compiler is actually supposed to know about.
  102. /// 25. BLOCK_HAS_COPY_DISPOSE - indicates that the block
  103. /// descriptor provides copy and dispose helper functions
  104. /// 26. BLOCK_HAS_CXX_OBJ - indicates that there's a captured
  105. /// object with a nontrivial destructor or copy constructor
  106. /// 28. BLOCK_IS_GLOBAL - indicates that the block is allocated
  107. /// as global memory
  108. /// 29. BLOCK_USE_STRET - indicates that the block function
  109. /// uses stret, which objc_msgSend needs to know about
  110. /// 30. BLOCK_HAS_SIGNATURE - indicates that the block has an
  111. /// @encoded signature string
  112. /// And we're not supposed to manipulate these:
  113. /// 24. BLOCK_NEEDS_FREE - indicates that the block has been moved
  114. /// to malloc'ed memory
  115. /// 27. BLOCK_IS_GC - indicates that the block has been moved to
  116. /// to GC-allocated memory
  117. /// Additionally, the bottom 16 bits are a reference count which
  118. /// should be zero on the stack.
  119. int flags;
  120. /// Reserved; should be zero-initialized.
  121. int reserved;
  122. /// Function pointer generated from block literal.
  123. _ResultType (*invoke)(Block_literal *, _ParamTypes...);
  124. /// Block description metadata generated from block literal.
  125. struct Block_descriptor *block_descriptor;
  126. /// Captured values follow.
  127. _CapturesTypes captures...;
  128. };
  129. */
  130. /// The number of fields in a block header.
  131. const unsigned BlockHeaderSize = 5;
  132. namespace {
  133. /// A chunk of data that we actually have to capture in the block.
  134. struct BlockLayoutChunk {
  135. CharUnits Alignment;
  136. CharUnits Size;
  137. const BlockDecl::Capture *Capture; // null for 'this'
  138. llvm::Type *Type;
  139. BlockLayoutChunk(CharUnits align, CharUnits size,
  140. const BlockDecl::Capture *capture,
  141. llvm::Type *type)
  142. : Alignment(align), Size(size), Capture(capture), Type(type) {}
  143. /// Tell the block info that this chunk has the given field index.
  144. void setIndex(CGBlockInfo &info, unsigned index) {
  145. if (!Capture)
  146. info.CXXThisIndex = index;
  147. else
  148. info.Captures[Capture->getVariable()]
  149. = CGBlockInfo::Capture::makeIndex(index);
  150. }
  151. };
  152. /// Order by descending alignment.
  153. bool operator<(const BlockLayoutChunk &left, const BlockLayoutChunk &right) {
  154. return left.Alignment > right.Alignment;
  155. }
  156. }
  157. /// Determines if the given type is safe for constant capture in C++.
  158. static bool isSafeForCXXConstantCapture(QualType type) {
  159. const RecordType *recordType =
  160. type->getBaseElementTypeUnsafe()->getAs<RecordType>();
  161. // Only records can be unsafe.
  162. if (!recordType) return true;
  163. const CXXRecordDecl *record = cast<CXXRecordDecl>(recordType->getDecl());
  164. // Maintain semantics for classes with non-trivial dtors or copy ctors.
  165. if (!record->hasTrivialDestructor()) return false;
  166. if (!record->hasTrivialCopyConstructor()) return false;
  167. // Otherwise, we just have to make sure there aren't any mutable
  168. // fields that might have changed since initialization.
  169. return !record->hasMutableFields();
  170. }
  171. /// It is illegal to modify a const object after initialization.
  172. /// Therefore, if a const object has a constant initializer, we don't
  173. /// actually need to keep storage for it in the block; we'll just
  174. /// rematerialize it at the start of the block function. This is
  175. /// acceptable because we make no promises about address stability of
  176. /// captured variables.
  177. static llvm::Constant *tryCaptureAsConstant(CodeGenModule &CGM,
  178. const VarDecl *var) {
  179. QualType type = var->getType();
  180. // We can only do this if the variable is const.
  181. if (!type.isConstQualified()) return 0;
  182. // Furthermore, in C++ we have to worry about mutable fields:
  183. // C++ [dcl.type.cv]p4:
  184. // Except that any class member declared mutable can be
  185. // modified, any attempt to modify a const object during its
  186. // lifetime results in undefined behavior.
  187. if (CGM.getLangOptions().CPlusPlus && !isSafeForCXXConstantCapture(type))
  188. return 0;
  189. // If the variable doesn't have any initializer (shouldn't this be
  190. // invalid?), it's not clear what we should do. Maybe capture as
  191. // zero?
  192. const Expr *init = var->getInit();
  193. if (!init) return 0;
  194. return CGM.EmitConstantExpr(init, var->getType());
  195. }
  196. /// Get the low bit of a nonzero character count. This is the
  197. /// alignment of the nth byte if the 0th byte is universally aligned.
  198. static CharUnits getLowBit(CharUnits v) {
  199. return CharUnits::fromQuantity(v.getQuantity() & (~v.getQuantity() + 1));
  200. }
  201. static void initializeForBlockHeader(CodeGenModule &CGM, CGBlockInfo &info,
  202. SmallVectorImpl<llvm::Type*> &elementTypes) {
  203. ASTContext &C = CGM.getContext();
  204. // The header is basically a 'struct { void *; int; int; void *; void *; }'.
  205. CharUnits ptrSize, ptrAlign, intSize, intAlign;
  206. llvm::tie(ptrSize, ptrAlign) = C.getTypeInfoInChars(C.VoidPtrTy);
  207. llvm::tie(intSize, intAlign) = C.getTypeInfoInChars(C.IntTy);
  208. // Are there crazy embedded platforms where this isn't true?
  209. assert(intSize <= ptrSize && "layout assumptions horribly violated");
  210. CharUnits headerSize = ptrSize;
  211. if (2 * intSize < ptrAlign) headerSize += ptrSize;
  212. else headerSize += 2 * intSize;
  213. headerSize += 2 * ptrSize;
  214. info.BlockAlign = ptrAlign;
  215. info.BlockSize = headerSize;
  216. assert(elementTypes.empty());
  217. llvm::Type *i8p = CGM.getTypes().ConvertType(C.VoidPtrTy);
  218. llvm::Type *intTy = CGM.getTypes().ConvertType(C.IntTy);
  219. elementTypes.push_back(i8p);
  220. elementTypes.push_back(intTy);
  221. elementTypes.push_back(intTy);
  222. elementTypes.push_back(i8p);
  223. elementTypes.push_back(CGM.getBlockDescriptorType());
  224. assert(elementTypes.size() == BlockHeaderSize);
  225. }
  226. /// Compute the layout of the given block. Attempts to lay the block
  227. /// out with minimal space requirements.
  228. static void computeBlockInfo(CodeGenModule &CGM, CGBlockInfo &info) {
  229. ASTContext &C = CGM.getContext();
  230. const BlockDecl *block = info.getBlockDecl();
  231. SmallVector<llvm::Type*, 8> elementTypes;
  232. initializeForBlockHeader(CGM, info, elementTypes);
  233. if (!block->hasCaptures()) {
  234. info.StructureType =
  235. llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
  236. info.CanBeGlobal = true;
  237. return;
  238. }
  239. // Collect the layout chunks.
  240. SmallVector<BlockLayoutChunk, 16> layout;
  241. layout.reserve(block->capturesCXXThis() +
  242. (block->capture_end() - block->capture_begin()));
  243. CharUnits maxFieldAlign;
  244. // First, 'this'.
  245. if (block->capturesCXXThis()) {
  246. const DeclContext *DC = block->getDeclContext();
  247. for (; isa<BlockDecl>(DC); DC = cast<BlockDecl>(DC)->getDeclContext())
  248. ;
  249. QualType thisType;
  250. if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC))
  251. thisType = C.getPointerType(C.getRecordType(RD));
  252. else
  253. thisType = cast<CXXMethodDecl>(DC)->getThisType(C);
  254. llvm::Type *llvmType = CGM.getTypes().ConvertType(thisType);
  255. std::pair<CharUnits,CharUnits> tinfo
  256. = CGM.getContext().getTypeInfoInChars(thisType);
  257. maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
  258. layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first, 0, llvmType));
  259. }
  260. // Next, all the block captures.
  261. for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
  262. ce = block->capture_end(); ci != ce; ++ci) {
  263. const VarDecl *variable = ci->getVariable();
  264. if (ci->isByRef()) {
  265. // We have to copy/dispose of the __block reference.
  266. info.NeedsCopyDispose = true;
  267. // Just use void* instead of a pointer to the byref type.
  268. QualType byRefPtrTy = C.VoidPtrTy;
  269. llvm::Type *llvmType = CGM.getTypes().ConvertType(byRefPtrTy);
  270. std::pair<CharUnits,CharUnits> tinfo
  271. = CGM.getContext().getTypeInfoInChars(byRefPtrTy);
  272. maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
  273. layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first,
  274. &*ci, llvmType));
  275. continue;
  276. }
  277. // Otherwise, build a layout chunk with the size and alignment of
  278. // the declaration.
  279. if (llvm::Constant *constant = tryCaptureAsConstant(CGM, variable)) {
  280. info.Captures[variable] = CGBlockInfo::Capture::makeConstant(constant);
  281. continue;
  282. }
  283. // If we have a lifetime qualifier, honor it for capture purposes.
  284. // That includes *not* copying it if it's __unsafe_unretained.
  285. if (Qualifiers::ObjCLifetime lifetime
  286. = variable->getType().getObjCLifetime()) {
  287. switch (lifetime) {
  288. case Qualifiers::OCL_None: llvm_unreachable("impossible");
  289. case Qualifiers::OCL_ExplicitNone:
  290. case Qualifiers::OCL_Autoreleasing:
  291. break;
  292. case Qualifiers::OCL_Strong:
  293. case Qualifiers::OCL_Weak:
  294. info.NeedsCopyDispose = true;
  295. }
  296. // Block pointers require copy/dispose. So do Objective-C pointers.
  297. } else if (variable->getType()->isObjCRetainableType()) {
  298. info.NeedsCopyDispose = true;
  299. // So do types that require non-trivial copy construction.
  300. } else if (ci->hasCopyExpr()) {
  301. info.NeedsCopyDispose = true;
  302. info.HasCXXObject = true;
  303. // And so do types with destructors.
  304. } else if (CGM.getLangOptions().CPlusPlus) {
  305. if (const CXXRecordDecl *record =
  306. variable->getType()->getAsCXXRecordDecl()) {
  307. if (!record->hasTrivialDestructor()) {
  308. info.HasCXXObject = true;
  309. info.NeedsCopyDispose = true;
  310. }
  311. }
  312. }
  313. CharUnits size = C.getTypeSizeInChars(variable->getType());
  314. CharUnits align = C.getDeclAlign(variable);
  315. maxFieldAlign = std::max(maxFieldAlign, align);
  316. llvm::Type *llvmType =
  317. CGM.getTypes().ConvertTypeForMem(variable->getType());
  318. layout.push_back(BlockLayoutChunk(align, size, &*ci, llvmType));
  319. }
  320. // If that was everything, we're done here.
  321. if (layout.empty()) {
  322. info.StructureType =
  323. llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
  324. info.CanBeGlobal = true;
  325. return;
  326. }
  327. // Sort the layout by alignment. We have to use a stable sort here
  328. // to get reproducible results. There should probably be an
  329. // llvm::array_pod_stable_sort.
  330. std::stable_sort(layout.begin(), layout.end());
  331. CharUnits &blockSize = info.BlockSize;
  332. info.BlockAlign = std::max(maxFieldAlign, info.BlockAlign);
  333. // Assuming that the first byte in the header is maximally aligned,
  334. // get the alignment of the first byte following the header.
  335. CharUnits endAlign = getLowBit(blockSize);
  336. // If the end of the header isn't satisfactorily aligned for the
  337. // maximum thing, look for things that are okay with the header-end
  338. // alignment, and keep appending them until we get something that's
  339. // aligned right. This algorithm is only guaranteed optimal if
  340. // that condition is satisfied at some point; otherwise we can get
  341. // things like:
  342. // header // next byte has alignment 4
  343. // something_with_size_5; // next byte has alignment 1
  344. // something_with_alignment_8;
  345. // which has 7 bytes of padding, as opposed to the naive solution
  346. // which might have less (?).
  347. if (endAlign < maxFieldAlign) {
  348. SmallVectorImpl<BlockLayoutChunk>::iterator
  349. li = layout.begin() + 1, le = layout.end();
  350. // Look for something that the header end is already
  351. // satisfactorily aligned for.
  352. for (; li != le && endAlign < li->Alignment; ++li)
  353. ;
  354. // If we found something that's naturally aligned for the end of
  355. // the header, keep adding things...
  356. if (li != le) {
  357. SmallVectorImpl<BlockLayoutChunk>::iterator first = li;
  358. for (; li != le; ++li) {
  359. assert(endAlign >= li->Alignment);
  360. li->setIndex(info, elementTypes.size());
  361. elementTypes.push_back(li->Type);
  362. blockSize += li->Size;
  363. endAlign = getLowBit(blockSize);
  364. // ...until we get to the alignment of the maximum field.
  365. if (endAlign >= maxFieldAlign)
  366. break;
  367. }
  368. // Don't re-append everything we just appended.
  369. layout.erase(first, li);
  370. }
  371. }
  372. // At this point, we just have to add padding if the end align still
  373. // isn't aligned right.
  374. if (endAlign < maxFieldAlign) {
  375. CharUnits padding = maxFieldAlign - endAlign;
  376. elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
  377. padding.getQuantity()));
  378. blockSize += padding;
  379. endAlign = getLowBit(blockSize);
  380. assert(endAlign >= maxFieldAlign);
  381. }
  382. // Slam everything else on now. This works because they have
  383. // strictly decreasing alignment and we expect that size is always a
  384. // multiple of alignment.
  385. for (SmallVectorImpl<BlockLayoutChunk>::iterator
  386. li = layout.begin(), le = layout.end(); li != le; ++li) {
  387. assert(endAlign >= li->Alignment);
  388. li->setIndex(info, elementTypes.size());
  389. elementTypes.push_back(li->Type);
  390. blockSize += li->Size;
  391. endAlign = getLowBit(blockSize);
  392. }
  393. info.StructureType =
  394. llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
  395. }
  396. /// Emit a block literal expression in the current function.
  397. llvm::Value *CodeGenFunction::EmitBlockLiteral(const BlockExpr *blockExpr) {
  398. std::string Name = CurFn->getName();
  399. CGBlockInfo blockInfo(blockExpr, Name.c_str());
  400. // Compute information about the layout, etc., of this block.
  401. computeBlockInfo(CGM, blockInfo);
  402. // Using that metadata, generate the actual block function.
  403. llvm::Constant *blockFn
  404. = CodeGenFunction(CGM).GenerateBlockFunction(CurGD, blockInfo,
  405. CurFuncDecl, LocalDeclMap);
  406. blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
  407. // If there is nothing to capture, we can emit this as a global block.
  408. if (blockInfo.CanBeGlobal)
  409. return buildGlobalBlock(CGM, blockInfo, blockFn);
  410. // Otherwise, we have to emit this as a local block.
  411. llvm::Constant *isa = CGM.getNSConcreteStackBlock();
  412. isa = llvm::ConstantExpr::getBitCast(isa, VoidPtrTy);
  413. // Build the block descriptor.
  414. llvm::Constant *descriptor = buildBlockDescriptor(CGM, blockInfo);
  415. llvm::Type *intTy = ConvertType(getContext().IntTy);
  416. llvm::AllocaInst *blockAddr =
  417. CreateTempAlloca(blockInfo.StructureType, "block");
  418. blockAddr->setAlignment(blockInfo.BlockAlign.getQuantity());
  419. // Compute the initial on-stack block flags.
  420. BlockFlags flags = BLOCK_HAS_SIGNATURE;
  421. if (blockInfo.NeedsCopyDispose) flags |= BLOCK_HAS_COPY_DISPOSE;
  422. if (blockInfo.HasCXXObject) flags |= BLOCK_HAS_CXX_OBJ;
  423. if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
  424. // Initialize the block literal.
  425. Builder.CreateStore(isa, Builder.CreateStructGEP(blockAddr, 0, "block.isa"));
  426. Builder.CreateStore(llvm::ConstantInt::get(intTy, flags.getBitMask()),
  427. Builder.CreateStructGEP(blockAddr, 1, "block.flags"));
  428. Builder.CreateStore(llvm::ConstantInt::get(intTy, 0),
  429. Builder.CreateStructGEP(blockAddr, 2, "block.reserved"));
  430. Builder.CreateStore(blockFn, Builder.CreateStructGEP(blockAddr, 3,
  431. "block.invoke"));
  432. Builder.CreateStore(descriptor, Builder.CreateStructGEP(blockAddr, 4,
  433. "block.descriptor"));
  434. // Finally, capture all the values into the block.
  435. const BlockDecl *blockDecl = blockInfo.getBlockDecl();
  436. // First, 'this'.
  437. if (blockDecl->capturesCXXThis()) {
  438. llvm::Value *addr = Builder.CreateStructGEP(blockAddr,
  439. blockInfo.CXXThisIndex,
  440. "block.captured-this.addr");
  441. Builder.CreateStore(LoadCXXThis(), addr);
  442. }
  443. // Next, captured variables.
  444. for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
  445. ce = blockDecl->capture_end(); ci != ce; ++ci) {
  446. const VarDecl *variable = ci->getVariable();
  447. const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
  448. // Ignore constant captures.
  449. if (capture.isConstant()) continue;
  450. QualType type = variable->getType();
  451. // This will be a [[type]]*, except that a byref entry will just be
  452. // an i8**.
  453. llvm::Value *blockField =
  454. Builder.CreateStructGEP(blockAddr, capture.getIndex(),
  455. "block.captured");
  456. // Compute the address of the thing we're going to move into the
  457. // block literal.
  458. llvm::Value *src;
  459. if (ci->isNested()) {
  460. // We need to use the capture from the enclosing block.
  461. const CGBlockInfo::Capture &enclosingCapture =
  462. BlockInfo->getCapture(variable);
  463. // This is a [[type]]*, except that a byref entry wil just be an i8**.
  464. src = Builder.CreateStructGEP(LoadBlockStruct(),
  465. enclosingCapture.getIndex(),
  466. "block.capture.addr");
  467. } else {
  468. // This is a [[type]]*.
  469. src = LocalDeclMap[variable];
  470. }
  471. // For byrefs, we just write the pointer to the byref struct into
  472. // the block field. There's no need to chase the forwarding
  473. // pointer at this point, since we're building something that will
  474. // live a shorter life than the stack byref anyway.
  475. if (ci->isByRef()) {
  476. // Get a void* that points to the byref struct.
  477. if (ci->isNested())
  478. src = Builder.CreateLoad(src, "byref.capture");
  479. else
  480. src = Builder.CreateBitCast(src, VoidPtrTy);
  481. // Write that void* into the capture field.
  482. Builder.CreateStore(src, blockField);
  483. // If we have a copy constructor, evaluate that into the block field.
  484. } else if (const Expr *copyExpr = ci->getCopyExpr()) {
  485. EmitSynthesizedCXXCopyCtor(blockField, src, copyExpr);
  486. // If it's a reference variable, copy the reference into the block field.
  487. } else if (type->isReferenceType()) {
  488. Builder.CreateStore(Builder.CreateLoad(src, "ref.val"), blockField);
  489. // Otherwise, fake up a POD copy into the block field.
  490. } else {
  491. // Fake up a new variable so that EmitScalarInit doesn't think
  492. // we're referring to the variable in its own initializer.
  493. ImplicitParamDecl blockFieldPseudoVar(/*DC*/ 0, SourceLocation(),
  494. /*name*/ 0, type);
  495. // We use one of these or the other depending on whether the
  496. // reference is nested.
  497. DeclRefExpr notNested(const_cast<VarDecl*>(variable), type, VK_LValue,
  498. SourceLocation());
  499. BlockDeclRefExpr nested(const_cast<VarDecl*>(variable), type,
  500. VK_LValue, SourceLocation(), /*byref*/ false);
  501. Expr *declRef =
  502. (ci->isNested() ? static_cast<Expr*>(&nested) : &notNested);
  503. ImplicitCastExpr l2r(ImplicitCastExpr::OnStack, type, CK_LValueToRValue,
  504. declRef, VK_RValue);
  505. EmitExprAsInit(&l2r, &blockFieldPseudoVar,
  506. LValue::MakeAddr(blockField, type,
  507. getContext().getDeclAlign(variable)
  508. .getQuantity(),
  509. getContext()),
  510. /*captured by init*/ false);
  511. }
  512. // Push a destructor if necessary. The semantics for when this
  513. // actually gets run are really obscure.
  514. if (!ci->isByRef()) {
  515. switch (QualType::DestructionKind dtorKind = type.isDestructedType()) {
  516. case QualType::DK_none:
  517. break;
  518. // Block captures count as local values and have imprecise semantics.
  519. // They also can't be arrays, so need to worry about that.
  520. case QualType::DK_objc_strong_lifetime: {
  521. // This local is a GCC and MSVC compiler workaround.
  522. Destroyer *destroyer = &destroyARCStrongImprecise;
  523. pushDestroy(getCleanupKind(dtorKind), blockField, type,
  524. *destroyer, /*useEHCleanupForArray*/ false);
  525. break;
  526. }
  527. case QualType::DK_objc_weak_lifetime:
  528. case QualType::DK_cxx_destructor:
  529. pushDestroy(dtorKind, blockField, type);
  530. break;
  531. }
  532. }
  533. }
  534. // Cast to the converted block-pointer type, which happens (somewhat
  535. // unfortunately) to be a pointer to function type.
  536. llvm::Value *result =
  537. Builder.CreateBitCast(blockAddr,
  538. ConvertType(blockInfo.getBlockExpr()->getType()));
  539. return result;
  540. }
  541. llvm::Type *CodeGenModule::getBlockDescriptorType() {
  542. if (BlockDescriptorType)
  543. return BlockDescriptorType;
  544. llvm::Type *UnsignedLongTy =
  545. getTypes().ConvertType(getContext().UnsignedLongTy);
  546. // struct __block_descriptor {
  547. // unsigned long reserved;
  548. // unsigned long block_size;
  549. //
  550. // // later, the following will be added
  551. //
  552. // struct {
  553. // void (*copyHelper)();
  554. // void (*copyHelper)();
  555. // } helpers; // !!! optional
  556. //
  557. // const char *signature; // the block signature
  558. // const char *layout; // reserved
  559. // };
  560. BlockDescriptorType =
  561. llvm::StructType::create("struct.__block_descriptor",
  562. UnsignedLongTy, UnsignedLongTy, NULL);
  563. // Now form a pointer to that.
  564. BlockDescriptorType = llvm::PointerType::getUnqual(BlockDescriptorType);
  565. return BlockDescriptorType;
  566. }
  567. llvm::Type *CodeGenModule::getGenericBlockLiteralType() {
  568. if (GenericBlockLiteralType)
  569. return GenericBlockLiteralType;
  570. llvm::Type *BlockDescPtrTy = getBlockDescriptorType();
  571. // struct __block_literal_generic {
  572. // void *__isa;
  573. // int __flags;
  574. // int __reserved;
  575. // void (*__invoke)(void *);
  576. // struct __block_descriptor *__descriptor;
  577. // };
  578. GenericBlockLiteralType =
  579. llvm::StructType::create("struct.__block_literal_generic",
  580. VoidPtrTy, IntTy, IntTy, VoidPtrTy,
  581. BlockDescPtrTy, NULL);
  582. return GenericBlockLiteralType;
  583. }
  584. RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr* E,
  585. ReturnValueSlot ReturnValue) {
  586. const BlockPointerType *BPT =
  587. E->getCallee()->getType()->getAs<BlockPointerType>();
  588. llvm::Value *Callee = EmitScalarExpr(E->getCallee());
  589. // Get a pointer to the generic block literal.
  590. llvm::Type *BlockLiteralTy =
  591. llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
  592. // Bitcast the callee to a block literal.
  593. llvm::Value *BlockLiteral =
  594. Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal");
  595. // Get the function pointer from the literal.
  596. llvm::Value *FuncPtr = Builder.CreateStructGEP(BlockLiteral, 3, "tmp");
  597. BlockLiteral = Builder.CreateBitCast(BlockLiteral, VoidPtrTy, "tmp");
  598. // Add the block literal.
  599. CallArgList Args;
  600. Args.add(RValue::get(BlockLiteral), getContext().VoidPtrTy);
  601. QualType FnType = BPT->getPointeeType();
  602. // And the rest of the arguments.
  603. EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(),
  604. E->arg_begin(), E->arg_end());
  605. // Load the function.
  606. llvm::Value *Func = Builder.CreateLoad(FuncPtr, "tmp");
  607. const FunctionType *FuncTy = FnType->castAs<FunctionType>();
  608. const CGFunctionInfo &FnInfo = CGM.getTypes().getFunctionInfo(Args, FuncTy);
  609. // Cast the function pointer to the right type.
  610. llvm::Type *BlockFTy =
  611. CGM.getTypes().GetFunctionType(FnInfo, false);
  612. llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
  613. Func = Builder.CreateBitCast(Func, BlockFTyPtr);
  614. // And call the block.
  615. return EmitCall(FnInfo, Func, ReturnValue, Args);
  616. }
  617. llvm::Value *CodeGenFunction::GetAddrOfBlockDecl(const VarDecl *variable,
  618. bool isByRef) {
  619. assert(BlockInfo && "evaluating block ref without block information?");
  620. const CGBlockInfo::Capture &capture = BlockInfo->getCapture(variable);
  621. // Handle constant captures.
  622. if (capture.isConstant()) return LocalDeclMap[variable];
  623. llvm::Value *addr =
  624. Builder.CreateStructGEP(LoadBlockStruct(), capture.getIndex(),
  625. "block.capture.addr");
  626. if (isByRef) {
  627. // addr should be a void** right now. Load, then cast the result
  628. // to byref*.
  629. addr = Builder.CreateLoad(addr);
  630. llvm::PointerType *byrefPointerType
  631. = llvm::PointerType::get(BuildByRefType(variable), 0);
  632. addr = Builder.CreateBitCast(addr, byrefPointerType,
  633. "byref.addr");
  634. // Follow the forwarding pointer.
  635. addr = Builder.CreateStructGEP(addr, 1, "byref.forwarding");
  636. addr = Builder.CreateLoad(addr, "byref.addr.forwarded");
  637. // Cast back to byref* and GEP over to the actual object.
  638. addr = Builder.CreateBitCast(addr, byrefPointerType);
  639. addr = Builder.CreateStructGEP(addr, getByRefValueLLVMField(variable),
  640. variable->getNameAsString());
  641. }
  642. if (variable->getType()->isReferenceType())
  643. addr = Builder.CreateLoad(addr, "ref.tmp");
  644. return addr;
  645. }
  646. llvm::Constant *
  647. CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *blockExpr,
  648. const char *name) {
  649. CGBlockInfo blockInfo(blockExpr, name);
  650. // Compute information about the layout, etc., of this block.
  651. computeBlockInfo(*this, blockInfo);
  652. // Using that metadata, generate the actual block function.
  653. llvm::Constant *blockFn;
  654. {
  655. llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap;
  656. blockFn = CodeGenFunction(*this).GenerateBlockFunction(GlobalDecl(),
  657. blockInfo,
  658. 0, LocalDeclMap);
  659. }
  660. blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
  661. return buildGlobalBlock(*this, blockInfo, blockFn);
  662. }
  663. static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
  664. const CGBlockInfo &blockInfo,
  665. llvm::Constant *blockFn) {
  666. assert(blockInfo.CanBeGlobal);
  667. // Generate the constants for the block literal initializer.
  668. llvm::Constant *fields[BlockHeaderSize];
  669. // isa
  670. fields[0] = CGM.getNSConcreteGlobalBlock();
  671. // __flags
  672. BlockFlags flags = BLOCK_IS_GLOBAL | BLOCK_HAS_SIGNATURE;
  673. if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
  674. fields[1] = llvm::ConstantInt::get(CGM.IntTy, flags.getBitMask());
  675. // Reserved
  676. fields[2] = llvm::Constant::getNullValue(CGM.IntTy);
  677. // Function
  678. fields[3] = blockFn;
  679. // Descriptor
  680. fields[4] = buildBlockDescriptor(CGM, blockInfo);
  681. llvm::Constant *init = llvm::ConstantStruct::getAnon(fields);
  682. llvm::GlobalVariable *literal =
  683. new llvm::GlobalVariable(CGM.getModule(),
  684. init->getType(),
  685. /*constant*/ true,
  686. llvm::GlobalVariable::InternalLinkage,
  687. init,
  688. "__block_literal_global");
  689. literal->setAlignment(blockInfo.BlockAlign.getQuantity());
  690. // Return a constant of the appropriately-casted type.
  691. llvm::Type *requiredType =
  692. CGM.getTypes().ConvertType(blockInfo.getBlockExpr()->getType());
  693. return llvm::ConstantExpr::getBitCast(literal, requiredType);
  694. }
  695. llvm::Function *
  696. CodeGenFunction::GenerateBlockFunction(GlobalDecl GD,
  697. const CGBlockInfo &blockInfo,
  698. const Decl *outerFnDecl,
  699. const DeclMapTy &ldm) {
  700. const BlockDecl *blockDecl = blockInfo.getBlockDecl();
  701. // Check if we should generate debug info for this block function.
  702. if (CGM.getModuleDebugInfo())
  703. DebugInfo = CGM.getModuleDebugInfo();
  704. BlockInfo = &blockInfo;
  705. // Arrange for local static and local extern declarations to appear
  706. // to be local to this function as well, in case they're directly
  707. // referenced in a block.
  708. for (DeclMapTy::const_iterator i = ldm.begin(), e = ldm.end(); i != e; ++i) {
  709. const VarDecl *var = dyn_cast<VarDecl>(i->first);
  710. if (var && !var->hasLocalStorage())
  711. LocalDeclMap[var] = i->second;
  712. }
  713. // Begin building the function declaration.
  714. // Build the argument list.
  715. FunctionArgList args;
  716. // The first argument is the block pointer. Just take it as a void*
  717. // and cast it later.
  718. QualType selfTy = getContext().VoidPtrTy;
  719. IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
  720. ImplicitParamDecl selfDecl(const_cast<BlockDecl*>(blockDecl),
  721. SourceLocation(), II, selfTy);
  722. args.push_back(&selfDecl);
  723. // Now add the rest of the parameters.
  724. for (BlockDecl::param_const_iterator i = blockDecl->param_begin(),
  725. e = blockDecl->param_end(); i != e; ++i)
  726. args.push_back(*i);
  727. // Create the function declaration.
  728. const FunctionProtoType *fnType =
  729. cast<FunctionProtoType>(blockInfo.getBlockExpr()->getFunctionType());
  730. const CGFunctionInfo &fnInfo =
  731. CGM.getTypes().getFunctionInfo(fnType->getResultType(), args,
  732. fnType->getExtInfo());
  733. if (CGM.ReturnTypeUsesSRet(fnInfo))
  734. blockInfo.UsesStret = true;
  735. llvm::FunctionType *fnLLVMType =
  736. CGM.getTypes().GetFunctionType(fnInfo, fnType->isVariadic());
  737. MangleBuffer name;
  738. CGM.getBlockMangledName(GD, name, blockDecl);
  739. llvm::Function *fn =
  740. llvm::Function::Create(fnLLVMType, llvm::GlobalValue::InternalLinkage,
  741. name.getString(), &CGM.getModule());
  742. CGM.SetInternalFunctionAttributes(blockDecl, fn, fnInfo);
  743. // Begin generating the function.
  744. StartFunction(blockDecl, fnType->getResultType(), fn, fnInfo, args,
  745. blockInfo.getBlockExpr()->getBody()->getLocStart());
  746. CurFuncDecl = outerFnDecl; // StartFunction sets this to blockDecl
  747. // Okay. Undo some of what StartFunction did.
  748. // Pull the 'self' reference out of the local decl map.
  749. llvm::Value *blockAddr = LocalDeclMap[&selfDecl];
  750. LocalDeclMap.erase(&selfDecl);
  751. BlockPointer = Builder.CreateBitCast(blockAddr,
  752. blockInfo.StructureType->getPointerTo(),
  753. "block");
  754. // If we have a C++ 'this' reference, go ahead and force it into
  755. // existence now.
  756. if (blockDecl->capturesCXXThis()) {
  757. llvm::Value *addr = Builder.CreateStructGEP(BlockPointer,
  758. blockInfo.CXXThisIndex,
  759. "block.captured-this");
  760. CXXThisValue = Builder.CreateLoad(addr, "this");
  761. }
  762. // LoadObjCSelf() expects there to be an entry for 'self' in LocalDeclMap;
  763. // appease it.
  764. if (const ObjCMethodDecl *method
  765. = dyn_cast_or_null<ObjCMethodDecl>(CurFuncDecl)) {
  766. const VarDecl *self = method->getSelfDecl();
  767. // There might not be a capture for 'self', but if there is...
  768. if (blockInfo.Captures.count(self)) {
  769. const CGBlockInfo::Capture &capture = blockInfo.getCapture(self);
  770. llvm::Value *selfAddr = Builder.CreateStructGEP(BlockPointer,
  771. capture.getIndex(),
  772. "block.captured-self");
  773. LocalDeclMap[self] = selfAddr;
  774. }
  775. }
  776. // Also force all the constant captures.
  777. for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
  778. ce = blockDecl->capture_end(); ci != ce; ++ci) {
  779. const VarDecl *variable = ci->getVariable();
  780. const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
  781. if (!capture.isConstant()) continue;
  782. unsigned align = getContext().getDeclAlign(variable).getQuantity();
  783. llvm::AllocaInst *alloca =
  784. CreateMemTemp(variable->getType(), "block.captured-const");
  785. alloca->setAlignment(align);
  786. Builder.CreateStore(capture.getConstant(), alloca, align);
  787. LocalDeclMap[variable] = alloca;
  788. }
  789. // Save a spot to insert the debug information for all the BlockDeclRefDecls.
  790. llvm::BasicBlock *entry = Builder.GetInsertBlock();
  791. llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
  792. --entry_ptr;
  793. EmitStmt(blockDecl->getBody());
  794. // Remember where we were...
  795. llvm::BasicBlock *resume = Builder.GetInsertBlock();
  796. // Go back to the entry.
  797. ++entry_ptr;
  798. Builder.SetInsertPoint(entry, entry_ptr);
  799. // Emit debug information for all the BlockDeclRefDecls.
  800. // FIXME: also for 'this'
  801. if (CGDebugInfo *DI = getDebugInfo()) {
  802. for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
  803. ce = blockDecl->capture_end(); ci != ce; ++ci) {
  804. const VarDecl *variable = ci->getVariable();
  805. DI->setLocation(variable->getLocation());
  806. const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
  807. if (capture.isConstant()) {
  808. DI->EmitDeclareOfAutoVariable(variable, LocalDeclMap[variable],
  809. Builder);
  810. continue;
  811. }
  812. DI->EmitDeclareOfBlockDeclRefVariable(variable, BlockPointer,
  813. Builder, blockInfo);
  814. }
  815. }
  816. // And resume where we left off.
  817. if (resume == 0)
  818. Builder.ClearInsertionPoint();
  819. else
  820. Builder.SetInsertPoint(resume);
  821. FinishFunction(cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
  822. return fn;
  823. }
  824. /*
  825. notes.push_back(HelperInfo());
  826. HelperInfo &note = notes.back();
  827. note.index = capture.getIndex();
  828. note.RequiresCopying = (ci->hasCopyExpr() || BlockRequiresCopying(type));
  829. note.cxxbar_import = ci->getCopyExpr();
  830. if (ci->isByRef()) {
  831. note.flag = BLOCK_FIELD_IS_BYREF;
  832. if (type.isObjCGCWeak())
  833. note.flag |= BLOCK_FIELD_IS_WEAK;
  834. } else if (type->isBlockPointerType()) {
  835. note.flag = BLOCK_FIELD_IS_BLOCK;
  836. } else {
  837. note.flag = BLOCK_FIELD_IS_OBJECT;
  838. }
  839. */
  840. llvm::Constant *
  841. CodeGenFunction::GenerateCopyHelperFunction(const CGBlockInfo &blockInfo) {
  842. ASTContext &C = getContext();
  843. FunctionArgList args;
  844. ImplicitParamDecl dstDecl(0, SourceLocation(), 0, C.VoidPtrTy);
  845. args.push_back(&dstDecl);
  846. ImplicitParamDecl srcDecl(0, SourceLocation(), 0, C.VoidPtrTy);
  847. args.push_back(&srcDecl);
  848. const CGFunctionInfo &FI =
  849. CGM.getTypes().getFunctionInfo(C.VoidTy, args, FunctionType::ExtInfo());
  850. // FIXME: it would be nice if these were mergeable with things with
  851. // identical semantics.
  852. llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI, false);
  853. llvm::Function *Fn =
  854. llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
  855. "__copy_helper_block_", &CGM.getModule());
  856. IdentifierInfo *II
  857. = &CGM.getContext().Idents.get("__copy_helper_block_");
  858. // Check if we should generate debug info for this block helper function.
  859. if (CGM.getModuleDebugInfo())
  860. DebugInfo = CGM.getModuleDebugInfo();
  861. FunctionDecl *FD = FunctionDecl::Create(C,
  862. C.getTranslationUnitDecl(),
  863. SourceLocation(),
  864. SourceLocation(), II, C.VoidTy, 0,
  865. SC_Static,
  866. SC_None,
  867. false,
  868. true);
  869. StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
  870. llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
  871. llvm::Value *src = GetAddrOfLocalVar(&srcDecl);
  872. src = Builder.CreateLoad(src);
  873. src = Builder.CreateBitCast(src, structPtrTy, "block.source");
  874. llvm::Value *dst = GetAddrOfLocalVar(&dstDecl);
  875. dst = Builder.CreateLoad(dst);
  876. dst = Builder.CreateBitCast(dst, structPtrTy, "block.dest");
  877. const BlockDecl *blockDecl = blockInfo.getBlockDecl();
  878. for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
  879. ce = blockDecl->capture_end(); ci != ce; ++ci) {
  880. const VarDecl *variable = ci->getVariable();
  881. QualType type = variable->getType();
  882. const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
  883. if (capture.isConstant()) continue;
  884. const Expr *copyExpr = ci->getCopyExpr();
  885. BlockFieldFlags flags;
  886. bool isARCWeakCapture = false;
  887. if (copyExpr) {
  888. assert(!ci->isByRef());
  889. // don't bother computing flags
  890. } else if (ci->isByRef()) {
  891. flags = BLOCK_FIELD_IS_BYREF;
  892. if (type.isObjCGCWeak())
  893. flags |= BLOCK_FIELD_IS_WEAK;
  894. } else if (type->isObjCRetainableType()) {
  895. flags = BLOCK_FIELD_IS_OBJECT;
  896. if (type->isBlockPointerType())
  897. flags = BLOCK_FIELD_IS_BLOCK;
  898. // Special rules for ARC captures:
  899. if (getLangOptions().ObjCAutoRefCount) {
  900. Qualifiers qs = type.getQualifiers();
  901. // Don't generate special copy logic for a captured object
  902. // unless it's __strong or __weak.
  903. if (!qs.hasStrongOrWeakObjCLifetime())
  904. continue;
  905. // Support __weak direct captures.
  906. if (qs.getObjCLifetime() == Qualifiers::OCL_Weak)
  907. isARCWeakCapture = true;
  908. }
  909. } else {
  910. continue;
  911. }
  912. unsigned index = capture.getIndex();
  913. llvm::Value *srcField = Builder.CreateStructGEP(src, index);
  914. llvm::Value *dstField = Builder.CreateStructGEP(dst, index);
  915. // If there's an explicit copy expression, we do that.
  916. if (copyExpr) {
  917. EmitSynthesizedCXXCopyCtor(dstField, srcField, copyExpr);
  918. } else if (isARCWeakCapture) {
  919. EmitARCCopyWeak(dstField, srcField);
  920. } else {
  921. llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
  922. srcValue = Builder.CreateBitCast(srcValue, VoidPtrTy);
  923. llvm::Value *dstAddr = Builder.CreateBitCast(dstField, VoidPtrTy);
  924. Builder.CreateCall3(CGM.getBlockObjectAssign(), dstAddr, srcValue,
  925. llvm::ConstantInt::get(Int32Ty, flags.getBitMask()));
  926. }
  927. }
  928. FinishFunction();
  929. return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
  930. }
  931. llvm::Constant *
  932. CodeGenFunction::GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo) {
  933. ASTContext &C = getContext();
  934. FunctionArgList args;
  935. ImplicitParamDecl srcDecl(0, SourceLocation(), 0, C.VoidPtrTy);
  936. args.push_back(&srcDecl);
  937. const CGFunctionInfo &FI =
  938. CGM.getTypes().getFunctionInfo(C.VoidTy, args, FunctionType::ExtInfo());
  939. // FIXME: We'd like to put these into a mergable by content, with
  940. // internal linkage.
  941. llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI, false);
  942. llvm::Function *Fn =
  943. llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
  944. "__destroy_helper_block_", &CGM.getModule());
  945. // Check if we should generate debug info for this block destroy function.
  946. if (CGM.getModuleDebugInfo())
  947. DebugInfo = CGM.getModuleDebugInfo();
  948. IdentifierInfo *II
  949. = &CGM.getContext().Idents.get("__destroy_helper_block_");
  950. FunctionDecl *FD = FunctionDecl::Create(C, C.getTranslationUnitDecl(),
  951. SourceLocation(),
  952. SourceLocation(), II, C.VoidTy, 0,
  953. SC_Static,
  954. SC_None,
  955. false, true);
  956. StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
  957. llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
  958. llvm::Value *src = GetAddrOfLocalVar(&srcDecl);
  959. src = Builder.CreateLoad(src);
  960. src = Builder.CreateBitCast(src, structPtrTy, "block");
  961. const BlockDecl *blockDecl = blockInfo.getBlockDecl();
  962. CodeGenFunction::RunCleanupsScope cleanups(*this);
  963. for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
  964. ce = blockDecl->capture_end(); ci != ce; ++ci) {
  965. const VarDecl *variable = ci->getVariable();
  966. QualType type = variable->getType();
  967. const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
  968. if (capture.isConstant()) continue;
  969. BlockFieldFlags flags;
  970. const CXXDestructorDecl *dtor = 0;
  971. bool isARCWeakCapture = false;
  972. if (ci->isByRef()) {
  973. flags = BLOCK_FIELD_IS_BYREF;
  974. if (type.isObjCGCWeak())
  975. flags |= BLOCK_FIELD_IS_WEAK;
  976. } else if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
  977. if (record->hasTrivialDestructor())
  978. continue;
  979. dtor = record->getDestructor();
  980. } else if (type->isObjCRetainableType()) {
  981. flags = BLOCK_FIELD_IS_OBJECT;
  982. if (type->isBlockPointerType())
  983. flags = BLOCK_FIELD_IS_BLOCK;
  984. // Special rules for ARC captures.
  985. if (getLangOptions().ObjCAutoRefCount) {
  986. Qualifiers qs = type.getQualifiers();
  987. // Don't generate special dispose logic for a captured object
  988. // unless it's __strong or __weak.
  989. if (!qs.hasStrongOrWeakObjCLifetime())
  990. continue;
  991. // Support __weak direct captures.
  992. if (qs.getObjCLifetime() == Qualifiers::OCL_Weak)
  993. isARCWeakCapture = true;
  994. }
  995. } else {
  996. continue;
  997. }
  998. unsigned index = capture.getIndex();
  999. llvm::Value *srcField = Builder.CreateStructGEP(src, index);
  1000. // If there's an explicit copy expression, we do that.
  1001. if (dtor) {
  1002. PushDestructorCleanup(dtor, srcField);
  1003. // If this is a __weak capture, emit the release directly.
  1004. } else if (isARCWeakCapture) {
  1005. EmitARCDestroyWeak(srcField);
  1006. // Otherwise we call _Block_object_dispose. It wouldn't be too
  1007. // hard to just emit this as a cleanup if we wanted to make sure
  1008. // that things were done in reverse.
  1009. } else {
  1010. llvm::Value *value = Builder.CreateLoad(srcField);
  1011. value = Builder.CreateBitCast(value, VoidPtrTy);
  1012. BuildBlockRelease(value, flags);
  1013. }
  1014. }
  1015. cleanups.ForceCleanup();
  1016. FinishFunction();
  1017. return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
  1018. }
  1019. namespace {
  1020. /// Emits the copy/dispose helper functions for a __block object of id type.
  1021. class ObjectByrefHelpers : public CodeGenModule::ByrefHelpers {
  1022. BlockFieldFlags Flags;
  1023. public:
  1024. ObjectByrefHelpers(CharUnits alignment, BlockFieldFlags flags)
  1025. : ByrefHelpers(alignment), Flags(flags) {}
  1026. void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
  1027. llvm::Value *srcField) {
  1028. destField = CGF.Builder.CreateBitCast(destField, CGF.VoidPtrTy);
  1029. srcField = CGF.Builder.CreateBitCast(srcField, CGF.VoidPtrPtrTy);
  1030. llvm::Value *srcValue = CGF.Builder.CreateLoad(srcField);
  1031. unsigned flags = (Flags | BLOCK_BYREF_CALLER).getBitMask();
  1032. llvm::Value *flagsVal = llvm::ConstantInt::get(CGF.Int32Ty, flags);
  1033. llvm::Value *fn = CGF.CGM.getBlockObjectAssign();
  1034. CGF.Builder.CreateCall3(fn, destField, srcValue, flagsVal);
  1035. }
  1036. void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
  1037. field = CGF.Builder.CreateBitCast(field, CGF.Int8PtrTy->getPointerTo(0));
  1038. llvm::Value *value = CGF.Builder.CreateLoad(field);
  1039. CGF.BuildBlockRelease(value, Flags | BLOCK_BYREF_CALLER);
  1040. }
  1041. void profileImpl(llvm::FoldingSetNodeID &id) const {
  1042. id.AddInteger(Flags.getBitMask());
  1043. }
  1044. };
  1045. /// Emits the copy/dispose helpers for an ARC __block __weak variable.
  1046. class ARCWeakByrefHelpers : public CodeGenModule::ByrefHelpers {
  1047. public:
  1048. ARCWeakByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
  1049. void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
  1050. llvm::Value *srcField) {
  1051. CGF.EmitARCMoveWeak(destField, srcField);
  1052. }
  1053. void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
  1054. CGF.EmitARCDestroyWeak(field);
  1055. }
  1056. void profileImpl(llvm::FoldingSetNodeID &id) const {
  1057. // 0 is distinguishable from all pointers and byref flags
  1058. id.AddInteger(0);
  1059. }
  1060. };
  1061. /// Emits the copy/dispose helpers for an ARC __block __strong variable
  1062. /// that's not of block-pointer type.
  1063. class ARCStrongByrefHelpers : public CodeGenModule::ByrefHelpers {
  1064. public:
  1065. ARCStrongByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
  1066. void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
  1067. llvm::Value *srcField) {
  1068. // Do a "move" by copying the value and then zeroing out the old
  1069. // variable.
  1070. llvm::Value *value = CGF.Builder.CreateLoad(srcField);
  1071. llvm::Value *null =
  1072. llvm::ConstantPointerNull::get(cast<llvm::PointerType>(value->getType()));
  1073. CGF.Builder.CreateStore(value, destField);
  1074. CGF.Builder.CreateStore(null, srcField);
  1075. }
  1076. void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
  1077. llvm::Value *value = CGF.Builder.CreateLoad(field);
  1078. CGF.EmitARCRelease(value, /*precise*/ false);
  1079. }
  1080. void profileImpl(llvm::FoldingSetNodeID &id) const {
  1081. // 1 is distinguishable from all pointers and byref flags
  1082. id.AddInteger(1);
  1083. }
  1084. };
  1085. /// Emits the copy/dispose helpers for a __block variable with a
  1086. /// nontrivial copy constructor or destructor.
  1087. class CXXByrefHelpers : public CodeGenModule::ByrefHelpers {
  1088. QualType VarType;
  1089. const Expr *CopyExpr;
  1090. public:
  1091. CXXByrefHelpers(CharUnits alignment, QualType type,
  1092. const Expr *copyExpr)
  1093. : ByrefHelpers(alignment), VarType(type), CopyExpr(copyExpr) {}
  1094. bool needsCopy() const { return CopyExpr != 0; }
  1095. void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
  1096. llvm::Value *srcField) {
  1097. if (!CopyExpr) return;
  1098. CGF.EmitSynthesizedCXXCopyCtor(destField, srcField, CopyExpr);
  1099. }
  1100. void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
  1101. EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin();
  1102. CGF.PushDestructorCleanup(VarType, field);
  1103. CGF.PopCleanupBlocks(cleanupDepth);
  1104. }
  1105. void profileImpl(llvm::FoldingSetNodeID &id) const {
  1106. id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr());
  1107. }
  1108. };
  1109. } // end anonymous namespace
  1110. static llvm::Constant *
  1111. generateByrefCopyHelper(CodeGenFunction &CGF,
  1112. llvm::StructType &byrefType,
  1113. CodeGenModule::ByrefHelpers &byrefInfo) {
  1114. ASTContext &Context = CGF.getContext();
  1115. QualType R = Context.VoidTy;
  1116. FunctionArgList args;
  1117. ImplicitParamDecl dst(0, SourceLocation(), 0, Context.VoidPtrTy);
  1118. args.push_back(&dst);
  1119. ImplicitParamDecl src(0, SourceLocation(), 0, Context.VoidPtrTy);
  1120. args.push_back(&src);
  1121. const CGFunctionInfo &FI =
  1122. CGF.CGM.getTypes().getFunctionInfo(R, args, FunctionType::ExtInfo());
  1123. CodeGenTypes &Types = CGF.CGM.getTypes();
  1124. llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
  1125. // FIXME: We'd like to put these into a mergable by content, with
  1126. // internal linkage.
  1127. llvm::Function *Fn =
  1128. llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
  1129. "__Block_byref_object_copy_", &CGF.CGM.getModule());
  1130. IdentifierInfo *II
  1131. = &Context.Idents.get("__Block_byref_object_copy_");
  1132. FunctionDecl *FD = FunctionDecl::Create(Context,
  1133. Context.getTranslationUnitDecl(),
  1134. SourceLocation(),
  1135. SourceLocation(), II, R, 0,
  1136. SC_Static,
  1137. SC_None,
  1138. false, true);
  1139. CGF.StartFunction(FD, R, Fn, FI, args, SourceLocation());
  1140. if (byrefInfo.needsCopy()) {
  1141. llvm::Type *byrefPtrType = byrefType.getPointerTo(0);
  1142. // dst->x
  1143. llvm::Value *destField = CGF.GetAddrOfLocalVar(&dst);
  1144. destField = CGF.Builder.CreateLoad(destField);
  1145. destField = CGF.Builder.CreateBitCast(destField, byrefPtrType);
  1146. destField = CGF.Builder.CreateStructGEP(destField, 6, "x");
  1147. // src->x
  1148. llvm::Value *srcField = CGF.GetAddrOfLocalVar(&src);
  1149. srcField = CGF.Builder.CreateLoad(srcField);
  1150. srcField = CGF.Builder.CreateBitCast(srcField, byrefPtrType);
  1151. srcField = CGF.Builder.CreateStructGEP(srcField, 6, "x");
  1152. byrefInfo.emitCopy(CGF, destField, srcField);
  1153. }
  1154. CGF.FinishFunction();
  1155. return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
  1156. }
  1157. /// Build the copy helper for a __block variable.
  1158. static llvm::Constant *buildByrefCopyHelper(CodeGenModule &CGM,
  1159. llvm::StructType &byrefType,
  1160. CodeGenModule::ByrefHelpers &info) {
  1161. CodeGenFunction CGF(CGM);
  1162. return generateByrefCopyHelper(CGF, byrefType, info);
  1163. }
  1164. /// Generate code for a __block variable's dispose helper.
  1165. static llvm::Constant *
  1166. generateByrefDisposeHelper(CodeGenFunction &CGF,
  1167. llvm::StructType &byrefType,
  1168. CodeGenModule::ByrefHelpers &byrefInfo) {
  1169. ASTContext &Context = CGF.getContext();
  1170. QualType R = Context.VoidTy;
  1171. FunctionArgList args;
  1172. ImplicitParamDecl src(0, SourceLocation(), 0, Context.VoidPtrTy);
  1173. args.push_back(&src);
  1174. const CGFunctionInfo &FI =
  1175. CGF.CGM.getTypes().getFunctionInfo(R, args, FunctionType::ExtInfo());
  1176. CodeGenTypes &Types = CGF.CGM.getTypes();
  1177. llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
  1178. // FIXME: We'd like to put these into a mergable by content, with
  1179. // internal linkage.
  1180. llvm::Function *Fn =
  1181. llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
  1182. "__Block_byref_object_dispose_",
  1183. &CGF.CGM.getModule());
  1184. IdentifierInfo *II
  1185. = &Context.Idents.get("__Block_byref_object_dispose_");
  1186. FunctionDecl *FD = FunctionDecl::Create(Context,
  1187. Context.getTranslationUnitDecl(),
  1188. SourceLocation(),
  1189. SourceLocation(), II, R, 0,
  1190. SC_Static,
  1191. SC_None,
  1192. false, true);
  1193. CGF.StartFunction(FD, R, Fn, FI, args, SourceLocation());
  1194. if (byrefInfo.needsDispose()) {
  1195. llvm::Value *V = CGF.GetAddrOfLocalVar(&src);
  1196. V = CGF.Builder.CreateLoad(V);
  1197. V = CGF.Builder.CreateBitCast(V, byrefType.getPointerTo(0));
  1198. V = CGF.Builder.CreateStructGEP(V, 6, "x");
  1199. byrefInfo.emitDispose(CGF, V);
  1200. }
  1201. CGF.FinishFunction();
  1202. return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
  1203. }
  1204. /// Build the dispose helper for a __block variable.
  1205. static llvm::Constant *buildByrefDisposeHelper(CodeGenModule &CGM,
  1206. llvm::StructType &byrefType,
  1207. CodeGenModule::ByrefHelpers &info) {
  1208. CodeGenFunction CGF(CGM);
  1209. return generateByrefDisposeHelper(CGF, byrefType, info);
  1210. }
  1211. ///
  1212. template <class T> static T *buildByrefHelpers(CodeGenModule &CGM,
  1213. llvm::StructType &byrefTy,
  1214. T &byrefInfo) {
  1215. // Increase the field's alignment to be at least pointer alignment,
  1216. // since the layout of the byref struct will guarantee at least that.
  1217. byrefInfo.Alignment = std::max(byrefInfo.Alignment,
  1218. CharUnits::fromQuantity(CGM.PointerAlignInBytes));
  1219. llvm::FoldingSetNodeID id;
  1220. byrefInfo.Profile(id);
  1221. void *insertPos;
  1222. CodeGenModule::ByrefHelpers *node
  1223. = CGM.ByrefHelpersCache.FindNodeOrInsertPos(id, insertPos);
  1224. if (node) return static_cast<T*>(node);
  1225. byrefInfo.CopyHelper = buildByrefCopyHelper(CGM, byrefTy, byrefInfo);
  1226. byrefInfo.DisposeHelper = buildByrefDisposeHelper(CGM, byrefTy, byrefInfo);
  1227. T *copy = new (CGM.getContext()) T(byrefInfo);
  1228. CGM.ByrefHelpersCache.InsertNode(copy, insertPos);
  1229. return copy;
  1230. }
  1231. CodeGenModule::ByrefHelpers *
  1232. CodeGenFunction::buildByrefHelpers(llvm::StructType &byrefType,
  1233. const AutoVarEmission &emission) {
  1234. const VarDecl &var = *emission.Variable;
  1235. QualType type = var.getType();
  1236. if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
  1237. const Expr *copyExpr = CGM.getContext().getBlockVarCopyInits(&var);
  1238. if (!copyExpr && record->hasTrivialDestructor()) return 0;
  1239. CXXByrefHelpers byrefInfo(emission.Alignment, type, copyExpr);
  1240. return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
  1241. }
  1242. // Otherwise, if we don't have a retainable type, there's nothing to do.
  1243. // that the runtime does extra copies.
  1244. if (!type->isObjCRetainableType()) return 0;
  1245. Qualifiers qs = type.getQualifiers();
  1246. // If we have lifetime, that dominates.
  1247. if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
  1248. assert(getLangOptions().ObjCAutoRefCount);
  1249. switch (lifetime) {
  1250. case Qualifiers::OCL_None: llvm_unreachable("impossible");
  1251. // These are just bits as far as the runtime is concerned.
  1252. case Qualifiers::OCL_ExplicitNone:
  1253. case Qualifiers::OCL_Autoreleasing:
  1254. return 0;
  1255. // Tell the runtime that this is ARC __weak, called by the
  1256. // byref routines.
  1257. case Qualifiers::OCL_Weak: {
  1258. ARCWeakByrefHelpers byrefInfo(emission.Alignment);
  1259. return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
  1260. }
  1261. // ARC __strong __block variables need to be retained.
  1262. case Qualifiers::OCL_Strong:
  1263. // Block-pointers need to be _Block_copy'ed, so we let the
  1264. // runtime be in charge. But we can't use the code below
  1265. // because we don't want to set BYREF_CALLER, which will
  1266. // just make the runtime ignore us.
  1267. if (type->isBlockPointerType()) {
  1268. BlockFieldFlags flags = BLOCK_FIELD_IS_BLOCK;
  1269. ObjectByrefHelpers byrefInfo(emission.Alignment, flags);
  1270. return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
  1271. // Otherwise, we transfer ownership of the retain from the stack
  1272. // to the heap.
  1273. } else {
  1274. ARCStrongByrefHelpers byrefInfo(emission.Alignment);
  1275. return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
  1276. }
  1277. }
  1278. llvm_unreachable("fell out of lifetime switch!");
  1279. }
  1280. BlockFieldFlags flags;
  1281. if (type->isBlockPointerType()) {
  1282. flags |= BLOCK_FIELD_IS_BLOCK;
  1283. } else if (CGM.getContext().isObjCNSObjectType(type) ||
  1284. type->isObjCObjectPointerType()) {
  1285. flags |= BLOCK_FIELD_IS_OBJECT;
  1286. } else {
  1287. return 0;
  1288. }
  1289. if (type.isObjCGCWeak())
  1290. flags |= BLOCK_FIELD_IS_WEAK;
  1291. ObjectByrefHelpers byrefInfo(emission.Alignment, flags);
  1292. return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
  1293. }
  1294. unsigned CodeGenFunction::getByRefValueLLVMField(const ValueDecl *VD) const {
  1295. assert(ByRefValueInfo.count(VD) && "Did not find value!");
  1296. return ByRefValueInfo.find(VD)->second.second;
  1297. }
  1298. llvm::Value *CodeGenFunction::BuildBlockByrefAddress(llvm::Value *BaseAddr,
  1299. const VarDecl *V) {
  1300. llvm::Value *Loc = Builder.CreateStructGEP(BaseAddr, 1, "forwarding");
  1301. Loc = Builder.CreateLoad(Loc);
  1302. Loc = Builder.CreateStructGEP(Loc, getByRefValueLLVMField(V),
  1303. V->getNameAsString());
  1304. return Loc;
  1305. }
  1306. /// BuildByRefType - This routine changes a __block variable declared as T x
  1307. /// into:
  1308. ///
  1309. /// struct {
  1310. /// void *__isa;
  1311. /// void *__forwarding;
  1312. /// int32_t __flags;
  1313. /// int32_t __size;
  1314. /// void *__copy_helper; // only if needed
  1315. /// void *__destroy_helper; // only if needed
  1316. /// char padding[X]; // only if needed
  1317. /// T x;
  1318. /// } x
  1319. ///
  1320. llvm::Type *CodeGenFunction::BuildByRefType(const VarDecl *D) {
  1321. std::pair<llvm::Type *, unsigned> &Info = ByRefValueInfo[D];
  1322. if (Info.first)
  1323. return Info.first;
  1324. QualType Ty = D->getType();
  1325. SmallVector<llvm::Type *, 8> types;
  1326. llvm::StructType *ByRefType =
  1327. llvm::StructType::create(getLLVMContext(),
  1328. "struct.__block_byref_" + D->getNameAsString());
  1329. // void *__isa;
  1330. types.push_back(Int8PtrTy);
  1331. // void *__forwarding;
  1332. types.push_back(llvm::PointerType::getUnqual(ByRefType));
  1333. // int32_t __flags;
  1334. types.push_back(Int32Ty);
  1335. // int32_t __size;
  1336. types.push_back(Int32Ty);
  1337. bool HasCopyAndDispose = getContext().BlockRequiresCopying(Ty);
  1338. if (HasCopyAndDispose) {
  1339. /// void *__copy_helper;
  1340. types.push_back(Int8PtrTy);
  1341. /// void *__destroy_helper;
  1342. types.push_back(Int8PtrTy);
  1343. }
  1344. bool Packed = false;
  1345. CharUnits Align = getContext().getDeclAlign(D);
  1346. if (Align > getContext().toCharUnitsFromBits(Target.getPointerAlign(0))) {
  1347. // We have to insert padding.
  1348. // The struct above has 2 32-bit integers.
  1349. unsigned CurrentOffsetInBytes = 4 * 2;
  1350. // And either 2 or 4 pointers.
  1351. CurrentOffsetInBytes += (HasCopyAndDispose ? 4 : 2) *
  1352. CGM.getTargetData().getTypeAllocSize(Int8PtrTy);
  1353. // Align the offset.
  1354. unsigned AlignedOffsetInBytes =
  1355. llvm::RoundUpToAlignment(CurrentOffsetInBytes, Align.getQuantity());
  1356. unsigned NumPaddingBytes = AlignedOffsetInBytes - CurrentOffsetInBytes;
  1357. if (NumPaddingBytes > 0) {
  1358. llvm::Type *Ty = llvm::Type::getInt8Ty(getLLVMContext());
  1359. // FIXME: We need a sema error for alignment larger than the minimum of
  1360. // the maximal stack alignment and the alignment of malloc on the system.
  1361. if (NumPaddingBytes > 1)
  1362. Ty = llvm::ArrayType::get(Ty, NumPaddingBytes);
  1363. types.push_back(Ty);
  1364. // We want a packed struct.
  1365. Packed = true;
  1366. }
  1367. }
  1368. // T x;
  1369. types.push_back(ConvertTypeForMem(Ty));
  1370. ByRefType->setBody(types, Packed);
  1371. Info.first = ByRefType;
  1372. Info.second = types.size() - 1;
  1373. return Info.first;
  1374. }
  1375. /// Initialize the structural components of a __block variable, i.e.
  1376. /// everything but the actual object.
  1377. void CodeGenFunction::emitByrefStructureInit(const AutoVarEmission &emission) {
  1378. // Find the address of the local.
  1379. llvm::Value *addr = emission.Address;
  1380. // That's an alloca of the byref structure type.
  1381. llvm::StructType *byrefType = cast<llvm::StructType>(
  1382. cast<llvm::PointerType>(addr->getType())->getElementType());
  1383. // Build the byref helpers if necessary. This is null if we don't need any.
  1384. CodeGenModule::ByrefHelpers *helpers =
  1385. buildByrefHelpers(*byrefType, emission);
  1386. const VarDecl &D = *emission.Variable;
  1387. QualType type = D.getType();
  1388. llvm::Value *V;
  1389. // Initialize the 'isa', which is just 0 or 1.
  1390. int isa = 0;
  1391. if (type.isObjCGCWeak())
  1392. isa = 1;
  1393. V = Builder.CreateIntToPtr(Builder.getInt32(isa), Int8PtrTy, "isa");
  1394. Builder.CreateStore(V, Builder.CreateStructGEP(addr, 0, "byref.isa"));
  1395. // Store the address of the variable into its own forwarding pointer.
  1396. Builder.CreateStore(addr,
  1397. Builder.CreateStructGEP(addr, 1, "byref.forwarding"));
  1398. // Blocks ABI:
  1399. // c) the flags field is set to either 0 if no helper functions are
  1400. // needed or BLOCK_HAS_COPY_DISPOSE if they are,
  1401. BlockFlags flags;
  1402. if (helpers) flags |= BLOCK_HAS_COPY_DISPOSE;
  1403. Builder.CreateStore(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
  1404. Builder.CreateStructGEP(addr, 2, "byref.flags"));
  1405. CharUnits byrefSize = CGM.GetTargetTypeStoreSize(byrefType);
  1406. V = llvm::ConstantInt::get(IntTy, byrefSize.getQuantity());
  1407. Builder.CreateStore(V, Builder.CreateStructGEP(addr, 3, "byref.size"));
  1408. if (helpers) {
  1409. llvm::Value *copy_helper = Builder.CreateStructGEP(addr, 4);
  1410. Builder.CreateStore(helpers->CopyHelper, copy_helper);
  1411. llvm::Value *destroy_helper = Builder.CreateStructGEP(addr, 5);
  1412. Builder.CreateStore(helpers->DisposeHelper, destroy_helper);
  1413. }
  1414. }
  1415. void CodeGenFunction::BuildBlockRelease(llvm::Value *V, BlockFieldFlags flags) {
  1416. llvm::Value *F = CGM.getBlockObjectDispose();
  1417. llvm::Value *N;
  1418. V = Builder.CreateBitCast(V, Int8PtrTy);
  1419. N = llvm::ConstantInt::get(Int32Ty, flags.getBitMask());
  1420. Builder.CreateCall2(F, V, N);
  1421. }
  1422. namespace {
  1423. struct CallBlockRelease : EHScopeStack::Cleanup {
  1424. llvm::Value *Addr;
  1425. CallBlockRelease(llvm::Value *Addr) : Addr(Addr) {}
  1426. void Emit(CodeGenFunction &CGF, Flags flags) {
  1427. // Should we be passing FIELD_IS_WEAK here?
  1428. CGF.BuildBlockRelease(Addr, BLOCK_FIELD_IS_BYREF);
  1429. }
  1430. };
  1431. }
  1432. /// Enter a cleanup to destroy a __block variable. Note that this
  1433. /// cleanup should be a no-op if the variable hasn't left the stack
  1434. /// yet; if a cleanup is required for the variable itself, that needs
  1435. /// to be done externally.
  1436. void CodeGenFunction::enterByrefCleanup(const AutoVarEmission &emission) {
  1437. // We don't enter this cleanup if we're in pure-GC mode.
  1438. if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
  1439. return;
  1440. EHStack.pushCleanup<CallBlockRelease>(NormalAndEHCleanup, emission.Address);
  1441. }