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