CGBlocks.cpp 98 KB

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