LLVM  10.0.0
Coroutines.cpp
Go to the documentation of this file.
1 //===- Coroutines.cpp -----------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the common infrastructure for Coroutine Passes.
10 //
11 //===----------------------------------------------------------------------===//
12 
14 #include "CoroInstr.h"
15 #include "CoroInternal.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/ADT/StringRef.h"
21 #include "llvm/IR/Attributes.h"
22 #include "llvm/IR/CallSite.h"
23 #include "llvm/IR/Constants.h"
24 #include "llvm/IR/DerivedTypes.h"
25 #include "llvm/IR/Function.h"
26 #include "llvm/IR/InstIterator.h"
27 #include "llvm/IR/Instructions.h"
28 #include "llvm/IR/IntrinsicInst.h"
29 #include "llvm/IR/Intrinsics.h"
31 #include "llvm/IR/Module.h"
32 #include "llvm/IR/Type.h"
33 #include "llvm/InitializePasses.h"
34 #include "llvm/Support/Casting.h"
36 #include "llvm/Transforms/IPO.h"
39 #include <cassert>
40 #include <cstddef>
41 #include <utility>
42 
43 using namespace llvm;
44 
50 }
51 
52 static void addCoroutineOpt0Passes(const PassManagerBuilder &Builder,
56 
59 }
60 
61 static void addCoroutineEarlyPasses(const PassManagerBuilder &Builder,
64 }
65 
69 }
70 
71 static void addCoroutineSCCPasses(const PassManagerBuilder &Builder,
74 }
75 
79 }
80 
92 }
93 
94 // Construct the lowerer base class and initialize its members.
96  : TheModule(M), Context(M.getContext()),
97  Int8Ptr(Type::getInt8PtrTy(Context)),
98  ResumeFnType(FunctionType::get(Type::getVoidTy(Context), Int8Ptr,
99  /*isVarArg=*/false)),
100  NullPtr(ConstantPointerNull::get(Int8Ptr)) {}
101 
102 // Creates a sequence of instructions to obtain a resume function address using
103 // llvm.coro.subfn.addr. It generates the following sequence:
104 //
105 // call i8* @llvm.coro.subfn.addr(i8* %Arg, i8 %index)
106 // bitcast i8* %2 to void(i8*)*
107 
109  Instruction *InsertPt) {
110  auto *IndexVal = ConstantInt::get(Type::getInt8Ty(Context), Index);
111  auto *Fn = Intrinsic::getDeclaration(&TheModule, Intrinsic::coro_subfn_addr);
112 
114  Index < CoroSubFnInst::IndexLast &&
115  "makeSubFnCall: Index value out of range");
116  auto *Call = CallInst::Create(Fn, {Arg, IndexVal}, "", InsertPt);
117 
118  auto *Bitcast =
119  new BitCastInst(Call, ResumeFnType->getPointerTo(), "", InsertPt);
120  return Bitcast;
121 }
122 
123 #ifndef NDEBUG
125  // NOTE: Must be sorted!
126  static const char *const CoroIntrinsics[] = {
127  "llvm.coro.alloc",
128  "llvm.coro.begin",
129  "llvm.coro.destroy",
130  "llvm.coro.done",
131  "llvm.coro.end",
132  "llvm.coro.frame",
133  "llvm.coro.free",
134  "llvm.coro.id",
135  "llvm.coro.id.retcon",
136  "llvm.coro.id.retcon.once",
137  "llvm.coro.noop",
138  "llvm.coro.param",
139  "llvm.coro.prepare.retcon",
140  "llvm.coro.promise",
141  "llvm.coro.resume",
142  "llvm.coro.save",
143  "llvm.coro.size",
144  "llvm.coro.subfn.addr",
145  "llvm.coro.suspend",
146  "llvm.coro.suspend.retcon",
147  };
148  return Intrinsic::lookupLLVMIntrinsicByName(CoroIntrinsics, Name) != -1;
149 }
150 #endif
151 
152 // Verifies if a module has named values listed. Also, in debug mode verifies
153 // that names are intrinsic names.
155  const std::initializer_list<StringRef> List) {
156  for (StringRef Name : List) {
157  assert(isCoroutineIntrinsicName(Name) && "not a coroutine intrinsic");
158  if (M.getNamedValue(Name))
159  return true;
160  }
161 
162  return false;
163 }
164 
165 // Replace all coro.frees associated with the provided CoroId either with 'null'
166 // if Elide is true and with its frame parameter otherwise.
167 void coro::replaceCoroFree(CoroIdInst *CoroId, bool Elide) {
169  for (User *U : CoroId->users())
170  if (auto CF = dyn_cast<CoroFreeInst>(U))
171  CoroFrees.push_back(CF);
172 
173  if (CoroFrees.empty())
174  return;
175 
176  Value *Replacement =
178  : CoroFrees.front()->getFrame();
179 
180  for (CoroFreeInst *CF : CoroFrees) {
181  CF->replaceAllUsesWith(Replacement);
182  CF->eraseFromParent();
183  }
184 }
185 
186 // FIXME: This code is stolen from CallGraph::addToCallGraph(Function *F), which
187 // happens to be private. It is better for this functionality exposed by the
188 // CallGraph.
189 static void buildCGN(CallGraph &CG, CallGraphNode *Node) {
190  Function *F = Node->getFunction();
191 
192  // Look for calls by this function.
193  for (Instruction &I : instructions(F))
194  if (auto *Call = dyn_cast<CallBase>(&I)) {
195  const Function *Callee = Call->getCalledFunction();
196  if (!Callee || !Intrinsic::isLeaf(Callee->getIntrinsicID()))
197  // Indirect calls of intrinsics are not allowed so no need to check.
198  // We can be more precise here by using TargetArg returned by
199  // Intrinsic::isLeaf.
200  Node->addCalledFunction(Call, CG.getCallsExternalNode());
201  else if (!Callee->isIntrinsic())
202  Node->addCalledFunction(Call, CG.getOrInsertFunction(Callee));
203  }
204 }
205 
206 // Rebuild CGN after we extracted parts of the code from ParentFunc into
207 // NewFuncs. Builds CGNs for the NewFuncs and adds them to the current SCC.
209  CallGraph &CG, CallGraphSCC &SCC) {
210  // Rebuild CGN from scratch for the ParentFunc
211  auto *ParentNode = CG[&ParentFunc];
212  ParentNode->removeAllCalledFunctions();
213  buildCGN(CG, ParentNode);
214 
215  SmallVector<CallGraphNode *, 8> Nodes(SCC.begin(), SCC.end());
216 
217  for (Function *F : NewFuncs) {
219  Nodes.push_back(Callee);
220  buildCGN(CG, Callee);
221  }
222 
223  SCC.initialize(Nodes);
224 }
225 
226 static void clear(coro::Shape &Shape) {
227  Shape.CoroBegin = nullptr;
228  Shape.CoroEnds.clear();
229  Shape.CoroSizes.clear();
230  Shape.CoroSuspends.clear();
231 
232  Shape.FrameTy = nullptr;
233  Shape.FramePtr = nullptr;
234  Shape.AllocaSpillBlock = nullptr;
235 }
236 
238  CoroSuspendInst *SuspendInst) {
239  Module *M = SuspendInst->getModule();
240  auto *Fn = Intrinsic::getDeclaration(M, Intrinsic::coro_save);
241  auto *SaveInst =
242  cast<CoroSaveInst>(CallInst::Create(Fn, CoroBegin, "", SuspendInst));
243  assert(!SuspendInst->getCoroSave());
244  SuspendInst->setArgOperand(0, SaveInst);
245  return SaveInst;
246 }
247 
248 // Collect "interesting" coroutine intrinsics.
250  bool HasFinalSuspend = false;
251  size_t FinalSuspendIndex = 0;
252  clear(*this);
254  SmallVector<CoroSaveInst *, 2> UnusedCoroSaves;
255 
256  for (Instruction &I : instructions(F)) {
257  if (auto II = dyn_cast<IntrinsicInst>(&I)) {
258  switch (II->getIntrinsicID()) {
259  default:
260  continue;
261  case Intrinsic::coro_size:
262  CoroSizes.push_back(cast<CoroSizeInst>(II));
263  break;
264  case Intrinsic::coro_frame:
265  CoroFrames.push_back(cast<CoroFrameInst>(II));
266  break;
267  case Intrinsic::coro_save:
268  // After optimizations, coro_suspends using this coro_save might have
269  // been removed, remember orphaned coro_saves to remove them later.
270  if (II->use_empty())
271  UnusedCoroSaves.push_back(cast<CoroSaveInst>(II));
272  break;
273  case Intrinsic::coro_suspend_retcon: {
274  auto Suspend = cast<CoroSuspendRetconInst>(II);
275  CoroSuspends.push_back(Suspend);
276  break;
277  }
278  case Intrinsic::coro_suspend: {
279  auto Suspend = cast<CoroSuspendInst>(II);
280  CoroSuspends.push_back(Suspend);
281  if (Suspend->isFinal()) {
282  if (HasFinalSuspend)
284  "Only one suspend point can be marked as final");
285  HasFinalSuspend = true;
286  FinalSuspendIndex = CoroSuspends.size() - 1;
287  }
288  break;
289  }
290  case Intrinsic::coro_begin: {
291  auto CB = cast<CoroBeginInst>(II);
292 
293  // Ignore coro id's that aren't pre-split.
294  auto Id = dyn_cast<CoroIdInst>(CB->getId());
295  if (Id && !Id->getInfo().isPreSplit())
296  break;
297 
298  if (CoroBegin)
300  "coroutine should have exactly one defining @llvm.coro.begin");
301  CB->addAttribute(AttributeList::ReturnIndex, Attribute::NonNull);
303  CB->removeAttribute(AttributeList::FunctionIndex,
304  Attribute::NoDuplicate);
305  CoroBegin = CB;
306  break;
307  }
308  case Intrinsic::coro_end:
309  CoroEnds.push_back(cast<CoroEndInst>(II));
310  if (CoroEnds.back()->isFallthrough()) {
311  // Make sure that the fallthrough coro.end is the first element in the
312  // CoroEnds vector.
313  if (CoroEnds.size() > 1) {
314  if (CoroEnds.front()->isFallthrough())
316  "Only one coro.end can be marked as fallthrough");
317  std::swap(CoroEnds.front(), CoroEnds.back());
318  }
319  }
320  break;
321  }
322  }
323  }
324 
325  // If for some reason, we were not able to find coro.begin, bailout.
326  if (!CoroBegin) {
327  // Replace coro.frame which are supposed to be lowered to the result of
328  // coro.begin with undef.
330  for (CoroFrameInst *CF : CoroFrames) {
331  CF->replaceAllUsesWith(Undef);
332  CF->eraseFromParent();
333  }
334 
335  // Replace all coro.suspend with undef and remove related coro.saves if
336  // present.
337  for (AnyCoroSuspendInst *CS : CoroSuspends) {
338  CS->replaceAllUsesWith(UndefValue::get(CS->getType()));
339  CS->eraseFromParent();
340  if (auto *CoroSave = CS->getCoroSave())
341  CoroSave->eraseFromParent();
342  }
343 
344  // Replace all coro.ends with unreachable instruction.
345  for (CoroEndInst *CE : CoroEnds)
346  changeToUnreachable(CE, /*UseLLVMTrap=*/false);
347 
348  return;
349  }
350 
351  auto Id = CoroBegin->getId();
352  switch (auto IdIntrinsic = Id->getIntrinsicID()) {
353  case Intrinsic::coro_id: {
354  auto SwitchId = cast<CoroIdInst>(Id);
355  this->ABI = coro::ABI::Switch;
356  this->SwitchLowering.HasFinalSuspend = HasFinalSuspend;
357  this->SwitchLowering.ResumeSwitch = nullptr;
358  this->SwitchLowering.PromiseAlloca = SwitchId->getPromise();
359  this->SwitchLowering.ResumeEntryBlock = nullptr;
360 
361  for (auto AnySuspend : CoroSuspends) {
362  auto Suspend = dyn_cast<CoroSuspendInst>(AnySuspend);
363  if (!Suspend) {
364 #ifndef NDEBUG
365  AnySuspend->dump();
366 #endif
367  report_fatal_error("coro.id must be paired with coro.suspend");
368  }
369 
370  if (!Suspend->getCoroSave())
371  createCoroSave(CoroBegin, Suspend);
372  }
373  break;
374  }
375 
376  case Intrinsic::coro_id_retcon:
377  case Intrinsic::coro_id_retcon_once: {
378  auto ContinuationId = cast<AnyCoroIdRetconInst>(Id);
379  ContinuationId->checkWellFormed();
380  this->ABI = (IdIntrinsic == Intrinsic::coro_id_retcon
383  auto Prototype = ContinuationId->getPrototype();
384  this->RetconLowering.ResumePrototype = Prototype;
385  this->RetconLowering.Alloc = ContinuationId->getAllocFunction();
386  this->RetconLowering.Dealloc = ContinuationId->getDeallocFunction();
387  this->RetconLowering.ReturnBlock = nullptr;
388  this->RetconLowering.IsFrameInlineInStorage = false;
389 
390  // Determine the result value types, and make sure they match up with
391  // the values passed to the suspends.
392  auto ResultTys = getRetconResultTypes();
393  auto ResumeTys = getRetconResumeTypes();
394 
395  for (auto AnySuspend : CoroSuspends) {
396  auto Suspend = dyn_cast<CoroSuspendRetconInst>(AnySuspend);
397  if (!Suspend) {
398 #ifndef NDEBUG
399  AnySuspend->dump();
400 #endif
401  report_fatal_error("coro.id.retcon.* must be paired with "
402  "coro.suspend.retcon");
403  }
404 
405  // Check that the argument types of the suspend match the results.
406  auto SI = Suspend->value_begin(), SE = Suspend->value_end();
407  auto RI = ResultTys.begin(), RE = ResultTys.end();
408  for (; SI != SE && RI != RE; ++SI, ++RI) {
409  auto SrcTy = (*SI)->getType();
410  if (SrcTy != *RI) {
411  // The optimizer likes to eliminate bitcasts leading into variadic
412  // calls, but that messes with our invariants. Re-insert the
413  // bitcast and ignore this type mismatch.
414  if (CastInst::isBitCastable(SrcTy, *RI)) {
415  auto BCI = new BitCastInst(*SI, *RI, "", Suspend);
416  SI->set(BCI);
417  continue;
418  }
419 
420 #ifndef NDEBUG
421  Suspend->dump();
422  Prototype->getFunctionType()->dump();
423 #endif
424  report_fatal_error("argument to coro.suspend.retcon does not "
425  "match corresponding prototype function result");
426  }
427  }
428  if (SI != SE || RI != RE) {
429 #ifndef NDEBUG
430  Suspend->dump();
431  Prototype->getFunctionType()->dump();
432 #endif
433  report_fatal_error("wrong number of arguments to coro.suspend.retcon");
434  }
435 
436  // Check that the result type of the suspend matches the resume types.
437  Type *SResultTy = Suspend->getType();
438  ArrayRef<Type*> SuspendResultTys;
439  if (SResultTy->isVoidTy()) {
440  // leave as empty array
441  } else if (auto SResultStructTy = dyn_cast<StructType>(SResultTy)) {
442  SuspendResultTys = SResultStructTy->elements();
443  } else {
444  // forms an ArrayRef using SResultTy, be careful
445  SuspendResultTys = SResultTy;
446  }
447  if (SuspendResultTys.size() != ResumeTys.size()) {
448 #ifndef NDEBUG
449  Suspend->dump();
450  Prototype->getFunctionType()->dump();
451 #endif
452  report_fatal_error("wrong number of results from coro.suspend.retcon");
453  }
454  for (size_t I = 0, E = ResumeTys.size(); I != E; ++I) {
455  if (SuspendResultTys[I] != ResumeTys[I]) {
456 #ifndef NDEBUG
457  Suspend->dump();
458  Prototype->getFunctionType()->dump();
459 #endif
460  report_fatal_error("result from coro.suspend.retcon does not "
461  "match corresponding prototype function param");
462  }
463  }
464  }
465  break;
466  }
467 
468  default:
469  llvm_unreachable("coro.begin is not dependent on a coro.id call");
470  }
471 
472  // The coro.free intrinsic is always lowered to the result of coro.begin.
473  for (CoroFrameInst *CF : CoroFrames) {
474  CF->replaceAllUsesWith(CoroBegin);
475  CF->eraseFromParent();
476  }
477 
478  // Move final suspend to be the last element in the CoroSuspends vector.
479  if (ABI == coro::ABI::Switch &&
480  SwitchLowering.HasFinalSuspend &&
481  FinalSuspendIndex != CoroSuspends.size() - 1)
482  std::swap(CoroSuspends[FinalSuspendIndex], CoroSuspends.back());
483 
484  // Remove orphaned coro.saves.
485  for (CoroSaveInst *CoroSave : UnusedCoroSaves)
486  CoroSave->eraseFromParent();
487 }
488 
489 static void propagateCallAttrsFromCallee(CallInst *Call, Function *Callee) {
490  Call->setCallingConv(Callee->getCallingConv());
491  // TODO: attributes?
492 }
493 
494 static void addCallToCallGraph(CallGraph *CG, CallInst *Call, Function *Callee){
495  if (CG)
496  (*CG)[Call->getFunction()]->addCalledFunction(Call, (*CG)[Callee]);
497 }
498 
500  CallGraph *CG) const {
501  switch (ABI) {
502  case coro::ABI::Switch:
503  llvm_unreachable("can't allocate memory in coro switch-lowering");
504 
505  case coro::ABI::Retcon:
506  case coro::ABI::RetconOnce: {
507  auto Alloc = RetconLowering.Alloc;
508  Size = Builder.CreateIntCast(Size,
509  Alloc->getFunctionType()->getParamType(0),
510  /*is signed*/ false);
511  auto *Call = Builder.CreateCall(Alloc, Size);
512  propagateCallAttrsFromCallee(Call, Alloc);
513  addCallToCallGraph(CG, Call, Alloc);
514  return Call;
515  }
516  }
517  llvm_unreachable("Unknown coro::ABI enum");
518 }
519 
521  CallGraph *CG) const {
522  switch (ABI) {
523  case coro::ABI::Switch:
524  llvm_unreachable("can't allocate memory in coro switch-lowering");
525 
526  case coro::ABI::Retcon:
527  case coro::ABI::RetconOnce: {
528  auto Dealloc = RetconLowering.Dealloc;
529  Ptr = Builder.CreateBitCast(Ptr,
530  Dealloc->getFunctionType()->getParamType(0));
531  auto *Call = Builder.CreateCall(Dealloc, Ptr);
532  propagateCallAttrsFromCallee(Call, Dealloc);
533  addCallToCallGraph(CG, Call, Dealloc);
534  return;
535  }
536  }
537  llvm_unreachable("Unknown coro::ABI enum");
538 }
539 
541 static void fail(const Instruction *I, const char *Reason, Value *V) {
542 #ifndef NDEBUG
543  I->dump();
544  if (V) {
545  errs() << " Value: ";
547  errs() << '\n';
548  }
549 #endif
550  report_fatal_error(Reason);
551 }
552 
553 /// Check that the given value is a well-formed prototype for the
554 /// llvm.coro.id.retcon.* intrinsics.
556  auto F = dyn_cast<Function>(V->stripPointerCasts());
557  if (!F)
558  fail(I, "llvm.coro.id.retcon.* prototype not a Function", V);
559 
560  auto FT = F->getFunctionType();
561 
562  if (isa<CoroIdRetconInst>(I)) {
563  bool ResultOkay;
564  if (FT->getReturnType()->isPointerTy()) {
565  ResultOkay = true;
566  } else if (auto SRetTy = dyn_cast<StructType>(FT->getReturnType())) {
567  ResultOkay = (!SRetTy->isOpaque() &&
568  SRetTy->getNumElements() > 0 &&
569  SRetTy->getElementType(0)->isPointerTy());
570  } else {
571  ResultOkay = false;
572  }
573  if (!ResultOkay)
574  fail(I, "llvm.coro.id.retcon prototype must return pointer as first "
575  "result", F);
576 
577  if (FT->getReturnType() !=
579  fail(I, "llvm.coro.id.retcon prototype return type must be same as"
580  "current function return type", F);
581  } else {
582  // No meaningful validation to do here for llvm.coro.id.unique.once.
583  }
584 
585  if (FT->getNumParams() == 0 || !FT->getParamType(0)->isPointerTy())
586  fail(I, "llvm.coro.id.retcon.* prototype must take pointer as "
587  "its first parameter", F);
588 }
589 
590 /// Check that the given value is a well-formed allocator.
591 static void checkWFAlloc(const Instruction *I, Value *V) {
592  auto F = dyn_cast<Function>(V->stripPointerCasts());
593  if (!F)
594  fail(I, "llvm.coro.* allocator not a Function", V);
595 
596  auto FT = F->getFunctionType();
597  if (!FT->getReturnType()->isPointerTy())
598  fail(I, "llvm.coro.* allocator must return a pointer", F);
599 
600  if (FT->getNumParams() != 1 ||
601  !FT->getParamType(0)->isIntegerTy())
602  fail(I, "llvm.coro.* allocator must take integer as only param", F);
603 }
604 
605 /// Check that the given value is a well-formed deallocator.
606 static void checkWFDealloc(const Instruction *I, Value *V) {
607  auto F = dyn_cast<Function>(V->stripPointerCasts());
608  if (!F)
609  fail(I, "llvm.coro.* deallocator not a Function", V);
610 
611  auto FT = F->getFunctionType();
612  if (!FT->getReturnType()->isVoidTy())
613  fail(I, "llvm.coro.* deallocator must return void", F);
614 
615  if (FT->getNumParams() != 1 ||
616  !FT->getParamType(0)->isPointerTy())
617  fail(I, "llvm.coro.* deallocator must take pointer as only param", F);
618 }
619 
620 static void checkConstantInt(const Instruction *I, Value *V,
621  const char *Reason) {
622  if (!isa<ConstantInt>(V)) {
623  fail(I, Reason, V);
624  }
625 }
626 
628  checkConstantInt(this, getArgOperand(SizeArg),
629  "size argument to coro.id.retcon.* must be constant");
630  checkConstantInt(this, getArgOperand(AlignArg),
631  "alignment argument to coro.id.retcon.* must be constant");
632  checkWFRetconPrototype(this, getArgOperand(PrototypeArg));
633  checkWFAlloc(this, getArgOperand(AllocArg));
634  checkWFDealloc(this, getArgOperand(DeallocArg));
635 }
636 
638  unwrap(PM)->add(createCoroEarlyLegacyPass());
639 }
640 
642  unwrap(PM)->add(createCoroSplitLegacyPass());
643 }
644 
646  unwrap(PM)->add(createCoroElideLegacyPass());
647 }
648 
651 }
bool isIntrinsic() const
isIntrinsic - Returns true if the function&#39;s name starts with "llvm.".
Definition: Function.h:198
This represents the llvm.coro.suspend.retcon instruction.
Definition: CoroInstr.h:404
The "returned-continuation" lowering, where each suspend point creates a single continuation function...
raw_ostream & errs()
This returns a reference to a raw_ostream for standard error.
Instruction * FramePtr
Definition: CoroInternal.h:110
LLVMContext & Context
The "resume-switch" lowering, where there are separate resume and destroy functions that are shared b...
PassManagerBuilder - This class is used to set up a standard optimization sequence for languages like...
The "unique returned-continuation" lowering, where each suspend point creates a single continuation f...
void initializeCoroElideLegacyPass(PassRegistry &)
CoroBeginInst * CoroBegin
Definition: CoroInternal.h:89
This represents the llvm.coro.id instruction.
Definition: CoroInstr.h:113
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:140
This class represents lattice values for constants.
Definition: AllocatorList.h:23
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:66
void LLVMAddCoroElidePass(LLVMPassManagerRef PM)
See llvm::createCoroElideLegacyPass function.
Definition: Coroutines.cpp:645
amdgpu Simplify well known AMD library false FunctionCallee Value const Twine & Name
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
iterator end() const
A global registry used in conjunction with static constructors to make pluggable components (like tar...
Definition: Registry.h:44
static void buildCGN(CallGraph &CG, CallGraphNode *Node)
Definition: Coroutines.cpp:189
This class represents a function call, abstracting a target machine&#39;s calling convention.
EP_ScalarOptimizerLate - This extension point allows adding optimization passes after most of the mai...
The two locations do not alias at all.
Definition: AliasAnalysis.h:84
static void addCoroutineSCCPasses(const PassManagerBuilder &Builder, legacy::PassManagerBase &PM)
Definition: Coroutines.cpp:71
LLVMContext & getContext() const
All values hold a context through their type.
Definition: Value.cpp:744
virtual void add(Pass *P)=0
Add a pass to the queue of passes to run.
void setArgOperand(unsigned i, Value *v)
Definition: InstrTypes.h:1251
F(f)
A node in the call graph for a module.
Definition: CallGraph.h:164
void dump() const
Support for debugging, callable in GDB: V->dump()
Definition: AsmWriter.cpp:4466
static bool isCoroutineIntrinsicName(StringRef Name)
Definition: Coroutines.cpp:124
Attribute unwrap(LLVMAttributeRef Attr)
Definition: Attributes.h:204
PointerType * getPointerTo(unsigned AddrSpace=0) const
Return a pointer to the current type.
Definition: Type.cpp:659
This represents the llvm.coro.suspend instruction.
Definition: CoroInstr.h:372
This file contains the simple types necessary to represent the attributes associated with functions a...
void buildFrom(Function &F)
Definition: Coroutines.cpp:249
This file provides interfaces used to build and manipulate a call graph, which is a very useful tool ...
Class to represent function types.
Definition: DerivedTypes.h:108
EP_EnabledOnOptLevel0 - This extension point allows adding passes that should not be disabled by O0 o...
Value * CreateBitCast(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:2101
FunctionType *const ResumeFnType
Definition: CoroInternal.h:59
SmallVector< CoroSizeInst *, 2 > CoroSizes
Definition: CoroInternal.h:91
Value * emitAlloc(IRBuilder<> &Builder, Value *Size, CallGraph *CG) const
Allocate memory according to the rules of the active lowering.
Definition: Coroutines.cpp:499
static void checkConstantInt(const Instruction *I, Value *V, const char *Reason)
Definition: Coroutines.cpp:620
static void addCoroutineOptimizerLastPasses(const PassManagerBuilder &Builder, legacy::PassManagerBase &PM)
Definition: Coroutines.cpp:76
This class represents a no-op cast from one type to another.
GlobalValue * getNamedValue(StringRef Name) const
Return the global value in the module with the specified name, of arbitrary type. ...
Definition: Module.cpp:113
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: APInt.h:32
Pass * createCoroEarlyLegacyPass()
Lower coroutine intrinsics that are not needed by later passes.
Function * getDeclaration(Module *M, ID id, ArrayRef< Type *> Tys=None)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
Definition: Function.cpp:1112
This represents either the llvm.coro.id.retcon or llvm.coro.id.retcon.once instruction.
Definition: CoroInstr.h:204
static void addCoroutineScalarOptimizerPasses(const PassManagerBuilder &Builder, legacy::PassManagerBase &PM)
Definition: Coroutines.cpp:66
static void checkWFDealloc(const Instruction *I, Value *V)
Check that the given value is a well-formed deallocator.
Definition: Coroutines.cpp:606
bool isVoidTy() const
Return true if this is &#39;void&#39;.
Definition: Type.h:141
iterator begin() const
static ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
Definition: Constants.cpp:1500
bool isLeaf(ID id)
Returns true if the intrinsic is a leaf, i.e.
Definition: Function.cpp:1095
CallGraphNode * getCallsExternalNode() const
Definition: CallGraph.h:138
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:46
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:158
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
void LLVMAddCoroEarlyPass(LLVMPassManagerRef PM)
See llvm::createCoroEarlyLegacyPass function.
Definition: Coroutines.cpp:637
This file contains the declarations for the subclasses of Constant, which represent the different fla...
void initializeCoroEarlyLegacyPass(PassRegistry &)
static bool isBitCastable(Type *SrcTy, Type *DestTy)
Check whether a bitcast between these types is valid.
This represents the llvm.coro.end instruction.
Definition: CoroInstr.h:441
static void addCallToCallGraph(CallGraph *CG, CallInst *Call, Function *Callee)
Definition: Coroutines.cpp:494
void setCallingConv(CallingConv::ID CC)
Definition: InstrTypes.h:1366
ModulePass * createBarrierNoopPass()
createBarrierNoopPass - This pass is purely a module pass barrier in a pass manager.
amdgpu Simplify well known AMD library false FunctionCallee Value * Arg
This represents the llvm.coro.save instruction.
Definition: CoroInstr.h:325
void initialize(ArrayRef< CallGraphNode *> NewNodes)
const Function * getFunction() const
Return the function this instruction belongs to.
Definition: Instruction.cpp:59
static void checkWFAlloc(const Instruction *I, Value *V)
Check that the given value is a well-formed allocator.
Definition: Coroutines.cpp:591
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function. ...
Definition: Function.cpp:223
static UndefValue * get(Type *T)
Static factory methods - Return an &#39;undef&#39; object of the specified type.
Definition: Constants.cpp:1514
const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
Definition: Value.cpp:530
EP_OptimizerLast – This extension point allows adding passes that run after everything else...
static PointerType * getInt8PtrTy(LLVMContext &C, unsigned AS=0)
Definition: Type.cpp:224
LLVMContext & Context
Definition: CoroInternal.h:57
EP_EarlyAsPossible - This extension point allows adding passes before any other transformations, allowing them to see the code as it is coming out of the frontend.
void printAsOperand(raw_ostream &O, bool PrintType=true, const Module *M=nullptr) const
Print the name of this Value out to the specified raw_ostream.
Definition: AsmWriter.cpp:4393
This represents the llvm.coro.free instruction.
Definition: CoroInstr.h:289
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
void dump() const
Definition: AsmWriter.cpp:4470
Function * getFunction() const
Returns the function that this call graph node represents.
Definition: CallGraph.h:187
EP_CGSCCOptimizerLate - This extension point allows adding CallGraphSCC passes at the end of the main...
StructType * FrameTy
Definition: CoroInternal.h:109
bool declaresIntrinsics(const Module &M, const std::initializer_list< StringRef >)
Definition: Coroutines.cpp:154
static void addCoroutineOpt0Passes(const PassManagerBuilder &Builder, legacy::PassManagerBase &PM)
Definition: Coroutines.cpp:52
PassManagerBase - An abstract interface to allow code to add passes to a pass manager without having ...
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
Definition: Function.h:212
void initializeCoroutines(PassRegistry &)
Initialize all passes linked into the Coroutines library.
Definition: Coroutines.cpp:45
Value * CreateIntCast(Value *V, Type *DestTy, bool isSigned, const Twine &Name="")
Definition: IRBuilder.h:2170
static CoroSaveInst * createCoroSave(CoroBeginInst *CoroBegin, CoroSuspendInst *SuspendInst)
Definition: Coroutines.cpp:237
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:837
Module.h This file contains the declarations for the Module class.
A constant pointer value that points to null.
Definition: Constants.h:539
Type * getReturnType() const
Definition: DerivedTypes.h:129
void checkWellFormed() const
Definition: Coroutines.cpp:627
#define LLVM_ATTRIBUTE_NORETURN
Definition: Compiler.h:248
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
Definition: Constants.cpp:704
static void addCoroutineEarlyPasses(const PassManagerBuilder &Builder, legacy::PassManagerBase &PM)
Definition: Coroutines.cpp:61
Intrinsic::ID getIntrinsicID() const LLVM_READONLY
getIntrinsicID - This method returns the ID number of the specified function, or Intrinsic::not_intri...
Definition: Function.h:193
void LLVMAddCoroSplitPass(LLVMPassManagerRef PM)
See llvm::createCoroSplitLegacyPass function.
Definition: Coroutines.cpp:641
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition: BitVector.h:940
FunctionType * getFunctionType() const
Returns the FunctionType for me.
Definition: Function.h:163
struct LLVMOpaquePassManager * LLVMPassManagerRef
Definition: Types.h:127
This class represents the llvm.coro.begin instruction.
Definition: CoroInstr.h:305
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
Definition: Instruction.cpp:55
Value * makeSubFnCall(Value *Arg, int Index, Instruction *InsertPt)
Definition: Coroutines.cpp:108
SmallVector< AnyCoroSuspendInst *, 4 > CoroSuspends
Definition: CoroInternal.h:92
amdgpu Simplify well known AMD library false FunctionCallee Callee
iterator_range< user_iterator > users()
Definition: Value.h:420
static void clear(coro::Shape &Shape)
Definition: Coroutines.cpp:226
The basic data container for the call graph of a Module of IR.
Definition: CallGraph.h:73
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:55
const NodeList & List
Definition: RDFGraph.cpp:201
Pass * createCoroSplitLegacyPass()
Split up coroutines into multiple functions driving their state machines.
Definition: CoroSplit.cpp:1616
#define I(x, y, z)
Definition: MD5.cpp:58
void emitDealloc(IRBuilder<> &Builder, Value *Ptr, CallGraph *CG) const
Deallocate memory according to the rules of the active lowering.
Definition: Coroutines.cpp:520
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:332
uint32_t Size
Definition: Profile.cpp:46
CallInst * CreateCall(FunctionType *FTy, Value *Callee, ArrayRef< Value *> Args=None, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition: IRBuilder.h:2419
void replaceCoroFree(CoroIdInst *CoroId, bool Elide)
Definition: Coroutines.cpp:167
static LLVM_ATTRIBUTE_NORETURN void fail(const Instruction *I, const char *Reason, Value *V)
Definition: Coroutines.cpp:541
void initializeCoroCleanupLegacyPass(PassRegistry &)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
SmallVector< CoroEndInst *, 4 > CoroEnds
Definition: CoroInternal.h:90
Pass * createCoroElideLegacyPass()
Analyze coroutines use sites, devirtualize resume/destroy calls and elide heap allocation for corouti...
Definition: CoroElide.cpp:344
This represents the llvm.coro.frame instruction.
Definition: CoroInstr.h:277
LLVM Value Representation.
Definition: Value.h:74
CallGraphSCC - This is a single SCC that a CallGraphSCCPass is run on.
CallGraphNode * getOrInsertFunction(const Function *F)
Similar to operator[], but this will insert a new CallGraphNode for F if one does not already exist...
Definition: CallGraph.cpp:148
void addCoroutinePassesToExtensionPoints(PassManagerBuilder &Builder)
Add all coroutine passes to appropriate extension points.
Definition: Coroutines.cpp:81
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:54
inst_range instructions(Function *F)
Definition: InstIterator.h:133
PassRegistry - This class manages the registration and intitialization of the pass subsystem as appli...
Definition: PassRegistry.h:38
int lookupLLVMIntrinsicByName(ArrayRef< const char *> NameTable, StringRef Name)
Looks up Name in NameTable via binary search.
void LLVMAddCoroCleanupPass(LLVMPassManagerRef PM)
See llvm::createCoroCleanupLegacyPass function.
Definition: Coroutines.cpp:649
BasicBlock * AllocaSpillBlock
Definition: CoroInternal.h:111
void initializeCoroSplitLegacyPass(PassRegistry &)
void addExtension(ExtensionPointTy Ty, ExtensionFn Fn)
static void checkWFRetconPrototype(const AnyCoroIdRetconInst *I, Value *V)
Check that the given value is a well-formed prototype for the llvm.coro.id.retcon.
Definition: Coroutines.cpp:555
Pass * createCoroCleanupLegacyPass()
Lower all remaining coroutine intrinsics.
unsigned changeToUnreachable(Instruction *I, bool UseLLVMTrap, bool PreserveLCSSA=false, DomTreeUpdater *DTU=nullptr, MemorySSAUpdater *MSSAU=nullptr)
Insert an unreachable instruction before the specified instruction, making it and the rest of the cod...
Definition: Local.cpp:1915
static IntegerType * getInt8Ty(LLVMContext &C)
Definition: Type.cpp:178
CoroSaveInst * getCoroSave() const
Definition: CoroInstr.h:376
void updateCallGraph(Function &Caller, ArrayRef< Function *> Funcs, CallGraph &CG, CallGraphSCC &SCC)
Definition: Coroutines.cpp:208
static void propagateCallAttrsFromCallee(CallInst *Call, Function *Callee)
Definition: Coroutines.cpp:489
void addCalledFunction(CallBase *Call, CallGraphNode *M)
Adds a function to the list of functions called by this one.
Definition: CallGraph.h:232