16 #include "llvm/Config/llvm-config.h" 58 unsigned LastGlobalConstantID = 0;
59 unsigned LastGlobalValueID = 0;
63 bool isGlobalConstant(
unsigned ID)
const {
64 return ID <= LastGlobalConstantID;
67 bool isGlobalValue(
unsigned ID)
const {
68 return ID <= LastGlobalValueID && !isGlobalConstant(ID);
71 unsigned size()
const {
return IDs.
size(); }
72 std::pair<unsigned, bool> &operator[](
const Value *V) {
return IDs[V]; }
74 std::pair<unsigned, bool>
lookup(
const Value *V)
const {
78 void index(
const Value *V) {
80 unsigned ID = IDs.
size() + 1;
88 if (OM.lookup(V).first)
91 if (
const Constant *
C = dyn_cast<Constant>(V))
94 if (!isa<BasicBlock>(
Op) && !isa<GlobalValue>(
Op))
113 if (
G.hasInitializer())
114 if (!isa<GlobalValue>(
G.getInitializer()))
117 if (!isa<GlobalValue>(A.getAliasee()))
120 if (!isa<GlobalValue>(
I.getResolver()))
123 for (
const Use &U :
F.operands())
124 if (!isa<GlobalValue>(U.get()))
127 OM.LastGlobalConstantID = OM.size();
145 OM.LastGlobalValueID = OM.size();
148 if (
F.isDeclaration())
159 for (
const Value *
Op :
I.operands())
160 if ((isa<Constant>(*
Op) && !isa<GlobalValue>(*
Op)) ||
171 unsigned ID,
const OrderMap &OM,
174 using Entry = std::pair<const Use *, unsigned>;
178 if (OM.lookup(U.getUser()).
first)
185 bool IsGlobalValue = OM.isGlobalValue(ID);
187 const Use *LU = L.first;
188 const Use *RU = R.first;
192 auto LID = OM.lookup(LU->getUser()).
first;
193 auto RID = OM.lookup(RU->getUser()).
first;
201 if (OM.isGlobalValue(LID) && OM.isGlobalValue(RID))
222 return LU->getOperandNo() < RU->getOperandNo();
223 return LU->getOperandNo() > RU->getOperandNo();
228 [](
const Entry &L,
const Entry &R) {
return L.second < R.second; }))
233 Stack.emplace_back(V, F, List.
size());
234 assert(List.
size() == Stack.back().Shuffle.size() &&
"Wrong size");
235 for (
size_t I = 0,
E = List.
size();
I !=
E; ++
I)
236 Stack.back().Shuffle[
I] = List[
I].second;
241 auto &IDPair = OM[V];
242 assert(IDPair.first &&
"Unmapped value");
248 IDPair.second =
true;
253 if (
const Constant *
C = dyn_cast<Constant>(V))
256 if (isa<Constant>(
Op))
283 for (
const Value *
Op :
I.operands())
284 if (isa<Constant>(*
Op) || isa<InlineAsm>(*Op))
302 if (
G.hasInitializer())
309 for (
const Use &U :
F.operands())
317 return V.first->getType()->isIntOrIntVectorTy();
321 bool ShouldPreserveUseListOrder)
322 : ShouldPreserveUseListOrder(ShouldPreserveUseListOrder) {
323 if (ShouldPreserveUseListOrder)
333 EnumerateAttributes(
F.getAttributes());
342 EnumerateValue(&GIF);
345 unsigned FirstConstant = Values.size();
349 if (GV.hasInitializer())
350 EnumerateValue(GV.getInitializer());
351 if (GV.hasAttributes())
357 EnumerateValue(GA.getAliasee());
361 EnumerateValue(GIF.getResolver());
365 for (
const Use &U :
F.operands())
366 EnumerateValue(U.get());
376 EnumerateValueSymbolTable(M.getValueSymbolTable());
377 EnumerateNamedMetadata(M);
382 GV.getAllMetadata(MDs);
383 for (
const auto &
I : MDs)
387 EnumerateMetadata(
nullptr,
I.second);
393 EnumerateType(A.getType());
397 F.getAllMetadata(MDs);
398 for (
const auto &
I : MDs)
399 EnumerateMetadata(
F.isDeclaration() ? nullptr : &
F,
I.second);
403 for (
const Use &
Op :
I.operands()) {
406 EnumerateOperandType(
Op);
411 if (isa<LocalAsMetadata>(MD->getMetadata()))
414 EnumerateMetadata(&F, MD->getMetadata());
416 EnumerateType(
I.getType());
417 if (
const auto *Call = dyn_cast<CallBase>(&
I))
418 EnumerateAttributes(Call->getAttributes());
422 I.getAllMetadataOtherThanDebugLoc(MDs);
423 for (
unsigned i = 0,
e = MDs.size(); i !=
e; ++i)
424 EnumerateMetadata(&F, MDs[i].
second);
430 EnumerateMetadata(&F,
Op);
435 OptimizeConstants(FirstConstant, Values.size());
443 assert(I != InstructionMap.
end() &&
"Instruction is not mapped!");
448 unsigned ComdatID = Comdats.
idFor(C);
449 assert(ComdatID &&
"Comdat not found!");
454 InstructionMap[
I] = InstructionCount++;
458 if (
auto *MD = dyn_cast<MetadataAsValue>(V))
466 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 476 const char *
Name)
const {
477 OS <<
"Map Name: " << Name <<
"\n";
478 OS <<
"Size: " << Map.
size() <<
"\n";
481 const Value *V =
I->first;
483 OS <<
"Value: " << V->
getName();
485 OS <<
"Value: [null]\n";
490 for (
const Use &U : V->
uses()) {
494 OS <<
" " << U->getName();
504 const char *
Name)
const {
505 OS <<
"Map Name: " << Name <<
"\n";
506 OS <<
"Size: " << Map.
size() <<
"\n";
509 OS <<
"Metadata: slot = " <<
I->second.ID <<
"\n";
510 OS <<
"Metadata: function = " <<
I->second.F <<
"\n";
517 void ValueEnumerator::OptimizeConstants(
unsigned CstStart,
unsigned CstEnd) {
518 if (CstStart == CstEnd || CstStart+1 == CstEnd)
return;
520 if (ShouldPreserveUseListOrder)
526 [
this](
const std::pair<const Value *, unsigned> &LHS,
527 const std::pair<const Value *, unsigned> &RHS) {
529 if (LHS.first->getType() != RHS.first->getType())
532 return LHS.second > RHS.second;
538 std::stable_partition(Values.begin() + CstStart, Values.begin() + CstEnd,
542 for (; CstStart != CstEnd; ++CstStart)
548 void ValueEnumerator::EnumerateValueSymbolTable(
const ValueSymbolTable &VST) {
551 EnumerateValue(
VI->getValue());
556 void ValueEnumerator::EnumerateNamedMetadata(
const Module &M) {
558 EnumerateNamedMDNode(&
I);
561 void ValueEnumerator::EnumerateNamedMDNode(
const NamedMDNode *MD) {
563 EnumerateMetadata(
nullptr, MD->
getOperand(i));
566 unsigned ValueEnumerator::getMetadataFunctionID(
const Function *
F)
const {
570 void ValueEnumerator::EnumerateMetadata(
const Function *F,
const Metadata *MD) {
571 EnumerateMetadata(getMetadataFunctionID(F), MD);
574 void ValueEnumerator::EnumerateFunctionLocalMetadata(
576 EnumerateFunctionLocalMetadata(getMetadataFunctionID(&F), Local);
579 void ValueEnumerator::dropFunctionFromMetadata(
583 auto &
Entry = MD.second;
595 if (
auto *
N = dyn_cast<MDNode>(MD.first))
599 while (!Worklist.
empty())
603 auto MD = MetadataMap.
find(
Op);
604 if (MD != MetadataMap.
end())
609 void ValueEnumerator::EnumerateMetadata(
unsigned F,
const Metadata *MD) {
619 if (
const MDNode *
N = enumerateMetadataImpl(F, MD))
620 Worklist.
push_back(std::make_pair(
N,
N->op_begin()));
622 while (!Worklist.
empty()) {
629 [&](
const Metadata *MD) {
return enumerateMetadataImpl(F, MD); });
631 auto *
Op = cast<MDNode>(*I);
632 Worklist.
back().second = ++
I;
645 MetadataMap[
N].ID = MDs.size();
649 if (Worklist.
empty() || Worklist.
back().first->isDistinct()) {
650 for (
const MDNode *N : DelayedDistinctNodes)
652 DelayedDistinctNodes.clear();
657 const MDNode *ValueEnumerator::enumerateMetadataImpl(
unsigned F,
const Metadata *MD) {
662 (isa<MDNode>(MD) || isa<MDString>(MD) || isa<ConstantAsMetadata>(MD)) &&
663 "Invalid metadata kind");
665 auto Insertion = MetadataMap.
insert(std::make_pair(MD, MDIndex(F)));
666 MDIndex &
Entry = Insertion.first->second;
667 if (!Insertion.second) {
669 if (Entry.hasDifferentFunction(F))
670 dropFunctionFromMetadata(*Insertion.first);
675 if (
auto *
N = dyn_cast<MDNode>(MD))
680 Entry.ID = MDs.size();
683 if (
auto *
C = dyn_cast<ConstantAsMetadata>(MD))
684 EnumerateValue(
C->getValue());
691 void ValueEnumerator::EnumerateFunctionLocalMetadata(
693 assert(F &&
"Expected a function");
696 MDIndex &
Index = MetadataMap[Local];
698 assert(Index.F == F &&
"Expected the same function");
702 MDs.push_back(Local);
704 Index.ID = MDs.size();
711 if (isa<MDString>(MD))
722 return N->isDistinct() ? 2 : 3;
725 void ValueEnumerator::organizeMetadata() {
727 "Metadata map and vector out of sync");
745 llvm::sort(Order, [
this](MDIndex LHS, MDIndex RHS) {
752 std::vector<const Metadata *> OldMDs;
754 MDs.reserve(OldMDs.size());
755 for (
unsigned I = 0,
E = Order.
size();
I !=
E && !Order[
I].F; ++
I) {
756 auto *MD = Order[
I].get(OldMDs);
758 MetadataMap[MD].ID =
I + 1;
759 if (isa<MDString>(MD))
764 if (MDs.size() == Order.
size())
769 FunctionMDs.reserve(OldMDs.size());
771 for (
unsigned I = MDs.size(),
E = Order.
size(),
ID = MDs.size();
I !=
E;
773 unsigned F = Order[
I].F;
776 }
else if (PrevF != F) {
777 R.Last = FunctionMDs.size();
779 R.First = FunctionMDs.size();
785 auto *MD = Order[
I].get(OldMDs);
786 FunctionMDs.push_back(MD);
787 MetadataMap[MD].ID = ++
ID;
788 if (isa<MDString>(MD))
791 R.Last = FunctionMDs.size();
792 FunctionMDInfo[PrevF] = R;
795 void ValueEnumerator::incorporateFunctionMetadata(
const Function &F) {
796 NumModuleMDs = MDs.size();
799 NumMDStrings = R.NumStrings;
800 MDs.insert(MDs.end(), FunctionMDs.begin() + R.First,
801 FunctionMDs.begin() + R.Last);
804 void ValueEnumerator::EnumerateValue(
const Value *V) {
806 assert(!isa<MetadataAsValue>(V) &&
"EnumerateValue doesn't handle Metadata!");
812 Values[ValueID-1].second++;
816 if (
auto *GO = dyn_cast<GlobalObject>(V))
817 if (
const Comdat *
C = GO->getComdat())
823 if (
const Constant *
C = dyn_cast<Constant>(V)) {
824 if (isa<GlobalValue>(
C)) {
837 if (!isa<BasicBlock>(*
I))
842 Values.push_back(std::make_pair(V, 1U));
849 Values.push_back(std::make_pair(V, 1U));
850 ValueID = Values.size();
854 void ValueEnumerator::EnumerateType(
Type *Ty) {
855 unsigned *
TypeID = &TypeMap[Ty];
864 if (
StructType *STy = dyn_cast<StructType>(Ty))
865 if (!STy->isLiteral())
871 EnumerateType(SubTy);
874 TypeID = &TypeMap[Ty];
881 if (*TypeID && *TypeID != ~0U)
887 *TypeID = Types.size();
892 void ValueEnumerator::EnumerateOperandType(
const Value *V) {
895 assert(!isa<MetadataAsValue>(V) &&
"Unexpected metadata operand");
911 if (isa<BasicBlock>(
Op))
914 EnumerateOperandType(
Op);
918 void ValueEnumerator::EnumerateAttributes(
AttributeList PAL) {
922 unsigned &
Entry = AttributeListMap[PAL];
925 AttributeLists.push_back(PAL);
926 Entry = AttributeLists.size();
935 unsigned &Entry = AttributeGroupMap[Pair];
937 AttributeGroups.push_back(Pair);
938 Entry = AttributeGroups.size();
944 InstructionCount = 0;
945 NumModuleValues = Values.size();
949 incorporateFunctionMetadata(F);
952 for (
const auto &
I : F.
args()) {
954 if (
I.hasAttribute(Attribute::ByVal))
955 EnumerateType(
I.getParamByValType());
957 FirstFuncConstantID = Values.size();
962 for (
const Use &OI :
I.operands()) {
963 if ((isa<Constant>(OI) && !isa<GlobalValue>(OI)) || isa<InlineAsm>(OI))
966 BasicBlocks.push_back(&BB);
971 OptimizeConstants(FirstFuncConstantID, Values.size());
975 EnumerateAttributes(F.getAttributes());
977 FirstInstID = Values.size();
983 for (
const Use &OI :
I.operands()) {
984 if (
auto *MD = dyn_cast<MetadataAsValue>(&OI))
985 if (
auto *Local = dyn_cast<LocalAsMetadata>(MD->getMetadata()))
990 if (!
I.getType()->isVoidTy())
996 for (
unsigned i = 0,
e = FnLocalMDVector.
size(); i !=
e; ++i) {
1000 "Missing value for metadata operand");
1001 EnumerateFunctionLocalMetadata(F, FnLocalMDVector[i]);
1007 for (
unsigned i = NumModuleValues,
e = Values.size(); i !=
e; ++i)
1009 for (
unsigned i = NumModuleMDs,
e = MDs.size(); i !=
e; ++i)
1010 MetadataMap.
erase(MDs[i]);
1011 for (
unsigned i = 0,
e = BasicBlocks.size(); i !=
e; ++i)
1014 Values.resize(NumModuleValues);
1015 MDs.resize(NumModuleMDs);
1016 BasicBlocks.clear();
1022 unsigned Counter = 0;
1024 IDMap[&BB] = ++Counter;
1031 unsigned &Idx = GlobalBasicBlockIDs[BB];
unsigned Log2_32_Ceil(uint32_t Value)
Return the ceil log base 2 of the specified value, 32 if the value is zero.
Tracking metadata reference owned by Metadata.
This class provides a symbol table of name/value pairs.
ArrayRef< Type * > subtypes() const
iterator_range< use_iterator > uses()
raw_ostream & errs()
This returns a reference to a raw_ostream for standard error.
static unsigned getMetadataTypeOrder(const Metadata *MD)
This class represents an incoming formal argument to a Function.
iterator begin()
Get an iterator that from the beginning of the symbol table.
unsigned getValueID(const Value *V) const
MDNode * getOperand(unsigned i) const
This class represents lattice values for constants.
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds...
static void predictValueUseListOrder(const Value *V, const Function *F, OrderMap &OM, UseListOrderStack &Stack)
A Module instance is used to store all the information related to an LLVM module. ...
amdgpu Simplify well known AMD library false FunctionCallee Value const Twine & Name
std::pair< unsigned, AttributeSet > IndexAndAttrSet
Attribute groups as encoded in bitcode are almost AttributeSets, but they include the AttributeList i...
void push_back(const T &Elt)
static bool lookup(const GsymReader &GR, DataExtractor &Data, uint64_t &Offset, uint64_t BaseAddr, uint64_t Addr, SourceLocations &SrcLocs, llvm::Error &Err)
A Lookup helper functions.
void setInstructionID(const Instruction *I)
static Type * getMetadataTy(LLVMContext &C)
unsigned index_end() const
This defines the Use class.
void reserve(size_type N)
static void predictValueUseListOrderImpl(const Value *V, const Function *F, unsigned ID, const OrderMap &OM, UseListOrderStack &Stack)
op_iterator op_end() const
unsigned getMetadataID(const Metadata *MD) const
void incorporateFunction(const Function &F)
incorporateFunction/purgeFunction - If you'd like to deal with a function, use these two methods to g...
static bool isIntOrIntVectorValue(const std::pair< const Value *, unsigned > &V)
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Class to represent struct types.
A Use represents the edge between a Value definition and its users.
const TypeList & getTypes() const
This file contains the simple types necessary to represent the attributes associated with functions a...
TypeID
Definitions of all of the base types for the Type system.
uint64_t computeBitsRequiredForTypeIndicies() const
unsigned getNumOperands() const
op_iterator op_begin() const
unsigned idFor(const T &Entry) const
idFor - return the ID for an existing entry.
Type * getType() const
All values are typed, get the type of this value.
op_range operands() const
llvm::detail::DenseMapPair< const Metadata *, MDIndex > value_type
iterator find(const KeyT &Val)
iterator end()
Get an iterator to the end of the symbol table.
iterator find(const_arg_type_t< KeyT > Val)
AttributeSet getAttributes(unsigned Index) const
The attributes for the specified index are returned.
bool isVoidTy() const
Return true if this is 'void'.
bool erase(const KeyT &Val)
LLVM Basic Block Representation.
The instances of the Type class are immutable: once they are created, they are never changed...
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
void print(raw_ostream &OS, const ValueMapType &Map, const char *Name) const
unsigned getInstructionID(const Instruction *I) const
std::vector< UseListOrder > UseListOrderStack
ValueEnumerator(const Module &M, bool ShouldPreserveUseListOrder)
iterator_range< named_metadata_iterator > named_metadata()
unsigned getGlobalBasicBlockID(const BasicBlock *BB) const
getGlobalBasicBlockID - This returns the function-specific ID for the specified basic block...
void print(raw_ostream &O, bool IsForDebug=false) const
Implement operator<< on Value.
static OrderMap orderModule(const Module &M)
static UseListOrderStack predictUseListOrder(const Module &M)
auto find_if(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range))
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly...
void sort(IteratorTy Start, IteratorTy End)
reverse_iterator rbegin()
unsigned getNumOperands() const
auto size(R &&Range, typename std::enable_if< std::is_same< typename std::iterator_traits< decltype(Range.begin())>::iterator_category, std::random_access_iterator_tag >::value, void >::type *=nullptr) -> decltype(std::distance(Range.begin(), Range.end()))
Get the size of a range.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Module.h This file contains the declarations for the Module class.
LLVM_NODISCARD T pop_back_val()
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
unsigned getTypeID(Type *T) const
UseListOrderStack UseListOrders
unsigned getNumUses() const
This method computes the number of uses of this Value.
static void orderValue(const Value *V, OrderMap &OM)
unsigned insert(const T &Entry)
insert - Append entry to the vector if it doesn't already exist.
LLVM_NODISCARD bool empty() const
StringRef getName() const
Return a constant reference to the value's name.
const Function * getParent() const
Return the enclosing method, or null if none.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
iterator_range< ifunc_iterator > ifuncs()
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
static void IncorporateFunctionInfoGlobalBBIDs(const Function *F, DenseMap< const BasicBlock *, unsigned > &IDMap)
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
size_type count(const KeyT &Val) const
Return 1 if the specified key is in the map, 0 otherwise.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
bool hasAttributes() const
Return true if attributes exists in this set.
void stable_sort(R &&Range)
LLVM Value Representation.
This class implements an extremely fast bulk output stream that can only output to a stream...
iterator_range< global_iterator > globals()
unsigned getComdatID(const Comdat *C) const
bool isEmpty() const
Return true if there are no attributes.
iterator_range< arg_iterator > args()
unsigned index_begin() const
Use these to iterate over the valid attribute indices.
bool erase(const KeyT &Val)
iterator_range< alias_iterator > aliases()