CGBlocks.cpp 72 KB

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