CGBlocks.cpp 114 KB

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