30 #define DEBUG_TYPE "openmp-ir-builder" 34 using namespace types;
38 cl::desc(
"Use optimistic attributes describing " 39 "'as-if' properties of runtime calls."),
45 #define OMP_ATTRS_SET(VarName, AttrSet) AttributeSet VarName = AttrSet; 46 #include "llvm/Frontend/OpenMP/OMPKinds.def" 50 #define OMP_RTL_ATTRS(Enum, FnAttrSet, RetAttrSet, ArgAttrSets) \ 53 AttributeList::get(Ctx, FnAttrSet, RetAttrSet, ArgAttrSets)); \ 55 #include "llvm/Frontend/OpenMP/OMPKinds.def" 67 #define OMP_RTL(Enum, Str, IsVarArg, ReturnType, ...) \ 69 Fn = M.getFunction(Str); \ 71 #include "llvm/Frontend/OpenMP/OMPKinds.def" 77 #define OMP_RTL(Enum, Str, IsVarArg, ReturnType, ...) \ 79 Fn = Function::Create(FunctionType::get(ReturnType, \ 80 ArrayRef<Type *>{__VA_ARGS__}, \ 82 GlobalValue::ExternalLinkage, Str, M); \ 84 #include "llvm/Frontend/OpenMP/OMPKinds.def" 87 addAttributes(FnID, *Fn);
90 assert(Fn &&
"Failed to create OpenMP runtime function");
99 LocFlags |= OMP_IDENT_FLAG_KMPC;
101 GlobalVariable *&DefaultIdent = IdentMap[{SrcLocStr, uint64_t(LocFlags)}];
106 I32Null, I32Null, SrcLocStr};
108 cast<StructType>(IdentPtr->getPointerElementType()), IdentData);
113 if (GV.getType() == IdentPtr && GV.hasInitializer())
114 if (GV.getInitializer() == Initializer)
115 return DefaultIdent = &GV;
117 DefaultIdent =
new GlobalVariable(M, IdentPtr->getPointerElementType(),
127 Constant *&SrcLocStr = SrcLocStrMap[LocStr];
135 if (GV.isConstant() && GV.hasInitializer() &&
136 GV.getInitializer() == Initializer)
139 SrcLocStr = Builder.CreateGlobalStringPtr(LocStr);
144 Constant *OpenMPIRBuilder::getOrCreateDefaultSrcLocStr() {
145 return getOrCreateSrcLocStr(
";unknown;unknown;0;0;;");
152 return getOrCreateDefaultSrcLocStr();
154 !DIL->getFilename().empty() ? DIL->getFilename() : M.getName();
157 !Function.
empty() ? Function : Loc.
IP.getBlock()->getParent()->getName();
160 std::stringstream SrcLocStr;
161 SrcLocStr <<
";" << Filename.
data() <<
";" << Function.
data() <<
";" 162 << LineStr <<
";" << ColumnStr <<
";;";
163 return getOrCreateSrcLocStr(SrcLocStr.str());
166 Value *OpenMPIRBuilder::getOrCreateThreadID(
Value *Ident) {
167 return Builder.CreateCall(
168 getOrCreateRuntimeFunction(OMPRTL___kmpc_global_thread_num), Ident,
169 "omp_global_thread_num");
174 bool ForceSimpleCall,
bool CheckCancelFlag) {
175 if (!updateToLocation(Loc))
177 return emitBarrierImpl(Loc, DK, ForceSimpleCall, CheckCancelFlag);
182 bool ForceSimpleCall,
bool CheckCancelFlag) {
189 BarrierLocFlags = OMP_IDENT_FLAG_BARRIER_IMPL_FOR;
192 BarrierLocFlags = OMP_IDENT_FLAG_BARRIER_IMPL_SECTIONS;
195 BarrierLocFlags = OMP_IDENT_FLAG_BARRIER_IMPL_SINGLE;
198 BarrierLocFlags = OMP_IDENT_FLAG_BARRIER_EXPL;
201 BarrierLocFlags = OMP_IDENT_FLAG_BARRIER_IMPL;
205 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc);
206 Value *
Args[] = {getOrCreateIdent(SrcLocStr, BarrierLocFlags),
207 getOrCreateThreadID(getOrCreateIdent(SrcLocStr))};
212 bool UseCancelBarrier =
213 !ForceSimpleCall && isLastFinalizationInfoCancellable(OMPD_parallel);
215 Value *Result = Builder.CreateCall(
216 getOrCreateRuntimeFunction(UseCancelBarrier ? OMPRTL___kmpc_cancel_barrier
217 : OMPRTL___kmpc_barrier),
220 if (UseCancelBarrier && CheckCancelFlag)
221 emitCancelationCheckImpl(Result, OMPD_parallel);
223 return Builder.saveIP();
230 if (!updateToLocation(Loc))
234 auto *UI = Builder.CreateUnreachable();
239 Builder.SetInsertPoint(ThenTI);
241 Value *CancelKind =
nullptr;
242 switch (CanceledDirective) {
243 #define OMP_CANCEL_KIND(Enum, Str, DirectiveEnum, Value) \ 244 case DirectiveEnum: \ 245 CancelKind = Builder.getInt32(Value); \ 247 #include "llvm/Frontend/OpenMP/OMPKinds.def" 252 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc);
253 Value *Ident = getOrCreateIdent(SrcLocStr);
254 Value *
Args[] = {Ident, getOrCreateThreadID(Ident), CancelKind};
255 Value *Result = Builder.CreateCall(
256 getOrCreateRuntimeFunction(OMPRTL___kmpc_cancel), Args);
259 emitCancelationCheckImpl(Result, CanceledDirective);
262 Builder.SetInsertPoint(UI->getParent());
263 UI->eraseFromParent();
265 return Builder.saveIP();
268 void OpenMPIRBuilder::emitCancelationCheckImpl(
270 assert(isLastFinalizationInfoCancellable(CanceledDirective) &&
271 "Unexpected cancellation!");
276 if (Builder.GetInsertPoint() == BB->
end()) {
282 NonCancellationBlock =
SplitBlock(BB, &*Builder.GetInsertPoint());
284 Builder.SetInsertPoint(BB);
290 Value *Cmp = Builder.CreateIsNull(CancelFlag);
291 Builder.CreateCondBr(Cmp, NonCancellationBlock, CancellationBlock,
296 Builder.SetInsertPoint(CancellationBlock);
297 auto &FI = FinalizationStack.back();
298 FI.FiniCB(Builder.saveIP());
301 Builder.SetInsertPoint(NonCancellationBlock, NonCancellationBlock->
begin());
308 if (!updateToLocation(Loc))
311 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc);
312 Value *Ident = getOrCreateIdent(SrcLocStr);
313 Value *ThreadID = getOrCreateThreadID(Ident);
319 Builder.CreateIntCast(NumThreads, Int32,
false)};
321 getOrCreateRuntimeFunction(OMPRTL___kmpc_push_num_threads), Args);
324 if (ProcBind != OMP_PROC_BIND_default) {
329 Builder.CreateCall(getOrCreateRuntimeFunction(OMPRTL___kmpc_push_proc_bind),
333 BasicBlock *InsertBB = Builder.GetInsertBlock();
341 AllocaInst *TIDAddr = Builder.CreateAlloca(Int32,
nullptr,
"tid.addr");
342 AllocaInst *ZeroAddr = Builder.CreateAlloca(Int32,
nullptr,
"zero.addr");
376 if (IP.getBlock()->end() == IP.getPoint()) {
378 Builder.restoreIP(IP);
382 assert(IP.getBlock()->getTerminator()->getNumSuccessors() == 1 &&
383 IP.getBlock()->getTerminator()->getSuccessor(0) == PRegExitBB &&
384 "Unexpected insertion point for finalization call!");
388 FinalizationStack.push_back({FiniCBWrapper, OMPD_parallel, IsCancellable});
394 Builder.restoreIP(AllocaIP);
396 Builder.CreateAlloca(Int32,
nullptr,
"tid.addr.local");
397 Instruction *PrivTID = Builder.CreateLoad(PrivTIDAddr,
"tid");
400 ToBeDeleted.
push_back(Builder.CreateLoad(TIDAddr,
"tid.addr.use"));
401 ToBeDeleted.
push_back(Builder.CreateLoad(ZeroAddr,
"zero.addr.use"));
418 LLVM_DEBUG(
dbgs() <<
"Before body codegen: " << *UI->getFunction() <<
"\n");
421 assert(BodyGenCB &&
"Expected body generation callback!");
423 BodyGenCB(AllocaIP, CodeGenIP, *PRegPreFiniBB);
425 LLVM_DEBUG(
dbgs() <<
"After body codegen: " << *UI->getFunction() <<
"\n");
429 ParallelRegionBlockSet.
insert(PRegEntryBB);
430 ParallelRegionBlockSet.insert(PRegExitBB);
434 while (!Worklist.
empty()) {
438 if (ParallelRegionBlockSet.insert(SuccBB).second)
455 Extractor.
findAllocas(CEAC, SinkingCands, HoistingCands, CommonExit);
458 LLVM_DEBUG(
dbgs() <<
"Before privatization: " << *UI->getFunction() <<
"\n");
461 getOrCreateRuntimeFunction(OMPRTL___kmpc_global_thread_num);
463 auto PrivHelper = [&](
Value &V) {
464 if (&V == TIDAddr || &V == ZeroAddr)
468 for (
Use &U : V.uses())
469 if (
auto *UserI = dyn_cast<Instruction>(U.getUser()))
470 if (ParallelRegionBlockSet.count(UserI->getParent()))
473 Value *ReplacementValue =
nullptr;
476 ReplacementValue = PrivTID;
479 PrivCB(AllocaIP, Builder.saveIP(), V, ReplacementValue));
480 assert(ReplacementValue &&
481 "Expected copy/create callback to set replacement value!");
482 if (ReplacementValue == &V)
486 for (
Use *UPtr : Uses)
487 UPtr->set(ReplacementValue);
490 for (
Value *Input : Inputs) {
494 for (
Value *Output : Outputs) {
499 LLVM_DEBUG(
dbgs() <<
"After privatization: " << *UI->getFunction() <<
"\n");
501 for (
auto *BB : ParallelRegionBlocks)
502 dbgs() <<
" PBR: " << BB->getName() <<
"\n";
509 OutlinedFn->addFnAttr(Attribute::NoUnwind);
510 OutlinedFn->addFnAttr(Attribute::NoRecurse);
512 LLVM_DEBUG(
dbgs() <<
"After outlining: " << *UI->getFunction() <<
"\n");
513 LLVM_DEBUG(
dbgs() <<
" Outlined function: " << *OutlinedFn <<
"\n");
517 OutlinedFn->removeFromParent();
518 M.getFunctionList().insertAfter(OuterFn->
getIterator(), OutlinedFn);
523 BasicBlock &ArtificialEntry = OutlinedFn->getEntryBlock();
529 LLVM_DEBUG(
dbgs() <<
"PP Outlined function: " << *OutlinedFn <<
"\n");
530 assert(&OutlinedFn->getEntryBlock() == PRegEntryBB);
532 assert(OutlinedFn && OutlinedFn->getNumUses() == 1);
533 assert(OutlinedFn->arg_size() >= 2 &&
534 "Expected at least tid and bounded tid as arguments");
535 unsigned NumCapturedVars = OutlinedFn->arg_size() - 2;
537 CallInst *CI = cast<CallInst>(OutlinedFn->user_back());
539 Builder.SetInsertPoint(CI);
542 Value *ForkCallArgs[] = {Ident, Builder.getInt32(NumCapturedVars),
543 Builder.CreateBitCast(OutlinedFn, ParallelTaskPtr)};
549 FunctionCallee RTLFn = getOrCreateRuntimeFunction(OMPRTL___kmpc_fork_call);
550 if (
auto *
F = dyn_cast<llvm::Function>(RTLFn.
getCallee())) {
551 if (!
F->hasMetadata(llvm::LLVMContext::MD_callback)) {
560 llvm::LLVMContext::MD_callback,
567 Builder.CreateCall(RTLFn, RealArgs);
570 << *Builder.GetInsertBlock()->getParent() <<
"\n");
572 InsertPointTy AfterIP(UI->getParent(), UI->getParent()->end());
574 UI->eraseFromParent();
577 Builder.SetInsertPoint(PrivTID);
579 Builder.CreateStore(Builder.CreateLoad(OutlinedAI), PrivTIDAddr);
589 Builder.SetInsertPoint(ElseTI);
592 Value *SerializedParallelCallArgs[] = {Ident, ThreadID};
594 getOrCreateRuntimeFunction(OMPRTL___kmpc_serialized_parallel),
595 SerializedParallelCallArgs);
602 Value *EndArgs[] = {Ident, ThreadID};
604 getOrCreateRuntimeFunction(OMPRTL___kmpc_end_serialized_parallel),
608 << *Builder.GetInsertBlock()->getParent() <<
"\n");
614 auto FiniInfo = FinalizationStack.pop_back_val();
616 assert(FiniInfo.DK == OMPD_parallel &&
617 "Unexpected finalization stack state!");
623 "Unexpected CFG structure!");
629 I->eraseFromParent();
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
const_iterator end(StringRef path)
Get end iterator over path.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
static Constant * getString(LLVMContext &Context, StringRef Initializer, bool AddNull=true)
This method constructs a CDS and initializes it with a text string.
RuntimeFunction
IDs for all omp runtime library (RTL) functions.
DILocation * get() const
Get the underlying DILocation.
This class represents an incoming formal argument to a Function.
const_iterator begin(StringRef path, Style style=Style::native)
Get begin iterator over path.
This class represents lattice values for constants.
void addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind)
adds the attribute to the list of attributes for the given arg.
BasicBlock * getSuccessor(unsigned Idx) const
Return the specified successor. This instruction must be a terminator.
A handy container for a FunctionType+Callee-pointer pair, which can be passed around as a single enti...
void push_back(const T &Elt)
This class represents a function call, abstracting a target machine's calling convention.
The two locations do not alias at all.
An efficient, type-erasing, non-owning reference to a callable.
Like Internal, but omit from symbol table.
User::op_iterator arg_end()
Return the iterator pointing to the end of the argument list.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
BasicBlock * SplitBlock(BasicBlock *Old, Instruction *SplitPt, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="")
Split the specified block at the specified instruction - everything before SplitPt stays in Old and e...
LLVMContext & getContext() const
Get the context in which this basic block lives.
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
iterator begin()
Instruction iterator methods.
IRBuilder<>::InsertPoint InsertPointTy
Type used throughout for insertion points.
A Use represents the edge between a Value definition and its users.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
void setName(const Twine &Name)
Change the name of the value.
LLVM_NODISCARD bool empty() const
empty - Check if the string is empty.
void initializeTypes(Module &M)
Helper to initialize all types defined in OpenMP/OMPKinds.def.
Directive
IDs for all OpenMP directives.
const BasicBlock * getUniquePredecessor() const
Return the predecessor of this block if it has a unique predecessor block.
ProcBindKind
IDs for the different proc bind kinds.
InsertPointTy CreateCancel(const LocationDescription &Loc, Value *IfCondition, omp::Directive CanceledDirective)
Generator for '#omp cancel'.
void addAttributes(omp::RuntimeFunction FnID, Function &Fn)
Add attributes known for FnID to Fn.
unsigned getNumSuccessors() const
Return the number of successors that this instruction has.
const BasicBlock & getEntryBlock() const
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata *> MDs)
initializer< Ty > init(const Ty &Val)
const Instruction * getFirstNonPHI() const
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
static cl::opt< bool > OptimisticAttributes("openmp-ir-builder-optimistic-attributes", cl::Hidden, cl::desc("Use optimistic attributes describing " "'as-if' properties of runtime calls."), cl::init(false))
LLVM Basic Block Representation.
This is an important class for using LLVM in a threaded context.
This function has undefined behavior.
This is an important base class in LLVM.
MDNode * createCallbackEncoding(unsigned CalleeArgNo, ArrayRef< int > Arguments, bool VarArgsArePassed)
Return metadata describing a callback (see llvm::AbstractCallSite).
void initialize()
Initialize the internal state, this will put structures types and potentially other helpers into the ...
static Constant * get(StructType *T, ArrayRef< Constant *> V)
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
self_iterator getIterator()
IRBuilder ::InsertPoint CreateParallel(const LocationDescription &Loc, BodyGenCallbackTy BodyGenCB, PrivatizeCallbackTy PrivCB, FinalizeCallbackTy FiniCB, Value *IfCondition, Value *NumThreads, omp::ProcBindKind ProcBind, bool IsCancellable)
Generator for '#omp parallel'.
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function. ...
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
static Constant * getPointerCast(Constant *C, Type *Ty)
Create a BitCast, AddrSpaceCast, or a PtrToInt cast constant expression.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
LLVM_NODISCARD T pop_back_val()
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.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
iterator insert(iterator I, T &&Elt)
void append(in_iter in_start, in_iter in_end)
Add the specified range to the end of the SmallVector.
InsertPointTy CreateBarrier(const LocationDescription &Loc, omp::Directive DK, bool ForceSimpleCall=false, bool CheckCancelFlag=true)
Emitter methods for OpenMP directives.
void removeFromParent()
This method unlinks 'this' from the containing basic block, but does not delete it.
void SplitBlockAndInsertIfThenElse(Value *Cond, Instruction *SplitBefore, Instruction **ThenTerm, Instruction **ElseTerm, MDNode *BranchWeights=nullptr)
SplitBlockAndInsertIfThenElse is similar to SplitBlockAndInsertIfThen, but also creates the ElseBlock...
User::op_iterator arg_begin()
Return the iterator pointing to the beginning of the argument list.
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
void setAlignment(MaybeAlign Align)
void setUnnamedAddr(UnnamedAddr Val)
LLVM_NODISCARD bool empty() const
Description of a LLVM-IR insertion point (IP) and a debug/source location (filename, line, column, ...).
StringRef getName() const
Return a constant reference to the value's name.
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation.
const Function * getParent() const
Return the enclosing method, or null if none.
SymbolTableList< BasicBlock >::iterator eraseFromParent()
Unlink 'this' from the containing function and delete it.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
BasicBlock * splitBasicBlock(iterator I, const Twine &BBName="")
Split the basic block into two basic blocks at the specified instruction.
const std::string to_string(const T &Value)
LLVM_NODISCARD const char * data() const
data - Get a pointer to the start of the string (which may not be null terminated).
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
std::function< void(InsertPointTy CodeGenIP)> FinalizeCallbackTy
Callback type for variable finalization (think destructors).
LLVM Value Representation.
succ_range successors(Instruction *I)
StringRef - Represent a constant reference to a string, i.e.
void moveBefore(BasicBlock *MovePos)
Unlink this basic block from its current function and insert it into the function that MovePos lives ...
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
const BasicBlock * getParent() const
IdentFlag
IDs for all omp runtime library ident_t flag encodings (see their defintion in openmp/runtime/src/kmp...
an instruction to allocate memory on the stack
const BasicBlock * getUniqueSuccessor() const
Return the successor of this block if it has a unique successor.