CGBlocks.cpp 114 KB

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