LLVM 24.0.0git
CoroFrame.cpp
Go to the documentation of this file.
1//===- CoroFrame.cpp - Builds and manipulates coroutine frame -------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8// This file contains classes used to discover if for a particular value
9// its definition precedes and its uses follow a suspend block. This is
10// referred to as a suspend crossing value.
11//
12// Using the information discovered we form a Coroutine Frame structure to
13// contain those values. All uses of those values are replaced with appropriate
14// GEP + load from the coroutine frame. At the point of the definition we spill
15// the value into the coroutine frame.
16//===----------------------------------------------------------------------===//
17
18#include "CoroInternal.h"
19#include "llvm/ADT/ScopeExit.h"
22#include "llvm/IR/DIBuilder.h"
23#include "llvm/IR/DebugInfo.h"
24#include "llvm/IR/Dominators.h"
25#include "llvm/IR/IRBuilder.h"
28#include "llvm/IR/LLVMContext.h"
29#include "llvm/IR/MDBuilder.h"
30#include "llvm/IR/Module.h"
33#include "llvm/Support/Debug.h"
43#include <algorithm>
44#include <optional>
45
46using namespace llvm;
47
48namespace llvm {
50}
51
52#define DEBUG_TYPE "coro-frame"
53
54namespace {
55class FrameTypeBuilder;
56// Mapping from the to-be-spilled value to all the users that need reload.
57struct FrameDataInfo {
58 // All the values (that are not allocas) that needs to be spilled to the
59 // frame.
60 coro::SpillInfo &Spills;
61 // Allocas contains all values defined as allocas that need to live in the
62 // frame.
64
65 FrameDataInfo(coro::SpillInfo &Spills,
67 : Spills(Spills), Allocas(Allocas) {}
68
69 SmallVector<Value *, 8> getAllDefs() const {
71 for (const auto &P : Spills)
72 Defs.push_back(P.first);
73 for (const auto &A : Allocas)
74 Defs.push_back(A.Alloca);
75 return Defs;
76 }
77
78 uint32_t getFieldIndex(Value *V) const {
79 auto Itr = FieldIndexMap.find(V);
80 assert(Itr != FieldIndexMap.end() &&
81 "Value does not have a frame field index");
82 return Itr->second;
83 }
84
85 void setFieldIndex(Value *V, uint32_t Index) {
86 assert(FieldIndexMap.count(V) == 0 &&
87 "Cannot set the index for the same field twice.");
88 FieldIndexMap[V] = Index;
89 }
90
91 Align getAlign(Value *V) const {
92 auto Iter = FieldAlignMap.find(V);
93 assert(Iter != FieldAlignMap.end());
94 return Iter->second;
95 }
96
97 void setAlign(Value *V, Align AL) {
98 assert(FieldAlignMap.count(V) == 0);
99 FieldAlignMap.insert({V, AL});
100 }
101
102 uint64_t getDynamicAlign(Value *V) const {
103 auto Iter = FieldDynamicAlignMap.find(V);
104 assert(Iter != FieldDynamicAlignMap.end());
105 return Iter->second;
106 }
107
108 void setDynamicAlign(Value *V, uint64_t Align) {
109 assert(FieldDynamicAlignMap.count(V) == 0);
110 FieldDynamicAlignMap.insert({V, Align});
111 }
112
113 uint64_t getOffset(Value *V) const {
114 auto Iter = FieldOffsetMap.find(V);
115 assert(Iter != FieldOffsetMap.end());
116 return Iter->second;
117 }
118
119 void setOffset(Value *V, uint64_t Offset) {
120 assert(FieldOffsetMap.count(V) == 0);
121 FieldOffsetMap.insert({V, Offset});
122 }
123
124 // Update field offset and alignment information from FrameTypeBuilder.
125 void updateLayoutInfo(FrameTypeBuilder &B);
126
127private:
128 // Map from values to their slot indexes on the frame (insertion order).
129 DenseMap<Value *, uint32_t> FieldIndexMap;
130 // Map from values to their alignment on the frame. They would be set after
131 // the frame is built.
132 DenseMap<Value *, Align> FieldAlignMap;
133 DenseMap<Value *, uint64_t> FieldDynamicAlignMap;
134 // Map from values to their offset on the frame. They would be set after
135 // the frame is built.
136 DenseMap<Value *, uint64_t> FieldOffsetMap;
137};
138} // namespace
139
140#ifndef NDEBUG
141static void dumpSpills(StringRef Title, const coro::SpillInfo &Spills) {
142 dbgs() << "------------- " << Title << " --------------\n";
143 for (const auto &E : Spills) {
144 E.first->dump();
145 dbgs() << " user: ";
146 for (auto *I : E.second)
147 I->dump();
148 }
149}
150
152 dbgs() << "------------- Allocas --------------\n";
153 for (const auto &A : Allocas) {
154 A.Alloca->dump();
155 }
156}
157#endif
158
159namespace {
160using FieldIDType = size_t;
161// We cannot rely solely on natural alignment of a type when building a
162// coroutine frame and if the alignment specified on the Alloca instruction
163// differs from the natural alignment of the alloca type we will need to insert
164// padding.
165class FrameTypeBuilder {
166private:
167 struct Field {
171 uint64_t DynamicAlignBuffer;
172 };
173
174 const DataLayout &DL;
175 uint64_t StructSize = 0;
176 Align StructAlign;
177 bool IsFinished = false;
178
179 std::optional<Align> MaxFrameAlignment;
180
182 DenseMap<Value*, unsigned> FieldIndexByKey;
183
184public:
185 FrameTypeBuilder(const DataLayout &DL, std::optional<Align> MaxFrameAlignment)
186 : DL(DL), MaxFrameAlignment(MaxFrameAlignment) {}
187
188 /// Add a field to this structure for the storage of an `alloca`
189 /// instruction.
190 [[nodiscard]] FieldIDType addFieldForAlloca(AllocaInst *AI,
191 bool IsHeader = false) {
192 auto Size = AI->getAllocationSize(AI->getDataLayout());
193 if (!Size || !Size->isFixed())
195 "Coroutines cannot handle non static or vscale allocas yet");
196 return addField(Size->getFixedValue(), AI->getAlign(), IsHeader);
197 }
198
199 /// We want to put the allocas whose lifetime-ranges are not overlapped
200 /// into one slot of coroutine frame.
201 /// Consider the example at:https://bugs.llvm.org/show_bug.cgi?id=45566
202 ///
203 /// cppcoro::task<void> alternative_paths(bool cond) {
204 /// if (cond) {
205 /// big_structure a;
206 /// process(a);
207 /// co_await something();
208 /// } else {
209 /// big_structure b;
210 /// process2(b);
211 /// co_await something();
212 /// }
213 /// }
214 ///
215 /// We want to put variable a and variable b in the same slot to
216 /// reduce the size of coroutine frame.
217 ///
218 /// This function use StackLifetime algorithm to partition the AllocaInsts in
219 /// Spills to non-overlapped sets in order to put Alloca in the same
220 /// non-overlapped set into the same slot in the Coroutine Frame. Then add
221 /// field for the allocas in the same non-overlapped set by using the largest
222 /// type as the field type.
223 ///
224 /// Side Effects: Because We sort the allocas, the order of allocas in the
225 /// frame may be different with the order in the source code.
226 void addFieldForAllocas(const Function &F, FrameDataInfo &FrameData,
227 coro::Shape &Shape, bool OptimizeFrame);
228
229 /// Add a field to this structure for a spill.
230 [[nodiscard]] FieldIDType addField(Type *Ty, MaybeAlign MaybeFieldAlignment,
231 bool IsHeader = false,
232 bool IsSpillOfValue = false) {
233 assert(Ty && "must provide a type for a field");
234 // The field size is the alloc size of the type.
235 uint64_t FieldSize = DL.getTypeAllocSize(Ty);
236 // The field alignment is usually the type alignment.
237 // But if we are spilling values we don't need to worry about ABI alignment
238 // concerns.
239 Align ABIAlign = DL.getABITypeAlign(Ty);
240 Align TyAlignment = ABIAlign;
241 if (IsSpillOfValue && MaxFrameAlignment && *MaxFrameAlignment < ABIAlign)
242 TyAlignment = *MaxFrameAlignment;
243 Align FieldAlignment = MaybeFieldAlignment.value_or(TyAlignment);
244 return addField(FieldSize, FieldAlignment, IsHeader);
245 }
246
247 /// Add a field to this structure.
248 [[nodiscard]] FieldIDType addField(uint64_t FieldSize, Align FieldAlignment,
249 bool IsHeader = false) {
250 assert(!IsFinished && "adding fields to a finished builder");
251
252 // For an alloca with size=0, we don't need to add a field and they
253 // can just point to any index in the frame. Use index 0.
254 if (FieldSize == 0)
255 return 0;
256
257 // The field alignment could be bigger than the max frame case, in that case
258 // we request additional storage to be able to dynamically align the
259 // pointer.
260 uint64_t DynamicAlignBuffer = 0;
261 if (MaxFrameAlignment && (FieldAlignment > *MaxFrameAlignment)) {
262 DynamicAlignBuffer =
263 offsetToAlignment(MaxFrameAlignment->value(), FieldAlignment);
264 FieldAlignment = *MaxFrameAlignment;
265 FieldSize = FieldSize + DynamicAlignBuffer;
266 }
267
268 // Lay out header fields immediately.
270 if (IsHeader) {
271 Offset = alignTo(StructSize, FieldAlignment);
272 StructSize = Offset + FieldSize;
273
274 // Everything else has a flexible offset.
275 } else {
277 }
278
279 Fields.push_back({FieldSize, Offset, FieldAlignment, DynamicAlignBuffer});
280 return Fields.size() - 1;
281 }
282
283 /// Finish the layout and compute final size and alignment.
284 void finish();
285
286 uint64_t getStructSize() const {
287 assert(IsFinished && "not yet finished!");
288 return StructSize;
289 }
290
291 Align getStructAlign() const {
292 assert(IsFinished && "not yet finished!");
293 return StructAlign;
294 }
295
296 Field getLayoutField(FieldIDType Id) const {
297 assert(IsFinished && "not yet finished!");
298 return Fields[Id];
299 }
300};
301} // namespace
302
303void FrameDataInfo::updateLayoutInfo(FrameTypeBuilder &B) {
304 auto Updater = [&](Value *I) {
305 uint32_t FieldIndex = getFieldIndex(I);
306 auto Field = B.getLayoutField(FieldIndex);
307 setAlign(I, Field.Alignment);
308 uint64_t dynamicAlign =
309 Field.DynamicAlignBuffer
310 ? Field.DynamicAlignBuffer + Field.Alignment.value()
311 : 0;
312 setDynamicAlign(I, dynamicAlign);
313 setOffset(I, Field.Offset);
314 };
315 for (auto &S : Spills)
316 Updater(S.first);
317 for (const auto &A : Allocas)
318 Updater(A.Alloca);
319}
320
321void FrameTypeBuilder::addFieldForAllocas(const Function &F,
322 FrameDataInfo &FrameData,
323 coro::Shape &Shape,
324 bool OptimizeFrame) {
325 using AllocaSetType = SmallVector<AllocaInst *, 4>;
326 SmallVector<AllocaSetType, 4> NonOverlapedAllocas;
327
328 // We need to add field for allocas at the end of this function.
329 llvm::scope_exit AddFieldForAllocasAtExit([&]() {
330 for (auto AllocaList : NonOverlapedAllocas) {
331 auto *LargestAI = *AllocaList.begin();
332 FieldIDType Id = addFieldForAlloca(LargestAI);
333 for (auto *Alloca : AllocaList)
334 FrameData.setFieldIndex(Alloca, Id);
335 }
336 });
337
338 if (!OptimizeFrame) {
339 for (const auto &A : FrameData.Allocas) {
340 AllocaInst *Alloca = A.Alloca;
341 NonOverlapedAllocas.emplace_back(AllocaSetType(1, Alloca));
342 }
343 return;
344 }
345
346 // Because there are paths from the lifetime.start to coro.end
347 // for each alloca, the liferanges for every alloca is overlaped
348 // in the blocks who contain coro.end and the successor blocks.
349 // So we choose to skip there blocks when we calculate the liferange
350 // for each alloca. It should be reasonable since there shouldn't be uses
351 // in these blocks and the coroutine frame shouldn't be used outside the
352 // coroutine body.
353 //
354 // Note that the user of coro.suspend may not be SwitchInst. However, this
355 // case seems too complex to handle. And it is harmless to skip these
356 // patterns since it just prevend putting the allocas to live in the same
357 // slot.
358 DenseMap<SwitchInst *, BasicBlock *> DefaultSuspendDest;
359 for (auto *CoroSuspendInst : Shape.CoroSuspends) {
360 for (auto *U : CoroSuspendInst->users()) {
361 if (auto *ConstSWI = dyn_cast<SwitchInst>(U)) {
362 auto *SWI = const_cast<SwitchInst *>(ConstSWI);
363 DefaultSuspendDest[SWI] = SWI->getDefaultDest();
364 SWI->setDefaultDest(SWI->getSuccessor(1));
365 }
366 }
367 }
368
369 auto ExtractAllocas = [&]() {
370 AllocaSetType Allocas;
371 Allocas.reserve(FrameData.Allocas.size());
372 for (const auto &A : FrameData.Allocas)
373 Allocas.push_back(A.Alloca);
374 return Allocas;
375 };
376 StackLifetime StackLifetimeAnalyzer(F, ExtractAllocas(),
377 StackLifetime::LivenessType::May);
378 StackLifetimeAnalyzer.run();
379 auto DoAllocasInterfere = [&](const AllocaInst *AI1, const AllocaInst *AI2) {
380 return StackLifetimeAnalyzer.getLiveRange(AI1).overlaps(
381 StackLifetimeAnalyzer.getLiveRange(AI2));
382 };
383 auto GetAllocaSize = [&](const coro::AllocaInfo &A) {
384 std::optional<TypeSize> RetSize = A.Alloca->getAllocationSize(DL);
385 assert(RetSize && "Variable Length Arrays (VLA) are not supported.\n");
386 assert(!RetSize->isScalable() && "Scalable vectors are not yet supported");
387 return RetSize->getFixedValue();
388 };
389 // Put larger allocas in the front. So the larger allocas have higher
390 // priority to merge, which can save more space potentially. Also each
391 // AllocaSet would be ordered. So we can get the largest Alloca in one
392 // AllocaSet easily.
393 sort(FrameData.Allocas, [&](const auto &Iter1, const auto &Iter2) {
394 return GetAllocaSize(Iter1) > GetAllocaSize(Iter2);
395 });
396 for (const auto &A : FrameData.Allocas) {
397 AllocaInst *Alloca = A.Alloca;
398 bool Merged = false;
399 // Try to find if the Alloca does not interfere with any existing
400 // NonOverlappedAllocaSet. If it is true, insert the alloca to that
401 // NonOverlappedAllocaSet.
402 for (auto &AllocaSet : NonOverlapedAllocas) {
403 assert(!AllocaSet.empty() && "Processing Alloca Set is not empty.\n");
404 bool NoInterference = none_of(AllocaSet, [&](auto Iter) {
405 return DoAllocasInterfere(Alloca, Iter);
406 });
407 // If the alignment of A is multiple of the alignment of B, the address
408 // of A should satisfy the requirement for aligning for B.
409 //
410 // There may be other more fine-grained strategies to handle the alignment
411 // infomation during the merging process. But it seems hard to handle
412 // these strategies and benefit little.
413 bool Alignable = [&]() -> bool {
414 auto *LargestAlloca = *AllocaSet.begin();
415 return LargestAlloca->getAlign().value() % Alloca->getAlign().value() ==
416 0;
417 }();
418 bool CouldMerge = NoInterference && Alignable;
419 if (!CouldMerge)
420 continue;
421 AllocaSet.push_back(Alloca);
422 Merged = true;
423 break;
424 }
425 if (!Merged) {
426 NonOverlapedAllocas.emplace_back(AllocaSetType(1, Alloca));
427 }
428 }
429 // Recover the default target destination for each Switch statement
430 // reserved.
431 for (auto SwitchAndDefaultDest : DefaultSuspendDest) {
432 SwitchInst *SWI = SwitchAndDefaultDest.first;
433 BasicBlock *DestBB = SwitchAndDefaultDest.second;
434 SWI->setDefaultDest(DestBB);
435 }
436 // This Debug Info could tell us which allocas are merged into one slot.
437 LLVM_DEBUG(for (auto &AllocaSet
438 : NonOverlapedAllocas) {
439 if (AllocaSet.size() > 1) {
440 dbgs() << "In Function:" << F.getName() << "\n";
441 dbgs() << "Find Union Set "
442 << "\n";
443 dbgs() << "\tAllocas are \n";
444 for (auto Alloca : AllocaSet)
445 dbgs() << "\t\t" << *Alloca << "\n";
446 }
447 });
448}
449
450void FrameTypeBuilder::finish() {
451 assert(!IsFinished && "already finished!");
452
453 // Prepare the optimal-layout field array.
454 // The Id in the layout field is a pointer to our Field for it.
456 LayoutFields.reserve(Fields.size());
457 for (auto &Field : Fields) {
458 LayoutFields.emplace_back(&Field, Field.Size, Field.Alignment,
459 Field.Offset);
460 }
461
462 // Perform layout to compute size, alignment, and field offsets.
463 auto SizeAndAlign = performOptimizedStructLayout(LayoutFields);
464 StructSize = SizeAndAlign.first;
465 StructAlign = SizeAndAlign.second;
466
467 auto getField = [](const OptimizedStructLayoutField &LayoutField) -> Field & {
468 return *static_cast<Field *>(const_cast<void*>(LayoutField.Id));
469 };
470
471 // Update field offsets from the computed layout.
472 for (auto &LayoutField : LayoutFields) {
473 auto &F = getField(LayoutField);
474 F.Offset = LayoutField.Offset;
475 }
476
477 IsFinished = true;
478}
479
480static void cacheDIVar(FrameDataInfo &FrameData,
482 for (auto *V : FrameData.getAllDefs()) {
483 if (DIVarCache.contains(V))
484 continue;
485
486 auto CacheIt = [&DIVarCache, V](const auto &Container) {
487 auto *I = llvm::find_if(Container, [](auto *DDI) {
488 return DDI->getExpression()->getNumElements() == 0;
489 });
490 if (I != Container.end())
491 DIVarCache.insert({V, (*I)->getVariable()});
492 };
493 CacheIt(findDVRDeclares(V));
494 CacheIt(findDVRDeclareValues(V));
495 }
496}
497
498/// Create name for Type. It uses MDString to store new created string to
499/// avoid memory leak.
501 if (Ty->isIntegerTy()) {
502 // The longest name in common may be '__int_128', which has 9 bits.
503 SmallString<16> Buffer;
504 raw_svector_ostream OS(Buffer);
505 OS << "__int_" << cast<IntegerType>(Ty)->getBitWidth();
506 auto *MDName = MDString::get(Ty->getContext(), OS.str());
507 return MDName->getString();
508 }
509
510 if (Ty->isFloatingPointTy()) {
511 if (Ty->isFloatTy())
512 return "__float_";
513 if (Ty->isDoubleTy())
514 return "__double_";
515 return "__floating_type_";
516 }
517
518 if (Ty->isPointerTy())
519 return "PointerType";
520
521 if (Ty->isStructTy()) {
522 if (!cast<StructType>(Ty)->hasName())
523 return "__LiteralStructType_";
524
525 auto Name = Ty->getStructName();
526
527 SmallString<16> Buffer(Name);
528 for (auto &Iter : Buffer)
529 if (Iter == '.' || Iter == ':')
530 Iter = '_';
531 auto *MDName = MDString::get(Ty->getContext(), Buffer.str());
532 return MDName->getString();
533 }
534
535 return "UnknownType";
536}
537
538static DIType *solveDIType(DIBuilder &Builder, Type *Ty,
539 const DataLayout &Layout, DIScope *Scope,
540 unsigned LineNum,
541 DenseMap<Type *, DIType *> &DITypeCache) {
542 if (DIType *DT = DITypeCache.lookup(Ty))
543 return DT;
544
545 StringRef Name = solveTypeName(Ty);
546
547 DIType *RetType = nullptr;
548
549 if (Ty->isIntegerTy()) {
550 auto BitWidth = cast<IntegerType>(Ty)->getBitWidth();
551 RetType = Builder.createBasicType(Name, BitWidth, dwarf::DW_ATE_signed,
552 llvm::DINode::FlagArtificial);
553 } else if (Ty->isFloatingPointTy()) {
554 RetType = Builder.createBasicType(Name, Layout.getTypeSizeInBits(Ty),
555 dwarf::DW_ATE_float,
556 llvm::DINode::FlagArtificial);
557 } else if (Ty->isPointerTy()) {
558 // Construct PointerType points to null (aka void *) instead of exploring
559 // pointee type to avoid infinite search problem. For example, we would be
560 // in trouble if we traverse recursively:
561 //
562 // struct Node {
563 // Node* ptr;
564 // };
565 RetType =
566 Builder.createPointerType(nullptr, Layout.getTypeSizeInBits(Ty),
567 Layout.getABITypeAlign(Ty).value() * CHAR_BIT,
568 /*DWARFAddressSpace=*/std::nullopt, Name);
569 } else if (Ty->isStructTy()) {
570 auto *DIStruct = Builder.createStructType(
571 Scope, Name, Scope->getFile(), LineNum, Layout.getTypeSizeInBits(Ty),
572 Layout.getPrefTypeAlign(Ty).value() * CHAR_BIT,
573 llvm::DINode::FlagArtificial, nullptr, llvm::DINodeArray());
574
575 auto *StructTy = cast<StructType>(Ty);
577 for (unsigned I = 0; I < StructTy->getNumElements(); I++) {
578 DIType *DITy = solveDIType(Builder, StructTy->getElementType(I), Layout,
579 DIStruct, LineNum, DITypeCache);
580 assert(DITy);
581 Elements.push_back(Builder.createMemberType(
582 DIStruct, DITy->getName(), DIStruct->getFile(), LineNum,
583 DITy->getSizeInBits(), DITy->getAlignInBits(),
584 Layout.getStructLayout(StructTy)->getElementOffsetInBits(I),
585 llvm::DINode::FlagArtificial, DITy));
586 }
587
588 Builder.replaceArrays(DIStruct, Builder.getOrCreateArray(Elements));
589
590 RetType = DIStruct;
591 } else {
592 LLVM_DEBUG(dbgs() << "Unresolved Type: " << *Ty << "\n");
593 TypeSize Size = Layout.getTypeSizeInBits(Ty);
594 auto *CharSizeType = Builder.createBasicType(
595 Name, 8, dwarf::DW_ATE_unsigned_char, llvm::DINode::FlagArtificial);
596
597 if (Size <= 8)
598 RetType = CharSizeType;
599 else {
600 if (Size % 8 != 0)
601 Size = TypeSize::getFixed(Size + 8 - (Size % 8));
602
603 RetType = Builder.createArrayType(
604 Size, Layout.getPrefTypeAlign(Ty).value(), CharSizeType,
605 Builder.getOrCreateArray(Builder.getOrCreateSubrange(0, Size / 8)));
606 }
607 }
608
609 DITypeCache.insert({Ty, RetType});
610 return RetType;
611}
612
613/// Build artificial debug info for C++ coroutine frames to allow users to
614/// inspect the contents of the frame directly
615///
616/// Create Debug information for coroutine frame with debug name "__coro_frame".
617/// The debug information for the fields of coroutine frame is constructed from
618/// the following way:
619/// 1. For all the value in the Frame, we search the use of dbg.declare to find
620/// the corresponding debug variables for the value. If we can find the
621/// debug variable, we can get full and accurate debug information.
622/// 2. If we can't get debug information in step 1 and 2, we could only try to
623/// build the DIType by Type. We did this in solveDIType. We only handle
624/// integer, float, double, integer type and struct type for now.
626 FrameDataInfo &FrameData) {
627 DISubprogram *DIS = F.getSubprogram();
628 // If there is no DISubprogram for F, it implies the function is compiled
629 // without debug info. So we also don't generate debug info for the frame.
630
631 if (!DIS || !DIS->getUnit())
632 return;
633
635 DIS->getUnit()->getSourceLanguage().getUnversionedName())) ||
636 DIS->getUnit()->getEmissionKind() !=
638 return;
639
640 assert(Shape.ABI == coro::ABI::Switch &&
641 "We could only build debug infomation for C++ coroutine now.\n");
642
643 DIBuilder DBuilder(*F.getParent(), /*AllowUnresolved*/ false);
644
645 DIFile *DFile = DIS->getFile();
646 unsigned LineNum = DIS->getLine();
647
648 DICompositeType *FrameDITy = DBuilder.createStructType(
649 DIS->getUnit(), Twine(F.getName() + ".coro_frame_ty").str(), DFile,
650 LineNum, Shape.FrameSize * 8, Shape.FrameAlign.value() * 8,
651 llvm::DINode::FlagArtificial, nullptr, llvm::DINodeArray());
653 DataLayout Layout = F.getDataLayout();
654
656 cacheDIVar(FrameData, DIVarCache);
657
658 // This counter is used to avoid same type names. e.g., there would be
659 // many i32 and i64 types in one coroutine. And we would use i32_0 and
660 // i32_1 to avoid the same type. Since it makes no sense the name of the
661 // fields confilicts with each other.
662 unsigned UnknownTypeNum = 0;
663 DenseMap<Type *, DIType *> DITypeCache;
664
665 auto addElement = [&](StringRef Name, uint64_t SizeInBits, uint64_t Alignment,
666 uint64_t Offset, DIType *DITy) {
667 Elements.push_back(DBuilder.createMemberType(
668 FrameDITy, Name, DFile, LineNum, SizeInBits, Alignment, Offset * 8,
669 llvm::DINode::FlagArtificial, DITy));
670 };
671
672 auto addDIDef = [&](Value *V) {
673 // Get the offset and alignment for this value.
674 uint64_t Offset = FrameData.getOffset(V);
675 Align Alignment = FrameData.getAlign(V);
676
677 std::string Name;
678 uint64_t SizeInBits;
679 DIType *DITy = nullptr;
680
681 auto It = DIVarCache.find(V);
682 if (It != DIVarCache.end()) {
683 // Get the type from the debug variable.
684 Name = It->second->getName().str();
685 DITy = It->second->getType();
686 } else {
687 if (auto AI = dyn_cast<AllocaInst>(V)) {
688 // Frame alloca
689 DITy = solveDIType(DBuilder, AI->getAllocatedType(), Layout, FrameDITy,
690 LineNum, DITypeCache);
691 } else {
692 // Spill
693 DITy = solveDIType(DBuilder, V->getType(), Layout, FrameDITy, LineNum,
694 DITypeCache);
695 }
696 assert(DITy && "SolveDIType shouldn't return nullptr.\n");
697 Name = DITy->getName().str();
698 Name += "_" + std::to_string(UnknownTypeNum);
699 UnknownTypeNum++;
700 }
701
702 if (auto AI = dyn_cast<AllocaInst>(V)) {
703 // Lookup the total size of this alloca originally
704 auto Size = AI->getAllocationSize(Layout);
705 assert(Size && Size->isFixed() &&
706 "unreachable due to addFieldForAlloca checks");
707 SizeInBits = Size->getFixedValue() * 8;
708 } else {
709 // Compute the size of the active data of this member for this spill
710 SizeInBits = Layout.getTypeSizeInBits(V->getType());
711 }
712
713 addElement(Name, SizeInBits, Alignment.value() * 8, Offset, DITy);
714 };
715
716 // For Switch ABI, add debug info for the added fields (resume, destroy).
717 if (Shape.ABI == coro::ABI::Switch) {
718 auto *FnPtrTy = Shape.getSwitchResumePointerType();
719 uint64_t PtrSize = Layout.getPointerSizeInBits(FnPtrTy->getAddressSpace());
720 uint64_t PtrAlign =
721 Layout.getPointerABIAlignment(FnPtrTy->getAddressSpace()).value() * 8;
722 auto *DIPtr = DBuilder.createPointerType(nullptr, PtrSize,
723 FnPtrTy->getAddressSpace());
724 addElement("__resume_fn", PtrSize, PtrAlign, 0, DIPtr);
725 addElement("__destroy_fn", PtrSize, PtrAlign,
726 Shape.SwitchLowering.DestroyOffset, DIPtr);
727 uint64_t IndexSize =
729 addElement("__coro_index", IndexSize, Shape.SwitchLowering.IndexAlign * 8,
731 DBuilder.createBasicType("__coro_index",
732 (IndexSize < 8) ? 8 : IndexSize,
733 dwarf::DW_ATE_unsigned_char));
734 }
735 auto Defs = FrameData.getAllDefs();
736 for (auto *V : Defs)
737 addDIDef(V);
738
739 DBuilder.replaceArrays(FrameDITy, DBuilder.getOrCreateArray(Elements));
740
741 auto *FrameDIVar =
742 DBuilder.createAutoVariable(DIS, "__coro_frame", DFile, LineNum,
743 FrameDITy, true, DINode::FlagArtificial);
744
745 // Subprogram would have ContainedNodes field which records the debug
746 // variables it contained. So we need to add __coro_frame to the
747 // ContainedNodes of it.
748 //
749 // If we don't add __coro_frame to the RetainedNodes, user may get
750 // `no symbol __coro_frame in context` rather than `__coro_frame`
751 // is optimized out, which is more precise.
752 DIS->retainNodes(&FrameDIVar, &FrameDIVar + 1);
753
754 // Construct the location for the frame debug variable. The column number
755 // is fake but it should be fine.
756 DILocation *DILoc =
757 DILocation::get(DIS->getContext(), LineNum, /*Column=*/1, DIS);
758 assert(FrameDIVar->isValidLocationForIntrinsic(DILoc));
759
760 DbgVariableRecord *NewDVR =
761 new DbgVariableRecord(ValueAsMetadata::get(Shape.FramePtr), FrameDIVar,
762 DBuilder.createExpression(), DILoc,
765 It->getParent()->insertDbgRecordBefore(NewDVR, It);
766}
767
768// If there is memory accessing to promise alloca before CoroBegin
770 coro::Shape &Shape) {
771 auto *PA = Shape.SwitchLowering.PromiseAlloca;
772 return llvm::any_of(PA->uses(), [&](Use &U) {
773 auto *Inst = dyn_cast<Instruction>(U.getUser());
774 if (!Inst || DT.dominates(Shape.CoroBegin, Inst))
775 return false;
776
777 if (auto *CI = dyn_cast<CallInst>(Inst)) {
778 // It is fine if the call wouldn't write to the Promise.
779 // This is possible for @llvm.coro.id intrinsics, which
780 // would take the promise as the second argument as a
781 // marker.
782 if (CI->onlyReadsMemory() || CI->onlyReadsMemory(CI->getArgOperandNo(&U)))
783 return false;
784 return true;
785 }
786
787 return isa<StoreInst>(Inst) ||
788 // It may take too much time to track the uses.
789 // Be conservative about the case the use may escape.
791 // There would always be a bitcast for the promise alloca
792 // before we enabled Opaque pointers. And now given
793 // opaque pointers are enabled by default. This should be
794 // fine.
795 isa<BitCastInst>(Inst);
796 });
797}
798// Build the coroutine frame type as a byte array.
799// The frame layout includes:
800// - Resume function pointer at offset 0 (Switch ABI only)
801// - Destroy function pointer at offset ptrsize (Switch ABI only)
802// - Promise alloca (Switch ABI only, only if present)
803// - Suspend/Resume index
804// - Spilled values and allocas
805static void buildFrameLayout(Function &F, const DominatorTree &DT,
806 coro::Shape &Shape, FrameDataInfo &FrameData,
807 bool OptimizeFrame) {
808 const DataLayout &DL = F.getDataLayout();
809
810 // We will use this value to cap the alignment of spilled values.
811 std::optional<Align> MaxFrameAlignment;
812 if (Shape.ABI == coro::ABI::Async)
813 MaxFrameAlignment = Shape.AsyncLowering.getContextAlignment();
814 FrameTypeBuilder B(DL, MaxFrameAlignment);
815
816 AllocaInst *PromiseAlloca = Shape.getPromiseAlloca();
817 std::optional<FieldIDType> SwitchIndexFieldId;
818 IntegerType *SwitchIndexType = nullptr;
819
820 if (Shape.ABI == coro::ABI::Switch) {
821 auto *FnPtrTy = Shape.getSwitchResumePointerType();
822
823 // Add header fields for the resume and destroy functions.
824 // We can rely on these being perfectly packed.
825 (void)B.addField(FnPtrTy, MaybeAlign(), /*header*/ true);
826 (void)B.addField(FnPtrTy, MaybeAlign(), /*header*/ true);
827
828 // PromiseAlloca field needs to be explicitly added here because it's
829 // a header field with a fixed offset based on its alignment. Hence it
830 // needs special handling.
831 if (PromiseAlloca)
832 FrameData.setFieldIndex(
833 PromiseAlloca, B.addFieldForAlloca(PromiseAlloca, /*header*/ true));
834
835 // Add a field to store the suspend index. This doesn't need to
836 // be in the header.
837 unsigned IndexBits = std::max(1U, Log2_64_Ceil(Shape.CoroSuspends.size()));
838 Type *LegalTy =
839 F.getDataLayout().getSmallestLegalIntType(F.getContext(), IndexBits);
840 SwitchIndexType = LegalTy ? cast<IntegerType>(LegalTy)
841 : Type::getIntNTy(F.getContext(), IndexBits);
842
843 SwitchIndexFieldId = B.addField(SwitchIndexType, MaybeAlign());
844 } else {
845 assert(PromiseAlloca == nullptr && "lowering doesn't support promises");
846 }
847
848 // Because multiple allocas may own the same field slot,
849 // we add allocas to field here.
850 B.addFieldForAllocas(F, FrameData, Shape, OptimizeFrame);
851 // Add PromiseAlloca to Allocas list so that
852 // 1. updateLayoutIndex could update its index after
853 // `performOptimizedStructLayout`
854 // 2. it is processed in insertSpills.
855 if (Shape.ABI == coro::ABI::Switch && PromiseAlloca) {
856 // We assume that no alias will be create before CoroBegin.
857 FrameData.Allocas.emplace_back(
858 PromiseAlloca, DenseMap<Instruction *, std::optional<APInt>>{},
859 hasAccessingPromiseBeforeCB(DT, Shape));
860 }
861 // Create an entry for every spilled value.
862 for (auto &S : FrameData.Spills) {
863 Type *FieldType = S.first->getType();
864 MaybeAlign MA;
865 // For byval arguments, we need to store the pointed value in the frame,
866 // instead of the pointer itself.
867 if (const Argument *A = dyn_cast<Argument>(S.first)) {
868 if (A->hasByValAttr()) {
869 FieldType = A->getParamByValType();
870 MA = A->getParamAlign();
871 }
872 }
873 FieldIDType Id =
874 B.addField(FieldType, MA, false /*header*/, true /*IsSpillOfValue*/);
875 FrameData.setFieldIndex(S.first, Id);
876 }
877
878 B.finish();
879
880 FrameData.updateLayoutInfo(B);
881 Shape.FrameAlign = B.getStructAlign();
882 Shape.FrameSize = B.getStructSize();
883
884 switch (Shape.ABI) {
885 case coro::ABI::Switch: {
886 // In the switch ABI, remember the function pointer and index field info.
887 // Resume and Destroy function pointers are in the frame header.
888 const DataLayout &DL = F.getDataLayout();
889 Shape.SwitchLowering.DestroyOffset = DL.getPointerSize();
890
891 auto IndexField = B.getLayoutField(*SwitchIndexFieldId);
892 Shape.SwitchLowering.IndexType = SwitchIndexType;
893 Shape.SwitchLowering.IndexAlign = IndexField.Alignment.value();
894 Shape.SwitchLowering.IndexOffset = IndexField.Offset;
895
896 // Also round the frame size up to a multiple of its alignment, as is
897 // generally expected in C/C++.
898 Shape.FrameSize = alignTo(Shape.FrameSize, Shape.FrameAlign);
899 break;
900 }
901
902 // In the retcon ABI, remember whether the frame is inline in the storage.
905 auto Id = Shape.getRetconCoroId();
907 = (B.getStructSize() <= Id->getStorageSize() &&
908 B.getStructAlign() <= Id->getStorageAlignment());
909 break;
910 }
911 case coro::ABI::Async: {
914 // Also make the final context size a multiple of the context alignment to
915 // make allocation easier for allocators.
919 if (Shape.AsyncLowering.getContextAlignment() < Shape.FrameAlign) {
921 "The alignment requirment of frame variables cannot be higher than "
922 "the alignment of the async function context");
923 }
924 break;
925 }
926 }
927}
928
929/// If MaybeArgument is a byval Argument, return its byval type. Also removes
930/// the captures attribute, so that the argument *value* may be stored directly
931/// on the coroutine frame.
932static Type *extractByvalIfArgument(Value *MaybeArgument) {
933 if (auto *Arg = dyn_cast<Argument>(MaybeArgument)) {
934 Arg->getParent()->removeParamAttr(Arg->getArgNo(), Attribute::Captures);
935
936 if (Arg->hasByValAttr())
937 return Arg->getParamByValType();
938 }
939 return nullptr;
940}
941
942/// Store Def into the coroutine frame.
943static void createStoreIntoFrame(IRBuilder<> &Builder, Value *Def,
944 Type *ByValTy, const coro::Shape &Shape,
945 const FrameDataInfo &FrameData) {
946 LLVMContext &Ctx = Shape.CoroBegin->getContext();
947 uint64_t Offset = FrameData.getOffset(Def);
948
949 Value *G = Shape.FramePtr;
950 if (Offset != 0) {
951 auto *OffsetVal = ConstantInt::get(Type::getInt64Ty(Ctx), Offset);
952 G = Builder.CreateInBoundsPtrAdd(G, OffsetVal,
953 Def->getName() + Twine(".spill.addr"));
954 }
955 auto SpillAlignment = Align(FrameData.getAlign(Def));
956
957 // For byval arguments, copy the pointed-to value to the frame.
958 if (ByValTy) {
959 auto &DL = Builder.GetInsertBlock()->getDataLayout();
960 auto Size = DL.getTypeStoreSize(ByValTy);
961 // Def is a pointer to the byval argument
962 Builder.CreateMemCpy(G, SpillAlignment, Def, SpillAlignment, Size);
963 } else {
964 Builder.CreateAlignedStore(Def, G, SpillAlignment);
965 }
966}
967
968/// Returns a pointer into the coroutine frame at the offset where Orig is
969/// located.
970static Value *createGEPToFramePointer(const FrameDataInfo &FrameData,
971 IRBuilder<> &Builder, coro::Shape &Shape,
972 Value *Orig) {
973 LLVMContext &Ctx = Shape.CoroBegin->getContext();
974 uint64_t Offset = FrameData.getOffset(Orig);
975 auto *OffsetVal = ConstantInt::get(Type::getInt64Ty(Ctx), Offset);
976 Value *Ptr = Builder.CreateInBoundsPtrAdd(Shape.FramePtr, OffsetVal);
977
978 if (auto *AI = dyn_cast<AllocaInst>(Orig)) {
979 if (FrameData.getDynamicAlign(Orig) != 0) {
980 assert(FrameData.getDynamicAlign(Orig) == AI->getAlign().value());
981 auto *M = AI->getModule();
982 auto *IntPtrTy = M->getDataLayout().getIntPtrType(AI->getType());
983 auto *PtrValue = Builder.CreatePtrToInt(Ptr, IntPtrTy);
984 auto *AlignMask = ConstantInt::get(IntPtrTy, AI->getAlign().value() - 1);
985 PtrValue = Builder.CreateAdd(PtrValue, AlignMask);
986 PtrValue = Builder.CreateAnd(PtrValue, Builder.CreateNot(AlignMask));
987 return Builder.CreateIntToPtr(PtrValue, AI->getType());
988 }
989 // If the type of Ptr is not equal to the type of AllocaInst, it implies
990 // that the AllocaInst may be reused in the Frame slot of other AllocaInst.
991 // Note: If the strategy dealing with alignment changes, this cast must be
992 // refined
993 if (Ptr->getType() != Orig->getType())
994 Ptr = Builder.CreateAddrSpaceCast(Ptr, Orig->getType(),
995 Orig->getName() + Twine(".cast"));
996 }
997 return Ptr;
998}
999
1000/// Find dbg.declare or dbg.declare_value records referencing `Def`. If none are
1001/// found, walk up the load chain to find one.
1002template <DbgVariableRecord::LocationType record_type>
1003static TinyPtrVector<DbgVariableRecord *>
1005 static_assert(record_type == DbgVariableRecord::LocationType::Declare ||
1007 constexpr auto FindFunc =
1011
1012 TinyPtrVector<DbgVariableRecord *> Records = FindFunc(Def);
1013
1014 if (!F.getSubprogram())
1015 return Records;
1016
1017 Value *CurDef = Def;
1018 while (Records.empty() && isa<LoadInst>(CurDef)) {
1019 auto *LdInst = cast<LoadInst>(CurDef);
1020 if (!LdInst->getType()->isPointerTy())
1021 break;
1022 CurDef = LdInst->getPointerOperand();
1023 if (!isa<AllocaInst, LoadInst>(CurDef))
1024 break;
1025 Records = FindFunc(CurDef);
1026 }
1027
1028 return Records;
1029}
1030
1031// Helper function to handle allocas that may be accessed before CoroBegin.
1032// This creates a memcpy from the original alloca to the coroutine frame after
1033// CoroBegin, ensuring the frame has the correct initial values.
1034static void handleAccessBeforeCoroBegin(const FrameDataInfo &FrameData,
1035 coro::Shape &Shape,
1036 IRBuilder<> &Builder,
1037 AllocaInst *Alloca) {
1038 Value *Size = Builder.CreateAllocationSize(Builder.getInt64Ty(), Alloca);
1039 auto *G = createGEPToFramePointer(FrameData, Builder, Shape, Alloca);
1040 Builder.CreateMemCpy(G, FrameData.getAlign(Alloca), Alloca,
1041 Alloca->getAlign(), Size);
1042}
1043
1044// Replace all alloca and SSA values that are accessed across suspend points
1045// with GetElementPointer from coroutine frame + loads and stores. Create an
1046// AllocaSpillBB that will become the new entry block for the resume parts of
1047// the coroutine:
1048//
1049// %hdl = coro.begin(...)
1050// whatever
1051//
1052// becomes:
1053//
1054// %hdl = coro.begin(...)
1055// br label %AllocaSpillBB
1056//
1057// AllocaSpillBB:
1058// ; geps corresponding to allocas that were moved to coroutine frame
1059// br label PostSpill
1060//
1061// PostSpill:
1062// whatever
1063//
1064//
1065static void insertSpills(const FrameDataInfo &FrameData, coro::Shape &Shape) {
1066 LLVMContext &C = Shape.CoroBegin->getContext();
1067 Function *F = Shape.CoroBegin->getFunction();
1068 IRBuilder<> Builder(C);
1069 DominatorTree DT(*F);
1071
1072 MDBuilder MDB(C);
1073 // Create a TBAA tag for accesses to certain coroutine frame slots, so that
1074 // subsequent alias analysis will understand they do not intersect with
1075 // user memory.
1076 // We do this only if a suitable TBAA root already exists in the module.
1077 MDNode *TBAATag = nullptr;
1078 if (auto *CppTBAAStr = MDString::getIfExists(C, "Simple C++ TBAA")) {
1079 auto *TBAARoot = MDNode::getIfExists(C, CppTBAAStr);
1080 // Create a "fake" scalar type; all other types defined in the source
1081 // language will be assumed non-aliasing with this type.
1082 MDNode *Scalar = MDB.createTBAAScalarTypeNode(
1083 (F->getName() + ".Frame Slot").str(), TBAARoot);
1084 TBAATag = MDB.createTBAAStructTagNode(Scalar, Scalar, 0);
1085 }
1086 for (auto const &E : FrameData.Spills) {
1087 Value *Def = E.first;
1088 Type *ByValTy = extractByvalIfArgument(Def);
1089
1090 Builder.SetInsertPoint(coro::getSpillInsertionPt(Shape, Def, DT));
1091 createStoreIntoFrame(Builder, Def, ByValTy, Shape, FrameData);
1092
1093 BasicBlock *CurrentBlock = nullptr;
1094 Value *CurrentReload = nullptr;
1095 for (auto *U : E.second) {
1096 // If we have not seen the use block, create a load instruction to reload
1097 // the spilled value from the coroutine frame. Populates the Value pointer
1098 // reference provided with the frame GEP.
1099 if (CurrentBlock != U->getParent()) {
1100 CurrentBlock = U->getParent();
1101 Builder.SetInsertPoint(CurrentBlock->getFirstInsertionPt());
1102
1103 auto *GEP = createGEPToFramePointer(FrameData, Builder, Shape, E.first);
1104 GEP->setName(E.first->getName() + Twine(".reload.addr"));
1105 if (ByValTy) {
1106 CurrentReload = GEP;
1107 } else {
1108 auto SpillAlignment = Align(FrameData.getAlign(Def));
1109 auto *LI =
1110 Builder.CreateAlignedLoad(E.first->getType(), GEP, SpillAlignment,
1111 E.first->getName() + Twine(".reload"));
1112 if (TBAATag)
1113 LI->setMetadata(LLVMContext::MD_tbaa, TBAATag);
1114 CurrentReload = LI;
1115 }
1116
1119
1120 auto SalvageOne = [&](DbgVariableRecord *DDI) {
1121 // This dbg.declare is preserved for all coro-split function
1122 // fragments. It will be unreachable in the main function, and
1123 // processed by coro::salvageDebugInfo() by the Cloner.
1125 ValueAsMetadata::get(CurrentReload), DDI->getVariable(),
1126 DDI->getExpression(), DDI->getDebugLoc(),
1128 Builder.GetInsertPoint()->getParent()->insertDbgRecordBefore(
1129 NewDVR, Builder.GetInsertPoint());
1130 // This dbg.declare is for the main function entry point. It
1131 // will be deleted in all coro-split functions.
1132 coro::salvageDebugInfo(ArgToAllocaMap, *DDI, false /*UseEntryValue*/);
1133 };
1134 for_each(DVRs, SalvageOne);
1135 }
1136
1137 TinyPtrVector<DbgVariableRecord *> DVRDeclareValues =
1140
1141 auto SalvageOneCoro = [&](auto *DDI) {
1142 // This dbg.declare_value is preserved for all coro-split function
1143 // fragments. It will be unreachable in the main function, and
1144 // processed by coro::salvageDebugInfo() by the Cloner. However, convert
1145 // it to a dbg.declare to make sure future passes don't have to deal
1146 // with a dbg.declare_value.
1147 auto *VAM = ValueAsMetadata::get(CurrentReload);
1148 Type *Ty = VAM->getValue()->getType();
1149 // If the metadata type is not a pointer, emit a dbg.value instead.
1151 ValueAsMetadata::get(CurrentReload), DDI->getVariable(),
1152 DDI->getExpression(), DDI->getDebugLoc(),
1155 Builder.GetInsertPoint()->getParent()->insertDbgRecordBefore(
1156 NewDVR, Builder.GetInsertPoint());
1157 // This dbg.declare_value is for the main function entry point. It
1158 // will be deleted in all coro-split functions.
1159 coro::salvageDebugInfo(ArgToAllocaMap, *DDI, false /*UseEntryValue*/);
1160 };
1161 for_each(DVRDeclareValues, SalvageOneCoro);
1162
1163 // If we have a single edge PHINode, remove it and replace it with a
1164 // reload from the coroutine frame. (We already took care of multi edge
1165 // PHINodes by normalizing them in the rewritePHIs function).
1166 if (auto *PN = dyn_cast<PHINode>(U)) {
1167 assert(PN->getNumIncomingValues() == 1 &&
1168 "unexpected number of incoming "
1169 "values in the PHINode");
1170 PN->replaceAllUsesWith(CurrentReload);
1171 PN->eraseFromParent();
1172 continue;
1173 }
1174
1175 // Replace all uses of CurrentValue in the current instruction with
1176 // reload.
1177 U->replaceUsesOfWith(Def, CurrentReload);
1178 // Instructions are added to Def's user list if the attached
1179 // debug records use Def. Update those now.
1180 for (DbgVariableRecord &DVR : filterDbgVars(U->getDbgRecordRange()))
1181 DVR.replaceVariableLocationOp(Def, CurrentReload, true);
1182 }
1183 }
1184
1185 BasicBlock *FramePtrBB = Shape.getInsertPtAfterFramePtr()->getParent();
1186
1187 auto SpillBlock = FramePtrBB->splitBasicBlock(
1188 Shape.getInsertPtAfterFramePtr(), "AllocaSpillBB");
1189 SpillBlock->splitBasicBlock(&SpillBlock->front(), "PostSpill");
1190 Shape.AllocaSpillBlock = SpillBlock;
1191
1192 // retcon and retcon.once lowering assumes all uses have been sunk.
1193 if (Shape.ABI == coro::ABI::Retcon || Shape.ABI == coro::ABI::RetconOnce ||
1194 Shape.ABI == coro::ABI::Async) {
1195 // If we found any allocas, replace all of their remaining uses with Geps.
1196 Builder.SetInsertPoint(SpillBlock->begin());
1197 for (const auto &P : FrameData.Allocas) {
1198 AllocaInst *Alloca = P.Alloca;
1199 auto *G = createGEPToFramePointer(FrameData, Builder, Shape, Alloca);
1200
1201 // Remove any lifetime intrinsics, now that these are no longer allocas.
1202 for (User *U : make_early_inc_range(Alloca->users())) {
1203 auto *I = cast<Instruction>(U);
1204 if (I->isLifetimeStartOrEnd())
1205 I->eraseFromParent();
1206 }
1207
1208 // We are not using ReplaceInstWithInst(P.first, cast<Instruction>(G))
1209 // here, as we are changing location of the instruction.
1210 G->takeName(Alloca);
1211 Alloca->replaceAllUsesWith(G);
1212 Alloca->eraseFromParent();
1213 }
1214 return;
1215 }
1216
1217 // If we found any alloca, replace all of their remaining uses with GEP
1218 // instructions. To remain debugbility, we replace the uses of allocas for
1219 // dbg.declares and dbg.values with the reload from the frame.
1220 // Note: We cannot replace the alloca with GEP instructions indiscriminately,
1221 // as some of the uses may not be dominated by CoroBegin.
1222 Builder.SetInsertPoint(Shape.AllocaSpillBlock->begin());
1223 SmallVector<Instruction *, 4> UsersToUpdate;
1224 for (const auto &A : FrameData.Allocas) {
1225 AllocaInst *Alloca = A.Alloca;
1226 UsersToUpdate.clear();
1227 for (User *U : make_early_inc_range(Alloca->users())) {
1228 auto *I = cast<Instruction>(U);
1229 // It is meaningless to retain the lifetime intrinsics refer for the
1230 // member of coroutine frames and the meaningless lifetime intrinsics
1231 // are possible to block further optimizations.
1232 if (I->isLifetimeStartOrEnd())
1233 I->eraseFromParent();
1234 else if (DT.dominates(Shape.CoroBegin, I))
1235 UsersToUpdate.push_back(I);
1236 }
1237
1238 if (UsersToUpdate.empty())
1239 continue;
1240 auto *G = createGEPToFramePointer(FrameData, Builder, Shape, Alloca);
1241 G->setName(Alloca->getName() + Twine(".reload.addr"));
1242
1243 SmallVector<DbgVariableRecord *> DbgVariableRecords;
1244 findDbgUsers(Alloca, DbgVariableRecords);
1245 for (auto *DVR : DbgVariableRecords)
1246 DVR->replaceVariableLocationOp(Alloca, G);
1247
1248 for (Instruction *I : UsersToUpdate)
1249 I->replaceUsesOfWith(Alloca, G);
1250
1251 if (Alloca->user_empty())
1252 Alloca->eraseFromParent();
1253 }
1254 Builder.SetInsertPoint(&*Shape.getInsertPtAfterFramePtr());
1255 for (const auto &A : FrameData.Allocas) {
1256 AllocaInst *Alloca = A.Alloca;
1257 if (A.MayWriteBeforeCoroBegin) {
1258 // isEscaped really means potentially modified before CoroBegin.
1259 handleAccessBeforeCoroBegin(FrameData, Shape, Builder, Alloca);
1260 }
1261 // For each alias to Alloca created before CoroBegin but used after
1262 // CoroBegin, we recreate them after CoroBegin by applying the offset
1263 // to the pointer in the frame.
1264 for (const auto &Alias : A.Aliases) {
1265 auto *FramePtr =
1266 createGEPToFramePointer(FrameData, Builder, Shape, Alloca);
1267 auto &Value = *Alias.second;
1268 auto ITy = IntegerType::get(C, Value.getBitWidth());
1269 auto *AliasPtr =
1270 Builder.CreateInBoundsPtrAdd(FramePtr, ConstantInt::get(ITy, Value));
1271 Alias.first->replaceUsesWithIf(
1272 AliasPtr, [&](Use &U) { return DT.dominates(Shape.CoroBegin, U); });
1273 }
1274 }
1275}
1276
1277// Moves the values in the PHIs in SuccBB that correspong to PredBB into a new
1278// PHI in InsertedBB.
1280 BasicBlock *InsertedBB,
1281 BasicBlock *PredBB,
1282 PHINode *UntilPHI = nullptr) {
1283 auto *PN = cast<PHINode>(&SuccBB->front());
1284 do {
1285 int Index = PN->getBasicBlockIndex(InsertedBB);
1286 Value *V = PN->getIncomingValue(Index);
1287 PHINode *InputV = PHINode::Create(
1288 V->getType(), 1, V->getName() + Twine(".") + SuccBB->getName());
1289 InputV->insertBefore(InsertedBB->begin());
1290 InputV->addIncoming(V, PredBB);
1291 PN->setIncomingValue(Index, InputV);
1292 PN = dyn_cast<PHINode>(PN->getNextNode());
1293 } while (PN != UntilPHI);
1294}
1295
1296// Rewrites the PHI Nodes in a cleanuppad.
1297static void rewritePHIsForCleanupPad(BasicBlock *CleanupPadBB,
1298 CleanupPadInst *CleanupPad) {
1299 // For every incoming edge to a CleanupPad we will create a new block holding
1300 // all incoming values in single-value PHI nodes. We will then create another
1301 // block to act as a dispather (as all unwind edges for related EH blocks
1302 // must be the same).
1303 //
1304 // cleanuppad:
1305 // %2 = phi i32[%0, %catchswitch], [%1, %catch.1]
1306 // %3 = cleanuppad within none []
1307 //
1308 // It will create:
1309 //
1310 // cleanuppad.corodispatch
1311 // %2 = phi i8[0, %catchswitch], [1, %catch.1]
1312 // %3 = cleanuppad within none []
1313 // switch i8 % 2, label %unreachable
1314 // [i8 0, label %cleanuppad.from.catchswitch
1315 // i8 1, label %cleanuppad.from.catch.1]
1316 // cleanuppad.from.catchswitch:
1317 // %4 = phi i32 [%0, %catchswitch]
1318 // br %label cleanuppad
1319 // cleanuppad.from.catch.1:
1320 // %6 = phi i32 [%1, %catch.1]
1321 // br %label cleanuppad
1322 // cleanuppad:
1323 // %8 = phi i32 [%4, %cleanuppad.from.catchswitch],
1324 // [%6, %cleanuppad.from.catch.1]
1325
1326 // Unreachable BB, in case switching on an invalid value in the dispatcher.
1327 auto *UnreachBB = BasicBlock::Create(
1328 CleanupPadBB->getContext(), "unreachable", CleanupPadBB->getParent());
1329 IRBuilder<> Builder(UnreachBB);
1330 Builder.CreateUnreachable();
1331
1332 // Create a new cleanuppad which will be the dispatcher.
1333 auto *NewCleanupPadBB =
1334 BasicBlock::Create(CleanupPadBB->getContext(),
1335 CleanupPadBB->getName() + Twine(".corodispatch"),
1336 CleanupPadBB->getParent(), CleanupPadBB);
1337 Builder.SetInsertPoint(NewCleanupPadBB);
1338 auto *SwitchType = Builder.getInt8Ty();
1339 auto *SetDispatchValuePN =
1340 Builder.CreatePHI(SwitchType, pred_size(CleanupPadBB));
1341 CleanupPad->removeFromParent();
1342 CleanupPad->insertAfter(SetDispatchValuePN->getIterator());
1343 auto *SwitchOnDispatch = Builder.CreateSwitch(SetDispatchValuePN, UnreachBB,
1344 pred_size(CleanupPadBB));
1345
1346 int SwitchIndex = 0;
1347 SmallVector<BasicBlock *, 8> Preds(predecessors(CleanupPadBB));
1348 for (BasicBlock *Pred : Preds) {
1349 // Create a new cleanuppad and move the PHI values to there.
1350 auto *CaseBB = BasicBlock::Create(CleanupPadBB->getContext(),
1351 CleanupPadBB->getName() +
1352 Twine(".from.") + Pred->getName(),
1353 CleanupPadBB->getParent(), CleanupPadBB);
1354 updatePhiNodes(CleanupPadBB, Pred, CaseBB);
1355 CaseBB->setName(CleanupPadBB->getName() + Twine(".from.") +
1356 Pred->getName());
1357 Builder.SetInsertPoint(CaseBB);
1358 Builder.CreateBr(CleanupPadBB);
1359 movePHIValuesToInsertedBlock(CleanupPadBB, CaseBB, NewCleanupPadBB);
1360
1361 // Update this Pred to the new unwind point.
1362 setUnwindEdgeTo(Pred->getTerminator(), NewCleanupPadBB);
1363
1364 // Setup the switch in the dispatcher.
1365 auto *SwitchConstant = ConstantInt::get(SwitchType, SwitchIndex);
1366 SetDispatchValuePN->addIncoming(SwitchConstant, Pred);
1367 SwitchOnDispatch->addCase(SwitchConstant, CaseBB);
1368 SwitchIndex++;
1369 }
1370
1372 // Add branch weights to SwitchOnDispatch, where branches are unreachable by
1373 // default. We mark all branches as having equal weights because they are
1374 // mutually exclusive.
1375 MDBuilder MDB(CleanupPadBB->getContext());
1376 SmallVector<uint32_t> Weights;
1377 Weights.push_back(0);
1378 for (int i = 0; i < SwitchIndex; ++i) {
1380 }
1381 SwitchOnDispatch->setMetadata(LLVMContext::MD_prof,
1382 MDB.createBranchWeights(Weights));
1383 }
1384}
1385
1388 for (auto &BB : F) {
1389 for (auto &Phi : BB.phis()) {
1390 if (Phi.getNumIncomingValues() == 1) {
1391 Worklist.push_back(&Phi);
1392 } else
1393 break;
1394 }
1395 }
1396 while (!Worklist.empty()) {
1397 auto *Phi = Worklist.pop_back_val();
1398 auto *OriginalValue = Phi->getIncomingValue(0);
1399 Phi->replaceAllUsesWith(OriginalValue);
1400 }
1401}
1402
1403static void rewritePHIs(BasicBlock &BB) {
1404 // For every incoming edge we will create a block holding all
1405 // incoming values in a single PHI nodes.
1406 //
1407 // loop:
1408 // %n.val = phi i32[%n, %entry], [%inc, %loop]
1409 //
1410 // It will create:
1411 //
1412 // loop.from.entry:
1413 // %n.loop.pre = phi i32 [%n, %entry]
1414 // br %label loop
1415 // loop.from.loop:
1416 // %inc.loop.pre = phi i32 [%inc, %loop]
1417 // br %label loop
1418 //
1419 // After this rewrite, further analysis will ignore any phi nodes with more
1420 // than one incoming edge.
1421
1422 // TODO: Simplify PHINodes in the basic block to remove duplicate
1423 // predecessors.
1424
1425 // Special case for CleanupPad: all EH blocks must have the same unwind edge
1426 // so we need to create an additional "dispatcher" block.
1427 if (!BB.empty()) {
1428 if (auto *CleanupPad =
1431 for (BasicBlock *Pred : Preds) {
1432 if (CatchSwitchInst *CS =
1433 dyn_cast<CatchSwitchInst>(Pred->getTerminator())) {
1434 // CleanupPad with a CatchSwitch predecessor: therefore this is an
1435 // unwind destination that needs to be handle specially.
1436 assert(CS->getUnwindDest() == &BB);
1437 (void)CS;
1438 rewritePHIsForCleanupPad(&BB, CleanupPad);
1439 return;
1440 }
1441 }
1442 }
1443 }
1444
1445 LandingPadInst *LandingPad = nullptr;
1446 PHINode *ReplPHI = nullptr;
1447 if (!BB.empty()) {
1448 if ((LandingPad =
1450 // ehAwareSplitEdge will clone the LandingPad in all the edge blocks.
1451 // We replace the original landing pad with a PHINode that will collect the
1452 // results from all of them.
1453 ReplPHI = PHINode::Create(LandingPad->getType(), 1, "");
1454 ReplPHI->insertBefore(LandingPad->getIterator());
1455 ReplPHI->takeName(LandingPad);
1456 LandingPad->replaceAllUsesWith(ReplPHI);
1457 // We will erase the original landing pad at the end of this function after
1458 // ehAwareSplitEdge cloned it in the transition blocks.
1459 }
1460 }
1461
1463 for (BasicBlock *Pred : Preds) {
1464 auto *IncomingBB = ehAwareSplitEdge(Pred, &BB, LandingPad, ReplPHI);
1465 IncomingBB->setName(BB.getName() + Twine(".from.") + Pred->getName());
1466
1467 // Stop the moving of values at ReplPHI, as this is either null or the PHI
1468 // that replaced the landing pad.
1469 movePHIValuesToInsertedBlock(&BB, IncomingBB, Pred, ReplPHI);
1470 }
1471
1472 if (LandingPad) {
1473 // Calls to ehAwareSplitEdge function cloned the original lading pad.
1474 // No longer need it.
1475 LandingPad->eraseFromParent();
1476 }
1477}
1478
1479static void rewritePHIs(Function &F) {
1481
1482 for (BasicBlock &BB : F)
1483 if (auto *PN = dyn_cast<PHINode>(&BB.front()))
1484 if (PN->getNumIncomingValues() > 1)
1485 WorkList.push_back(&BB);
1486
1487 for (BasicBlock *BB : WorkList)
1488 rewritePHIs(*BB);
1489}
1490
1491// Splits the block at a particular instruction unless it is the first
1492// instruction in the block with a single predecessor.
1494 auto *BB = I->getParent();
1495 if (&BB->front() == I) {
1496 if (BB->getSinglePredecessor()) {
1497 BB->setName(Name);
1498 return BB;
1499 }
1500 }
1501 return BB->splitBasicBlock(I, Name);
1502}
1503
1504// Split above and below a particular instruction so that it
1505// will be all alone by itself in a block.
1506static void splitAround(Instruction *I, const Twine &Name) {
1507 splitBlockIfNotFirst(I, Name);
1508 splitBlockIfNotFirst(I->getNextNode(), "After" + Name);
1509}
1510
1511/// After we split the coroutine, will the given basic block be along
1512/// an obvious exit path for the resumption function?
1514 unsigned depth = 3) {
1515 // If we've bottomed out our depth count, stop searching and assume
1516 // that the path might loop back.
1517 if (depth == 0) return false;
1518
1519 // If this is a suspend block, we're about to exit the resumption function.
1520 if (coro::isSuspendBlock(BB))
1521 return true;
1522
1523 // Recurse into the successors.
1524 for (auto *Succ : successors(BB)) {
1525 if (!willLeaveFunctionImmediatelyAfter(Succ, depth - 1))
1526 return false;
1527 }
1528
1529 // If none of the successors leads back in a loop, we're on an exit/abort.
1530 return true;
1531}
1532
1534 // Look for a free that isn't sufficiently obviously followed by
1535 // either a suspend or a termination, i.e. something that will leave
1536 // the coro resumption frame.
1537 for (auto *U : AI->users()) {
1538 auto FI = dyn_cast<CoroAllocaFreeInst>(U);
1539 if (!FI) continue;
1540
1541 if (!willLeaveFunctionImmediatelyAfter(FI->getParent()))
1542 return true;
1543 }
1544
1545 // If we never found one, we don't need a stack save.
1546 return false;
1547}
1548
1549/// Turn each of the given local allocas into a normal (dynamic) alloca
1550/// instruction.
1552 SmallVectorImpl<Instruction*> &DeadInsts) {
1553 for (auto *AI : LocalAllocas) {
1554 IRBuilder<> Builder(AI);
1555
1556 // Save the stack depth. Try to avoid doing this if the stackrestore
1557 // is going to immediately precede a return or something.
1558 Value *StackSave = nullptr;
1560 StackSave = Builder.CreateStackSave();
1561
1562 // Allocate memory.
1563 auto Alloca = Builder.CreateAlloca(Builder.getInt8Ty(), AI->getSize());
1564 Alloca->setAlignment(AI->getAlignment());
1565
1566 for (auto *U : AI->users()) {
1567 // Replace gets with the allocation.
1568 if (isa<CoroAllocaGetInst>(U)) {
1569 U->replaceAllUsesWith(Alloca);
1570
1571 // Replace frees with stackrestores. This is safe because
1572 // alloca.alloc is required to obey a stack discipline, although we
1573 // don't enforce that structurally.
1574 } else {
1575 auto FI = cast<CoroAllocaFreeInst>(U);
1576 if (StackSave) {
1577 Builder.SetInsertPoint(FI);
1578 Builder.CreateStackRestore(StackSave);
1579 }
1580 }
1581 DeadInsts.push_back(cast<Instruction>(U));
1582 }
1583
1584 DeadInsts.push_back(AI);
1585 }
1586}
1587
1588/// Get the current swifterror value.
1590 coro::Shape &Shape) {
1591 // Make a fake function pointer as a sort of intrinsic.
1592 auto FnTy = FunctionType::get(ValueTy, {}, false);
1593 auto Fn = ConstantPointerNull::get(Builder.getPtrTy());
1594
1595 auto Call = Builder.CreateCall(FnTy, Fn, {});
1596 Shape.SwiftErrorOps.push_back(Call);
1597
1598 return Call;
1599}
1600
1601/// Set the given value as the current swifterror value.
1602///
1603/// Returns a slot that can be used as a swifterror slot.
1605 coro::Shape &Shape) {
1606 // Make a fake function pointer as a sort of intrinsic.
1607 auto FnTy = FunctionType::get(Builder.getPtrTy(),
1608 {V->getType()}, false);
1609 auto Fn = ConstantPointerNull::get(Builder.getPtrTy());
1610
1611 auto Call = Builder.CreateCall(FnTy, Fn, { V });
1612 Shape.SwiftErrorOps.push_back(Call);
1613
1614 return Call;
1615}
1616
1617/// Set the swifterror value from the given alloca before a call,
1618/// then put in back in the alloca afterwards.
1619///
1620/// Returns an address that will stand in for the swifterror slot
1621/// until splitting.
1623 AllocaInst *Alloca,
1624 coro::Shape &Shape) {
1625 auto ValueTy = Alloca->getAllocatedType();
1626 IRBuilder<> Builder(Call);
1627
1628 // Load the current value from the alloca and set it as the
1629 // swifterror value.
1630 auto ValueBeforeCall = Builder.CreateLoad(ValueTy, Alloca);
1631 auto Addr = emitSetSwiftErrorValue(Builder, ValueBeforeCall, Shape);
1632
1633 // Move to after the call. Since swifterror only has a guaranteed
1634 // value on normal exits, we can ignore implicit and explicit unwind
1635 // edges.
1636 if (isa<CallInst>(Call)) {
1637 Builder.SetInsertPoint(Call->getNextNode());
1638 } else {
1639 auto Invoke = cast<InvokeInst>(Call);
1640 Builder.SetInsertPoint(Invoke->getNormalDest()->getFirstNonPHIOrDbg());
1641 }
1642
1643 // Get the current swifterror value and store it to the alloca.
1644 auto ValueAfterCall = emitGetSwiftErrorValue(Builder, ValueTy, Shape);
1645 Builder.CreateStore(ValueAfterCall, Alloca);
1646
1647 return Addr;
1648}
1649
1650/// Eliminate a formerly-swifterror alloca by inserting the get/set
1651/// intrinsics and attempting to MemToReg the alloca away.
1653 coro::Shape &Shape) {
1654 for (Use &Use : llvm::make_early_inc_range(Alloca->uses())) {
1655 // swifterror values can only be used in very specific ways.
1656 // We take advantage of that here.
1657 auto User = Use.getUser();
1659 continue;
1660
1662 auto Call = cast<Instruction>(User);
1663
1664 auto Addr = emitSetAndGetSwiftErrorValueAround(Call, Alloca, Shape);
1665
1666 // Use the returned slot address as the call argument.
1667 Use.set(Addr);
1668 }
1669
1670 // All the uses should be loads and stores now.
1671 assert(isAllocaPromotable(Alloca));
1672}
1673
1674/// "Eliminate" a swifterror argument by reducing it to the alloca case
1675/// and then loading and storing in the prologue and epilog.
1676///
1677/// The argument keeps the swifterror flag.
1679 coro::Shape &Shape,
1680 SmallVectorImpl<AllocaInst*> &AllocasToPromote) {
1681 IRBuilder<> Builder(&F.getEntryBlock(),
1682 F.getEntryBlock().getFirstNonPHIOrDbg());
1683
1684 auto ArgTy = cast<PointerType>(Arg.getType());
1685 auto ValueTy = PointerType::getUnqual(F.getContext());
1686
1687 // Reduce to the alloca case:
1688
1689 // Create an alloca and replace all uses of the arg with it.
1690 auto Alloca = Builder.CreateAlloca(ValueTy, ArgTy->getAddressSpace());
1691 Arg.replaceAllUsesWith(Alloca);
1692
1693 // Set an initial value in the alloca. swifterror is always null on entry.
1694 auto InitialValue = Constant::getNullValue(ValueTy);
1695 Builder.CreateStore(InitialValue, Alloca);
1696
1697 // Find all the suspends in the function and save and restore around them.
1698 for (auto *Suspend : Shape.CoroSuspends) {
1699 (void) emitSetAndGetSwiftErrorValueAround(Suspend, Alloca, Shape);
1700 }
1701
1702 // Find all the coro.ends in the function and restore the error value.
1703 for (auto *End : Shape.CoroEnds) {
1704 Builder.SetInsertPoint(End);
1705 auto FinalValue = Builder.CreateLoad(ValueTy, Alloca);
1706 (void) emitSetSwiftErrorValue(Builder, FinalValue, Shape);
1707 }
1708
1709 // Now we can use the alloca logic.
1710 AllocasToPromote.push_back(Alloca);
1711 eliminateSwiftErrorAlloca(F, Alloca, Shape);
1712}
1713
1714/// Eliminate all problematic uses of swifterror arguments and allocas
1715/// from the function. We'll fix them up later when splitting the function.
1717 SmallVector<AllocaInst*, 4> AllocasToPromote;
1718
1719 // Look for a swifterror argument.
1720 for (auto &Arg : F.args()) {
1721 if (!Arg.hasSwiftErrorAttr()) continue;
1722
1723 eliminateSwiftErrorArgument(F, Arg, Shape, AllocasToPromote);
1724 break;
1725 }
1726
1727 // Look for swifterror allocas.
1728 for (auto &Inst : F.getEntryBlock()) {
1729 auto Alloca = dyn_cast<AllocaInst>(&Inst);
1730 if (!Alloca || !Alloca->isSwiftError()) continue;
1731
1732 // Clear the swifterror flag.
1733 Alloca->setSwiftError(false);
1734
1735 AllocasToPromote.push_back(Alloca);
1736 eliminateSwiftErrorAlloca(F, Alloca, Shape);
1737 }
1738
1739 // If we have any allocas to promote, compute a dominator tree and
1740 // promote them en masse.
1741 if (!AllocasToPromote.empty()) {
1742 DominatorTree DT(F);
1743 PromoteMemToReg(AllocasToPromote, DT);
1744 }
1745}
1746
1747/// For each local variable that all of its user are only used inside one of
1748/// suspended region, we sink their lifetime.start markers to the place where
1749/// after the suspend block. Doing so minimizes the lifetime of each variable,
1750/// hence minimizing the amount of data we end up putting on the frame.
1752 SuspendCrossingInfo &Checker,
1753 const DominatorTree &DT) {
1754 if (F.hasOptNone())
1755 return;
1756
1757 // Collect all possible basic blocks which may dominate all uses of allocas.
1759 DomSet.insert(&F.getEntryBlock());
1760 for (auto *CSI : Shape.CoroSuspends) {
1761 BasicBlock *SuspendBlock = CSI->getParent();
1762 assert(coro::isSuspendBlock(SuspendBlock) &&
1763 SuspendBlock->getSingleSuccessor() &&
1764 "should have split coro.suspend into its own block");
1765 DomSet.insert(SuspendBlock->getSingleSuccessor());
1766 }
1767
1768 for (Instruction &I : instructions(F)) {
1770 if (!AI)
1771 continue;
1772
1773 for (BasicBlock *DomBB : DomSet) {
1774 bool Valid = true;
1776
1777 auto isLifetimeStart = [](Instruction* I) {
1778 if (auto* II = dyn_cast<IntrinsicInst>(I))
1779 return II->getIntrinsicID() == Intrinsic::lifetime_start;
1780 return false;
1781 };
1782
1783 auto collectLifetimeStart = [&](Instruction *U, AllocaInst *AI) {
1784 if (isLifetimeStart(U)) {
1785 Lifetimes.push_back(U);
1786 return true;
1787 }
1788 if (!U->hasOneUse() || U->stripPointerCasts() != AI)
1789 return false;
1790 if (isLifetimeStart(U->user_back())) {
1791 Lifetimes.push_back(U->user_back());
1792 return true;
1793 }
1794 return false;
1795 };
1796
1797 for (User *U : AI->users()) {
1799 // For all users except lifetime.start markers, if they are all
1800 // dominated by one of the basic blocks and do not cross
1801 // suspend points as well, then there is no need to spill the
1802 // instruction.
1803 if (!DT.dominates(DomBB, UI->getParent()) ||
1804 Checker.isDefinitionAcrossSuspend(DomBB, UI)) {
1805 // Skip lifetime.start, GEP and bitcast used by lifetime.start
1806 // markers.
1807 if (collectLifetimeStart(UI, AI))
1808 continue;
1809 Valid = false;
1810 break;
1811 }
1812 }
1813 // Sink lifetime.start markers to dominate block when they are
1814 // only used outside the region.
1815 if (Valid && Lifetimes.size() != 0) {
1816 auto *NewLifetime = Lifetimes[0]->clone();
1817 NewLifetime->replaceUsesOfWith(NewLifetime->getOperand(0), AI);
1818 NewLifetime->insertBefore(DomBB->getTerminator()->getIterator());
1819
1820 // All the outsided lifetime.start markers are no longer necessary.
1821 for (Instruction *S : Lifetimes)
1822 S->eraseFromParent();
1823
1824 break;
1825 }
1826 }
1827 }
1828}
1829
1830static std::optional<std::pair<Value &, DIExpression &>>
1832 bool UseEntryValue, Function *F, Value *Storage,
1833 DIExpression *Expr, bool SkipOutermostLoad) {
1834 IRBuilder<> Builder(F->getContext());
1835 auto InsertPt = F->getEntryBlock().getFirstInsertionPt();
1836 while (isa<IntrinsicInst>(InsertPt))
1837 ++InsertPt;
1838 Builder.SetInsertPoint(InsertPt);
1839
1840 while (auto *Inst = dyn_cast_or_null<Instruction>(Storage)) {
1841 if (auto *LdInst = dyn_cast<LoadInst>(Inst)) {
1842 Storage = LdInst->getPointerOperand();
1843 // FIXME: This is a heuristic that works around the fact that
1844 // LLVM IR debug intrinsics cannot yet distinguish between
1845 // memory and value locations: Because a dbg.declare(alloca) is
1846 // implicitly a memory location no DW_OP_deref operation for the
1847 // last direct load from an alloca is necessary. This condition
1848 // effectively drops the *last* DW_OP_deref in the expression.
1849 if (!SkipOutermostLoad)
1851 } else if (auto *StInst = dyn_cast<StoreInst>(Inst)) {
1852 Storage = StInst->getValueOperand();
1853 } else {
1855 SmallVector<Value *, 0> AdditionalValues;
1857 *Inst, Expr ? Expr->getNumLocationOperands() : 0, Ops,
1858 AdditionalValues);
1859 if (!Op || !AdditionalValues.empty()) {
1860 // If salvaging failed or salvaging produced more than one location
1861 // operand, give up.
1862 break;
1863 }
1864 Storage = Op;
1865 Expr = DIExpression::appendOpsToArg(Expr, Ops, 0, /*StackValue*/ false);
1866 }
1867 SkipOutermostLoad = false;
1868 }
1869 if (!Storage)
1870 return std::nullopt;
1871
1872 auto *StorageAsArg = dyn_cast<Argument>(Storage);
1873
1874 const bool IsSingleLocationExpression = Expr->isSingleLocationExpression();
1875 // Use an EntryValue when requested (UseEntryValue) for swift async Arguments.
1876 // Entry values in variadic expressions are not supported.
1877 const bool WillUseEntryValue =
1878 UseEntryValue && StorageAsArg &&
1879 StorageAsArg->hasAttribute(Attribute::SwiftAsync) &&
1880 !Expr->isEntryValue() && IsSingleLocationExpression;
1881
1882 if (WillUseEntryValue)
1884
1885 // If the coroutine frame is an Argument, store it in an alloca to improve
1886 // its availability (e.g. registers may be clobbered).
1887 // Avoid this if the value is guaranteed to be available through other means
1888 // (e.g. swift ABI guarantees).
1889 // Avoid this if multiple location expressions are involved, as LLVM does not
1890 // know how to prepend a deref in this scenario.
1891 if (StorageAsArg && !WillUseEntryValue && IsSingleLocationExpression) {
1892 auto &Cached = ArgToAllocaMap[StorageAsArg];
1893 if (!Cached) {
1894 Cached = Builder.CreateAlloca(Storage->getType(), 0, nullptr,
1895 Storage->getName() + ".debug");
1896 Builder.CreateStore(Storage, Cached);
1897 }
1898 Storage = Cached;
1899 // FIXME: LLVM lacks nuanced semantics to differentiate between
1900 // memory and direct locations at the IR level. The backend will
1901 // turn a dbg.declare(alloca, ..., DIExpression()) into a memory
1902 // location. Thus, if there are deref and offset operations in the
1903 // expression, we need to add a DW_OP_deref at the *start* of the
1904 // expression to first load the contents of the alloca before
1905 // adjusting it with the expression.
1907 }
1908
1909 Expr = Expr->foldConstantMath();
1910 return {{*Storage, *Expr}};
1911}
1912
1915 DbgVariableRecord &DVR, bool UseEntryValue) {
1916
1917 Function *F = DVR.getFunction();
1918 // Follow the pointer arithmetic all the way to the incoming
1919 // function argument and convert into a DIExpression.
1920 bool SkipOutermostLoad = DVR.isDbgDeclare() || DVR.isDbgDeclareValue();
1921 Value *OriginalStorage = DVR.getVariableLocationOp(0);
1922
1923 auto SalvagedInfo =
1924 ::salvageDebugInfoImpl(ArgToAllocaMap, UseEntryValue, F, OriginalStorage,
1925 DVR.getExpression(), SkipOutermostLoad);
1926 if (!SalvagedInfo)
1927 return;
1928
1929 Value *Storage = &SalvagedInfo->first;
1930 DIExpression *Expr = &SalvagedInfo->second;
1931
1932 DVR.replaceVariableLocationOp(OriginalStorage, Storage);
1933 DVR.setExpression(Expr);
1934 // We only hoist dbg.declare and dbg.declare_value today since it doesn't make
1935 // sense to hoist dbg.value since it does not have the same function wide
1936 // guarantees that dbg.declare does.
1939 std::optional<BasicBlock::iterator> InsertPt;
1940 if (auto *I = dyn_cast<Instruction>(Storage)) {
1941 InsertPt = I->getInsertionPointAfterDef();
1942 // Update DILocation only if variable was not inlined.
1943 DebugLoc ILoc = I->getDebugLoc();
1944 DebugLoc DVRLoc = DVR.getDebugLoc();
1945 if (ILoc && DVRLoc &&
1946 DVRLoc->getScope()->getSubprogram() ==
1947 ILoc->getScope()->getSubprogram())
1948 DVR.setDebugLoc(ILoc);
1949 } else if (isa<Argument>(Storage))
1950 InsertPt = F->getEntryBlock().begin();
1951 if (InsertPt) {
1952 DVR.removeFromParent();
1953 // If there is a dbg.declare_value being reinserted, insert it as a
1954 // dbg.declare instead, so that subsequent passes don't have to deal with
1955 // a dbg.declare_value.
1957 auto *MD = DVR.getRawLocation();
1958 if (auto *VAM = dyn_cast<ValueAsMetadata>(MD)) {
1959 Type *Ty = VAM->getValue()->getType();
1960 if (Ty->isPointerTy())
1962 else
1964 }
1965 }
1966 (*InsertPt)->getParent()->insertDbgRecordBefore(&DVR, *InsertPt);
1967 }
1968 }
1969}
1970
1973 // Don't eliminate swifterror in async functions that won't be split.
1974 if (Shape.ABI != coro::ABI::Async || !Shape.CoroSuspends.empty())
1976
1977 if (Shape.ABI == coro::ABI::Switch &&
1980 }
1981
1982 // Make sure that all coro.save, coro.suspend and the fallthrough coro.end
1983 // intrinsics are in their own blocks to simplify the logic of building up
1984 // SuspendCrossing data.
1985 for (auto *CSI : Shape.CoroSuspends) {
1986 if (auto *Save = CSI->getCoroSave())
1987 splitAround(Save, "CoroSave");
1988 splitAround(CSI, "CoroSuspend");
1989 }
1990
1991 // Put CoroEnds into their own blocks.
1992 for (AnyCoroEndInst *CE : Shape.CoroEnds) {
1993 splitAround(CE, "CoroEnd");
1994
1995 // Emit the musttail call function in a new block before the CoroEnd.
1996 // We do this here so that the right suspend crossing info is computed for
1997 // the uses of the musttail call function call. (Arguments to the coro.end
1998 // instructions would be ignored)
1999 if (auto *AsyncEnd = dyn_cast<CoroAsyncEndInst>(CE)) {
2000 auto *MustTailCallFn = AsyncEnd->getMustTailCallFunction();
2001 if (!MustTailCallFn)
2002 continue;
2003 IRBuilder<> Builder(AsyncEnd);
2004 SmallVector<Value *, 8> Args(AsyncEnd->args());
2005 auto Arguments = ArrayRef<Value *>(Args).drop_front(3);
2007 AsyncEnd->getDebugLoc(), MustTailCallFn, TTI, Arguments, Builder);
2008 splitAround(Call, "MustTailCall.Before.CoroEnd");
2009 }
2010 }
2011
2012 // Later code makes structural assumptions about single predecessors phis e.g
2013 // that they are not live across a suspend point.
2015
2016 // Transforms multi-edge PHI Nodes, so that any value feeding into a PHI will
2017 // never have its definition separated from the PHI by the suspend point.
2018 rewritePHIs(F);
2019}
2020
2021void coro::BaseABI::buildCoroutineFrame(bool OptimizeFrame) {
2022 SuspendCrossingInfo Checker(F, Shape);
2024
2025 const DominatorTree DT(F);
2026 if (Shape.ABI != coro::ABI::Async && Shape.ABI != coro::ABI::Retcon &&
2028 sinkLifetimeStartMarkers(F, Shape, Checker, DT);
2029
2030 // All values (that are not allocas) that needs to be spilled to the frame.
2031 coro::SpillInfo Spills;
2032 // All values defined as allocas that need to live in the frame.
2034
2035 // Collect the spills for arguments and other not-materializable values.
2036 coro::collectSpillsFromArgs(Spills, F, Checker);
2037 SmallVector<Instruction *, 4> DeadInstructions;
2039 coro::collectSpillsAndAllocasFromInsts(Spills, Allocas, DeadInstructions,
2040 LocalAllocas, F, Checker, DT, Shape);
2041 coro::collectSpillsFromDbgInfo(Spills, F, Checker);
2042
2043 LLVM_DEBUG(dumpAllocas(Allocas));
2044 LLVM_DEBUG(dumpSpills("Spills", Spills));
2045
2046 if (Shape.ABI == coro::ABI::Retcon || Shape.ABI == coro::ABI::RetconOnce ||
2047 Shape.ABI == coro::ABI::Async)
2048 sinkSpillUsesAfterCoroBegin(DT, Shape.CoroBegin, Spills, Allocas);
2049
2050 // Build frame layout
2051 FrameDataInfo FrameData(Spills, Allocas);
2052 buildFrameLayout(F, DT, Shape, FrameData, OptimizeFrame);
2053 Shape.FramePtr = Shape.CoroBegin;
2054 // For now, this works for C++ programs only.
2055 buildFrameDebugInfo(F, Shape, FrameData);
2056 // Insert spills and reloads
2057 insertSpills(FrameData, Shape);
2058 lowerLocalAllocas(LocalAllocas, DeadInstructions);
2059
2060 for (auto *I : DeadInstructions)
2061 I->eraseFromParent();
2062}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned uint64_t
AMDGPU Lower Kernel Arguments
Rewrite undef for false bool rewritePHIs(Function &F, UniformityInfo &UA, DominatorTree *DT)
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Expand Atomic instructions
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static void cleanupSinglePredPHIs(Function &F)
static TinyPtrVector< DbgVariableRecord * > findDbgRecordsThroughLoads(Function &F, Value *Def)
Find dbg.declare or dbg.declare_value records referencing Def.
static void createStoreIntoFrame(IRBuilder<> &Builder, Value *Def, Type *ByValTy, const coro::Shape &Shape, const FrameDataInfo &FrameData)
Store Def into the coroutine frame.
static void eliminateSwiftError(Function &F, coro::Shape &Shape)
Eliminate all problematic uses of swifterror arguments and allocas from the function.
static void lowerLocalAllocas(ArrayRef< CoroAllocaAllocInst * > LocalAllocas, SmallVectorImpl< Instruction * > &DeadInsts)
Turn each of the given local allocas into a normal (dynamic) alloca instruction.
static Value * emitSetSwiftErrorValue(IRBuilder<> &Builder, Value *V, coro::Shape &Shape)
Set the given value as the current swifterror value.
static Value * emitSetAndGetSwiftErrorValueAround(Instruction *Call, AllocaInst *Alloca, coro::Shape &Shape)
Set the swifterror value from the given alloca before a call, then put in back in the alloca afterwar...
static void cacheDIVar(FrameDataInfo &FrameData, DenseMap< Value *, DILocalVariable * > &DIVarCache)
static bool localAllocaNeedsStackSave(CoroAllocaAllocInst *AI)
static void dumpAllocas(const SmallVectorImpl< coro::AllocaInfo > &Allocas)
static void splitAround(Instruction *I, const Twine &Name)
static void eliminateSwiftErrorAlloca(Function &F, AllocaInst *Alloca, coro::Shape &Shape)
Eliminate a formerly-swifterror alloca by inserting the get/set intrinsics and attempting to MemToReg...
static void buildFrameLayout(Function &F, const DominatorTree &DT, coro::Shape &Shape, FrameDataInfo &FrameData, bool OptimizeFrame)
static void movePHIValuesToInsertedBlock(BasicBlock *SuccBB, BasicBlock *InsertedBB, BasicBlock *PredBB, PHINode *UntilPHI=nullptr)
static void dumpSpills(StringRef Title, const coro::SpillInfo &Spills)
static DIType * solveDIType(DIBuilder &Builder, Type *Ty, const DataLayout &Layout, DIScope *Scope, unsigned LineNum, DenseMap< Type *, DIType * > &DITypeCache)
static bool willLeaveFunctionImmediatelyAfter(BasicBlock *BB, unsigned depth=3)
After we split the coroutine, will the given basic block be along an obvious exit path for the resump...
static void eliminateSwiftErrorArgument(Function &F, Argument &Arg, coro::Shape &Shape, SmallVectorImpl< AllocaInst * > &AllocasToPromote)
"Eliminate" a swifterror argument by reducing it to the alloca case and then loading and storing in t...
static void buildFrameDebugInfo(Function &F, coro::Shape &Shape, FrameDataInfo &FrameData)
Build artificial debug info for C++ coroutine frames to allow users to inspect the contents of the fr...
static Value * createGEPToFramePointer(const FrameDataInfo &FrameData, IRBuilder<> &Builder, coro::Shape &Shape, Value *Orig)
Returns a pointer into the coroutine frame at the offset where Orig is located.
static bool hasAccessingPromiseBeforeCB(const DominatorTree &DT, coro::Shape &Shape)
static BasicBlock * splitBlockIfNotFirst(Instruction *I, const Twine &Name)
static void rewritePHIsForCleanupPad(BasicBlock *CleanupPadBB, CleanupPadInst *CleanupPad)
static void sinkLifetimeStartMarkers(Function &F, coro::Shape &Shape, SuspendCrossingInfo &Checker, const DominatorTree &DT)
For each local variable that all of its user are only used inside one of suspended region,...
static Type * extractByvalIfArgument(Value *MaybeArgument)
If MaybeArgument is a byval Argument, return its byval type.
static StringRef solveTypeName(Type *Ty)
Create name for Type.
static Value * emitGetSwiftErrorValue(IRBuilder<> &Builder, Type *ValueTy, coro::Shape &Shape)
Get the current swifterror value.
static void insertSpills(const FrameDataInfo &FrameData, coro::Shape &Shape)
static void handleAccessBeforeCoroBegin(const FrameDataInfo &FrameData, coro::Shape &Shape, IRBuilder<> &Builder, AllocaInst *Alloca)
static bool isLifetimeStart(const Instruction *Inst)
Definition GVN.cpp:1522
Hexagon Common GEP
static MaybeAlign getAlign(Value *Ptr)
Module.h This file contains the declarations for the Module class.
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define G(x, y, z)
Definition MD5.cpp:55
uint64_t IntrinsicInst * II
OptimizedStructLayoutField Field
This file provides an interface for laying out a sequence of fields as a struct in a way that attempt...
#define P(N)
This file contains the declarations for profiling metadata utility functions.
This file defines the scope_exit class, which executes user-defined cleanup logic at scope exit.
This file defines the SmallString class.
#define LLVM_DEBUG(...)
Definition Debug.h:119
static const unsigned FramePtr
an instruction to allocate memory on the stack
bool isSwiftError() const
Return true if this alloca is used as a swifterror argument to a call.
void setSwiftError(bool V)
Specify whether this alloca is used to represent a swifterror.
Align getAlign() const
Return the alignment of the memory that is being allocated by the instruction.
PointerType * getType() const
Overload to return most specific pointer type.
Type * getAllocatedType() const
Return the type that is being allocated by the instruction.
LLVM_ABI std::optional< TypeSize > getAllocationSize(const DataLayout &DL) const
Get allocation size in bytes.
void setAlignment(Align Align)
This class represents an incoming formal argument to a Function.
Definition Argument.h:32
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:446
LLVM_ABI const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
LLVM_ABI BasicBlock * splitBasicBlock(iterator I, const Twine &BBName="")
Split the basic block into two basic blocks at the specified instruction.
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
bool empty() const
Definition BasicBlock.h:468
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:206
const Instruction & front() const
Definition BasicBlock.h:469
LLVM_ABI const BasicBlock * getSingleSuccessor() const
Return the successor of this block if it has a single successor.
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
LLVM_ABI LLVMContext & getContext() const
Get the context in which this basic block lives.
static LLVM_ABI ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
This represents the llvm.coro.alloca.alloc instruction.
Definition CoroInstr.h:776
void clearPromise()
Definition CoroInstr.h:159
LLVM_ABI DICompositeType * createStructType(DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber, Metadata *SizeInBits, uint32_t AlignInBits, DINode::DIFlags Flags, DIType *DerivedFrom, DINodeArray Elements, unsigned RunTimeLang=0, DIType *VTableHolder=nullptr, StringRef UniqueIdentifier="", DIType *Specification=nullptr, uint32_t NumExtraInhabitants=0, DINodeArray Annotations=nullptr)
Create debugging information entry for a struct.
LLVM_ABI DIDerivedType * createMemberType(DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNo, Metadata *SizeInBits, uint32_t AlignInBits, Metadata *OffsetInBits, DINode::DIFlags Flags, DIType *Ty, DINodeArray Annotations=nullptr)
Create debugging information entry for a member.
LLVM_ABI DIDerivedType * createPointerType(DIType *PointeeTy, uint64_t SizeInBits, uint32_t AlignInBits=0, std::optional< unsigned > DWARFAddressSpace=std::nullopt, StringRef Name="", DINodeArray Annotations=nullptr)
Create debugging information entry for a pointer.
LLVM_ABI DIBasicType * createBasicType(StringRef Name, uint64_t SizeInBits, unsigned Encoding, DINode::DIFlags Flags=DINode::FlagZero, uint32_t NumExtraInhabitants=0, uint32_t DataSizeInBits=0)
Create debugging information entry for a basic type.
LLVM_ABI DINodeArray getOrCreateArray(ArrayRef< Metadata * > Elements)
Get a DINodeArray, create one if required.
LLVM_ABI DIExpression * createExpression(ArrayRef< uint64_t > Addr={})
Create a new descriptor for the specified variable which has a complex address expression for its add...
LLVM_ABI DILocalVariable * createAutoVariable(DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNo, DIType *Ty, bool AlwaysPreserve=false, DINode::DIFlags Flags=DINode::FlagZero, uint32_t AlignInBits=0)
Create a new descriptor for an auto variable.
LLVM_ABI void replaceArrays(DICompositeType *&T, DINodeArray Elements, DINodeArray TParams=DINodeArray())
Replace arrays on a composite type.
DWARF expression.
LLVM_ABI bool isEntryValue() const
Check if the expression consists of exactly one entry value operand.
static LLVM_ABI DIExpression * appendOpsToArg(const DIExpression *Expr, ArrayRef< uint64_t > Ops, unsigned ArgNo, bool StackValue=false)
Create a copy of Expr by appending the given list of Ops to each instance of the operand DW_OP_LLVM_a...
LLVM_ABI DIExpression * foldConstantMath()
Try to shorten an expression with constant math operations that can be evaluated at compile time.
LLVM_ABI uint64_t getNumLocationOperands() const
Return the number of unique location operands referred to (via DW_OP_LLVM_arg) in this expression; th...
static LLVM_ABI DIExpression * prepend(const DIExpression *Expr, uint8_t Flags, int64_t Offset=0)
Prepend DIExpr with a deref and offset operation and optionally turn it into a stack value or/and an ...
LLVM_ABI bool isSingleLocationExpression() const
Return whether the evaluated expression makes use of a single location at the start of the expression...
Base class for scope-like contexts.
DIFile * getFile() const
Subprogram description. Uses SubclassData1.
Base class for types.
StringRef getName() const
uint64_t getSizeInBits() const
LLVM_ABI uint32_t getAlignInBits() const
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
unsigned getPointerSizeInBits(unsigned AS=0) const
The size in bits of the pointer representation in a given address space.
Definition DataLayout.h:501
LLVM_ABI const StructLayout * getStructLayout(StructType *Ty) const
Returns a StructLayout object, indicating the alignment of the struct, its size, and the offsets of i...
LLVM_ABI Align getABITypeAlign(Type *Ty) const
Returns the minimum ABI-required alignment for the specified type.
TypeSize getTypeSizeInBits(Type *Ty) const
Size examples:
Definition DataLayout.h:791
LLVM_ABI Align getPointerABIAlignment(unsigned AS) const
Layout pointer alignment.
LLVM_ABI Align getPrefTypeAlign(Type *Ty) const
Returns the preferred stack/global alignment for the specified type.
LLVM_ABI void removeFromParent()
DebugLoc getDebugLoc() const
void setDebugLoc(DebugLoc Loc)
LLVM_ABI Function * getFunction()
Record of a variable value-assignment, aka a non instruction representation of the dbg....
LocationType Type
Classification of the debug-info record that this DbgVariableRecord represents.
LLVM_ABI void replaceVariableLocationOp(Value *OldValue, Value *NewValue, bool AllowEmpty=false)
LLVM_ABI Value * getVariableLocationOp(unsigned OpIdx) const
void setExpression(DIExpression *NewExpr)
DIExpression * getExpression() const
Metadata * getRawLocation() const
Returns the metadata operand for the first location description.
A debug info location.
Definition DebugLoc.h:126
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
Definition DenseMap.h:773
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:782
iterator end()
Definition DenseMap.h:702
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Definition DenseMap.h:809
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:843
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
static LLVM_ABI FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2901
LLVM_ABI void removeFromParent()
This method unlinks 'this' from the containing basic block, but does not delete it.
LLVM_ABI const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
LLVM_ABI void insertBefore(InstListType::iterator InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified position.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
iterator_range< user_iterator > users()
LLVM_ABI void insertAfter(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately after the specified instruction.
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this instruction belongs to.
Class to represent integer types.
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition Type.cpp:338
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
The landingpad instruction holds all of the information necessary to generate correct exception handl...
LLVM_ABI MDNode * createBranchWeights(uint32_t TrueWeight, uint32_t FalseWeight, bool IsExpected=false)
Return metadata containing two branch weights.
Definition MDBuilder.cpp:38
LLVM_ABI MDNode * createTBAAScalarTypeNode(StringRef Name, MDNode *Parent, uint64_t Offset=0)
Return metadata for a TBAA scalar type node with the given name, an offset and a parent in the TBAA t...
static constexpr uint32_t kUnlikelyBranchWeight
The weight for a branch taken with low probability.
Definition MDBuilder.h:53
LLVM_ABI MDNode * createTBAAStructTagNode(MDNode *BaseType, MDNode *AccessType, uint64_t Offset, bool IsConstant=false)
Return metadata for a TBAA tag node with the given base type, access type and offset relative to the ...
Metadata node.
Definition Metadata.h:1081
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1579
LLVMContext & getContext() const
Definition Metadata.h:1245
static MDTuple * getIfExists(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1583
static LLVM_ABI MDString * getIfExists(LLVMContext &Context, StringRef Str)
Definition Metadata.cpp:607
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
Definition Metadata.cpp:597
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static PointerType * getUnqual(LLVMContext &C)
This constructs an opaque pointer to an object in the default address space (address space zero).
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:26
StringRef str() const
Explicit conversion to StringRef.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void reserve(size_type N)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
std::string str() const
Get the contents as an std::string.
Definition StringRef.h:222
TypeSize getElementOffsetInBits(unsigned Idx) const
Definition DataLayout.h:779
bool isDefinitionAcrossSuspend(BasicBlock *DefBB, User *U) const
void setDefaultDest(BasicBlock *DefaultCase)
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
TinyPtrVector - This class is specialized for cases where there are normally 0 or 1 element in a vect...
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
LLVM_ABI std::string str() const
Return the twine contents as a std::string.
Definition Twine.cpp:17
static constexpr TypeSize getFixed(ScalarTy ExactSize)
Definition TypeSize.h:339
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
Definition Type.cpp:300
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:303
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
LLVM_ABI void set(Value *Val)
Definition Value.h:876
User * getUser() const
Returns the User that contains this Use.
Definition Use.h:61
static LLVM_ABI ValueAsMetadata * get(Value *V)
Definition Metadata.cpp:514
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:553
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
iterator_range< use_iterator > uses()
Definition Value.h:382
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:319
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:400
bool user_empty() const
Definition Value.h:391
std::function< bool(Instruction &I)> IsMaterializable
Definition ABI.h:64
Function & F
Definition ABI.h:59
virtual void buildCoroutineFrame(bool OptimizeFrame)
coro::Shape & Shape
Definition ABI.h:60
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:200
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
A raw_ostream that writes to an SmallVector or SmallString.
StringRef str() const
Return a StringRef for the vector contents.
CallInst * Call
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
SmallMapVector< Value *, SmallVector< Instruction *, 2 >, 8 > SpillInfo
Definition SpillUtils.h:18
@ Async
The "async continuation" lowering, where each suspend point creates a single continuation function.
Definition CoroShape.h:49
@ RetconOnce
The "unique returned-continuation" lowering, where each suspend point creates a single continuation f...
Definition CoroShape.h:44
@ Retcon
The "returned-continuation" lowering, where each suspend point creates a single continuation function...
Definition CoroShape.h:37
@ Switch
The "resume-switch" lowering, where there are separate resume and destroy functions that are shared b...
Definition CoroShape.h:32
LLVM_ABI BasicBlock::iterator getSpillInsertionPt(const coro::Shape &, Value *Def, const DominatorTree &DT)
bool isSuspendBlock(BasicBlock *BB)
void normalizeCoroutine(Function &F, coro::Shape &Shape, TargetTransformInfo &TTI)
CallInst * createMustTailCall(DebugLoc Loc, Function *MustTailCallFn, TargetTransformInfo &TTI, ArrayRef< Value * > Arguments, IRBuilder<> &)
LLVM_ABI void sinkSpillUsesAfterCoroBegin(const DominatorTree &DT, CoroBeginInst *CoroBegin, coro::SpillInfo &Spills, SmallVectorImpl< coro::AllocaInfo > &Allocas)
Async and Retcon{Once} conventions assume that all spill uses can be sunk after the coro....
LLVM_ABI void doRematerializations(Function &F, SuspendCrossingInfo &Checker, std::function< bool(Instruction &)> IsMaterializable)
LLVM_ABI void collectSpillsFromArgs(SpillInfo &Spills, Function &F, const SuspendCrossingInfo &Checker)
LLVM_ABI void collectSpillsFromDbgInfo(SpillInfo &Spills, Function &F, const SuspendCrossingInfo &Checker)
void salvageDebugInfo(SmallDenseMap< Argument *, AllocaInst *, 4 > &ArgToAllocaMap, DbgVariableRecord &DVR, bool UseEntryValue)
Attempts to rewrite the location operand of debug records in terms of the coroutine frame pointer,...
LLVM_ABI void collectSpillsAndAllocasFromInsts(SpillInfo &Spills, SmallVector< AllocaInfo, 8 > &Allocas, SmallVector< Instruction *, 4 > &DeadInstructions, SmallVector< CoroAllocaAllocInst *, 4 > &LocalAllocas, Function &F, const SuspendCrossingInfo &Checker, const DominatorTree &DT, const coro::Shape &Shape)
bool isCPlusPlus(SourceLanguage S)
Definition Dwarf.h:566
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
LLVM_ABI cl::opt< bool > ProfcheckDisableMetadataFixes
Definition LoopInfo.cpp:60
UnaryFunction for_each(R &&Range, UnaryFunction F)
Provide wrappers to std::for_each which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1748
LLVM_ABI void PromoteMemToReg(ArrayRef< AllocaInst * > Allocas, DominatorTree &DT, AssumptionCache *AC=nullptr)
Promote the specified list of alloca instructions into scalar registers, inserting PHI nodes as appro...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
unsigned Log2_64_Ceil(uint64_t Value)
Return the ceil log base 2 of the specified value, 64 if the value is zero.
Definition MathExtras.h:345
auto successors(const MachineBasicBlock *BB)
scope_exit(Callable) -> scope_exit< Callable >
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:649
auto pred_size(const MachineBasicBlock *BB)
LLVM_ABI bool isAllocaPromotable(const AllocaInst *AI)
Return true if this alloca is legal for promotion.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
static Error getOffset(const SymbolRef &Sym, SectionRef Sec, uint64_t &Result)
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1769
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:144
LLVM_ABI BasicBlock * ehAwareSplitEdge(BasicBlock *BB, BasicBlock *Succ, LandingPadInst *OriginalPad=nullptr, PHINode *LandingPadReplacement=nullptr, const CriticalEdgeSplittingOptions &Options=CriticalEdgeSplittingOptions(), const Twine &BBName="")
Split the edge connect the specficed blocks in the case that Succ is an Exception Handling Block.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI Value * salvageDebugInfoImpl(Instruction &I, uint64_t CurrentLocOps, SmallVectorImpl< uint64_t > &Ops, SmallVectorImpl< Value * > &AdditionalValues)
Definition Local.cpp:2304
uint64_t offsetToAlignment(uint64_t Value, Align Alignment)
Returns the offset to the next integer (mod 2**64) that is greater than or equal to Value and is a mu...
Definition Alignment.h:186
TargetTransformInfo TTI
LLVM_ABI std::pair< uint64_t, Align > performOptimizedStructLayout(MutableArrayRef< OptimizedStructLayoutField > Fields)
Compute a layout for a struct containing the given fields, making a best-effort attempt to minimize t...
IntPtrTy
Definition InstrProf.h:82
DWARFExpression::Operation Op
LLVM_ABI TinyPtrVector< DbgVariableRecord * > findDVRDeclareValues(Value *V)
As above, for DVRDeclareValues.
Definition DebugInfo.cpp:65
ArrayRef(const T &OneElt) -> ArrayRef< T >
constexpr unsigned BitWidth
LLVM_ABI void updatePhiNodes(BasicBlock *DestBB, BasicBlock *OldPred, BasicBlock *NewPred, PHINode *Until=nullptr)
Replaces all uses of OldPred with the NewPred block in all PHINodes in a block.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1788
LLVM_ABI TinyPtrVector< DbgVariableRecord * > findDVRDeclares(Value *V)
Finds dbg.declare records declaring local variables as living in the memory that 'V' points to.
Definition DebugInfo.cpp:48
auto predecessors(const MachineBasicBlock *BB)
LLVM_ABI void setUnwindEdgeTo(Instruction *TI, BasicBlock *Succ)
Sets the unwind edge of an instruction to a particular successor.
static auto filterDbgVars(iterator_range< simple_ilist< DbgRecord >::iterator > R)
Filter the DbgRecord range to DbgVariableRecord types only and downcast.
LLVM_ABI void findDbgUsers(Value *V, SmallVectorImpl< DbgVariableRecord * > &DbgVariableRecords)
Finds the debug info records describing a value.
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
constexpr uint64_t value() const
This is a hole in the type system and should not be abused.
Definition Alignment.h:77
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition Alignment.h:106
Align Alignment
The required alignment of this field.
uint64_t Offset
The offset of this field in the final layout.
uint64_t Size
The required size of this field in bytes.
static constexpr uint64_t FlexibleOffset
A special value for Offset indicating that the field can be moved anywhere.
AsyncLoweringStorage AsyncLowering
Definition CoroShape.h:148
IntegerType * getIndexType() const
Definition CoroShape.h:166
AnyCoroIdRetconInst * getRetconCoroId() const
Definition CoroShape.h:156
PointerType * getSwitchResumePointerType() const
Definition CoroShape.h:175
CoroIdInst * getSwitchCoroId() const
Definition CoroShape.h:151
SmallVector< AnyCoroSuspendInst *, 4 > CoroSuspends
Definition CoroShape.h:60
uint64_t FrameSize
Definition CoroShape.h:106
AllocaInst * getPromiseAlloca() const
Definition CoroShape.h:235
SwitchLoweringStorage SwitchLowering
Definition CoroShape.h:146
CoroBeginInst * CoroBegin
Definition CoroShape.h:55
BasicBlock::iterator getInsertPtAfterFramePtr() const
Definition CoroShape.h:241
RetconLoweringStorage RetconLowering
Definition CoroShape.h:147
SmallVector< AnyCoroEndInst *, 4 > CoroEnds
Definition CoroShape.h:56
SmallVector< CallInst *, 2 > SwiftErrorOps
Definition CoroShape.h:70
BasicBlock * AllocaSpillBlock
Definition CoroShape.h:108