This commit is contained in:
nephacks
2025-06-04 03:22:50 +02:00
parent f234f23848
commit f12416cffd
14243 changed files with 6446499 additions and 26 deletions

View File

@@ -0,0 +1,100 @@
//===-- llvm/Argument.h - Definition of the Argument class ------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file declares the Argument class.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_IR_ARGUMENT_H
#define LLVM_IR_ARGUMENT_H
#include "llvm/ADT/Twine.h"
#include "llvm/ADT/ilist_node.h"
#include "llvm/IR/Attributes.h"
#include "llvm/IR/Value.h"
namespace llvm {
template<typename ValueSubClass, typename ItemParentClass>
class SymbolTableListTraits;
/// \brief LLVM Argument representation
///
/// This class represents an incoming formal argument to a Function. A formal
/// argument, since it is ``formal'', does not contain an actual value but
/// instead represents the type, argument number, and attributes of an argument
/// for a specific function. When used in the body of said function, the
/// argument of course represents the value of the actual argument that the
/// function was called with.
class Argument : public Value, public ilist_node<Argument> {
virtual void anchor();
Function *Parent;
friend class SymbolTableListTraits<Argument, Function>;
void setParent(Function *parent);
public:
/// \brief Constructor.
///
/// If \p F is specified, the argument is inserted at the end of the argument
/// list for \p F.
explicit Argument(Type *Ty, const Twine &Name = "", Function *F = 0);
inline const Function *getParent() const { return Parent; }
inline Function *getParent() { return Parent; }
/// \brief Return the index of this formal argument in its containing
/// function.
///
/// For example in "void foo(int a, float b)" a is 0 and b is 1.
unsigned getArgNo() const;
/// \brief Return true if this argument has the byval attribute on it in its
/// containing function.
bool hasByValAttr() const;
/// \brief If this is a byval argument, return its alignment.
unsigned getParamAlignment() const;
/// \brief Return true if this argument has the nest attribute on it in its
/// containing function.
bool hasNestAttr() const;
/// \brief Return true if this argument has the noalias attribute on it in its
/// containing function.
bool hasNoAliasAttr() const;
/// \brief Return true if this argument has the nocapture attribute on it in
/// its containing function.
bool hasNoCaptureAttr() const;
/// \brief Return true if this argument has the sret attribute on it in its
/// containing function.
bool hasStructRetAttr() const;
/// \brief Return true if this argument has the returned attribute on it in
/// its containing function.
bool hasReturnedAttr() const;
/// \brief Add a Attribute to an argument.
void addAttr(AttributeSet AS);
/// \brief Remove a Attribute from an argument.
void removeAttr(AttributeSet AS);
/// \brief Method for support type inquiry through isa, cast, and
/// dyn_cast.
static inline bool classof(const Value *V) {
return V->getValueID() == ArgumentVal;
}
};
} // End llvm namespace
#endif

View File

@@ -0,0 +1,498 @@
//===-- llvm/Attributes.h - Container for Attributes ------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// \file
/// \brief This file contains the simple types necessary to represent the
/// attributes associated with functions and their calls.
///
//===----------------------------------------------------------------------===//
#ifndef LLVM_IR_ATTRIBUTES_H
#define LLVM_IR_ATTRIBUTES_H
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/FoldingSet.h"
#include "llvm/Support/PointerLikeTypeTraits.h"
#include <bitset>
#include <cassert>
#include <map>
#include <string>
namespace llvm {
class AttrBuilder;
class AttributeImpl;
class AttributeSetImpl;
class AttributeSetNode;
class Constant;
template<typename T> struct DenseMapInfo;
class LLVMContext;
class Type;
//===----------------------------------------------------------------------===//
/// \class
/// \brief Functions, function parameters, and return types can have attributes
/// to indicate how they should be treated by optimizations and code
/// generation. This class represents one of those attributes. It's light-weight
/// and should be passed around by-value.
class Attribute {
public:
/// This enumeration lists the attributes that can be associated with
/// parameters, function results, or the function itself.
///
/// Note: The `uwtable' attribute is about the ABI or the user mandating an
/// entry in the unwind table. The `nounwind' attribute is about an exception
/// passing by the function.
///
/// In a theoretical system that uses tables for profiling and SjLj for
/// exceptions, they would be fully independent. In a normal system that uses
/// tables for both, the semantics are:
///
/// nil = Needs an entry because an exception might pass by.
/// nounwind = No need for an entry
/// uwtable = Needs an entry because the ABI says so and because
/// an exception might pass by.
/// uwtable + nounwind = Needs an entry because the ABI says so.
enum AttrKind {
// IR-Level Attributes
None, ///< No attributes have been set
Alignment, ///< Alignment of parameter (5 bits)
///< stored as log2 of alignment with +1 bias
///< 0 means unaligned (different from align(1))
AlwaysInline, ///< inline=always
ByVal, ///< Pass structure by value
InlineHint, ///< Source said inlining was desirable
InReg, ///< Force argument to be passed in register
MinSize, ///< Function must be optimized for size first
Naked, ///< Naked function
Nest, ///< Nested function static chain
NoAlias, ///< Considered to not alias after call
NoBuiltin, ///< Callee isn't recognized as a builtin
NoCapture, ///< Function creates no aliases of pointer
NoDuplicate, ///< Call cannot be duplicated
NoImplicitFloat, ///< Disable implicit floating point insts
NoInline, ///< inline=never
NonLazyBind, ///< Function is called early and/or
///< often, so lazy binding isn't worthwhile
NoRedZone, ///< Disable redzone
NoReturn, ///< Mark the function as not returning
NoUnwind, ///< Function doesn't unwind stack
OptimizeForSize, ///< opt_size
ReadNone, ///< Function does not access memory
ReadOnly, ///< Function only reads from memory
Returned, ///< Return value is always equal to this argument
ReturnsTwice, ///< Function can return twice
SExt, ///< Sign extended before/after call
StackAlignment, ///< Alignment of stack for function (3 bits)
///< stored as log2 of alignment with +1 bias 0
///< means unaligned (different from
///< alignstack=(1))
StackProtect, ///< Stack protection.
StackProtectReq, ///< Stack protection required.
StackProtectStrong, ///< Strong Stack protection.
StructRet, ///< Hidden pointer to structure to return
SanitizeAddress, ///< AddressSanitizer is on.
SanitizeThread, ///< ThreadSanitizer is on.
SanitizeMemory, ///< MemorySanitizer is on.
UWTable, ///< Function must be in a unwind table
ZExt, ///< Zero extended before/after call
EndAttrKinds ///< Sentinal value useful for loops
};
private:
AttributeImpl *pImpl;
Attribute(AttributeImpl *A) : pImpl(A) {}
public:
Attribute() : pImpl(0) {}
//===--------------------------------------------------------------------===//
// Attribute Construction
//===--------------------------------------------------------------------===//
/// \brief Return a uniquified Attribute object.
static Attribute get(LLVMContext &Context, AttrKind Kind, uint64_t Val = 0);
static Attribute get(LLVMContext &Context, StringRef Kind,
StringRef Val = StringRef());
/// \brief Return a uniquified Attribute object that has the specific
/// alignment set.
static Attribute getWithAlignment(LLVMContext &Context, uint64_t Align);
static Attribute getWithStackAlignment(LLVMContext &Context, uint64_t Align);
//===--------------------------------------------------------------------===//
// Attribute Accessors
//===--------------------------------------------------------------------===//
/// \brief Return true if the attribute is an Attribute::AttrKind type.
bool isEnumAttribute() const;
/// \brief Return true if the attribute is an alignment attribute.
bool isAlignAttribute() const;
/// \brief Return true if the attribute is a string (target-dependent)
/// attribute.
bool isStringAttribute() const;
/// \brief Return true if the attribute is present.
bool hasAttribute(AttrKind Val) const;
/// \brief Return true if the target-dependent attribute is present.
bool hasAttribute(StringRef Val) const;
/// \brief Return the attribute's kind as an enum (Attribute::AttrKind). This
/// requires the attribute to be an enum or alignment attribute.
Attribute::AttrKind getKindAsEnum() const;
/// \brief Return the attribute's value as an integer. This requires that the
/// attribute be an alignment attribute.
uint64_t getValueAsInt() const;
/// \brief Return the attribute's kind as a string. This requires the
/// attribute to be a string attribute.
StringRef getKindAsString() const;
/// \brief Return the attribute's value as a string. This requires the
/// attribute to be a string attribute.
StringRef getValueAsString() const;
/// \brief Returns the alignment field of an attribute as a byte alignment
/// value.
unsigned getAlignment() const;
/// \brief Returns the stack alignment field of an attribute as a byte
/// alignment value.
unsigned getStackAlignment() const;
/// \brief The Attribute is converted to a string of equivalent mnemonic. This
/// is, presumably, for writing out the mnemonics for the assembly writer.
std::string getAsString(bool InAttrGrp = false) const;
/// \brief Equality and non-equality operators.
bool operator==(Attribute A) const { return pImpl == A.pImpl; }
bool operator!=(Attribute A) const { return pImpl != A.pImpl; }
/// \brief Less-than operator. Useful for sorting the attributes list.
bool operator<(Attribute A) const;
void Profile(FoldingSetNodeID &ID) const {
ID.AddPointer(pImpl);
}
};
//===----------------------------------------------------------------------===//
/// \class
/// \brief This class holds the attributes for a function, its return value, and
/// its parameters. You access the attributes for each of them via an index into
/// the AttributeSet object. The function attributes are at index
/// `AttributeSet::FunctionIndex', the return value is at index
/// `AttributeSet::ReturnIndex', and the attributes for the parameters start at
/// index `1'.
class AttributeSet {
public:
enum AttrIndex {
ReturnIndex = 0U,
FunctionIndex = ~0U
};
private:
friend class AttrBuilder;
friend class AttributeSetImpl;
template <typename Ty> friend struct DenseMapInfo;
/// \brief The attributes that we are managing. This can be null to represent
/// the empty attributes list.
AttributeSetImpl *pImpl;
/// \brief The attributes for the specified index are returned.
AttributeSetNode *getAttributes(unsigned Index) const;
/// \brief Create an AttributeSet with the specified parameters in it.
static AttributeSet get(LLVMContext &C,
ArrayRef<std::pair<unsigned, Attribute> > Attrs);
static AttributeSet get(LLVMContext &C,
ArrayRef<std::pair<unsigned,
AttributeSetNode*> > Attrs);
static AttributeSet getImpl(LLVMContext &C,
ArrayRef<std::pair<unsigned,
AttributeSetNode*> > Attrs);
explicit AttributeSet(AttributeSetImpl *LI) : pImpl(LI) {}
public:
AttributeSet() : pImpl(0) {}
//===--------------------------------------------------------------------===//
// AttributeSet Construction and Mutation
//===--------------------------------------------------------------------===//
/// \brief Return an AttributeSet with the specified parameters in it.
static AttributeSet get(LLVMContext &C, ArrayRef<AttributeSet> Attrs);
static AttributeSet get(LLVMContext &C, unsigned Index,
ArrayRef<Attribute::AttrKind> Kind);
static AttributeSet get(LLVMContext &C, unsigned Index, AttrBuilder &B);
/// \brief Add an attribute to the attribute set at the given index. Since
/// attribute sets are immutable, this returns a new set.
AttributeSet addAttribute(LLVMContext &C, unsigned Index,
Attribute::AttrKind Attr) const;
/// \brief Add an attribute to the attribute set at the given index. Since
/// attribute sets are immutable, this returns a new set.
AttributeSet addAttribute(LLVMContext &C, unsigned Index,
StringRef Kind) const;
/// \brief Add attributes to the attribute set at the given index. Since
/// attribute sets are immutable, this returns a new set.
AttributeSet addAttributes(LLVMContext &C, unsigned Index,
AttributeSet Attrs) const;
/// \brief Remove the specified attribute at the specified index from this
/// attribute list. Since attribute lists are immutable, this returns the new
/// list.
AttributeSet removeAttribute(LLVMContext &C, unsigned Index,
Attribute::AttrKind Attr) const;
/// \brief Remove the specified attributes at the specified index from this
/// attribute list. Since attribute lists are immutable, this returns the new
/// list.
AttributeSet removeAttributes(LLVMContext &C, unsigned Index,
AttributeSet Attrs) const;
//===--------------------------------------------------------------------===//
// AttributeSet Accessors
//===--------------------------------------------------------------------===//
/// \brief Retrieve the LLVM context.
LLVMContext &getContext() const;
/// \brief The attributes for the specified index are returned.
AttributeSet getParamAttributes(unsigned Index) const;
/// \brief The attributes for the ret value are returned.
AttributeSet getRetAttributes() const;
/// \brief The function attributes are returned.
AttributeSet getFnAttributes() const;
/// \brief Return true if the attribute exists at the given index.
bool hasAttribute(unsigned Index, Attribute::AttrKind Kind) const;
/// \brief Return true if the attribute exists at the given index.
bool hasAttribute(unsigned Index, StringRef Kind) const;
/// \brief Return true if attribute exists at the given index.
bool hasAttributes(unsigned Index) const;
/// \brief Return true if the specified attribute is set for at least one
/// parameter or for the return value.
bool hasAttrSomewhere(Attribute::AttrKind Attr) const;
/// \brief Return the attribute object that exists at the given index.
Attribute getAttribute(unsigned Index, Attribute::AttrKind Kind) const;
/// \brief Return the attribute object that exists at the given index.
Attribute getAttribute(unsigned Index, StringRef Kind) const;
/// \brief Return the alignment for the specified function parameter.
unsigned getParamAlignment(unsigned Index) const;
/// \brief Get the stack alignment.
unsigned getStackAlignment(unsigned Index) const;
/// \brief Return the attributes at the index as a string.
std::string getAsString(unsigned Index, bool TargetIndependent = true,
bool InAttrGrp = false) const;
typedef ArrayRef<Attribute>::iterator iterator;
iterator begin(unsigned Slot) const;
iterator end(unsigned Slot) const;
/// operator==/!= - Provide equality predicates.
bool operator==(const AttributeSet &RHS) const {
return pImpl == RHS.pImpl;
}
bool operator!=(const AttributeSet &RHS) const {
return pImpl != RHS.pImpl;
}
//===--------------------------------------------------------------------===//
// AttributeSet Introspection
//===--------------------------------------------------------------------===//
// FIXME: Remove this.
uint64_t Raw(unsigned Index) const;
/// \brief Return a raw pointer that uniquely identifies this attribute list.
void *getRawPointer() const {
return pImpl;
}
/// \brief Return true if there are no attributes.
bool isEmpty() const {
return getNumSlots() == 0;
}
/// \brief Return the number of slots used in this attribute list. This is
/// the number of arguments that have an attribute set on them (including the
/// function itself).
unsigned getNumSlots() const;
/// \brief Return the index for the given slot.
uint64_t getSlotIndex(unsigned Slot) const;
/// \brief Return the attributes at the given slot.
AttributeSet getSlotAttributes(unsigned Slot) const;
void dump() const;
};
//===----------------------------------------------------------------------===//
/// \class
/// \brief Provide DenseMapInfo for AttributeSet.
template<> struct DenseMapInfo<AttributeSet> {
static inline AttributeSet getEmptyKey() {
uintptr_t Val = static_cast<uintptr_t>(-1);
Val <<= PointerLikeTypeTraits<void*>::NumLowBitsAvailable;
return AttributeSet(reinterpret_cast<AttributeSetImpl*>(Val));
}
static inline AttributeSet getTombstoneKey() {
uintptr_t Val = static_cast<uintptr_t>(-2);
Val <<= PointerLikeTypeTraits<void*>::NumLowBitsAvailable;
return AttributeSet(reinterpret_cast<AttributeSetImpl*>(Val));
}
static unsigned getHashValue(AttributeSet AS) {
return (unsigned((uintptr_t)AS.pImpl) >> 4) ^
(unsigned((uintptr_t)AS.pImpl) >> 9);
}
static bool isEqual(AttributeSet LHS, AttributeSet RHS) { return LHS == RHS; }
};
//===----------------------------------------------------------------------===//
/// \class
/// \brief This class is used in conjunction with the Attribute::get method to
/// create an Attribute object. The object itself is uniquified. The Builder's
/// value, however, is not. So this can be used as a quick way to test for
/// equality, presence of attributes, etc.
class AttrBuilder {
std::bitset<Attribute::EndAttrKinds> Attrs;
std::map<std::string, std::string> TargetDepAttrs;
uint64_t Alignment;
uint64_t StackAlignment;
public:
AttrBuilder() : Attrs(0), Alignment(0), StackAlignment(0) {}
explicit AttrBuilder(uint64_t Val)
: Attrs(0), Alignment(0), StackAlignment(0) {
addRawValue(Val);
}
AttrBuilder(const Attribute &A) : Attrs(0), Alignment(0), StackAlignment(0) {
addAttribute(A);
}
AttrBuilder(AttributeSet AS, unsigned Idx);
AttrBuilder(const AttrBuilder &B)
: Attrs(B.Attrs),
TargetDepAttrs(B.TargetDepAttrs.begin(), B.TargetDepAttrs.end()),
Alignment(B.Alignment), StackAlignment(B.StackAlignment) {}
void clear();
/// \brief Add an attribute to the builder.
AttrBuilder &addAttribute(Attribute::AttrKind Val);
/// \brief Add the Attribute object to the builder.
AttrBuilder &addAttribute(Attribute A);
/// \brief Add the target-dependent attribute to the builder.
AttrBuilder &addAttribute(StringRef A, StringRef V = StringRef());
/// \brief Remove an attribute from the builder.
AttrBuilder &removeAttribute(Attribute::AttrKind Val);
/// \brief Remove the attributes from the builder.
AttrBuilder &removeAttributes(AttributeSet A, uint64_t Index);
/// \brief Remove the target-dependent attribute to the builder.
AttrBuilder &removeAttribute(StringRef A);
/// \brief Add the attributes from the builder.
AttrBuilder &merge(const AttrBuilder &B);
/// \brief Return true if the builder has the specified attribute.
bool contains(Attribute::AttrKind A) const {
assert((unsigned)A < Attribute::EndAttrKinds && "Attribute out of range!");
return Attrs[A];
}
/// \brief Return true if the builder has the specified target-dependent
/// attribute.
bool contains(StringRef A) const;
/// \brief Return true if the builder has IR-level attributes.
bool hasAttributes() const;
/// \brief Return true if the builder has any attribute that's in the
/// specified attribute.
bool hasAttributes(AttributeSet A, uint64_t Index) const;
/// \brief Return true if the builder has an alignment attribute.
bool hasAlignmentAttr() const;
/// \brief Retrieve the alignment attribute, if it exists.
uint64_t getAlignment() const { return Alignment; }
/// \brief Retrieve the stack alignment attribute, if it exists.
uint64_t getStackAlignment() const { return StackAlignment; }
/// \brief This turns an int alignment (which must be a power of 2) into the
/// form used internally in Attribute.
AttrBuilder &addAlignmentAttr(unsigned Align);
/// \brief This turns an int stack alignment (which must be a power of 2) into
/// the form used internally in Attribute.
AttrBuilder &addStackAlignmentAttr(unsigned Align);
/// \brief Return true if the builder contains no target-independent
/// attributes.
bool empty() const { return Attrs.none(); }
// Iterators for target-dependent attributes.
typedef std::pair<std::string, std::string> td_type;
typedef std::map<std::string, std::string>::iterator td_iterator;
typedef std::map<std::string, std::string>::const_iterator td_const_iterator;
td_iterator td_begin() { return TargetDepAttrs.begin(); }
td_iterator td_end() { return TargetDepAttrs.end(); }
td_const_iterator td_begin() const { return TargetDepAttrs.begin(); }
td_const_iterator td_end() const { return TargetDepAttrs.end(); }
bool td_empty() const { return TargetDepAttrs.empty(); }
bool operator==(const AttrBuilder &B);
bool operator!=(const AttrBuilder &B) {
return !(*this == B);
}
// FIXME: Remove this in 4.0.
/// \brief Add the raw value to the internal representation.
AttrBuilder &addRawValue(uint64_t Val);
};
namespace AttributeFuncs {
/// \brief Which attributes cannot be applied to a type.
AttributeSet typeIncompatible(Type *Ty, uint64_t Index);
} // end AttributeFuncs namespace
} // end llvm namespace
#endif

View File

@@ -0,0 +1,303 @@
//===-- llvm/BasicBlock.h - Represent a basic block in the VM ---*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains the declaration of the BasicBlock class.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_IR_BASICBLOCK_H
#define LLVM_IR_BASICBLOCK_H
#include "llvm/ADT/Twine.h"
#include "llvm/ADT/ilist.h"
#include "llvm/IR/Instruction.h"
#include "llvm/IR/SymbolTableListTraits.h"
#include "llvm/Support/DataTypes.h"
namespace llvm {
class LandingPadInst;
class TerminatorInst;
class LLVMContext;
class BlockAddress;
template<> struct ilist_traits<Instruction>
: public SymbolTableListTraits<Instruction, BasicBlock> {
/// \brief Return a node that marks the end of a list.
///
/// The sentinel is relative to this instance, so we use a non-static
/// method.
Instruction *createSentinel() const {
// Since i(p)lists always publicly derive from their corresponding traits,
// placing a data member in this class will augment the i(p)list. But since
// the NodeTy is expected to be publicly derive from ilist_node<NodeTy>,
// there is a legal viable downcast from it to NodeTy. We use this trick to
// superimpose an i(p)list with a "ghostly" NodeTy, which becomes the
// sentinel. Dereferencing the sentinel is forbidden (save the
// ilist_node<NodeTy>), so no one will ever notice the superposition.
return static_cast<Instruction*>(&Sentinel);
}
static void destroySentinel(Instruction*) {}
Instruction *provideInitialHead() const { return createSentinel(); }
Instruction *ensureHead(Instruction*) const { return createSentinel(); }
static void noteHead(Instruction*, Instruction*) {}
private:
mutable ilist_half_node<Instruction> Sentinel;
};
/// \brief LLVM Basic Block Representation
///
/// This represents a single basic block in LLVM. A basic block is simply a
/// container of instructions that execute sequentially. Basic blocks are Values
/// because they are referenced by instructions such as branches and switch
/// tables. The type of a BasicBlock is "Type::LabelTy" because the basic block
/// represents a label to which a branch can jump.
///
/// A well formed basic block is formed of a list of non-terminating
/// instructions followed by a single TerminatorInst instruction.
/// TerminatorInst's may not occur in the middle of basic blocks, and must
/// terminate the blocks. The BasicBlock class allows malformed basic blocks to
/// occur because it may be useful in the intermediate stage of constructing or
/// modifying a program. However, the verifier will ensure that basic blocks
/// are "well formed".
class BasicBlock : public Value, // Basic blocks are data objects also
public ilist_node<BasicBlock> {
friend class BlockAddress;
public:
typedef iplist<Instruction> InstListType;
private:
InstListType InstList;
Function *Parent;
void setParent(Function *parent);
friend class SymbolTableListTraits<BasicBlock, Function>;
BasicBlock(const BasicBlock &) LLVM_DELETED_FUNCTION;
void operator=(const BasicBlock &) LLVM_DELETED_FUNCTION;
/// \brief Constructor.
///
/// If the function parameter is specified, the basic block is automatically
/// inserted at either the end of the function (if InsertBefore is null), or
/// before the specified basic block.
explicit BasicBlock(LLVMContext &C, const Twine &Name = "",
Function *Parent = 0, BasicBlock *InsertBefore = 0);
public:
/// \brief Get the context in which this basic block lives.
LLVMContext &getContext() const;
/// Instruction iterators...
typedef InstListType::iterator iterator;
typedef InstListType::const_iterator const_iterator;
typedef InstListType::reverse_iterator reverse_iterator;
typedef InstListType::const_reverse_iterator const_reverse_iterator;
/// \brief Creates a new BasicBlock.
///
/// If the Parent parameter is specified, the basic block is automatically
/// inserted at either the end of the function (if InsertBefore is 0), or
/// before the specified basic block.
static BasicBlock *Create(LLVMContext &Context, const Twine &Name = "",
Function *Parent = 0,BasicBlock *InsertBefore = 0) {
return new BasicBlock(Context, Name, Parent, InsertBefore);
}
~BasicBlock();
/// \brief Return the enclosing method, or null if none.
const Function *getParent() const { return Parent; }
Function *getParent() { return Parent; }
/// \brief Returns the terminator instruction if the block is well formed or
/// null if the block is not well formed.
TerminatorInst *getTerminator();
const TerminatorInst *getTerminator() const;
/// \brief Returns a pointer to the first instruction in this block that is
/// not a PHINode instruction.
///
/// When adding instructions to the beginning of the basic block, they should
/// be added before the returned value, not before the first instruction,
/// which might be PHI. Returns 0 is there's no non-PHI instruction.
Instruction* getFirstNonPHI();
const Instruction* getFirstNonPHI() const {
return const_cast<BasicBlock*>(this)->getFirstNonPHI();
}
/// \brief Returns a pointer to the first instruction in this block that is not
/// a PHINode or a debug intrinsic.
Instruction* getFirstNonPHIOrDbg();
const Instruction* getFirstNonPHIOrDbg() const {
return const_cast<BasicBlock*>(this)->getFirstNonPHIOrDbg();
}
/// \brief Returns a pointer to the first instruction in this block that is not
/// a PHINode, a debug intrinsic, or a lifetime intrinsic.
Instruction* getFirstNonPHIOrDbgOrLifetime();
const Instruction* getFirstNonPHIOrDbgOrLifetime() const {
return const_cast<BasicBlock*>(this)->getFirstNonPHIOrDbgOrLifetime();
}
/// \brief Returns an iterator to the first instruction in this block that is
/// suitable for inserting a non-PHI instruction.
///
/// In particular, it skips all PHIs and LandingPad instructions.
iterator getFirstInsertionPt();
const_iterator getFirstInsertionPt() const {
return const_cast<BasicBlock*>(this)->getFirstInsertionPt();
}
/// \brief Unlink 'this' from the containing function, but do not delete it.
void removeFromParent();
/// \brief Unlink 'this' from the containing function and delete it.
void eraseFromParent();
/// \brief Unlink this basic block from its current function and insert it
/// into the function that \p MovePos lives in, right before \p MovePos.
void moveBefore(BasicBlock *MovePos);
/// \brief Unlink this basic block from its current function and insert it
/// right after \p MovePos in the function \p MovePos lives in.
void moveAfter(BasicBlock *MovePos);
/// \brief Return this block if it has a single predecessor block. Otherwise
/// return a null pointer.
BasicBlock *getSinglePredecessor();
const BasicBlock *getSinglePredecessor() const {
return const_cast<BasicBlock*>(this)->getSinglePredecessor();
}
/// \brief Return this block if it has a unique predecessor block. Otherwise return a null pointer.
///
/// Note that unique predecessor doesn't mean single edge, there can be
/// multiple edges from the unique predecessor to this block (for example a
/// switch statement with multiple cases having the same destination).
BasicBlock *getUniquePredecessor();
const BasicBlock *getUniquePredecessor() const {
return const_cast<BasicBlock*>(this)->getUniquePredecessor();
}
//===--------------------------------------------------------------------===//
/// Instruction iterator methods
///
inline iterator begin() { return InstList.begin(); }
inline const_iterator begin() const { return InstList.begin(); }
inline iterator end () { return InstList.end(); }
inline const_iterator end () const { return InstList.end(); }
inline reverse_iterator rbegin() { return InstList.rbegin(); }
inline const_reverse_iterator rbegin() const { return InstList.rbegin(); }
inline reverse_iterator rend () { return InstList.rend(); }
inline const_reverse_iterator rend () const { return InstList.rend(); }
inline size_t size() const { return InstList.size(); }
inline bool empty() const { return InstList.empty(); }
inline const Instruction &front() const { return InstList.front(); }
inline Instruction &front() { return InstList.front(); }
inline const Instruction &back() const { return InstList.back(); }
inline Instruction &back() { return InstList.back(); }
/// \brief Return the underlying instruction list container.
///
/// Currently you need to access the underlying instruction list container
/// directly if you want to modify it.
const InstListType &getInstList() const { return InstList; }
InstListType &getInstList() { return InstList; }
/// \brief Returns a pointer to a member of the instruction list.
static iplist<Instruction> BasicBlock::*getSublistAccess(Instruction*) {
return &BasicBlock::InstList;
}
/// \brief Returns a pointer to the symbol table if one exists.
ValueSymbolTable *getValueSymbolTable();
/// \brief Methods for support type inquiry through isa, cast, and dyn_cast.
static inline bool classof(const Value *V) {
return V->getValueID() == Value::BasicBlockVal;
}
/// \brief Cause all subinstructions to "let go" of all the references that
/// said subinstructions are maintaining.
///
/// This allows one to 'delete' a whole class at a time, even though there may
/// be circular references... first all references are dropped, and all use
/// counts go to zero. Then everything is delete'd for real. Note that no
/// operations are valid on an object that has "dropped all references",
/// except operator delete.
void dropAllReferences();
/// \brief Notify the BasicBlock that the predecessor \p Pred is no longer
/// able to reach it.
///
/// This is actually not used to update the Predecessor list, but is actually
/// used to update the PHI nodes that reside in the block. Note that this
/// should be called while the predecessor still refers to this block.
void removePredecessor(BasicBlock *Pred, bool DontDeleteUselessPHIs = false);
/// \brief Split the basic block into two basic blocks at the specified
/// instruction.
///
/// Note that all instructions BEFORE the specified iterator stay as part of
/// the original basic block, an unconditional branch is added to the original
/// BB, and the rest of the instructions in the BB are moved to the new BB,
/// including the old terminator. The newly formed BasicBlock is returned.
/// This function invalidates the specified iterator.
///
/// Note that this only works on well formed basic blocks (must have a
/// terminator), and 'I' must not be the end of instruction list (which would
/// cause a degenerate basic block to be formed, having a terminator inside of
/// the basic block).
///
/// Also note that this doesn't preserve any passes. To split blocks while
/// keeping loop information consistent, use the SplitBlock utility function.
BasicBlock *splitBasicBlock(iterator I, const Twine &BBName = "");
/// \brief Returns true if there are any uses of this basic block other than
/// direct branches, switches, etc. to it.
bool hasAddressTaken() const { return getSubclassDataFromValue() != 0; }
/// \brief Update all phi nodes in this basic block's successors to refer to
/// basic block \p New instead of to it.
void replaceSuccessorsPhiUsesWith(BasicBlock *New);
/// \brief Return true if this basic block is a landing pad.
///
/// Being a ``landing pad'' means that the basic block is the destination of
/// the 'unwind' edge of an invoke instruction.
bool isLandingPad() const;
/// \brief Return the landingpad instruction associated with the landing pad.
LandingPadInst *getLandingPadInst();
const LandingPadInst *getLandingPadInst() const;
private:
/// \brief Increment the internal refcount of the number of BlockAddresses
/// referencing this BasicBlock by \p Amt.
///
/// This is almost always 0, sometimes one possibly, but almost never 2, and
/// inconceivably 3 or more.
void AdjustBlockAddressRefCount(int Amt) {
setValueSubclassData(getSubclassDataFromValue()+Amt);
assert((int)(signed char)getSubclassDataFromValue() >= 0 &&
"Refcount wrap-around");
}
/// \brief Shadow Value::setValueSubclassData with a private forwarding method
/// so that any future subclasses cannot accidentally use it.
void setValueSubclassData(unsigned short D) {
Value::setValueSubclassData(D);
}
};
} // End llvm namespace
#endif

View File

@@ -0,0 +1,129 @@
//===-- llvm/CallingConv.h - LLVM Calling Conventions -----------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines LLVM's set of calling conventions.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_IR_CALLINGCONV_H
#define LLVM_IR_CALLINGCONV_H
namespace llvm {
/// CallingConv Namespace - This namespace contains an enum with a value for
/// the well-known calling conventions.
///
namespace CallingConv {
/// A set of enums which specify the assigned numeric values for known llvm
/// calling conventions.
/// @brief LLVM Calling Convention Representation
enum ID {
/// C - The default llvm calling convention, compatible with C. This
/// convention is the only calling convention that supports varargs calls.
/// As with typical C calling conventions, the callee/caller have to
/// tolerate certain amounts of prototype mismatch.
C = 0,
// Generic LLVM calling conventions. None of these calling conventions
// support varargs calls, and all assume that the caller and callee
// prototype exactly match.
/// Fast - This calling convention attempts to make calls as fast as
/// possible (e.g. by passing things in registers).
Fast = 8,
// Cold - This calling convention attempts to make code in the caller as
// efficient as possible under the assumption that the call is not commonly
// executed. As such, these calls often preserve all registers so that the
// call does not break any live ranges in the caller side.
Cold = 9,
// GHC - Calling convention used by the Glasgow Haskell Compiler (GHC).
GHC = 10,
// HiPE - Calling convention used by the High-Performance Erlang Compiler
// (HiPE).
HiPE = 11,
// Target - This is the start of the target-specific calling conventions,
// e.g. fastcall and thiscall on X86.
FirstTargetCC = 64,
/// X86_StdCall - stdcall is the calling conventions mostly used by the
/// Win32 API. It is basically the same as the C convention with the
/// difference in that the callee is responsible for popping the arguments
/// from the stack.
X86_StdCall = 64,
/// X86_FastCall - 'fast' analog of X86_StdCall. Passes first two arguments
/// in ECX:EDX registers, others - via stack. Callee is responsible for
/// stack cleaning.
X86_FastCall = 65,
/// ARM_APCS - ARM Procedure Calling Standard calling convention (obsolete,
/// but still used on some targets).
ARM_APCS = 66,
/// ARM_AAPCS - ARM Architecture Procedure Calling Standard calling
/// convention (aka EABI). Soft float variant.
ARM_AAPCS = 67,
/// ARM_AAPCS_VFP - Same as ARM_AAPCS, but uses hard floating point ABI.
ARM_AAPCS_VFP = 68,
/// MSP430_INTR - Calling convention used for MSP430 interrupt routines.
MSP430_INTR = 69,
/// X86_ThisCall - Similar to X86_StdCall. Passes first argument in ECX,
/// others via stack. Callee is responsible for stack cleaning. MSVC uses
/// this by default for methods in its ABI.
X86_ThisCall = 70,
/// PTX_Kernel - Call to a PTX kernel.
/// Passes all arguments in parameter space.
PTX_Kernel = 71,
/// PTX_Device - Call to a PTX device function.
/// Passes all arguments in register or parameter space.
PTX_Device = 72,
/// MBLAZE_INTR - Calling convention used for MBlaze interrupt routines.
MBLAZE_INTR = 73,
/// MBLAZE_INTR - Calling convention used for MBlaze interrupt support
/// routines (i.e. GCC's save_volatiles attribute).
MBLAZE_SVOL = 74,
/// SPIR_FUNC - Calling convention for SPIR non-kernel device functions.
/// No lowering or expansion of arguments.
/// Structures are passed as a pointer to a struct with the byval attribute.
/// Functions can only call SPIR_FUNC and SPIR_KERNEL functions.
/// Functions can only have zero or one return values.
/// Variable arguments are not allowed, except for printf.
/// How arguments/return values are lowered are not specified.
/// Functions are only visible to the devices.
SPIR_FUNC = 75,
/// SPIR_KERNEL - Calling convention for SPIR kernel functions.
/// Inherits the restrictions of SPIR_FUNC, except
/// Cannot have non-void return values.
/// Cannot have variable arguments.
/// Can also be called by the host.
/// Is externally visible.
SPIR_KERNEL = 76,
/// Intel_OCL_BI - Calling conventions for Intel OpenCL built-ins
Intel_OCL_BI = 77
};
} // End CallingConv namespace
} // End llvm namespace
#endif

View File

@@ -0,0 +1,170 @@
//===-- llvm/Constant.h - Constant class definition -------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains the declaration of the Constant class.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_IR_CONSTANT_H
#define LLVM_IR_CONSTANT_H
#include "llvm/IR/User.h"
namespace llvm {
class APInt;
template<typename T> class SmallVectorImpl;
/// This is an important base class in LLVM. It provides the common facilities
/// of all constant values in an LLVM program. A constant is a value that is
/// immutable at runtime. Functions are constants because their address is
/// immutable. Same with global variables.
///
/// All constants share the capabilities provided in this class. All constants
/// can have a null value. They can have an operand list. Constants can be
/// simple (integer and floating point values), complex (arrays and structures),
/// or expression based (computations yielding a constant value composed of
/// only certain operators and other constant values).
///
/// Note that Constants are immutable (once created they never change)
/// and are fully shared by structural equivalence. This means that two
/// structurally equivalent constants will always have the same address.
/// Constants are created on demand as needed and never deleted: thus clients
/// don't have to worry about the lifetime of the objects.
/// @brief LLVM Constant Representation
class Constant : public User {
void operator=(const Constant &) LLVM_DELETED_FUNCTION;
Constant(const Constant &) LLVM_DELETED_FUNCTION;
virtual void anchor();
protected:
Constant(Type *ty, ValueTy vty, Use *Ops, unsigned NumOps)
: User(ty, vty, Ops, NumOps) {}
void destroyConstantImpl();
public:
/// isNullValue - Return true if this is the value that would be returned by
/// getNullValue.
bool isNullValue() const;
/// isAllOnesValue - Return true if this is the value that would be returned by
/// getAllOnesValue.
bool isAllOnesValue() const;
/// isNegativeZeroValue - Return true if the value is what would be returned
/// by getZeroValueForNegation.
bool isNegativeZeroValue() const;
/// Return true if the value is negative zero or null value.
bool isZeroValue() const;
/// canTrap - Return true if evaluation of this constant could trap. This is
/// true for things like constant expressions that could divide by zero.
bool canTrap() const;
/// isThreadDependent - Return true if the value can vary between threads.
bool isThreadDependent() const;
/// isConstantUsed - Return true if the constant has users other than constant
/// exprs and other dangling things.
bool isConstantUsed() const;
enum PossibleRelocationsTy {
NoRelocation = 0,
LocalRelocation = 1,
GlobalRelocations = 2
};
/// getRelocationInfo - This method classifies the entry according to
/// whether or not it may generate a relocation entry. This must be
/// conservative, so if it might codegen to a relocatable entry, it should say
/// so. The return values are:
///
/// NoRelocation: This constant pool entry is guaranteed to never have a
/// relocation applied to it (because it holds a simple constant like
/// '4').
/// LocalRelocation: This entry has relocations, but the entries are
/// guaranteed to be resolvable by the static linker, so the dynamic
/// linker will never see them.
/// GlobalRelocations: This entry may have arbitrary relocations.
///
/// FIXME: This really should not be in VMCore.
PossibleRelocationsTy getRelocationInfo() const;
/// getAggregateElement - For aggregates (struct/array/vector) return the
/// constant that corresponds to the specified element if possible, or null if
/// not. This can return null if the element index is a ConstantExpr, or if
/// 'this' is a constant expr.
Constant *getAggregateElement(unsigned Elt) const;
Constant *getAggregateElement(Constant *Elt) const;
/// getSplatValue - If this is a splat vector constant, meaning that all of
/// the elements have the same value, return that value. Otherwise return 0.
Constant *getSplatValue() const;
/// If C is a constant integer then return its value, otherwise C must be a
/// vector of constant integers, all equal, and the common value is returned.
const APInt &getUniqueInteger() const;
/// destroyConstant - Called if some element of this constant is no longer
/// valid. At this point only other constants may be on the use_list for this
/// constant. Any constants on our Use list must also be destroy'd. The
/// implementation must be sure to remove the constant from the list of
/// available cached constants. Implementations should call
/// destroyConstantImpl as the last thing they do, to destroy all users and
/// delete this.
virtual void destroyConstant() { llvm_unreachable("Not reached!"); }
//// Methods for support type inquiry through isa, cast, and dyn_cast:
static inline bool classof(const Value *V) {
return V->getValueID() >= ConstantFirstVal &&
V->getValueID() <= ConstantLastVal;
}
/// replaceUsesOfWithOnConstant - This method is a special form of
/// User::replaceUsesOfWith (which does not work on constants) that does work
/// on constants. Basically this method goes through the trouble of building
/// a new constant that is equivalent to the current one, with all uses of
/// From replaced with uses of To. After this construction is completed, all
/// of the users of 'this' are replaced to use the new constant, and then
/// 'this' is deleted. In general, you should not call this method, instead,
/// use Value::replaceAllUsesWith, which automatically dispatches to this
/// method as needed.
///
virtual void replaceUsesOfWithOnConstant(Value *, Value *, Use *) {
// Provide a default implementation for constants (like integers) that
// cannot use any other values. This cannot be called at runtime, but needs
// to be here to avoid link errors.
assert(getNumOperands() == 0 && "replaceUsesOfWithOnConstant must be "
"implemented for all constants that have operands!");
llvm_unreachable("Constants that do not have operands cannot be using "
"'From'!");
}
static Constant *getNullValue(Type* Ty);
/// @returns the value for an integer or vector of integer constant of the
/// given type that has all its bits set to true.
/// @brief Get the all ones value
static Constant *getAllOnesValue(Type* Ty);
/// getIntegerValue - Return the value for an integer or pointer constant,
/// or a vector thereof, with the given scalar value.
static Constant *getIntegerValue(Type* Ty, const APInt &V);
/// removeDeadConstantUsers - If there are any dead constant users dangling
/// off of this constant, remove them. This method is useful for clients
/// that want to check to see if a global is unused, but don't want to deal
/// with potentially dead constants hanging off of the globals.
void removeDeadConstantUsers() const;
};
} // End llvm namespace
#endif

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,477 @@
//===--------- llvm/DataLayout.h - Data size & alignment info ---*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines layout properties related to datatype size/offset/alignment
// information. It uses lazy annotations to cache information about how
// structure types are laid out and used.
//
// This structure should be created once, filled in if the defaults are not
// correct and then passed around by const&. None of the members functions
// require modification to the object.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_IR_DATALAYOUT_H
#define LLVM_IR_DATALAYOUT_H
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Type.h"
#include "llvm/Pass.h"
#include "llvm/Support/DataTypes.h"
namespace llvm {
class Value;
class Type;
class IntegerType;
class StructType;
class StructLayout;
class GlobalVariable;
class LLVMContext;
template<typename T>
class ArrayRef;
/// Enum used to categorize the alignment types stored by LayoutAlignElem
enum AlignTypeEnum {
INVALID_ALIGN = 0, ///< An invalid alignment
INTEGER_ALIGN = 'i', ///< Integer type alignment
VECTOR_ALIGN = 'v', ///< Vector type alignment
FLOAT_ALIGN = 'f', ///< Floating point type alignment
AGGREGATE_ALIGN = 'a', ///< Aggregate alignment
STACK_ALIGN = 's' ///< Stack objects alignment
};
/// Layout alignment element.
///
/// Stores the alignment data associated with a given alignment type (integer,
/// vector, float) and type bit width.
///
/// @note The unusual order of elements in the structure attempts to reduce
/// padding and make the structure slightly more cache friendly.
struct LayoutAlignElem {
unsigned AlignType : 8; ///< Alignment type (AlignTypeEnum)
unsigned TypeBitWidth : 24; ///< Type bit width
unsigned ABIAlign : 16; ///< ABI alignment for this type/bitw
unsigned PrefAlign : 16; ///< Pref. alignment for this type/bitw
/// Initializer
static LayoutAlignElem get(AlignTypeEnum align_type, unsigned abi_align,
unsigned pref_align, uint32_t bit_width);
/// Equality predicate
bool operator==(const LayoutAlignElem &rhs) const;
};
/// Layout pointer alignment element.
///
/// Stores the alignment data associated with a given pointer and address space.
///
/// @note The unusual order of elements in the structure attempts to reduce
/// padding and make the structure slightly more cache friendly.
struct PointerAlignElem {
unsigned ABIAlign; ///< ABI alignment for this type/bitw
unsigned PrefAlign; ///< Pref. alignment for this type/bitw
uint32_t TypeBitWidth; ///< Type bit width
uint32_t AddressSpace; ///< Address space for the pointer type
/// Initializer
static PointerAlignElem get(uint32_t addr_space, unsigned abi_align,
unsigned pref_align, uint32_t bit_width);
/// Equality predicate
bool operator==(const PointerAlignElem &rhs) const;
};
/// DataLayout - This class holds a parsed version of the target data layout
/// string in a module and provides methods for querying it. The target data
/// layout string is specified *by the target* - a frontend generating LLVM IR
/// is required to generate the right target data for the target being codegen'd
/// to. If some measure of portability is desired, an empty string may be
/// specified in the module.
class DataLayout : public ImmutablePass {
private:
bool LittleEndian; ///< Defaults to false
unsigned StackNaturalAlign; ///< Stack natural alignment
SmallVector<unsigned char, 8> LegalIntWidths; ///< Legal Integers.
/// Alignments - Where the primitive type alignment data is stored.
///
/// @sa init().
/// @note Could support multiple size pointer alignments, e.g., 32-bit
/// pointers vs. 64-bit pointers by extending LayoutAlignment, but for now,
/// we don't.
SmallVector<LayoutAlignElem, 16> Alignments;
DenseMap<unsigned, PointerAlignElem> Pointers;
/// InvalidAlignmentElem - This member is a signal that a requested alignment
/// type and bit width were not found in the SmallVector.
static const LayoutAlignElem InvalidAlignmentElem;
/// InvalidPointerElem - This member is a signal that a requested pointer
/// type and bit width were not found in the DenseSet.
static const PointerAlignElem InvalidPointerElem;
// The StructType -> StructLayout map.
mutable void *LayoutMap;
//! Set/initialize target alignments
void setAlignment(AlignTypeEnum align_type, unsigned abi_align,
unsigned pref_align, uint32_t bit_width);
unsigned getAlignmentInfo(AlignTypeEnum align_type, uint32_t bit_width,
bool ABIAlign, Type *Ty) const;
//! Set/initialize pointer alignments
void setPointerAlignment(uint32_t addr_space, unsigned abi_align,
unsigned pref_align, uint32_t bit_width);
//! Internal helper method that returns requested alignment for type.
unsigned getAlignment(Type *Ty, bool abi_or_pref) const;
/// Valid alignment predicate.
///
/// Predicate that tests a LayoutAlignElem reference returned by get() against
/// InvalidAlignmentElem.
bool validAlignment(const LayoutAlignElem &align) const {
return &align != &InvalidAlignmentElem;
}
/// Valid pointer predicate.
///
/// Predicate that tests a PointerAlignElem reference returned by get() against
/// InvalidPointerElem.
bool validPointer(const PointerAlignElem &align) const {
return &align != &InvalidPointerElem;
}
/// Parses a target data specification string. Assert if the string is
/// malformed.
void parseSpecifier(StringRef LayoutDescription);
public:
/// Default ctor.
///
/// @note This has to exist, because this is a pass, but it should never be
/// used.
DataLayout();
/// Constructs a DataLayout from a specification string. See init().
explicit DataLayout(StringRef LayoutDescription)
: ImmutablePass(ID) {
init(LayoutDescription);
}
/// Initialize target data from properties stored in the module.
explicit DataLayout(const Module *M);
DataLayout(const DataLayout &DL) :
ImmutablePass(ID),
LittleEndian(DL.isLittleEndian()),
StackNaturalAlign(DL.StackNaturalAlign),
LegalIntWidths(DL.LegalIntWidths),
Alignments(DL.Alignments),
Pointers(DL.Pointers),
LayoutMap(0)
{ }
~DataLayout(); // Not virtual, do not subclass this class
/// DataLayout is an immutable pass, but holds state. This allows the pass
/// manager to clear its mutable state.
bool doFinalization(Module &M);
/// Parse a data layout string (with fallback to default values). Ensure that
/// the data layout pass is registered.
void init(StringRef LayoutDescription);
/// Layout endianness...
bool isLittleEndian() const { return LittleEndian; }
bool isBigEndian() const { return !LittleEndian; }
/// getStringRepresentation - Return the string representation of the
/// DataLayout. This representation is in the same format accepted by the
/// string constructor above.
std::string getStringRepresentation() const;
/// isLegalInteger - This function returns true if the specified type is
/// known to be a native integer type supported by the CPU. For example,
/// i64 is not native on most 32-bit CPUs and i37 is not native on any known
/// one. This returns false if the integer width is not legal.
///
/// The width is specified in bits.
///
bool isLegalInteger(unsigned Width) const {
for (unsigned i = 0, e = (unsigned)LegalIntWidths.size(); i != e; ++i)
if (LegalIntWidths[i] == Width)
return true;
return false;
}
bool isIllegalInteger(unsigned Width) const {
return !isLegalInteger(Width);
}
/// Returns true if the given alignment exceeds the natural stack alignment.
bool exceedsNaturalStackAlignment(unsigned Align) const {
return (StackNaturalAlign != 0) && (Align > StackNaturalAlign);
}
/// fitsInLegalInteger - This function returns true if the specified type fits
/// in a native integer type supported by the CPU. For example, if the CPU
/// only supports i32 as a native integer type, then i27 fits in a legal
// integer type but i45 does not.
bool fitsInLegalInteger(unsigned Width) const {
for (unsigned i = 0, e = (unsigned)LegalIntWidths.size(); i != e; ++i)
if (Width <= LegalIntWidths[i])
return true;
return false;
}
/// Layout pointer alignment
/// FIXME: The defaults need to be removed once all of
/// the backends/clients are updated.
unsigned getPointerABIAlignment(unsigned AS = 0) const {
DenseMap<unsigned, PointerAlignElem>::const_iterator val = Pointers.find(AS);
if (val == Pointers.end()) {
val = Pointers.find(0);
}
return val->second.ABIAlign;
}
/// Return target's alignment for stack-based pointers
/// FIXME: The defaults need to be removed once all of
/// the backends/clients are updated.
unsigned getPointerPrefAlignment(unsigned AS = 0) const {
DenseMap<unsigned, PointerAlignElem>::const_iterator val = Pointers.find(AS);
if (val == Pointers.end()) {
val = Pointers.find(0);
}
return val->second.PrefAlign;
}
/// Layout pointer size
/// FIXME: The defaults need to be removed once all of
/// the backends/clients are updated.
unsigned getPointerSize(unsigned AS = 0) const {
DenseMap<unsigned, PointerAlignElem>::const_iterator val = Pointers.find(AS);
if (val == Pointers.end()) {
val = Pointers.find(0);
}
return val->second.TypeBitWidth;
}
/// Layout pointer size, in bits
/// FIXME: The defaults need to be removed once all of
/// the backends/clients are updated.
unsigned getPointerSizeInBits(unsigned AS = 0) const {
return getPointerSize(AS) * 8;
}
/// Size examples:
///
/// Type SizeInBits StoreSizeInBits AllocSizeInBits[*]
/// ---- ---------- --------------- ---------------
/// i1 1 8 8
/// i8 8 8 8
/// i19 19 24 32
/// i32 32 32 32
/// i100 100 104 128
/// i128 128 128 128
/// Float 32 32 32
/// Double 64 64 64
/// X86_FP80 80 80 96
///
/// [*] The alloc size depends on the alignment, and thus on the target.
/// These values are for x86-32 linux.
/// getTypeSizeInBits - Return the number of bits necessary to hold the
/// specified type. For example, returns 36 for i36 and 80 for x86_fp80.
/// The type passed must have a size (Type::isSized() must return true).
uint64_t getTypeSizeInBits(Type *Ty) const;
/// getTypeStoreSize - Return the maximum number of bytes that may be
/// overwritten by storing the specified type. For example, returns 5
/// for i36 and 10 for x86_fp80.
uint64_t getTypeStoreSize(Type *Ty) const {
return (getTypeSizeInBits(Ty)+7)/8;
}
/// getTypeStoreSizeInBits - Return the maximum number of bits that may be
/// overwritten by storing the specified type; always a multiple of 8. For
/// example, returns 40 for i36 and 80 for x86_fp80.
uint64_t getTypeStoreSizeInBits(Type *Ty) const {
return 8*getTypeStoreSize(Ty);
}
/// getTypeAllocSize - Return the offset in bytes between successive objects
/// of the specified type, including alignment padding. This is the amount
/// that alloca reserves for this type. For example, returns 12 or 16 for
/// x86_fp80, depending on alignment.
uint64_t getTypeAllocSize(Type *Ty) const {
// Round up to the next alignment boundary.
return RoundUpAlignment(getTypeStoreSize(Ty), getABITypeAlignment(Ty));
}
/// getTypeAllocSizeInBits - Return the offset in bits between successive
/// objects of the specified type, including alignment padding; always a
/// multiple of 8. This is the amount that alloca reserves for this type.
/// For example, returns 96 or 128 for x86_fp80, depending on alignment.
uint64_t getTypeAllocSizeInBits(Type *Ty) const {
return 8*getTypeAllocSize(Ty);
}
/// getABITypeAlignment - Return the minimum ABI-required alignment for the
/// specified type.
unsigned getABITypeAlignment(Type *Ty) const;
/// getABIIntegerTypeAlignment - Return the minimum ABI-required alignment for
/// an integer type of the specified bitwidth.
unsigned getABIIntegerTypeAlignment(unsigned BitWidth) const;
/// getCallFrameTypeAlignment - Return the minimum ABI-required alignment
/// for the specified type when it is part of a call frame.
unsigned getCallFrameTypeAlignment(Type *Ty) const;
/// getPrefTypeAlignment - Return the preferred stack/global alignment for
/// the specified type. This is always at least as good as the ABI alignment.
unsigned getPrefTypeAlignment(Type *Ty) const;
/// getPreferredTypeAlignmentShift - Return the preferred alignment for the
/// specified type, returned as log2 of the value (a shift amount).
unsigned getPreferredTypeAlignmentShift(Type *Ty) const;
/// getIntPtrType - Return an integer type with size at least as big as that
/// of a pointer in the given address space.
IntegerType *getIntPtrType(LLVMContext &C, unsigned AddressSpace = 0) const;
/// getIntPtrType - Return an integer (vector of integer) type with size at
/// least as big as that of a pointer of the given pointer (vector of pointer)
/// type.
Type *getIntPtrType(Type *) const;
/// getSmallestLegalIntType - Return the smallest integer type with size at
/// least as big as Width bits.
Type *getSmallestLegalIntType(LLVMContext &C, unsigned Width = 0) const;
/// getIndexedOffset - return the offset from the beginning of the type for
/// the specified indices. This is used to implement getelementptr.
uint64_t getIndexedOffset(Type *Ty, ArrayRef<Value *> Indices) const;
/// getStructLayout - Return a StructLayout object, indicating the alignment
/// of the struct, its size, and the offsets of its fields. Note that this
/// information is lazily cached.
const StructLayout *getStructLayout(StructType *Ty) const;
/// getPreferredAlignment - Return the preferred alignment of the specified
/// global. This includes an explicitly requested alignment (if the global
/// has one).
unsigned getPreferredAlignment(const GlobalVariable *GV) const;
/// getPreferredAlignmentLog - Return the preferred alignment of the
/// specified global, returned in log form. This includes an explicitly
/// requested alignment (if the global has one).
unsigned getPreferredAlignmentLog(const GlobalVariable *GV) const;
/// RoundUpAlignment - Round the specified value up to the next alignment
/// boundary specified by Alignment. For example, 7 rounded up to an
/// alignment boundary of 4 is 8. 8 rounded up to the alignment boundary of 4
/// is 8 because it is already aligned.
template <typename UIntTy>
static UIntTy RoundUpAlignment(UIntTy Val, unsigned Alignment) {
assert((Alignment & (Alignment-1)) == 0 && "Alignment must be power of 2!");
return (Val + (Alignment-1)) & ~UIntTy(Alignment-1);
}
static char ID; // Pass identification, replacement for typeid
};
/// StructLayout - used to lazily calculate structure layout information for a
/// target machine, based on the DataLayout structure.
///
class StructLayout {
uint64_t StructSize;
unsigned StructAlignment;
unsigned NumElements;
uint64_t MemberOffsets[1]; // variable sized array!
public:
uint64_t getSizeInBytes() const {
return StructSize;
}
uint64_t getSizeInBits() const {
return 8*StructSize;
}
unsigned getAlignment() const {
return StructAlignment;
}
/// getElementContainingOffset - Given a valid byte offset into the structure,
/// return the structure index that contains it.
///
unsigned getElementContainingOffset(uint64_t Offset) const;
uint64_t getElementOffset(unsigned Idx) const {
assert(Idx < NumElements && "Invalid element idx!");
return MemberOffsets[Idx];
}
uint64_t getElementOffsetInBits(unsigned Idx) const {
return getElementOffset(Idx)*8;
}
private:
friend class DataLayout; // Only DataLayout can create this class
StructLayout(StructType *ST, const DataLayout &DL);
};
// The implementation of this method is provided inline as it is particularly
// well suited to constant folding when called on a specific Type subclass.
inline uint64_t DataLayout::getTypeSizeInBits(Type *Ty) const {
assert(Ty->isSized() && "Cannot getTypeInfo() on a type that is unsized!");
switch (Ty->getTypeID()) {
case Type::LabelTyID:
return getPointerSizeInBits(0);
case Type::PointerTyID:
return getPointerSizeInBits(cast<PointerType>(Ty)->getAddressSpace());
case Type::ArrayTyID: {
ArrayType *ATy = cast<ArrayType>(Ty);
return ATy->getNumElements() *
getTypeAllocSizeInBits(ATy->getElementType());
}
case Type::StructTyID:
// Get the layout annotation... which is lazily created on demand.
return getStructLayout(cast<StructType>(Ty))->getSizeInBits();
case Type::IntegerTyID:
return cast<IntegerType>(Ty)->getBitWidth();
case Type::HalfTyID:
return 16;
case Type::FloatTyID:
return 32;
case Type::DoubleTyID:
case Type::X86_MMXTyID:
return 64;
case Type::PPC_FP128TyID:
case Type::FP128TyID:
return 128;
// In memory objects this is always aligned to a higher boundary, but
// only 80 bits contain information.
case Type::X86_FP80TyID:
return 80;
case Type::VectorTyID: {
VectorType *VTy = cast<VectorType>(Ty);
return VTy->getNumElements() * getTypeSizeInBits(VTy->getElementType());
}
default:
llvm_unreachable("DataLayout::getTypeSizeInBits(): Unsupported type");
}
}
} // End llvm namespace
#endif

View File

@@ -0,0 +1,455 @@
//===-- llvm/DerivedTypes.h - Classes for handling data types ---*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains the declarations of classes that represent "derived
// types". These are things like "arrays of x" or "structure of x, y, z" or
// "function returning x taking (y,z) as parameters", etc...
//
// The implementations of these classes live in the Type.cpp file.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_IR_DERIVEDTYPES_H
#define LLVM_IR_DERIVEDTYPES_H
#include "llvm/IR/Type.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/DataTypes.h"
namespace llvm {
class Value;
class APInt;
class LLVMContext;
template<typename T> class ArrayRef;
class StringRef;
/// Class to represent integer types. Note that this class is also used to
/// represent the built-in integer types: Int1Ty, Int8Ty, Int16Ty, Int32Ty and
/// Int64Ty.
/// @brief Integer representation type
class IntegerType : public Type {
friend class LLVMContextImpl;
protected:
explicit IntegerType(LLVMContext &C, unsigned NumBits) : Type(C, IntegerTyID){
setSubclassData(NumBits);
}
public:
/// This enum is just used to hold constants we need for IntegerType.
enum {
MIN_INT_BITS = 1, ///< Minimum number of bits that can be specified
MAX_INT_BITS = (1<<23)-1 ///< Maximum number of bits that can be specified
///< Note that bit width is stored in the Type classes SubclassData field
///< which has 23 bits. This yields a maximum bit width of 8,388,607 bits.
};
/// This static method is the primary way of constructing an IntegerType.
/// If an IntegerType with the same NumBits value was previously instantiated,
/// that instance will be returned. Otherwise a new one will be created. Only
/// one instance with a given NumBits value is ever created.
/// @brief Get or create an IntegerType instance.
static IntegerType *get(LLVMContext &C, unsigned NumBits);
/// @brief Get the number of bits in this IntegerType
unsigned getBitWidth() const { return getSubclassData(); }
/// getBitMask - Return a bitmask with ones set for all of the bits
/// that can be set by an unsigned version of this type. This is 0xFF for
/// i8, 0xFFFF for i16, etc.
uint64_t getBitMask() const {
return ~uint64_t(0UL) >> (64-getBitWidth());
}
/// getSignBit - Return a uint64_t with just the most significant bit set (the
/// sign bit, if the value is treated as a signed number).
uint64_t getSignBit() const {
return 1ULL << (getBitWidth()-1);
}
/// For example, this is 0xFF for an 8 bit integer, 0xFFFF for i16, etc.
/// @returns a bit mask with ones set for all the bits of this type.
/// @brief Get a bit mask for this type.
APInt getMask() const;
/// This method determines if the width of this IntegerType is a power-of-2
/// in terms of 8 bit bytes.
/// @returns true if this is a power-of-2 byte width.
/// @brief Is this a power-of-2 byte-width IntegerType ?
bool isPowerOf2ByteWidth() const;
/// Methods for support type inquiry through isa, cast, and dyn_cast.
static inline bool classof(const Type *T) {
return T->getTypeID() == IntegerTyID;
}
};
/// FunctionType - Class to represent function types
///
class FunctionType : public Type {
FunctionType(const FunctionType &) LLVM_DELETED_FUNCTION;
const FunctionType &operator=(const FunctionType &) LLVM_DELETED_FUNCTION;
FunctionType(Type *Result, ArrayRef<Type*> Params, bool IsVarArgs);
public:
/// FunctionType::get - This static method is the primary way of constructing
/// a FunctionType.
///
static FunctionType *get(Type *Result,
ArrayRef<Type*> Params, bool isVarArg);
/// FunctionType::get - Create a FunctionType taking no parameters.
///
static FunctionType *get(Type *Result, bool isVarArg);
/// isValidReturnType - Return true if the specified type is valid as a return
/// type.
static bool isValidReturnType(Type *RetTy);
/// isValidArgumentType - Return true if the specified type is valid as an
/// argument type.
static bool isValidArgumentType(Type *ArgTy);
bool isVarArg() const { return getSubclassData(); }
Type *getReturnType() const { return ContainedTys[0]; }
typedef Type::subtype_iterator param_iterator;
param_iterator param_begin() const { return ContainedTys + 1; }
param_iterator param_end() const { return &ContainedTys[NumContainedTys]; }
/// Parameter type accessors.
Type *getParamType(unsigned i) const { return ContainedTys[i+1]; }
/// getNumParams - Return the number of fixed parameters this function type
/// requires. This does not consider varargs.
///
unsigned getNumParams() const { return NumContainedTys - 1; }
/// Methods for support type inquiry through isa, cast, and dyn_cast.
static inline bool classof(const Type *T) {
return T->getTypeID() == FunctionTyID;
}
};
/// CompositeType - Common super class of ArrayType, StructType, PointerType
/// and VectorType.
class CompositeType : public Type {
protected:
explicit CompositeType(LLVMContext &C, TypeID tid) : Type(C, tid) { }
public:
/// getTypeAtIndex - Given an index value into the type, return the type of
/// the element.
///
Type *getTypeAtIndex(const Value *V);
Type *getTypeAtIndex(unsigned Idx);
bool indexValid(const Value *V) const;
bool indexValid(unsigned Idx) const;
/// Methods for support type inquiry through isa, cast, and dyn_cast.
static inline bool classof(const Type *T) {
return T->getTypeID() == ArrayTyID ||
T->getTypeID() == StructTyID ||
T->getTypeID() == PointerTyID ||
T->getTypeID() == VectorTyID;
}
};
/// StructType - Class to represent struct types. There are two different kinds
/// of struct types: Literal structs and Identified structs.
///
/// Literal struct types (e.g. { i32, i32 }) are uniqued structurally, and must
/// always have a body when created. You can get one of these by using one of
/// the StructType::get() forms.
///
/// Identified structs (e.g. %foo or %42) may optionally have a name and are not
/// uniqued. The names for identified structs are managed at the LLVMContext
/// level, so there can only be a single identified struct with a given name in
/// a particular LLVMContext. Identified structs may also optionally be opaque
/// (have no body specified). You get one of these by using one of the
/// StructType::create() forms.
///
/// Independent of what kind of struct you have, the body of a struct type are
/// laid out in memory consequtively with the elements directly one after the
/// other (if the struct is packed) or (if not packed) with padding between the
/// elements as defined by DataLayout (which is required to match what the code
/// generator for a target expects).
///
class StructType : public CompositeType {
StructType(const StructType &) LLVM_DELETED_FUNCTION;
const StructType &operator=(const StructType &) LLVM_DELETED_FUNCTION;
StructType(LLVMContext &C)
: CompositeType(C, StructTyID), SymbolTableEntry(0) {}
enum {
/// This is the contents of the SubClassData field.
SCDB_HasBody = 1,
SCDB_Packed = 2,
SCDB_IsLiteral = 4,
SCDB_IsSized = 8
};
/// SymbolTableEntry - For a named struct that actually has a name, this is a
/// pointer to the symbol table entry (maintained by LLVMContext) for the
/// struct. This is null if the type is an literal struct or if it is
/// a identified type that has an empty name.
///
void *SymbolTableEntry;
public:
~StructType() {
delete [] ContainedTys; // Delete the body.
}
/// StructType::create - This creates an identified struct.
static StructType *create(LLVMContext &Context, StringRef Name);
static StructType *create(LLVMContext &Context);
static StructType *create(ArrayRef<Type*> Elements,
StringRef Name,
bool isPacked = false);
static StructType *create(ArrayRef<Type*> Elements);
static StructType *create(LLVMContext &Context,
ArrayRef<Type*> Elements,
StringRef Name,
bool isPacked = false);
static StructType *create(LLVMContext &Context, ArrayRef<Type*> Elements);
static StructType *create(StringRef Name, Type *elt1, ...) END_WITH_NULL;
/// StructType::get - This static method is the primary way to create a
/// literal StructType.
static StructType *get(LLVMContext &Context, ArrayRef<Type*> Elements,
bool isPacked = false);
/// StructType::get - Create an empty structure type.
///
static StructType *get(LLVMContext &Context, bool isPacked = false);
/// StructType::get - This static method is a convenience method for creating
/// structure types by specifying the elements as arguments. Note that this
/// method always returns a non-packed struct, and requires at least one
/// element type.
static StructType *get(Type *elt1, ...) END_WITH_NULL;
bool isPacked() const { return (getSubclassData() & SCDB_Packed) != 0; }
/// isLiteral - Return true if this type is uniqued by structural
/// equivalence, false if it is a struct definition.
bool isLiteral() const { return (getSubclassData() & SCDB_IsLiteral) != 0; }
/// isOpaque - Return true if this is a type with an identity that has no body
/// specified yet. These prints as 'opaque' in .ll files.
bool isOpaque() const { return (getSubclassData() & SCDB_HasBody) == 0; }
/// isSized - Return true if this is a sized type.
bool isSized() const;
/// hasName - Return true if this is a named struct that has a non-empty name.
bool hasName() const { return SymbolTableEntry != 0; }
/// getName - Return the name for this struct type if it has an identity.
/// This may return an empty string for an unnamed struct type. Do not call
/// this on an literal type.
StringRef getName() const;
/// setName - Change the name of this type to the specified name, or to a name
/// with a suffix if there is a collision. Do not call this on an literal
/// type.
void setName(StringRef Name);
/// setBody - Specify a body for an opaque identified type.
void setBody(ArrayRef<Type*> Elements, bool isPacked = false);
void setBody(Type *elt1, ...) END_WITH_NULL;
/// isValidElementType - Return true if the specified type is valid as a
/// element type.
static bool isValidElementType(Type *ElemTy);
// Iterator access to the elements.
typedef Type::subtype_iterator element_iterator;
element_iterator element_begin() const { return ContainedTys; }
element_iterator element_end() const { return &ContainedTys[NumContainedTys];}
/// isLayoutIdentical - Return true if this is layout identical to the
/// specified struct.
bool isLayoutIdentical(StructType *Other) const;
/// Random access to the elements
unsigned getNumElements() const { return NumContainedTys; }
Type *getElementType(unsigned N) const {
assert(N < NumContainedTys && "Element number out of range!");
return ContainedTys[N];
}
/// Methods for support type inquiry through isa, cast, and dyn_cast.
static inline bool classof(const Type *T) {
return T->getTypeID() == StructTyID;
}
};
/// SequentialType - This is the superclass of the array, pointer and vector
/// type classes. All of these represent "arrays" in memory. The array type
/// represents a specifically sized array, pointer types are unsized/unknown
/// size arrays, vector types represent specifically sized arrays that
/// allow for use of SIMD instructions. SequentialType holds the common
/// features of all, which stem from the fact that all three lay their
/// components out in memory identically.
///
class SequentialType : public CompositeType {
Type *ContainedType; ///< Storage for the single contained type.
SequentialType(const SequentialType &) LLVM_DELETED_FUNCTION;
const SequentialType &operator=(const SequentialType &) LLVM_DELETED_FUNCTION;
protected:
SequentialType(TypeID TID, Type *ElType)
: CompositeType(ElType->getContext(), TID), ContainedType(ElType) {
ContainedTys = &ContainedType;
NumContainedTys = 1;
}
public:
Type *getElementType() const { return ContainedTys[0]; }
/// Methods for support type inquiry through isa, cast, and dyn_cast.
static inline bool classof(const Type *T) {
return T->getTypeID() == ArrayTyID ||
T->getTypeID() == PointerTyID ||
T->getTypeID() == VectorTyID;
}
};
/// ArrayType - Class to represent array types.
///
class ArrayType : public SequentialType {
uint64_t NumElements;
ArrayType(const ArrayType &) LLVM_DELETED_FUNCTION;
const ArrayType &operator=(const ArrayType &) LLVM_DELETED_FUNCTION;
ArrayType(Type *ElType, uint64_t NumEl);
public:
/// ArrayType::get - This static method is the primary way to construct an
/// ArrayType
///
static ArrayType *get(Type *ElementType, uint64_t NumElements);
/// isValidElementType - Return true if the specified type is valid as a
/// element type.
static bool isValidElementType(Type *ElemTy);
uint64_t getNumElements() const { return NumElements; }
/// Methods for support type inquiry through isa, cast, and dyn_cast.
static inline bool classof(const Type *T) {
return T->getTypeID() == ArrayTyID;
}
};
/// VectorType - Class to represent vector types.
///
class VectorType : public SequentialType {
unsigned NumElements;
VectorType(const VectorType &) LLVM_DELETED_FUNCTION;
const VectorType &operator=(const VectorType &) LLVM_DELETED_FUNCTION;
VectorType(Type *ElType, unsigned NumEl);
public:
/// VectorType::get - This static method is the primary way to construct an
/// VectorType.
///
static VectorType *get(Type *ElementType, unsigned NumElements);
/// VectorType::getInteger - This static method gets a VectorType with the
/// same number of elements as the input type, and the element type is an
/// integer type of the same width as the input element type.
///
static VectorType *getInteger(VectorType *VTy) {
unsigned EltBits = VTy->getElementType()->getPrimitiveSizeInBits();
assert(EltBits && "Element size must be of a non-zero size");
Type *EltTy = IntegerType::get(VTy->getContext(), EltBits);
return VectorType::get(EltTy, VTy->getNumElements());
}
/// VectorType::getExtendedElementVectorType - This static method is like
/// getInteger except that the element types are twice as wide as the
/// elements in the input type.
///
static VectorType *getExtendedElementVectorType(VectorType *VTy) {
unsigned EltBits = VTy->getElementType()->getPrimitiveSizeInBits();
Type *EltTy = IntegerType::get(VTy->getContext(), EltBits * 2);
return VectorType::get(EltTy, VTy->getNumElements());
}
/// VectorType::getTruncatedElementVectorType - This static method is like
/// getInteger except that the element types are half as wide as the
/// elements in the input type.
///
static VectorType *getTruncatedElementVectorType(VectorType *VTy) {
unsigned EltBits = VTy->getElementType()->getPrimitiveSizeInBits();
assert((EltBits & 1) == 0 &&
"Cannot truncate vector element with odd bit-width");
Type *EltTy = IntegerType::get(VTy->getContext(), EltBits / 2);
return VectorType::get(EltTy, VTy->getNumElements());
}
/// isValidElementType - Return true if the specified type is valid as a
/// element type.
static bool isValidElementType(Type *ElemTy);
/// @brief Return the number of elements in the Vector type.
unsigned getNumElements() const { return NumElements; }
/// @brief Return the number of bits in the Vector type.
/// Returns zero when the vector is a vector of pointers.
unsigned getBitWidth() const {
return NumElements * getElementType()->getPrimitiveSizeInBits();
}
/// Methods for support type inquiry through isa, cast, and dyn_cast.
static inline bool classof(const Type *T) {
return T->getTypeID() == VectorTyID;
}
};
/// PointerType - Class to represent pointers.
///
class PointerType : public SequentialType {
PointerType(const PointerType &) LLVM_DELETED_FUNCTION;
const PointerType &operator=(const PointerType &) LLVM_DELETED_FUNCTION;
explicit PointerType(Type *ElType, unsigned AddrSpace);
public:
/// PointerType::get - This constructs a pointer to an object of the specified
/// type in a numbered address space.
static PointerType *get(Type *ElementType, unsigned AddressSpace);
/// PointerType::getUnqual - This constructs a pointer to an object of the
/// specified type in the generic address space (address space zero).
static PointerType *getUnqual(Type *ElementType) {
return PointerType::get(ElementType, 0);
}
/// isValidElementType - Return true if the specified type is valid as a
/// element type.
static bool isValidElementType(Type *ElemTy);
/// @brief Return the address space of the Pointer type.
inline unsigned getAddressSpace() const { return getSubclassData(); }
/// Implement support type inquiry through isa, cast, and dyn_cast.
static inline bool classof(const Type *T) {
return T->getTypeID() == PointerTyID;
}
};
} // End llvm namespace
#endif

View File

@@ -0,0 +1,470 @@
//===-- llvm/Function.h - Class to represent a single function --*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains the declaration of the Function class, which represents a
// single function/procedure in LLVM.
//
// A function basically consists of a list of basic blocks, a list of arguments,
// and a symbol table.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_IR_FUNCTION_H
#define LLVM_IR_FUNCTION_H
#include "llvm/IR/Argument.h"
#include "llvm/IR/Attributes.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/CallingConv.h"
#include "llvm/IR/GlobalValue.h"
#include "llvm/Support/Compiler.h"
namespace llvm {
class FunctionType;
class LLVMContext;
// Traits for intrusive list of basic blocks...
template<> struct ilist_traits<BasicBlock>
: public SymbolTableListTraits<BasicBlock, Function> {
// createSentinel is used to get hold of the node that marks the end of the
// list... (same trick used here as in ilist_traits<Instruction>)
BasicBlock *createSentinel() const {
return static_cast<BasicBlock*>(&Sentinel);
}
static void destroySentinel(BasicBlock*) {}
BasicBlock *provideInitialHead() const { return createSentinel(); }
BasicBlock *ensureHead(BasicBlock*) const { return createSentinel(); }
static void noteHead(BasicBlock*, BasicBlock*) {}
static ValueSymbolTable *getSymTab(Function *ItemParent);
private:
mutable ilist_half_node<BasicBlock> Sentinel;
};
template<> struct ilist_traits<Argument>
: public SymbolTableListTraits<Argument, Function> {
Argument *createSentinel() const {
return static_cast<Argument*>(&Sentinel);
}
static void destroySentinel(Argument*) {}
Argument *provideInitialHead() const { return createSentinel(); }
Argument *ensureHead(Argument*) const { return createSentinel(); }
static void noteHead(Argument*, Argument*) {}
static ValueSymbolTable *getSymTab(Function *ItemParent);
private:
mutable ilist_half_node<Argument> Sentinel;
};
class Function : public GlobalValue,
public ilist_node<Function> {
public:
typedef iplist<Argument> ArgumentListType;
typedef iplist<BasicBlock> BasicBlockListType;
// BasicBlock iterators...
typedef BasicBlockListType::iterator iterator;
typedef BasicBlockListType::const_iterator const_iterator;
typedef ArgumentListType::iterator arg_iterator;
typedef ArgumentListType::const_iterator const_arg_iterator;
private:
// Important things that make up a function!
BasicBlockListType BasicBlocks; ///< The basic blocks
mutable ArgumentListType ArgumentList; ///< The formal arguments
ValueSymbolTable *SymTab; ///< Symbol table of args/instructions
AttributeSet AttributeSets; ///< Parameter attributes
// HasLazyArguments is stored in Value::SubclassData.
/*bool HasLazyArguments;*/
// The Calling Convention is stored in Value::SubclassData.
/*CallingConv::ID CallingConvention;*/
friend class SymbolTableListTraits<Function, Module>;
void setParent(Module *parent);
/// hasLazyArguments/CheckLazyArguments - The argument list of a function is
/// built on demand, so that the list isn't allocated until the first client
/// needs it. The hasLazyArguments predicate returns true if the arg list
/// hasn't been set up yet.
bool hasLazyArguments() const {
return getSubclassDataFromValue() & 1;
}
void CheckLazyArguments() const {
if (hasLazyArguments())
BuildLazyArguments();
}
void BuildLazyArguments() const;
Function(const Function&) LLVM_DELETED_FUNCTION;
void operator=(const Function&) LLVM_DELETED_FUNCTION;
/// Do the actual lookup of an intrinsic ID when the query could not be
/// answered from the cache.
unsigned lookupIntrinsicID() const LLVM_READONLY;
/// Function ctor - If the (optional) Module argument is specified, the
/// function is automatically inserted into the end of the function list for
/// the module.
///
Function(FunctionType *Ty, LinkageTypes Linkage,
const Twine &N = "", Module *M = 0);
public:
static Function *Create(FunctionType *Ty, LinkageTypes Linkage,
const Twine &N = "", Module *M = 0) {
return new(0) Function(Ty, Linkage, N, M);
}
~Function();
Type *getReturnType() const; // Return the type of the ret val
FunctionType *getFunctionType() const; // Return the FunctionType for me
/// getContext - Return a pointer to the LLVMContext associated with this
/// function, or NULL if this function is not bound to a context yet.
LLVMContext &getContext() const;
/// isVarArg - Return true if this function takes a variable number of
/// arguments.
bool isVarArg() const;
/// getIntrinsicID - This method returns the ID number of the specified
/// function, or Intrinsic::not_intrinsic if the function is not an
/// intrinsic, or if the pointer is null. This value is always defined to be
/// zero to allow easy checking for whether a function is intrinsic or not.
/// The particular intrinsic functions which correspond to this value are
/// defined in llvm/Intrinsics.h. Results are cached in the LLVM context,
/// subsequent requests for the same ID return results much faster from the
/// cache.
///
unsigned getIntrinsicID() const LLVM_READONLY;
bool isIntrinsic() const { return getName().startswith("llvm."); }
/// getCallingConv()/setCallingConv(CC) - These method get and set the
/// calling convention of this function. The enum values for the known
/// calling conventions are defined in CallingConv.h.
CallingConv::ID getCallingConv() const {
return static_cast<CallingConv::ID>(getSubclassDataFromValue() >> 1);
}
void setCallingConv(CallingConv::ID CC) {
setValueSubclassData((getSubclassDataFromValue() & 1) |
(static_cast<unsigned>(CC) << 1));
}
/// getAttributes - Return the attribute list for this Function.
///
AttributeSet getAttributes() const { return AttributeSets; }
/// setAttributes - Set the attribute list for this Function.
///
void setAttributes(AttributeSet attrs) { AttributeSets = attrs; }
/// addFnAttr - Add function attributes to this function.
///
void addFnAttr(Attribute::AttrKind N) {
setAttributes(AttributeSets.addAttribute(getContext(),
AttributeSet::FunctionIndex, N));
}
/// addFnAttr - Add function attributes to this function.
///
void addFnAttr(StringRef Kind) {
setAttributes(
AttributeSets.addAttribute(getContext(),
AttributeSet::FunctionIndex, Kind));
}
/// \brief Return true if the function has the attribute.
bool hasFnAttribute(Attribute::AttrKind Kind) const {
return AttributeSets.hasAttribute(AttributeSet::FunctionIndex, Kind);
}
bool hasFnAttribute(StringRef Kind) const {
return AttributeSets.hasAttribute(AttributeSet::FunctionIndex, Kind);
}
/// hasGC/getGC/setGC/clearGC - The name of the garbage collection algorithm
/// to use during code generation.
bool hasGC() const;
const char *getGC() const;
void setGC(const char *Str);
void clearGC();
/// @brief adds the attribute to the list of attributes.
void addAttribute(unsigned i, Attribute::AttrKind attr);
/// @brief adds the attributes to the list of attributes.
void addAttributes(unsigned i, AttributeSet attrs);
/// @brief removes the attributes from the list of attributes.
void removeAttributes(unsigned i, AttributeSet attr);
/// @brief Extract the alignment for a call or parameter (0=unknown).
unsigned getParamAlignment(unsigned i) const {
return AttributeSets.getParamAlignment(i);
}
/// @brief Determine if the function does not access memory.
bool doesNotAccessMemory() const {
return AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
Attribute::ReadNone);
}
void setDoesNotAccessMemory() {
addFnAttr(Attribute::ReadNone);
}
/// @brief Determine if the function does not access or only reads memory.
bool onlyReadsMemory() const {
return doesNotAccessMemory() ||
AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
Attribute::ReadOnly);
}
void setOnlyReadsMemory() {
addFnAttr(Attribute::ReadOnly);
}
/// @brief Determine if the function cannot return.
bool doesNotReturn() const {
return AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
Attribute::NoReturn);
}
void setDoesNotReturn() {
addFnAttr(Attribute::NoReturn);
}
/// @brief Determine if the function cannot unwind.
bool doesNotThrow() const {
return AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
Attribute::NoUnwind);
}
void setDoesNotThrow() {
addFnAttr(Attribute::NoUnwind);
}
/// @brief Determine if the call cannot be duplicated.
bool cannotDuplicate() const {
return AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
Attribute::NoDuplicate);
}
void setCannotDuplicate() {
addFnAttr(Attribute::NoDuplicate);
}
/// @brief True if the ABI mandates (or the user requested) that this
/// function be in a unwind table.
bool hasUWTable() const {
return AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
Attribute::UWTable);
}
void setHasUWTable() {
addFnAttr(Attribute::UWTable);
}
/// @brief True if this function needs an unwind table.
bool needsUnwindTableEntry() const {
return hasUWTable() || !doesNotThrow();
}
/// @brief Determine if the function returns a structure through first
/// pointer argument.
bool hasStructRetAttr() const {
return AttributeSets.hasAttribute(1, Attribute::StructRet);
}
/// @brief Determine if the parameter does not alias other parameters.
/// @param n The parameter to check. 1 is the first parameter, 0 is the return
bool doesNotAlias(unsigned n) const {
return AttributeSets.hasAttribute(n, Attribute::NoAlias);
}
void setDoesNotAlias(unsigned n) {
addAttribute(n, Attribute::NoAlias);
}
/// @brief Determine if the parameter can be captured.
/// @param n The parameter to check. 1 is the first parameter, 0 is the return
bool doesNotCapture(unsigned n) const {
return AttributeSets.hasAttribute(n, Attribute::NoCapture);
}
void setDoesNotCapture(unsigned n) {
addAttribute(n, Attribute::NoCapture);
}
/// copyAttributesFrom - copy all additional attributes (those not needed to
/// create a Function) from the Function Src to this one.
void copyAttributesFrom(const GlobalValue *Src);
/// deleteBody - This method deletes the body of the function, and converts
/// the linkage to external.
///
void deleteBody() {
dropAllReferences();
setLinkage(ExternalLinkage);
}
/// removeFromParent - This method unlinks 'this' from the containing module,
/// but does not delete it.
///
virtual void removeFromParent();
/// eraseFromParent - This method unlinks 'this' from the containing module
/// and deletes it.
///
virtual void eraseFromParent();
/// Get the underlying elements of the Function... the basic block list is
/// empty for external functions.
///
const ArgumentListType &getArgumentList() const {
CheckLazyArguments();
return ArgumentList;
}
ArgumentListType &getArgumentList() {
CheckLazyArguments();
return ArgumentList;
}
static iplist<Argument> Function::*getSublistAccess(Argument*) {
return &Function::ArgumentList;
}
const BasicBlockListType &getBasicBlockList() const { return BasicBlocks; }
BasicBlockListType &getBasicBlockList() { return BasicBlocks; }
static iplist<BasicBlock> Function::*getSublistAccess(BasicBlock*) {
return &Function::BasicBlocks;
}
const BasicBlock &getEntryBlock() const { return front(); }
BasicBlock &getEntryBlock() { return front(); }
//===--------------------------------------------------------------------===//
// Symbol Table Accessing functions...
/// getSymbolTable() - Return the symbol table...
///
inline ValueSymbolTable &getValueSymbolTable() { return *SymTab; }
inline const ValueSymbolTable &getValueSymbolTable() const { return *SymTab; }
//===--------------------------------------------------------------------===//
// BasicBlock iterator forwarding functions
//
iterator begin() { return BasicBlocks.begin(); }
const_iterator begin() const { return BasicBlocks.begin(); }
iterator end () { return BasicBlocks.end(); }
const_iterator end () const { return BasicBlocks.end(); }
size_t size() const { return BasicBlocks.size(); }
bool empty() const { return BasicBlocks.empty(); }
const BasicBlock &front() const { return BasicBlocks.front(); }
BasicBlock &front() { return BasicBlocks.front(); }
const BasicBlock &back() const { return BasicBlocks.back(); }
BasicBlock &back() { return BasicBlocks.back(); }
//===--------------------------------------------------------------------===//
// Argument iterator forwarding functions
//
arg_iterator arg_begin() {
CheckLazyArguments();
return ArgumentList.begin();
}
const_arg_iterator arg_begin() const {
CheckLazyArguments();
return ArgumentList.begin();
}
arg_iterator arg_end() {
CheckLazyArguments();
return ArgumentList.end();
}
const_arg_iterator arg_end() const {
CheckLazyArguments();
return ArgumentList.end();
}
size_t arg_size() const;
bool arg_empty() const;
/// viewCFG - This function is meant for use from the debugger. You can just
/// say 'call F->viewCFG()' and a ghostview window should pop up from the
/// program, displaying the CFG of the current function with the code for each
/// basic block inside. This depends on there being a 'dot' and 'gv' program
/// in your path.
///
void viewCFG() const;
/// viewCFGOnly - This function is meant for use from the debugger. It works
/// just like viewCFG, but it does not include the contents of basic blocks
/// into the nodes, just the label. If you are only interested in the CFG
/// this can make the graph smaller.
///
void viewCFGOnly() const;
/// Methods for support type inquiry through isa, cast, and dyn_cast:
static inline bool classof(const Value *V) {
return V->getValueID() == Value::FunctionVal;
}
/// dropAllReferences() - This method causes all the subinstructions to "let
/// go" of all references that they are maintaining. This allows one to
/// 'delete' a whole module at a time, even though there may be circular
/// references... first all references are dropped, and all use counts go to
/// zero. Then everything is deleted for real. Note that no operations are
/// valid on an object that has "dropped all references", except operator
/// delete.
///
/// Since no other object in the module can have references into the body of a
/// function, dropping all references deletes the entire body of the function,
/// including any contained basic blocks.
///
void dropAllReferences();
/// hasAddressTaken - returns true if there are any uses of this function
/// other than direct calls or invokes to it, or blockaddress expressions.
/// Optionally passes back an offending user for diagnostic purposes.
///
bool hasAddressTaken(const User** = 0) const;
/// isDefTriviallyDead - Return true if it is trivially safe to remove
/// this function definition from the module (because it isn't externally
/// visible, does not have its address taken, and has no callers). To make
/// this more accurate, call removeDeadConstantUsers first.
bool isDefTriviallyDead() const;
/// callsFunctionThatReturnsTwice - Return true if the function has a call to
/// setjmp or other function that gcc recognizes as "returning twice".
bool callsFunctionThatReturnsTwice() const;
private:
// Shadow Value::setValueSubclassData with a private forwarding method so that
// subclasses cannot accidentally use it.
void setValueSubclassData(unsigned short D) {
Value::setValueSubclassData(D);
}
};
inline ValueSymbolTable *
ilist_traits<BasicBlock>::getSymTab(Function *F) {
return F ? &F->getValueSymbolTable() : 0;
}
inline ValueSymbolTable *
ilist_traits<Argument>::getSymTab(Function *F) {
return F ? &F->getValueSymbolTable() : 0;
}
} // End llvm namespace
#endif

View File

@@ -0,0 +1,93 @@
//===-------- llvm/GlobalAlias.h - GlobalAlias class ------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains the declaration of the GlobalAlias class, which
// represents a single function or variable alias in the IR.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_IR_GLOBALALIAS_H
#define LLVM_IR_GLOBALALIAS_H
#include "llvm/ADT/Twine.h"
#include "llvm/ADT/ilist_node.h"
#include "llvm/IR/GlobalValue.h"
#include "llvm/IR/OperandTraits.h"
namespace llvm {
class Module;
template<typename ValueSubClass, typename ItemParentClass>
class SymbolTableListTraits;
class GlobalAlias : public GlobalValue, public ilist_node<GlobalAlias> {
friend class SymbolTableListTraits<GlobalAlias, Module>;
void operator=(const GlobalAlias &) LLVM_DELETED_FUNCTION;
GlobalAlias(const GlobalAlias &) LLVM_DELETED_FUNCTION;
void setParent(Module *parent);
public:
// allocate space for exactly one operand
void *operator new(size_t s) {
return User::operator new(s, 1);
}
/// GlobalAlias ctor - If a parent module is specified, the alias is
/// automatically inserted into the end of the specified module's alias list.
GlobalAlias(Type *Ty, LinkageTypes Linkage, const Twine &Name = "",
Constant* Aliasee = 0, Module *Parent = 0);
/// Provide fast operand accessors
DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Constant);
/// removeFromParent - This method unlinks 'this' from the containing module,
/// but does not delete it.
///
virtual void removeFromParent();
/// eraseFromParent - This method unlinks 'this' from the containing module
/// and deletes it.
///
virtual void eraseFromParent();
/// set/getAliasee - These methods retrive and set alias target.
void setAliasee(Constant *GV);
const Constant *getAliasee() const {
return getOperand(0);
}
Constant *getAliasee() {
return getOperand(0);
}
/// getAliasedGlobal() - Aliasee can be either global or bitcast of
/// global. This method retrives the global for both aliasee flavours.
const GlobalValue *getAliasedGlobal() const;
/// resolveAliasedGlobal() - This method tries to ultimately resolve the alias
/// by going through the aliasing chain and trying to find the very last
/// global. Returns NULL if a cycle was found. If stopOnWeak is false, then
/// the whole chain aliasing chain is traversed, otherwise - only strong
/// aliases.
const GlobalValue *resolveAliasedGlobal(bool stopOnWeak = true) const;
// Methods for support type inquiry through isa, cast, and dyn_cast:
static inline bool classof(const Value *V) {
return V->getValueID() == Value::GlobalAliasVal;
}
};
template <>
struct OperandTraits<GlobalAlias> :
public FixedNumOperandTraits<GlobalAlias, 1> {
};
DEFINE_TRANSPARENT_OPERAND_ACCESSORS(GlobalAlias, Constant)
} // End llvm namespace
#endif

View File

@@ -0,0 +1,299 @@
//===-- llvm/GlobalValue.h - Class to represent a global value --*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file is a common base class of all globally definable objects. As such,
// it is subclassed by GlobalVariable, GlobalAlias and by Function. This is
// used because you can do certain things with these global objects that you
// can't do to anything else. For example, use the address of one as a
// constant.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_IR_GLOBALVALUE_H
#define LLVM_IR_GLOBALVALUE_H
#include "llvm/IR/Constant.h"
namespace llvm {
class PointerType;
class Module;
class GlobalValue : public Constant {
GlobalValue(const GlobalValue &) LLVM_DELETED_FUNCTION;
public:
/// @brief An enumeration for the kinds of linkage for global values.
enum LinkageTypes {
ExternalLinkage = 0,///< Externally visible function
AvailableExternallyLinkage, ///< Available for inspection, not emission.
LinkOnceAnyLinkage, ///< Keep one copy of function when linking (inline)
LinkOnceODRLinkage, ///< Same, but only replaced by something equivalent.
LinkOnceODRAutoHideLinkage, ///< Like LinkOnceODRLinkage but addr not taken.
WeakAnyLinkage, ///< Keep one copy of named function when linking (weak)
WeakODRLinkage, ///< Same, but only replaced by something equivalent.
AppendingLinkage, ///< Special purpose, only applies to global arrays
InternalLinkage, ///< Rename collisions when linking (static functions).
PrivateLinkage, ///< Like Internal, but omit from symbol table.
LinkerPrivateLinkage, ///< Like Private, but linker removes.
LinkerPrivateWeakLinkage, ///< Like LinkerPrivate, but weak.
DLLImportLinkage, ///< Function to be imported from DLL
DLLExportLinkage, ///< Function to be accessible from DLL.
ExternalWeakLinkage,///< ExternalWeak linkage description.
CommonLinkage ///< Tentative definitions.
};
/// @brief An enumeration for the kinds of visibility of global values.
enum VisibilityTypes {
DefaultVisibility = 0, ///< The GV is visible
HiddenVisibility, ///< The GV is hidden
ProtectedVisibility ///< The GV is protected
};
protected:
GlobalValue(Type *ty, ValueTy vty, Use *Ops, unsigned NumOps,
LinkageTypes linkage, const Twine &Name)
: Constant(ty, vty, Ops, NumOps), Linkage(linkage),
Visibility(DefaultVisibility), Alignment(0), UnnamedAddr(0), Parent(0) {
setName(Name);
}
// Note: VC++ treats enums as signed, so an extra bit is required to prevent
// Linkage and Visibility from turning into negative values.
LinkageTypes Linkage : 5; // The linkage of this global
unsigned Visibility : 2; // The visibility style of this global
unsigned Alignment : 16; // Alignment of this symbol, must be power of two
unsigned UnnamedAddr : 1; // This value's address is not significant
Module *Parent; // The containing module.
std::string Section; // Section to emit this into, empty mean default
public:
~GlobalValue() {
removeDeadConstantUsers(); // remove any dead constants using this.
}
unsigned getAlignment() const {
return (1u << Alignment) >> 1;
}
void setAlignment(unsigned Align);
bool hasUnnamedAddr() const { return UnnamedAddr; }
void setUnnamedAddr(bool Val) { UnnamedAddr = Val; }
VisibilityTypes getVisibility() const { return VisibilityTypes(Visibility); }
bool hasDefaultVisibility() const { return Visibility == DefaultVisibility; }
bool hasHiddenVisibility() const { return Visibility == HiddenVisibility; }
bool hasProtectedVisibility() const {
return Visibility == ProtectedVisibility;
}
void setVisibility(VisibilityTypes V) { Visibility = V; }
bool hasSection() const { return !Section.empty(); }
const std::string &getSection() const { return Section; }
void setSection(StringRef S) { Section = S; }
/// If the usage is empty (except transitively dead constants), then this
/// global value can be safely deleted since the destructor will
/// delete the dead constants as well.
/// @brief Determine if the usage of this global value is empty except
/// for transitively dead constants.
bool use_empty_except_constants();
/// getType - Global values are always pointers.
inline PointerType *getType() const {
return reinterpret_cast<PointerType*>(User::getType());
}
static LinkageTypes getLinkOnceLinkage(bool ODR) {
return ODR ? LinkOnceODRLinkage : LinkOnceAnyLinkage;
}
static LinkageTypes getWeakLinkage(bool ODR) {
return ODR ? WeakODRLinkage : WeakAnyLinkage;
}
static bool isExternalLinkage(LinkageTypes Linkage) {
return Linkage == ExternalLinkage;
}
static bool isAvailableExternallyLinkage(LinkageTypes Linkage) {
return Linkage == AvailableExternallyLinkage;
}
static bool isLinkOnceLinkage(LinkageTypes Linkage) {
return Linkage == LinkOnceAnyLinkage ||
Linkage == LinkOnceODRLinkage ||
Linkage == LinkOnceODRAutoHideLinkage;
}
static bool isLinkOnceODRAutoHideLinkage(LinkageTypes Linkage) {
return Linkage == LinkOnceODRAutoHideLinkage;
}
static bool isWeakLinkage(LinkageTypes Linkage) {
return Linkage == WeakAnyLinkage || Linkage == WeakODRLinkage;
}
static bool isAppendingLinkage(LinkageTypes Linkage) {
return Linkage == AppendingLinkage;
}
static bool isInternalLinkage(LinkageTypes Linkage) {
return Linkage == InternalLinkage;
}
static bool isPrivateLinkage(LinkageTypes Linkage) {
return Linkage == PrivateLinkage;
}
static bool isLinkerPrivateLinkage(LinkageTypes Linkage) {
return Linkage == LinkerPrivateLinkage;
}
static bool isLinkerPrivateWeakLinkage(LinkageTypes Linkage) {
return Linkage == LinkerPrivateWeakLinkage;
}
static bool isLocalLinkage(LinkageTypes Linkage) {
return isInternalLinkage(Linkage) || isPrivateLinkage(Linkage) ||
isLinkerPrivateLinkage(Linkage) || isLinkerPrivateWeakLinkage(Linkage);
}
static bool isDLLImportLinkage(LinkageTypes Linkage) {
return Linkage == DLLImportLinkage;
}
static bool isDLLExportLinkage(LinkageTypes Linkage) {
return Linkage == DLLExportLinkage;
}
static bool isExternalWeakLinkage(LinkageTypes Linkage) {
return Linkage == ExternalWeakLinkage;
}
static bool isCommonLinkage(LinkageTypes Linkage) {
return Linkage == CommonLinkage;
}
/// isDiscardableIfUnused - Whether the definition of this global may be
/// discarded if it is not used in its compilation unit.
static bool isDiscardableIfUnused(LinkageTypes Linkage) {
return isLinkOnceLinkage(Linkage) || isLocalLinkage(Linkage);
}
/// mayBeOverridden - Whether the definition of this global may be replaced
/// by something non-equivalent at link time. For example, if a function has
/// weak linkage then the code defining it may be replaced by different code.
static bool mayBeOverridden(LinkageTypes Linkage) {
return Linkage == WeakAnyLinkage ||
Linkage == LinkOnceAnyLinkage ||
Linkage == CommonLinkage ||
Linkage == ExternalWeakLinkage ||
Linkage == LinkerPrivateWeakLinkage;
}
/// isWeakForLinker - Whether the definition of this global may be replaced at
/// link time. NB: Using this method outside of the code generators is almost
/// always a mistake: when working at the IR level use mayBeOverridden instead
/// as it knows about ODR semantics.
static bool isWeakForLinker(LinkageTypes Linkage) {
return Linkage == AvailableExternallyLinkage ||
Linkage == WeakAnyLinkage ||
Linkage == WeakODRLinkage ||
Linkage == LinkOnceAnyLinkage ||
Linkage == LinkOnceODRLinkage ||
Linkage == LinkOnceODRAutoHideLinkage ||
Linkage == CommonLinkage ||
Linkage == ExternalWeakLinkage ||
Linkage == LinkerPrivateWeakLinkage;
}
bool hasExternalLinkage() const { return isExternalLinkage(Linkage); }
bool hasAvailableExternallyLinkage() const {
return isAvailableExternallyLinkage(Linkage);
}
bool hasLinkOnceLinkage() const {
return isLinkOnceLinkage(Linkage);
}
bool hasLinkOnceODRAutoHideLinkage() const {
return isLinkOnceODRAutoHideLinkage(Linkage);
}
bool hasWeakLinkage() const {
return isWeakLinkage(Linkage);
}
bool hasAppendingLinkage() const { return isAppendingLinkage(Linkage); }
bool hasInternalLinkage() const { return isInternalLinkage(Linkage); }
bool hasPrivateLinkage() const { return isPrivateLinkage(Linkage); }
bool hasLinkerPrivateLinkage() const { return isLinkerPrivateLinkage(Linkage); }
bool hasLinkerPrivateWeakLinkage() const {
return isLinkerPrivateWeakLinkage(Linkage);
}
bool hasLocalLinkage() const { return isLocalLinkage(Linkage); }
bool hasDLLImportLinkage() const { return isDLLImportLinkage(Linkage); }
bool hasDLLExportLinkage() const { return isDLLExportLinkage(Linkage); }
bool hasExternalWeakLinkage() const { return isExternalWeakLinkage(Linkage); }
bool hasCommonLinkage() const { return isCommonLinkage(Linkage); }
void setLinkage(LinkageTypes LT) { Linkage = LT; }
LinkageTypes getLinkage() const { return Linkage; }
bool isDiscardableIfUnused() const {
return isDiscardableIfUnused(Linkage);
}
bool mayBeOverridden() const { return mayBeOverridden(Linkage); }
bool isWeakForLinker() const { return isWeakForLinker(Linkage); }
/// copyAttributesFrom - copy all additional attributes (those not needed to
/// create a GlobalValue) from the GlobalValue Src to this one.
virtual void copyAttributesFrom(const GlobalValue *Src);
/// @name Materialization
/// Materialization is used to construct functions only as they're needed. This
/// is useful to reduce memory usage in LLVM or parsing work done by the
/// BitcodeReader to load the Module.
/// @{
/// isMaterializable - If this function's Module is being lazily streamed in
/// functions from disk or some other source, this method can be used to check
/// to see if the function has been read in yet or not.
bool isMaterializable() const;
/// isDematerializable - Returns true if this function was loaded from a
/// GVMaterializer that's still attached to its Module and that knows how to
/// dematerialize the function.
bool isDematerializable() const;
/// Materialize - make sure this GlobalValue is fully read. If the module is
/// corrupt, this returns true and fills in the optional string with
/// information about the problem. If successful, this returns false.
bool Materialize(std::string *ErrInfo = 0);
/// Dematerialize - If this GlobalValue is read in, and if the GVMaterializer
/// supports it, release the memory for the function, and set it up to be
/// materialized lazily. If !isDematerializable(), this method is a noop.
void Dematerialize();
/// @}
/// Override from Constant class.
virtual void destroyConstant();
/// isDeclaration - Return true if the primary definition of this global
/// value is outside of the current translation unit.
bool isDeclaration() const;
/// removeFromParent - This method unlinks 'this' from the containing module,
/// but does not delete it.
virtual void removeFromParent() = 0;
/// eraseFromParent - This method unlinks 'this' from the containing module
/// and deletes it.
virtual void eraseFromParent() = 0;
/// getParent - Get the module that this global value is contained inside
/// of...
inline Module *getParent() { return Parent; }
inline const Module *getParent() const { return Parent; }
// Methods for support type inquiry through isa, cast, and dyn_cast:
static inline bool classof(const Value *V) {
return V->getValueID() == Value::FunctionVal ||
V->getValueID() == Value::GlobalVariableVal ||
V->getValueID() == Value::GlobalAliasVal;
}
};
} // End llvm namespace
#endif

View File

@@ -0,0 +1,210 @@
//===-- llvm/GlobalVariable.h - GlobalVariable class ------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains the declaration of the GlobalVariable class, which
// represents a single global variable (or constant) in the VM.
//
// Global variables are constant pointers that refer to hunks of space that are
// allocated by either the VM, or by the linker in a static compiler. A global
// variable may have an initial value, which is copied into the executables .data
// area. Global Constants are required to have initializers.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_IR_GLOBALVARIABLE_H
#define LLVM_IR_GLOBALVARIABLE_H
#include "llvm/ADT/Twine.h"
#include "llvm/ADT/ilist_node.h"
#include "llvm/IR/GlobalValue.h"
#include "llvm/IR/OperandTraits.h"
namespace llvm {
class Module;
class Constant;
template<typename ValueSubClass, typename ItemParentClass>
class SymbolTableListTraits;
class GlobalVariable : public GlobalValue, public ilist_node<GlobalVariable> {
friend class SymbolTableListTraits<GlobalVariable, Module>;
void *operator new(size_t, unsigned) LLVM_DELETED_FUNCTION;
void operator=(const GlobalVariable &) LLVM_DELETED_FUNCTION;
GlobalVariable(const GlobalVariable &) LLVM_DELETED_FUNCTION;
void setParent(Module *parent);
bool isConstantGlobal : 1; // Is this a global constant?
unsigned threadLocalMode : 3; // Is this symbol "Thread Local",
// if so, what is the desired
// model?
bool isExternallyInitializedConstant : 1; // Is this a global whose value
// can change from its initial
// value before global
// initializers are run?
public:
// allocate space for exactly one operand
void *operator new(size_t s) {
return User::operator new(s, 1);
}
enum ThreadLocalMode {
NotThreadLocal = 0,
GeneralDynamicTLSModel,
LocalDynamicTLSModel,
InitialExecTLSModel,
LocalExecTLSModel
};
/// GlobalVariable ctor - If a parent module is specified, the global is
/// automatically inserted into the end of the specified modules global list.
GlobalVariable(Type *Ty, bool isConstant, LinkageTypes Linkage,
Constant *Initializer = 0, const Twine &Name = "",
ThreadLocalMode = NotThreadLocal, unsigned AddressSpace = 0,
bool isExternallyInitialized = false);
/// GlobalVariable ctor - This creates a global and inserts it before the
/// specified other global.
GlobalVariable(Module &M, Type *Ty, bool isConstant,
LinkageTypes Linkage, Constant *Initializer,
const Twine &Name = "", GlobalVariable *InsertBefore = 0,
ThreadLocalMode = NotThreadLocal, unsigned AddressSpace = 0,
bool isExternallyInitialized = false);
~GlobalVariable() {
NumOperands = 1; // FIXME: needed by operator delete
}
/// Provide fast operand accessors
DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
/// hasInitializer - Unless a global variable isExternal(), it has an
/// initializer. The initializer for the global variable/constant is held by
/// Initializer if an initializer is specified.
///
inline bool hasInitializer() const { return !isDeclaration(); }
/// hasDefinitiveInitializer - Whether the global variable has an initializer,
/// and any other instances of the global (this can happen due to weak
/// linkage) are guaranteed to have the same initializer.
///
/// Note that if you want to transform a global, you must use
/// hasUniqueInitializer() instead, because of the *_odr linkage type.
///
/// Example:
///
/// @a = global SomeType* null - Initializer is both definitive and unique.
///
/// @b = global weak SomeType* null - Initializer is neither definitive nor
/// unique.
///
/// @c = global weak_odr SomeType* null - Initializer is definitive, but not
/// unique.
inline bool hasDefinitiveInitializer() const {
return hasInitializer() &&
// The initializer of a global variable with weak linkage may change at
// link time.
!mayBeOverridden() &&
// The initializer of a global variable with the externally_initialized
// marker may change at runtime before C++ initializers are evaluated.
!isExternallyInitialized();
}
/// hasUniqueInitializer - Whether the global variable has an initializer, and
/// any changes made to the initializer will turn up in the final executable.
inline bool hasUniqueInitializer() const {
return hasInitializer() &&
// It's not safe to modify initializers of global variables with weak
// linkage, because the linker might choose to discard the initializer and
// use the initializer from another instance of the global variable
// instead. It is wrong to modify the initializer of a global variable
// with *_odr linkage because then different instances of the global may
// have different initializers, breaking the One Definition Rule.
!isWeakForLinker() &&
// It is not safe to modify initializers of global variables with the
// external_initializer marker since the value may be changed at runtime
// before C++ initializers are evaluated.
!isExternallyInitialized();
}
/// getInitializer - Return the initializer for this global variable. It is
/// illegal to call this method if the global is external, because we cannot
/// tell what the value is initialized to!
///
inline const Constant *getInitializer() const {
assert(hasInitializer() && "GV doesn't have initializer!");
return static_cast<Constant*>(Op<0>().get());
}
inline Constant *getInitializer() {
assert(hasInitializer() && "GV doesn't have initializer!");
return static_cast<Constant*>(Op<0>().get());
}
/// setInitializer - Sets the initializer for this global variable, removing
/// any existing initializer if InitVal==NULL. If this GV has type T*, the
/// initializer must have type T.
void setInitializer(Constant *InitVal);
/// If the value is a global constant, its value is immutable throughout the
/// runtime execution of the program. Assigning a value into the constant
/// leads to undefined behavior.
///
bool isConstant() const { return isConstantGlobal; }
void setConstant(bool Val) { isConstantGlobal = Val; }
/// If the value is "Thread Local", its value isn't shared by the threads.
bool isThreadLocal() const { return threadLocalMode != NotThreadLocal; }
void setThreadLocal(bool Val) {
threadLocalMode = Val ? GeneralDynamicTLSModel : NotThreadLocal;
}
void setThreadLocalMode(ThreadLocalMode Val) { threadLocalMode = Val; }
ThreadLocalMode getThreadLocalMode() const {
return static_cast<ThreadLocalMode>(threadLocalMode);
}
bool isExternallyInitialized() const {
return isExternallyInitializedConstant;
}
void setExternallyInitialized(bool Val) {
isExternallyInitializedConstant = Val;
}
/// copyAttributesFrom - copy all additional attributes (those not needed to
/// create a GlobalVariable) from the GlobalVariable Src to this one.
void copyAttributesFrom(const GlobalValue *Src);
/// removeFromParent - This method unlinks 'this' from the containing module,
/// but does not delete it.
///
virtual void removeFromParent();
/// eraseFromParent - This method unlinks 'this' from the containing module
/// and deletes it.
///
virtual void eraseFromParent();
/// Override Constant's implementation of this method so we can
/// replace constant initializers.
virtual void replaceUsesOfWithOnConstant(Value *From, Value *To, Use *U);
// Methods for support type inquiry through isa, cast, and dyn_cast:
static inline bool classof(const Value *V) {
return V->getValueID() == Value::GlobalVariableVal;
}
};
template <>
struct OperandTraits<GlobalVariable> :
public OptionalOperandTraits<GlobalVariable> {
};
DEFINE_TRANSPARENT_OPERAND_ACCESSORS(GlobalVariable, Value)
} // End llvm namespace
#endif

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,309 @@
//===-- llvm/InlineAsm.h - Class to represent inline asm strings-*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This class represents the inline asm strings, which are Value*'s that are
// used as the callee operand of call instructions. InlineAsm's are uniqued
// like constants, and created via InlineAsm::get(...).
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_IR_INLINEASM_H
#define LLVM_IR_INLINEASM_H
#include "llvm/ADT/StringRef.h"
#include "llvm/IR/Value.h"
#include <vector>
namespace llvm {
class PointerType;
class FunctionType;
class Module;
struct InlineAsmKeyType;
template<class ValType, class ValRefType, class TypeClass, class ConstantClass,
bool HasLargeKey>
class ConstantUniqueMap;
template<class ConstantClass, class TypeClass, class ValType>
struct ConstantCreator;
class InlineAsm : public Value {
public:
enum AsmDialect {
AD_ATT,
AD_Intel
};
private:
friend struct ConstantCreator<InlineAsm, PointerType, InlineAsmKeyType>;
friend class ConstantUniqueMap<InlineAsmKeyType, const InlineAsmKeyType&,
PointerType, InlineAsm, false>;
InlineAsm(const InlineAsm &) LLVM_DELETED_FUNCTION;
void operator=(const InlineAsm&) LLVM_DELETED_FUNCTION;
std::string AsmString, Constraints;
bool HasSideEffects;
bool IsAlignStack;
AsmDialect Dialect;
InlineAsm(PointerType *Ty, const std::string &AsmString,
const std::string &Constraints, bool hasSideEffects,
bool isAlignStack, AsmDialect asmDialect);
virtual ~InlineAsm();
/// When the ConstantUniqueMap merges two types and makes two InlineAsms
/// identical, it destroys one of them with this method.
void destroyConstant();
public:
/// InlineAsm::get - Return the specified uniqued inline asm string.
///
static InlineAsm *get(FunctionType *Ty, StringRef AsmString,
StringRef Constraints, bool hasSideEffects,
bool isAlignStack = false,
AsmDialect asmDialect = AD_ATT);
bool hasSideEffects() const { return HasSideEffects; }
bool isAlignStack() const { return IsAlignStack; }
AsmDialect getDialect() const { return Dialect; }
/// getType - InlineAsm's are always pointers.
///
PointerType *getType() const {
return reinterpret_cast<PointerType*>(Value::getType());
}
/// getFunctionType - InlineAsm's are always pointers to functions.
///
FunctionType *getFunctionType() const;
const std::string &getAsmString() const { return AsmString; }
const std::string &getConstraintString() const { return Constraints; }
/// Verify - This static method can be used by the parser to check to see if
/// the specified constraint string is legal for the type. This returns true
/// if legal, false if not.
///
static bool Verify(FunctionType *Ty, StringRef Constraints);
// Constraint String Parsing
enum ConstraintPrefix {
isInput, // 'x'
isOutput, // '=x'
isClobber // '~x'
};
typedef std::vector<std::string> ConstraintCodeVector;
struct SubConstraintInfo {
/// MatchingInput - If this is not -1, this is an output constraint where an
/// input constraint is required to match it (e.g. "0"). The value is the
/// constraint number that matches this one (for example, if this is
/// constraint #0 and constraint #4 has the value "0", this will be 4).
signed char MatchingInput;
/// Code - The constraint code, either the register name (in braces) or the
/// constraint letter/number.
ConstraintCodeVector Codes;
/// Default constructor.
SubConstraintInfo() : MatchingInput(-1) {}
};
typedef std::vector<SubConstraintInfo> SubConstraintInfoVector;
struct ConstraintInfo;
typedef std::vector<ConstraintInfo> ConstraintInfoVector;
struct ConstraintInfo {
/// Type - The basic type of the constraint: input/output/clobber
///
ConstraintPrefix Type;
/// isEarlyClobber - "&": output operand writes result before inputs are all
/// read. This is only ever set for an output operand.
bool isEarlyClobber;
/// MatchingInput - If this is not -1, this is an output constraint where an
/// input constraint is required to match it (e.g. "0"). The value is the
/// constraint number that matches this one (for example, if this is
/// constraint #0 and constraint #4 has the value "0", this will be 4).
signed char MatchingInput;
/// hasMatchingInput - Return true if this is an output constraint that has
/// a matching input constraint.
bool hasMatchingInput() const { return MatchingInput != -1; }
/// isCommutative - This is set to true for a constraint that is commutative
/// with the next operand.
bool isCommutative;
/// isIndirect - True if this operand is an indirect operand. This means
/// that the address of the source or destination is present in the call
/// instruction, instead of it being returned or passed in explicitly. This
/// is represented with a '*' in the asm string.
bool isIndirect;
/// Code - The constraint code, either the register name (in braces) or the
/// constraint letter/number.
ConstraintCodeVector Codes;
/// isMultipleAlternative - '|': has multiple-alternative constraints.
bool isMultipleAlternative;
/// multipleAlternatives - If there are multiple alternative constraints,
/// this array will contain them. Otherwise it will be empty.
SubConstraintInfoVector multipleAlternatives;
/// The currently selected alternative constraint index.
unsigned currentAlternativeIndex;
///Default constructor.
ConstraintInfo();
/// Copy constructor.
ConstraintInfo(const ConstraintInfo &other);
/// Parse - Analyze the specified string (e.g. "=*&{eax}") and fill in the
/// fields in this structure. If the constraint string is not understood,
/// return true, otherwise return false.
bool Parse(StringRef Str, ConstraintInfoVector &ConstraintsSoFar);
/// selectAlternative - Point this constraint to the alternative constraint
/// indicated by the index.
void selectAlternative(unsigned index);
};
/// ParseConstraints - Split up the constraint string into the specific
/// constraints and their prefixes. If this returns an empty vector, and if
/// the constraint string itself isn't empty, there was an error parsing.
static ConstraintInfoVector ParseConstraints(StringRef ConstraintString);
/// ParseConstraints - Parse the constraints of this inlineasm object,
/// returning them the same way that ParseConstraints(str) does.
ConstraintInfoVector ParseConstraints() const {
return ParseConstraints(Constraints);
}
// Methods for support type inquiry through isa, cast, and dyn_cast:
static inline bool classof(const Value *V) {
return V->getValueID() == Value::InlineAsmVal;
}
// These are helper methods for dealing with flags in the INLINEASM SDNode
// in the backend.
enum {
// Fixed operands on an INLINEASM SDNode.
Op_InputChain = 0,
Op_AsmString = 1,
Op_MDNode = 2,
Op_ExtraInfo = 3, // HasSideEffects, IsAlignStack, AsmDialect.
Op_FirstOperand = 4,
// Fixed operands on an INLINEASM MachineInstr.
MIOp_AsmString = 0,
MIOp_ExtraInfo = 1, // HasSideEffects, IsAlignStack, AsmDialect.
MIOp_FirstOperand = 2,
// Interpretation of the MIOp_ExtraInfo bit field.
Extra_HasSideEffects = 1,
Extra_IsAlignStack = 2,
Extra_AsmDialect = 4,
Extra_MayLoad = 8,
Extra_MayStore = 16,
// Inline asm operands map to multiple SDNode / MachineInstr operands.
// The first operand is an immediate describing the asm operand, the low
// bits is the kind:
Kind_RegUse = 1, // Input register, "r".
Kind_RegDef = 2, // Output register, "=r".
Kind_RegDefEarlyClobber = 3, // Early-clobber output register, "=&r".
Kind_Clobber = 4, // Clobbered register, "~r".
Kind_Imm = 5, // Immediate.
Kind_Mem = 6, // Memory operand, "m".
Flag_MatchingOperand = 0x80000000
};
static unsigned getFlagWord(unsigned Kind, unsigned NumOps) {
assert(((NumOps << 3) & ~0xffff) == 0 && "Too many inline asm operands!");
assert(Kind >= Kind_RegUse && Kind <= Kind_Mem && "Invalid Kind");
return Kind | (NumOps << 3);
}
/// getFlagWordForMatchingOp - Augment an existing flag word returned by
/// getFlagWord with information indicating that this input operand is tied
/// to a previous output operand.
static unsigned getFlagWordForMatchingOp(unsigned InputFlag,
unsigned MatchedOperandNo) {
assert(MatchedOperandNo <= 0x7fff && "Too big matched operand");
assert((InputFlag & ~0xffff) == 0 && "High bits already contain data");
return InputFlag | Flag_MatchingOperand | (MatchedOperandNo << 16);
}
/// getFlagWordForRegClass - Augment an existing flag word returned by
/// getFlagWord with the required register class for the following register
/// operands.
/// A tied use operand cannot have a register class, use the register class
/// from the def operand instead.
static unsigned getFlagWordForRegClass(unsigned InputFlag, unsigned RC) {
// Store RC + 1, reserve the value 0 to mean 'no register class'.
++RC;
assert(RC <= 0x7fff && "Too large register class ID");
assert((InputFlag & ~0xffff) == 0 && "High bits already contain data");
return InputFlag | (RC << 16);
}
static unsigned getKind(unsigned Flags) {
return Flags & 7;
}
static bool isRegDefKind(unsigned Flag){ return getKind(Flag) == Kind_RegDef;}
static bool isImmKind(unsigned Flag) { return getKind(Flag) == Kind_Imm; }
static bool isMemKind(unsigned Flag) { return getKind(Flag) == Kind_Mem; }
static bool isRegDefEarlyClobberKind(unsigned Flag) {
return getKind(Flag) == Kind_RegDefEarlyClobber;
}
static bool isClobberKind(unsigned Flag) {
return getKind(Flag) == Kind_Clobber;
}
/// getNumOperandRegisters - Extract the number of registers field from the
/// inline asm operand flag.
static unsigned getNumOperandRegisters(unsigned Flag) {
return (Flag & 0xffff) >> 3;
}
/// isUseOperandTiedToDef - Return true if the flag of the inline asm
/// operand indicates it is an use operand that's matched to a def operand.
static bool isUseOperandTiedToDef(unsigned Flag, unsigned &Idx) {
if ((Flag & Flag_MatchingOperand) == 0)
return false;
Idx = (Flag & ~Flag_MatchingOperand) >> 16;
return true;
}
/// hasRegClassConstraint - Returns true if the flag contains a register
/// class constraint. Sets RC to the register class ID.
static bool hasRegClassConstraint(unsigned Flag, unsigned &RC) {
if (Flag & Flag_MatchingOperand)
return false;
unsigned High = Flag >> 16;
// getFlagWordForRegClass() uses 0 to mean no register class, and otherwise
// stores RC + 1.
if (!High)
return false;
RC = High - 1;
return true;
}
};
} // End llvm namespace
#endif

View File

@@ -0,0 +1,851 @@
//===-- llvm/InstrTypes.h - Important Instruction subclasses ----*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines various meta classes of instructions that exist in the VM
// representation. Specific concrete subclasses of these may be found in the
// i*.h files...
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_IR_INSTRTYPES_H
#define LLVM_IR_INSTRTYPES_H
#include "llvm/ADT/Twine.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Instruction.h"
#include "llvm/IR/OperandTraits.h"
namespace llvm {
class LLVMContext;
//===----------------------------------------------------------------------===//
// TerminatorInst Class
//===----------------------------------------------------------------------===//
/// TerminatorInst - Subclasses of this class are all able to terminate a basic
/// block. Thus, these are all the flow control type of operations.
///
class TerminatorInst : public Instruction {
protected:
TerminatorInst(Type *Ty, Instruction::TermOps iType,
Use *Ops, unsigned NumOps,
Instruction *InsertBefore = 0)
: Instruction(Ty, iType, Ops, NumOps, InsertBefore) {}
TerminatorInst(Type *Ty, Instruction::TermOps iType,
Use *Ops, unsigned NumOps, BasicBlock *InsertAtEnd)
: Instruction(Ty, iType, Ops, NumOps, InsertAtEnd) {}
// Out of line virtual method, so the vtable, etc has a home.
~TerminatorInst();
/// Virtual methods - Terminators should overload these and provide inline
/// overrides of non-V methods.
virtual BasicBlock *getSuccessorV(unsigned idx) const = 0;
virtual unsigned getNumSuccessorsV() const = 0;
virtual void setSuccessorV(unsigned idx, BasicBlock *B) = 0;
virtual TerminatorInst *clone_impl() const = 0;
public:
/// getNumSuccessors - Return the number of successors that this terminator
/// has.
unsigned getNumSuccessors() const {
return getNumSuccessorsV();
}
/// getSuccessor - Return the specified successor.
///
BasicBlock *getSuccessor(unsigned idx) const {
return getSuccessorV(idx);
}
/// setSuccessor - Update the specified successor to point at the provided
/// block.
void setSuccessor(unsigned idx, BasicBlock *B) {
setSuccessorV(idx, B);
}
// Methods for support type inquiry through isa, cast, and dyn_cast:
static inline bool classof(const Instruction *I) {
return I->isTerminator();
}
static inline bool classof(const Value *V) {
return isa<Instruction>(V) && classof(cast<Instruction>(V));
}
};
//===----------------------------------------------------------------------===//
// UnaryInstruction Class
//===----------------------------------------------------------------------===//
class UnaryInstruction : public Instruction {
void *operator new(size_t, unsigned) LLVM_DELETED_FUNCTION;
protected:
UnaryInstruction(Type *Ty, unsigned iType, Value *V,
Instruction *IB = 0)
: Instruction(Ty, iType, &Op<0>(), 1, IB) {
Op<0>() = V;
}
UnaryInstruction(Type *Ty, unsigned iType, Value *V, BasicBlock *IAE)
: Instruction(Ty, iType, &Op<0>(), 1, IAE) {
Op<0>() = V;
}
public:
// allocate space for exactly one operand
void *operator new(size_t s) {
return User::operator new(s, 1);
}
// Out of line virtual method, so the vtable, etc has a home.
~UnaryInstruction();
/// Transparently provide more efficient getOperand methods.
DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
// Methods for support type inquiry through isa, cast, and dyn_cast:
static inline bool classof(const Instruction *I) {
return I->getOpcode() == Instruction::Alloca ||
I->getOpcode() == Instruction::Load ||
I->getOpcode() == Instruction::VAArg ||
I->getOpcode() == Instruction::ExtractValue ||
(I->getOpcode() >= CastOpsBegin && I->getOpcode() < CastOpsEnd);
}
static inline bool classof(const Value *V) {
return isa<Instruction>(V) && classof(cast<Instruction>(V));
}
};
template <>
struct OperandTraits<UnaryInstruction> :
public FixedNumOperandTraits<UnaryInstruction, 1> {
};
DEFINE_TRANSPARENT_OPERAND_ACCESSORS(UnaryInstruction, Value)
//===----------------------------------------------------------------------===//
// BinaryOperator Class
//===----------------------------------------------------------------------===//
class BinaryOperator : public Instruction {
void *operator new(size_t, unsigned) LLVM_DELETED_FUNCTION;
protected:
void init(BinaryOps iType);
BinaryOperator(BinaryOps iType, Value *S1, Value *S2, Type *Ty,
const Twine &Name, Instruction *InsertBefore);
BinaryOperator(BinaryOps iType, Value *S1, Value *S2, Type *Ty,
const Twine &Name, BasicBlock *InsertAtEnd);
virtual BinaryOperator *clone_impl() const LLVM_OVERRIDE;
public:
// allocate space for exactly two operands
void *operator new(size_t s) {
return User::operator new(s, 2);
}
/// Transparently provide more efficient getOperand methods.
DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
/// Create() - Construct a binary instruction, given the opcode and the two
/// operands. Optionally (if InstBefore is specified) insert the instruction
/// into a BasicBlock right before the specified instruction. The specified
/// Instruction is allowed to be a dereferenced end iterator.
///
static BinaryOperator *Create(BinaryOps Op, Value *S1, Value *S2,
const Twine &Name = Twine(),
Instruction *InsertBefore = 0);
/// Create() - Construct a binary instruction, given the opcode and the two
/// operands. Also automatically insert this instruction to the end of the
/// BasicBlock specified.
///
static BinaryOperator *Create(BinaryOps Op, Value *S1, Value *S2,
const Twine &Name, BasicBlock *InsertAtEnd);
/// Create* - These methods just forward to Create, and are useful when you
/// statically know what type of instruction you're going to create. These
/// helpers just save some typing.
#define HANDLE_BINARY_INST(N, OPC, CLASS) \
static BinaryOperator *Create##OPC(Value *V1, Value *V2, \
const Twine &Name = "") {\
return Create(Instruction::OPC, V1, V2, Name);\
}
#include "llvm/IR/Instruction.def"
#define HANDLE_BINARY_INST(N, OPC, CLASS) \
static BinaryOperator *Create##OPC(Value *V1, Value *V2, \
const Twine &Name, BasicBlock *BB) {\
return Create(Instruction::OPC, V1, V2, Name, BB);\
}
#include "llvm/IR/Instruction.def"
#define HANDLE_BINARY_INST(N, OPC, CLASS) \
static BinaryOperator *Create##OPC(Value *V1, Value *V2, \
const Twine &Name, Instruction *I) {\
return Create(Instruction::OPC, V1, V2, Name, I);\
}
#include "llvm/IR/Instruction.def"
static BinaryOperator *CreateNSW(BinaryOps Opc, Value *V1, Value *V2,
const Twine &Name = "") {
BinaryOperator *BO = Create(Opc, V1, V2, Name);
BO->setHasNoSignedWrap(true);
return BO;
}
static BinaryOperator *CreateNSW(BinaryOps Opc, Value *V1, Value *V2,
const Twine &Name, BasicBlock *BB) {
BinaryOperator *BO = Create(Opc, V1, V2, Name, BB);
BO->setHasNoSignedWrap(true);
return BO;
}
static BinaryOperator *CreateNSW(BinaryOps Opc, Value *V1, Value *V2,
const Twine &Name, Instruction *I) {
BinaryOperator *BO = Create(Opc, V1, V2, Name, I);
BO->setHasNoSignedWrap(true);
return BO;
}
static BinaryOperator *CreateNUW(BinaryOps Opc, Value *V1, Value *V2,
const Twine &Name = "") {
BinaryOperator *BO = Create(Opc, V1, V2, Name);
BO->setHasNoUnsignedWrap(true);
return BO;
}
static BinaryOperator *CreateNUW(BinaryOps Opc, Value *V1, Value *V2,
const Twine &Name, BasicBlock *BB) {
BinaryOperator *BO = Create(Opc, V1, V2, Name, BB);
BO->setHasNoUnsignedWrap(true);
return BO;
}
static BinaryOperator *CreateNUW(BinaryOps Opc, Value *V1, Value *V2,
const Twine &Name, Instruction *I) {
BinaryOperator *BO = Create(Opc, V1, V2, Name, I);
BO->setHasNoUnsignedWrap(true);
return BO;
}
static BinaryOperator *CreateExact(BinaryOps Opc, Value *V1, Value *V2,
const Twine &Name = "") {
BinaryOperator *BO = Create(Opc, V1, V2, Name);
BO->setIsExact(true);
return BO;
}
static BinaryOperator *CreateExact(BinaryOps Opc, Value *V1, Value *V2,
const Twine &Name, BasicBlock *BB) {
BinaryOperator *BO = Create(Opc, V1, V2, Name, BB);
BO->setIsExact(true);
return BO;
}
static BinaryOperator *CreateExact(BinaryOps Opc, Value *V1, Value *V2,
const Twine &Name, Instruction *I) {
BinaryOperator *BO = Create(Opc, V1, V2, Name, I);
BO->setIsExact(true);
return BO;
}
#define DEFINE_HELPERS(OPC, NUWNSWEXACT) \
static BinaryOperator *Create ## NUWNSWEXACT ## OPC \
(Value *V1, Value *V2, const Twine &Name = "") { \
return Create ## NUWNSWEXACT(Instruction::OPC, V1, V2, Name); \
} \
static BinaryOperator *Create ## NUWNSWEXACT ## OPC \
(Value *V1, Value *V2, const Twine &Name, BasicBlock *BB) { \
return Create ## NUWNSWEXACT(Instruction::OPC, V1, V2, Name, BB); \
} \
static BinaryOperator *Create ## NUWNSWEXACT ## OPC \
(Value *V1, Value *V2, const Twine &Name, Instruction *I) { \
return Create ## NUWNSWEXACT(Instruction::OPC, V1, V2, Name, I); \
}
DEFINE_HELPERS(Add, NSW) // CreateNSWAdd
DEFINE_HELPERS(Add, NUW) // CreateNUWAdd
DEFINE_HELPERS(Sub, NSW) // CreateNSWSub
DEFINE_HELPERS(Sub, NUW) // CreateNUWSub
DEFINE_HELPERS(Mul, NSW) // CreateNSWMul
DEFINE_HELPERS(Mul, NUW) // CreateNUWMul
DEFINE_HELPERS(Shl, NSW) // CreateNSWShl
DEFINE_HELPERS(Shl, NUW) // CreateNUWShl
DEFINE_HELPERS(SDiv, Exact) // CreateExactSDiv
DEFINE_HELPERS(UDiv, Exact) // CreateExactUDiv
DEFINE_HELPERS(AShr, Exact) // CreateExactAShr
DEFINE_HELPERS(LShr, Exact) // CreateExactLShr
#undef DEFINE_HELPERS
/// Helper functions to construct and inspect unary operations (NEG and NOT)
/// via binary operators SUB and XOR:
///
/// CreateNeg, CreateNot - Create the NEG and NOT
/// instructions out of SUB and XOR instructions.
///
static BinaryOperator *CreateNeg(Value *Op, const Twine &Name = "",
Instruction *InsertBefore = 0);
static BinaryOperator *CreateNeg(Value *Op, const Twine &Name,
BasicBlock *InsertAtEnd);
static BinaryOperator *CreateNSWNeg(Value *Op, const Twine &Name = "",
Instruction *InsertBefore = 0);
static BinaryOperator *CreateNSWNeg(Value *Op, const Twine &Name,
BasicBlock *InsertAtEnd);
static BinaryOperator *CreateNUWNeg(Value *Op, const Twine &Name = "",
Instruction *InsertBefore = 0);
static BinaryOperator *CreateNUWNeg(Value *Op, const Twine &Name,
BasicBlock *InsertAtEnd);
static BinaryOperator *CreateFNeg(Value *Op, const Twine &Name = "",
Instruction *InsertBefore = 0);
static BinaryOperator *CreateFNeg(Value *Op, const Twine &Name,
BasicBlock *InsertAtEnd);
static BinaryOperator *CreateNot(Value *Op, const Twine &Name = "",
Instruction *InsertBefore = 0);
static BinaryOperator *CreateNot(Value *Op, const Twine &Name,
BasicBlock *InsertAtEnd);
/// isNeg, isFNeg, isNot - Check if the given Value is a
/// NEG, FNeg, or NOT instruction.
///
static bool isNeg(const Value *V);
static bool isFNeg(const Value *V, bool IgnoreZeroSign=false);
static bool isNot(const Value *V);
/// getNegArgument, getNotArgument - Helper functions to extract the
/// unary argument of a NEG, FNEG or NOT operation implemented via
/// Sub, FSub, or Xor.
///
static const Value *getNegArgument(const Value *BinOp);
static Value *getNegArgument( Value *BinOp);
static const Value *getFNegArgument(const Value *BinOp);
static Value *getFNegArgument( Value *BinOp);
static const Value *getNotArgument(const Value *BinOp);
static Value *getNotArgument( Value *BinOp);
BinaryOps getOpcode() const {
return static_cast<BinaryOps>(Instruction::getOpcode());
}
/// swapOperands - Exchange the two operands to this instruction.
/// This instruction is safe to use on any binary instruction and
/// does not modify the semantics of the instruction. If the instruction
/// cannot be reversed (ie, it's a Div), then return true.
///
bool swapOperands();
/// setHasNoUnsignedWrap - Set or clear the nsw flag on this instruction,
/// which must be an operator which supports this flag. See LangRef.html
/// for the meaning of this flag.
void setHasNoUnsignedWrap(bool b = true);
/// setHasNoSignedWrap - Set or clear the nsw flag on this instruction,
/// which must be an operator which supports this flag. See LangRef.html
/// for the meaning of this flag.
void setHasNoSignedWrap(bool b = true);
/// setIsExact - Set or clear the exact flag on this instruction,
/// which must be an operator which supports this flag. See LangRef.html
/// for the meaning of this flag.
void setIsExact(bool b = true);
/// hasNoUnsignedWrap - Determine whether the no unsigned wrap flag is set.
bool hasNoUnsignedWrap() const;
/// hasNoSignedWrap - Determine whether the no signed wrap flag is set.
bool hasNoSignedWrap() const;
/// isExact - Determine whether the exact flag is set.
bool isExact() const;
// Methods for support type inquiry through isa, cast, and dyn_cast:
static inline bool classof(const Instruction *I) {
return I->isBinaryOp();
}
static inline bool classof(const Value *V) {
return isa<Instruction>(V) && classof(cast<Instruction>(V));
}
};
template <>
struct OperandTraits<BinaryOperator> :
public FixedNumOperandTraits<BinaryOperator, 2> {
};
DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BinaryOperator, Value)
//===----------------------------------------------------------------------===//
// CastInst Class
//===----------------------------------------------------------------------===//
/// CastInst - This is the base class for all instructions that perform data
/// casts. It is simply provided so that instruction category testing
/// can be performed with code like:
///
/// if (isa<CastInst>(Instr)) { ... }
/// @brief Base class of casting instructions.
class CastInst : public UnaryInstruction {
virtual void anchor() LLVM_OVERRIDE;
protected:
/// @brief Constructor with insert-before-instruction semantics for subclasses
CastInst(Type *Ty, unsigned iType, Value *S,
const Twine &NameStr = "", Instruction *InsertBefore = 0)
: UnaryInstruction(Ty, iType, S, InsertBefore) {
setName(NameStr);
}
/// @brief Constructor with insert-at-end-of-block semantics for subclasses
CastInst(Type *Ty, unsigned iType, Value *S,
const Twine &NameStr, BasicBlock *InsertAtEnd)
: UnaryInstruction(Ty, iType, S, InsertAtEnd) {
setName(NameStr);
}
public:
/// Provides a way to construct any of the CastInst subclasses using an
/// opcode instead of the subclass's constructor. The opcode must be in the
/// CastOps category (Instruction::isCast(opcode) returns true). This
/// constructor has insert-before-instruction semantics to automatically
/// insert the new CastInst before InsertBefore (if it is non-null).
/// @brief Construct any of the CastInst subclasses
static CastInst *Create(
Instruction::CastOps, ///< The opcode of the cast instruction
Value *S, ///< The value to be casted (operand 0)
Type *Ty, ///< The type to which cast should be made
const Twine &Name = "", ///< Name for the instruction
Instruction *InsertBefore = 0 ///< Place to insert the instruction
);
/// Provides a way to construct any of the CastInst subclasses using an
/// opcode instead of the subclass's constructor. The opcode must be in the
/// CastOps category. This constructor has insert-at-end-of-block semantics
/// to automatically insert the new CastInst at the end of InsertAtEnd (if
/// its non-null).
/// @brief Construct any of the CastInst subclasses
static CastInst *Create(
Instruction::CastOps, ///< The opcode for the cast instruction
Value *S, ///< The value to be casted (operand 0)
Type *Ty, ///< The type to which operand is casted
const Twine &Name, ///< The name for the instruction
BasicBlock *InsertAtEnd ///< The block to insert the instruction into
);
/// @brief Create a ZExt or BitCast cast instruction
static CastInst *CreateZExtOrBitCast(
Value *S, ///< The value to be casted (operand 0)
Type *Ty, ///< The type to which cast should be made
const Twine &Name = "", ///< Name for the instruction
Instruction *InsertBefore = 0 ///< Place to insert the instruction
);
/// @brief Create a ZExt or BitCast cast instruction
static CastInst *CreateZExtOrBitCast(
Value *S, ///< The value to be casted (operand 0)
Type *Ty, ///< The type to which operand is casted
const Twine &Name, ///< The name for the instruction
BasicBlock *InsertAtEnd ///< The block to insert the instruction into
);
/// @brief Create a SExt or BitCast cast instruction
static CastInst *CreateSExtOrBitCast(
Value *S, ///< The value to be casted (operand 0)
Type *Ty, ///< The type to which cast should be made
const Twine &Name = "", ///< Name for the instruction
Instruction *InsertBefore = 0 ///< Place to insert the instruction
);
/// @brief Create a SExt or BitCast cast instruction
static CastInst *CreateSExtOrBitCast(
Value *S, ///< The value to be casted (operand 0)
Type *Ty, ///< The type to which operand is casted
const Twine &Name, ///< The name for the instruction
BasicBlock *InsertAtEnd ///< The block to insert the instruction into
);
/// @brief Create a BitCast or a PtrToInt cast instruction
static CastInst *CreatePointerCast(
Value *S, ///< The pointer value to be casted (operand 0)
Type *Ty, ///< The type to which operand is casted
const Twine &Name, ///< The name for the instruction
BasicBlock *InsertAtEnd ///< The block to insert the instruction into
);
/// @brief Create a BitCast or a PtrToInt cast instruction
static CastInst *CreatePointerCast(
Value *S, ///< The pointer value to be casted (operand 0)
Type *Ty, ///< The type to which cast should be made
const Twine &Name = "", ///< Name for the instruction
Instruction *InsertBefore = 0 ///< Place to insert the instruction
);
/// @brief Create a ZExt, BitCast, or Trunc for int -> int casts.
static CastInst *CreateIntegerCast(
Value *S, ///< The pointer value to be casted (operand 0)
Type *Ty, ///< The type to which cast should be made
bool isSigned, ///< Whether to regard S as signed or not
const Twine &Name = "", ///< Name for the instruction
Instruction *InsertBefore = 0 ///< Place to insert the instruction
);
/// @brief Create a ZExt, BitCast, or Trunc for int -> int casts.
static CastInst *CreateIntegerCast(
Value *S, ///< The integer value to be casted (operand 0)
Type *Ty, ///< The integer type to which operand is casted
bool isSigned, ///< Whether to regard S as signed or not
const Twine &Name, ///< The name for the instruction
BasicBlock *InsertAtEnd ///< The block to insert the instruction into
);
/// @brief Create an FPExt, BitCast, or FPTrunc for fp -> fp casts
static CastInst *CreateFPCast(
Value *S, ///< The floating point value to be casted
Type *Ty, ///< The floating point type to cast to
const Twine &Name = "", ///< Name for the instruction
Instruction *InsertBefore = 0 ///< Place to insert the instruction
);
/// @brief Create an FPExt, BitCast, or FPTrunc for fp -> fp casts
static CastInst *CreateFPCast(
Value *S, ///< The floating point value to be casted
Type *Ty, ///< The floating point type to cast to
const Twine &Name, ///< The name for the instruction
BasicBlock *InsertAtEnd ///< The block to insert the instruction into
);
/// @brief Create a Trunc or BitCast cast instruction
static CastInst *CreateTruncOrBitCast(
Value *S, ///< The value to be casted (operand 0)
Type *Ty, ///< The type to which cast should be made
const Twine &Name = "", ///< Name for the instruction
Instruction *InsertBefore = 0 ///< Place to insert the instruction
);
/// @brief Create a Trunc or BitCast cast instruction
static CastInst *CreateTruncOrBitCast(
Value *S, ///< The value to be casted (operand 0)
Type *Ty, ///< The type to which operand is casted
const Twine &Name, ///< The name for the instruction
BasicBlock *InsertAtEnd ///< The block to insert the instruction into
);
/// @brief Check whether it is valid to call getCastOpcode for these types.
static bool isCastable(
Type *SrcTy, ///< The Type from which the value should be cast.
Type *DestTy ///< The Type to which the value should be cast.
);
/// Returns the opcode necessary to cast Val into Ty using usual casting
/// rules.
/// @brief Infer the opcode for cast operand and type
static Instruction::CastOps getCastOpcode(
const Value *Val, ///< The value to cast
bool SrcIsSigned, ///< Whether to treat the source as signed
Type *Ty, ///< The Type to which the value should be casted
bool DstIsSigned ///< Whether to treate the dest. as signed
);
/// There are several places where we need to know if a cast instruction
/// only deals with integer source and destination types. To simplify that
/// logic, this method is provided.
/// @returns true iff the cast has only integral typed operand and dest type.
/// @brief Determine if this is an integer-only cast.
bool isIntegerCast() const;
/// A lossless cast is one that does not alter the basic value. It implies
/// a no-op cast but is more stringent, preventing things like int->float,
/// long->double, or int->ptr.
/// @returns true iff the cast is lossless.
/// @brief Determine if this is a lossless cast.
bool isLosslessCast() const;
/// A no-op cast is one that can be effected without changing any bits.
/// It implies that the source and destination types are the same size. The
/// IntPtrTy argument is used to make accurate determinations for casts
/// involving Integer and Pointer types. They are no-op casts if the integer
/// is the same size as the pointer. However, pointer size varies with
/// platform. Generally, the result of DataLayout::getIntPtrType() should be
/// passed in. If that's not available, use Type::Int64Ty, which will make
/// the isNoopCast call conservative.
/// @brief Determine if the described cast is a no-op cast.
static bool isNoopCast(
Instruction::CastOps Opcode, ///< Opcode of cast
Type *SrcTy, ///< SrcTy of cast
Type *DstTy, ///< DstTy of cast
Type *IntPtrTy ///< Integer type corresponding to Ptr types, or null
);
/// @brief Determine if this cast is a no-op cast.
bool isNoopCast(
Type *IntPtrTy ///< Integer type corresponding to pointer
) const;
/// Determine how a pair of casts can be eliminated, if they can be at all.
/// This is a helper function for both CastInst and ConstantExpr.
/// @returns 0 if the CastInst pair can't be eliminated, otherwise
/// returns Instruction::CastOps value for a cast that can replace
/// the pair, casting SrcTy to DstTy.
/// @brief Determine if a cast pair is eliminable
static unsigned isEliminableCastPair(
Instruction::CastOps firstOpcode, ///< Opcode of first cast
Instruction::CastOps secondOpcode, ///< Opcode of second cast
Type *SrcTy, ///< SrcTy of 1st cast
Type *MidTy, ///< DstTy of 1st cast & SrcTy of 2nd cast
Type *DstTy, ///< DstTy of 2nd cast
Type *SrcIntPtrTy, ///< Integer type corresponding to Ptr SrcTy, or null
Type *MidIntPtrTy, ///< Integer type corresponding to Ptr MidTy, or null
Type *DstIntPtrTy ///< Integer type corresponding to Ptr DstTy, or null
);
/// @brief Return the opcode of this CastInst
Instruction::CastOps getOpcode() const {
return Instruction::CastOps(Instruction::getOpcode());
}
/// @brief Return the source type, as a convenience
Type* getSrcTy() const { return getOperand(0)->getType(); }
/// @brief Return the destination type, as a convenience
Type* getDestTy() const { return getType(); }
/// This method can be used to determine if a cast from S to DstTy using
/// Opcode op is valid or not.
/// @returns true iff the proposed cast is valid.
/// @brief Determine if a cast is valid without creating one.
static bool castIsValid(Instruction::CastOps op, Value *S, Type *DstTy);
/// @brief Methods for support type inquiry through isa, cast, and dyn_cast:
static inline bool classof(const Instruction *I) {
return I->isCast();
}
static inline bool classof(const Value *V) {
return isa<Instruction>(V) && classof(cast<Instruction>(V));
}
};
//===----------------------------------------------------------------------===//
// CmpInst Class
//===----------------------------------------------------------------------===//
/// This class is the base class for the comparison instructions.
/// @brief Abstract base class of comparison instructions.
class CmpInst : public Instruction {
void *operator new(size_t, unsigned) LLVM_DELETED_FUNCTION;
CmpInst() LLVM_DELETED_FUNCTION;
protected:
CmpInst(Type *ty, Instruction::OtherOps op, unsigned short pred,
Value *LHS, Value *RHS, const Twine &Name = "",
Instruction *InsertBefore = 0);
CmpInst(Type *ty, Instruction::OtherOps op, unsigned short pred,
Value *LHS, Value *RHS, const Twine &Name,
BasicBlock *InsertAtEnd);
virtual void anchor() LLVM_OVERRIDE; // Out of line virtual method.
public:
/// This enumeration lists the possible predicates for CmpInst subclasses.
/// Values in the range 0-31 are reserved for FCmpInst, while values in the
/// range 32-64 are reserved for ICmpInst. This is necessary to ensure the
/// predicate values are not overlapping between the classes.
enum Predicate {
// Opcode U L G E Intuitive operation
FCMP_FALSE = 0, ///< 0 0 0 0 Always false (always folded)
FCMP_OEQ = 1, ///< 0 0 0 1 True if ordered and equal
FCMP_OGT = 2, ///< 0 0 1 0 True if ordered and greater than
FCMP_OGE = 3, ///< 0 0 1 1 True if ordered and greater than or equal
FCMP_OLT = 4, ///< 0 1 0 0 True if ordered and less than
FCMP_OLE = 5, ///< 0 1 0 1 True if ordered and less than or equal
FCMP_ONE = 6, ///< 0 1 1 0 True if ordered and operands are unequal
FCMP_ORD = 7, ///< 0 1 1 1 True if ordered (no nans)
FCMP_UNO = 8, ///< 1 0 0 0 True if unordered: isnan(X) | isnan(Y)
FCMP_UEQ = 9, ///< 1 0 0 1 True if unordered or equal
FCMP_UGT = 10, ///< 1 0 1 0 True if unordered or greater than
FCMP_UGE = 11, ///< 1 0 1 1 True if unordered, greater than, or equal
FCMP_ULT = 12, ///< 1 1 0 0 True if unordered or less than
FCMP_ULE = 13, ///< 1 1 0 1 True if unordered, less than, or equal
FCMP_UNE = 14, ///< 1 1 1 0 True if unordered or not equal
FCMP_TRUE = 15, ///< 1 1 1 1 Always true (always folded)
FIRST_FCMP_PREDICATE = FCMP_FALSE,
LAST_FCMP_PREDICATE = FCMP_TRUE,
BAD_FCMP_PREDICATE = FCMP_TRUE + 1,
ICMP_EQ = 32, ///< equal
ICMP_NE = 33, ///< not equal
ICMP_UGT = 34, ///< unsigned greater than
ICMP_UGE = 35, ///< unsigned greater or equal
ICMP_ULT = 36, ///< unsigned less than
ICMP_ULE = 37, ///< unsigned less or equal
ICMP_SGT = 38, ///< signed greater than
ICMP_SGE = 39, ///< signed greater or equal
ICMP_SLT = 40, ///< signed less than
ICMP_SLE = 41, ///< signed less or equal
FIRST_ICMP_PREDICATE = ICMP_EQ,
LAST_ICMP_PREDICATE = ICMP_SLE,
BAD_ICMP_PREDICATE = ICMP_SLE + 1
};
// allocate space for exactly two operands
void *operator new(size_t s) {
return User::operator new(s, 2);
}
/// Construct a compare instruction, given the opcode, the predicate and
/// the two operands. Optionally (if InstBefore is specified) insert the
/// instruction into a BasicBlock right before the specified instruction.
/// The specified Instruction is allowed to be a dereferenced end iterator.
/// @brief Create a CmpInst
static CmpInst *Create(OtherOps Op,
unsigned short predicate, Value *S1,
Value *S2, const Twine &Name = "",
Instruction *InsertBefore = 0);
/// Construct a compare instruction, given the opcode, the predicate and the
/// two operands. Also automatically insert this instruction to the end of
/// the BasicBlock specified.
/// @brief Create a CmpInst
static CmpInst *Create(OtherOps Op, unsigned short predicate, Value *S1,
Value *S2, const Twine &Name, BasicBlock *InsertAtEnd);
/// @brief Get the opcode casted to the right type
OtherOps getOpcode() const {
return static_cast<OtherOps>(Instruction::getOpcode());
}
/// @brief Return the predicate for this instruction.
Predicate getPredicate() const {
return Predicate(getSubclassDataFromInstruction());
}
/// @brief Set the predicate for this instruction to the specified value.
void setPredicate(Predicate P) { setInstructionSubclassData(P); }
static bool isFPPredicate(Predicate P) {
return P >= FIRST_FCMP_PREDICATE && P <= LAST_FCMP_PREDICATE;
}
static bool isIntPredicate(Predicate P) {
return P >= FIRST_ICMP_PREDICATE && P <= LAST_ICMP_PREDICATE;
}
bool isFPPredicate() const { return isFPPredicate(getPredicate()); }
bool isIntPredicate() const { return isIntPredicate(getPredicate()); }
/// For example, EQ -> NE, UGT -> ULE, SLT -> SGE,
/// OEQ -> UNE, UGT -> OLE, OLT -> UGE, etc.
/// @returns the inverse predicate for the instruction's current predicate.
/// @brief Return the inverse of the instruction's predicate.
Predicate getInversePredicate() const {
return getInversePredicate(getPredicate());
}
/// For example, EQ -> NE, UGT -> ULE, SLT -> SGE,
/// OEQ -> UNE, UGT -> OLE, OLT -> UGE, etc.
/// @returns the inverse predicate for predicate provided in \p pred.
/// @brief Return the inverse of a given predicate
static Predicate getInversePredicate(Predicate pred);
/// For example, EQ->EQ, SLE->SGE, ULT->UGT,
/// OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
/// @returns the predicate that would be the result of exchanging the two
/// operands of the CmpInst instruction without changing the result
/// produced.
/// @brief Return the predicate as if the operands were swapped
Predicate getSwappedPredicate() const {
return getSwappedPredicate(getPredicate());
}
/// This is a static version that you can use without an instruction
/// available.
/// @brief Return the predicate as if the operands were swapped.
static Predicate getSwappedPredicate(Predicate pred);
/// @brief Provide more efficient getOperand methods.
DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
/// This is just a convenience that dispatches to the subclasses.
/// @brief Swap the operands and adjust predicate accordingly to retain
/// the same comparison.
void swapOperands();
/// This is just a convenience that dispatches to the subclasses.
/// @brief Determine if this CmpInst is commutative.
bool isCommutative() const;
/// This is just a convenience that dispatches to the subclasses.
/// @brief Determine if this is an equals/not equals predicate.
bool isEquality() const;
/// @returns true if the comparison is signed, false otherwise.
/// @brief Determine if this instruction is using a signed comparison.
bool isSigned() const {
return isSigned(getPredicate());
}
/// @returns true if the comparison is unsigned, false otherwise.
/// @brief Determine if this instruction is using an unsigned comparison.
bool isUnsigned() const {
return isUnsigned(getPredicate());
}
/// This is just a convenience.
/// @brief Determine if this is true when both operands are the same.
bool isTrueWhenEqual() const {
return isTrueWhenEqual(getPredicate());
}
/// This is just a convenience.
/// @brief Determine if this is false when both operands are the same.
bool isFalseWhenEqual() const {
return isFalseWhenEqual(getPredicate());
}
/// @returns true if the predicate is unsigned, false otherwise.
/// @brief Determine if the predicate is an unsigned operation.
static bool isUnsigned(unsigned short predicate);
/// @returns true if the predicate is signed, false otherwise.
/// @brief Determine if the predicate is an signed operation.
static bool isSigned(unsigned short predicate);
/// @brief Determine if the predicate is an ordered operation.
static bool isOrdered(unsigned short predicate);
/// @brief Determine if the predicate is an unordered operation.
static bool isUnordered(unsigned short predicate);
/// Determine if the predicate is true when comparing a value with itself.
static bool isTrueWhenEqual(unsigned short predicate);
/// Determine if the predicate is false when comparing a value with itself.
static bool isFalseWhenEqual(unsigned short predicate);
/// @brief Methods for support type inquiry through isa, cast, and dyn_cast:
static inline bool classof(const Instruction *I) {
return I->getOpcode() == Instruction::ICmp ||
I->getOpcode() == Instruction::FCmp;
}
static inline bool classof(const Value *V) {
return isa<Instruction>(V) && classof(cast<Instruction>(V));
}
/// @brief Create a result type for fcmp/icmp
static Type* makeCmpResultType(Type* opnd_type) {
if (VectorType* vt = dyn_cast<VectorType>(opnd_type)) {
return VectorType::get(Type::getInt1Ty(opnd_type->getContext()),
vt->getNumElements());
}
return Type::getInt1Ty(opnd_type->getContext());
}
private:
// Shadow Value::setValueSubclassData with a private forwarding method so that
// subclasses cannot accidentally use it.
void setValueSubclassData(unsigned short D) {
Value::setValueSubclassData(D);
}
};
// FIXME: these are redundant if CmpInst < BinaryOperator
template <>
struct OperandTraits<CmpInst> : public FixedNumOperandTraits<CmpInst, 2> {
};
DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CmpInst, Value)
} // End llvm namespace
#endif

View File

@@ -0,0 +1,199 @@
//===-- llvm/Instruction.def - File that describes Instructions -*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains descriptions of the various LLVM instructions. This is
// used as a central place for enumerating the different instructions and
// should eventually be the place to put comments about the instructions.
//
//===----------------------------------------------------------------------===//
// NOTE: NO INCLUDE GUARD DESIRED!
// Provide definitions of macros so that users of this file do not have to
// define everything to use it...
//
#ifndef FIRST_TERM_INST
#define FIRST_TERM_INST(num)
#endif
#ifndef HANDLE_TERM_INST
#ifndef HANDLE_INST
#define HANDLE_TERM_INST(num, opcode, Class)
#else
#define HANDLE_TERM_INST(num, opcode, Class) HANDLE_INST(num, opcode, Class)
#endif
#endif
#ifndef LAST_TERM_INST
#define LAST_TERM_INST(num)
#endif
#ifndef FIRST_BINARY_INST
#define FIRST_BINARY_INST(num)
#endif
#ifndef HANDLE_BINARY_INST
#ifndef HANDLE_INST
#define HANDLE_BINARY_INST(num, opcode, instclass)
#else
#define HANDLE_BINARY_INST(num, opcode, Class) HANDLE_INST(num, opcode, Class)
#endif
#endif
#ifndef LAST_BINARY_INST
#define LAST_BINARY_INST(num)
#endif
#ifndef FIRST_MEMORY_INST
#define FIRST_MEMORY_INST(num)
#endif
#ifndef HANDLE_MEMORY_INST
#ifndef HANDLE_INST
#define HANDLE_MEMORY_INST(num, opcode, Class)
#else
#define HANDLE_MEMORY_INST(num, opcode, Class) HANDLE_INST(num, opcode, Class)
#endif
#endif
#ifndef LAST_MEMORY_INST
#define LAST_MEMORY_INST(num)
#endif
#ifndef FIRST_CAST_INST
#define FIRST_CAST_INST(num)
#endif
#ifndef HANDLE_CAST_INST
#ifndef HANDLE_INST
#define HANDLE_CAST_INST(num, opcode, Class)
#else
#define HANDLE_CAST_INST(num, opcode, Class) HANDLE_INST(num, opcode, Class)
#endif
#endif
#ifndef LAST_CAST_INST
#define LAST_CAST_INST(num)
#endif
#ifndef FIRST_OTHER_INST
#define FIRST_OTHER_INST(num)
#endif
#ifndef HANDLE_OTHER_INST
#ifndef HANDLE_INST
#define HANDLE_OTHER_INST(num, opcode, Class)
#else
#define HANDLE_OTHER_INST(num, opcode, Class) HANDLE_INST(num, opcode, Class)
#endif
#endif
#ifndef LAST_OTHER_INST
#define LAST_OTHER_INST(num)
#endif
// Terminator Instructions - These instructions are used to terminate a basic
// block of the program. Every basic block must end with one of these
// instructions for it to be a well formed basic block.
//
FIRST_TERM_INST ( 1)
HANDLE_TERM_INST ( 1, Ret , ReturnInst)
HANDLE_TERM_INST ( 2, Br , BranchInst)
HANDLE_TERM_INST ( 3, Switch , SwitchInst)
HANDLE_TERM_INST ( 4, IndirectBr , IndirectBrInst)
HANDLE_TERM_INST ( 5, Invoke , InvokeInst)
HANDLE_TERM_INST ( 6, Resume , ResumeInst)
HANDLE_TERM_INST ( 7, Unreachable, UnreachableInst)
LAST_TERM_INST ( 7)
// Standard binary operators...
FIRST_BINARY_INST( 8)
HANDLE_BINARY_INST( 8, Add , BinaryOperator)
HANDLE_BINARY_INST( 9, FAdd , BinaryOperator)
HANDLE_BINARY_INST(10, Sub , BinaryOperator)
HANDLE_BINARY_INST(11, FSub , BinaryOperator)
HANDLE_BINARY_INST(12, Mul , BinaryOperator)
HANDLE_BINARY_INST(13, FMul , BinaryOperator)
HANDLE_BINARY_INST(14, UDiv , BinaryOperator)
HANDLE_BINARY_INST(15, SDiv , BinaryOperator)
HANDLE_BINARY_INST(16, FDiv , BinaryOperator)
HANDLE_BINARY_INST(17, URem , BinaryOperator)
HANDLE_BINARY_INST(18, SRem , BinaryOperator)
HANDLE_BINARY_INST(19, FRem , BinaryOperator)
// Logical operators (integer operands)
HANDLE_BINARY_INST(20, Shl , BinaryOperator) // Shift left (logical)
HANDLE_BINARY_INST(21, LShr , BinaryOperator) // Shift right (logical)
HANDLE_BINARY_INST(22, AShr , BinaryOperator) // Shift right (arithmetic)
HANDLE_BINARY_INST(23, And , BinaryOperator)
HANDLE_BINARY_INST(24, Or , BinaryOperator)
HANDLE_BINARY_INST(25, Xor , BinaryOperator)
LAST_BINARY_INST(25)
// Memory operators...
FIRST_MEMORY_INST(26)
HANDLE_MEMORY_INST(26, Alloca, AllocaInst) // Stack management
HANDLE_MEMORY_INST(27, Load , LoadInst ) // Memory manipulation instrs
HANDLE_MEMORY_INST(28, Store , StoreInst )
HANDLE_MEMORY_INST(29, GetElementPtr, GetElementPtrInst)
HANDLE_MEMORY_INST(30, Fence , FenceInst )
HANDLE_MEMORY_INST(31, AtomicCmpXchg , AtomicCmpXchgInst )
HANDLE_MEMORY_INST(32, AtomicRMW , AtomicRMWInst )
LAST_MEMORY_INST(32)
// Cast operators ...
// NOTE: The order matters here because CastInst::isEliminableCastPair
// NOTE: (see Instructions.cpp) encodes a table based on this ordering.
FIRST_CAST_INST(33)
HANDLE_CAST_INST(33, Trunc , TruncInst ) // Truncate integers
HANDLE_CAST_INST(34, ZExt , ZExtInst ) // Zero extend integers
HANDLE_CAST_INST(35, SExt , SExtInst ) // Sign extend integers
HANDLE_CAST_INST(36, FPToUI , FPToUIInst ) // floating point -> UInt
HANDLE_CAST_INST(37, FPToSI , FPToSIInst ) // floating point -> SInt
HANDLE_CAST_INST(38, UIToFP , UIToFPInst ) // UInt -> floating point
HANDLE_CAST_INST(39, SIToFP , SIToFPInst ) // SInt -> floating point
HANDLE_CAST_INST(40, FPTrunc , FPTruncInst ) // Truncate floating point
HANDLE_CAST_INST(41, FPExt , FPExtInst ) // Extend floating point
HANDLE_CAST_INST(42, PtrToInt, PtrToIntInst) // Pointer -> Integer
HANDLE_CAST_INST(43, IntToPtr, IntToPtrInst) // Integer -> Pointer
HANDLE_CAST_INST(44, BitCast , BitCastInst ) // Type cast
LAST_CAST_INST(44)
// Other operators...
FIRST_OTHER_INST(45)
HANDLE_OTHER_INST(45, ICmp , ICmpInst ) // Integer comparison instruction
HANDLE_OTHER_INST(46, FCmp , FCmpInst ) // Floating point comparison instr.
HANDLE_OTHER_INST(47, PHI , PHINode ) // PHI node instruction
HANDLE_OTHER_INST(48, Call , CallInst ) // Call a function
HANDLE_OTHER_INST(49, Select , SelectInst ) // select instruction
HANDLE_OTHER_INST(50, UserOp1, Instruction) // May be used internally in a pass
HANDLE_OTHER_INST(51, UserOp2, Instruction) // Internal to passes only
HANDLE_OTHER_INST(52, VAArg , VAArgInst ) // vaarg instruction
HANDLE_OTHER_INST(53, ExtractElement, ExtractElementInst)// extract from vector
HANDLE_OTHER_INST(54, InsertElement, InsertElementInst) // insert into vector
HANDLE_OTHER_INST(55, ShuffleVector, ShuffleVectorInst) // shuffle two vectors.
HANDLE_OTHER_INST(56, ExtractValue, ExtractValueInst)// extract from aggregate
HANDLE_OTHER_INST(57, InsertValue, InsertValueInst) // insert into aggregate
HANDLE_OTHER_INST(58, LandingPad, LandingPadInst) // Landing pad instruction.
LAST_OTHER_INST(58)
#undef FIRST_TERM_INST
#undef HANDLE_TERM_INST
#undef LAST_TERM_INST
#undef FIRST_BINARY_INST
#undef HANDLE_BINARY_INST
#undef LAST_BINARY_INST
#undef FIRST_MEMORY_INST
#undef HANDLE_MEMORY_INST
#undef LAST_MEMORY_INST
#undef FIRST_CAST_INST
#undef HANDLE_CAST_INST
#undef LAST_CAST_INST
#undef FIRST_OTHER_INST
#undef HANDLE_OTHER_INST
#undef LAST_OTHER_INST
#ifdef HANDLE_INST
#undef HANDLE_INST
#endif

View File

@@ -0,0 +1,467 @@
//===-- llvm/Instruction.h - Instruction class definition -------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains the declaration of the Instruction class, which is the
// base class for all of the LLVM instructions.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_IR_INSTRUCTION_H
#define LLVM_IR_INSTRUCTION_H
#include "llvm/ADT/ilist_node.h"
#include "llvm/IR/User.h"
#include "llvm/Support/DebugLoc.h"
namespace llvm {
class FastMathFlags;
class LLVMContext;
class MDNode;
template<typename ValueSubClass, typename ItemParentClass>
class SymbolTableListTraits;
class Instruction : public User, public ilist_node<Instruction> {
void operator=(const Instruction &) LLVM_DELETED_FUNCTION;
Instruction(const Instruction &) LLVM_DELETED_FUNCTION;
BasicBlock *Parent;
DebugLoc DbgLoc; // 'dbg' Metadata cache.
enum {
/// HasMetadataBit - This is a bit stored in the SubClassData field which
/// indicates whether this instruction has metadata attached to it or not.
HasMetadataBit = 1 << 15
};
public:
// Out of line virtual method, so the vtable, etc has a home.
~Instruction();
/// use_back - Specialize the methods defined in Value, as we know that an
/// instruction can only be used by other instructions.
Instruction *use_back() { return cast<Instruction>(*use_begin());}
const Instruction *use_back() const { return cast<Instruction>(*use_begin());}
inline const BasicBlock *getParent() const { return Parent; }
inline BasicBlock *getParent() { return Parent; }
/// removeFromParent - This method unlinks 'this' from the containing basic
/// block, but does not delete it.
///
void removeFromParent();
/// eraseFromParent - This method unlinks 'this' from the containing basic
/// block and deletes it.
///
void eraseFromParent();
/// insertBefore - Insert an unlinked instructions into a basic block
/// immediately before the specified instruction.
void insertBefore(Instruction *InsertPos);
/// insertAfter - Insert an unlinked instructions into a basic block
/// immediately after the specified instruction.
void insertAfter(Instruction *InsertPos);
/// moveBefore - Unlink this instruction from its current basic block and
/// insert it into the basic block that MovePos lives in, right before
/// MovePos.
void moveBefore(Instruction *MovePos);
//===--------------------------------------------------------------------===//
// Subclass classification.
//===--------------------------------------------------------------------===//
/// getOpcode() returns a member of one of the enums like Instruction::Add.
unsigned getOpcode() const { return getValueID() - InstructionVal; }
const char *getOpcodeName() const { return getOpcodeName(getOpcode()); }
bool isTerminator() const { return isTerminator(getOpcode()); }
bool isBinaryOp() const { return isBinaryOp(getOpcode()); }
bool isShift() { return isShift(getOpcode()); }
bool isCast() const { return isCast(getOpcode()); }
static const char* getOpcodeName(unsigned OpCode);
static inline bool isTerminator(unsigned OpCode) {
return OpCode >= TermOpsBegin && OpCode < TermOpsEnd;
}
static inline bool isBinaryOp(unsigned Opcode) {
return Opcode >= BinaryOpsBegin && Opcode < BinaryOpsEnd;
}
/// @brief Determine if the Opcode is one of the shift instructions.
static inline bool isShift(unsigned Opcode) {
return Opcode >= Shl && Opcode <= AShr;
}
/// isLogicalShift - Return true if this is a logical shift left or a logical
/// shift right.
inline bool isLogicalShift() const {
return getOpcode() == Shl || getOpcode() == LShr;
}
/// isArithmeticShift - Return true if this is an arithmetic shift right.
inline bool isArithmeticShift() const {
return getOpcode() == AShr;
}
/// @brief Determine if the OpCode is one of the CastInst instructions.
static inline bool isCast(unsigned OpCode) {
return OpCode >= CastOpsBegin && OpCode < CastOpsEnd;
}
//===--------------------------------------------------------------------===//
// Metadata manipulation.
//===--------------------------------------------------------------------===//
/// hasMetadata() - Return true if this instruction has any metadata attached
/// to it.
bool hasMetadata() const {
return !DbgLoc.isUnknown() || hasMetadataHashEntry();
}
/// hasMetadataOtherThanDebugLoc - Return true if this instruction has
/// metadata attached to it other than a debug location.
bool hasMetadataOtherThanDebugLoc() const {
return hasMetadataHashEntry();
}
/// getMetadata - Get the metadata of given kind attached to this Instruction.
/// If the metadata is not found then return null.
MDNode *getMetadata(unsigned KindID) const {
if (!hasMetadata()) return 0;
return getMetadataImpl(KindID);
}
/// getMetadata - Get the metadata of given kind attached to this Instruction.
/// If the metadata is not found then return null.
MDNode *getMetadata(StringRef Kind) const {
if (!hasMetadata()) return 0;
return getMetadataImpl(Kind);
}
/// getAllMetadata - Get all metadata attached to this Instruction. The first
/// element of each pair returned is the KindID, the second element is the
/// metadata value. This list is returned sorted by the KindID.
void getAllMetadata(SmallVectorImpl<std::pair<unsigned, MDNode*> > &MDs)const{
if (hasMetadata())
getAllMetadataImpl(MDs);
}
/// getAllMetadataOtherThanDebugLoc - This does the same thing as
/// getAllMetadata, except that it filters out the debug location.
void getAllMetadataOtherThanDebugLoc(SmallVectorImpl<std::pair<unsigned,
MDNode*> > &MDs) const {
if (hasMetadataOtherThanDebugLoc())
getAllMetadataOtherThanDebugLocImpl(MDs);
}
/// setMetadata - Set the metadata of the specified kind to the specified
/// node. This updates/replaces metadata if already present, or removes it if
/// Node is null.
void setMetadata(unsigned KindID, MDNode *Node);
void setMetadata(StringRef Kind, MDNode *Node);
/// setDebugLoc - Set the debug location information for this instruction.
void setDebugLoc(const DebugLoc &Loc) { DbgLoc = Loc; }
/// getDebugLoc - Return the debug location for this node as a DebugLoc.
const DebugLoc &getDebugLoc() const { return DbgLoc; }
/// Set or clear the unsafe-algebra flag on this instruction, which must be an
/// operator which supports this flag. See LangRef.html for the meaning of
/// this flag.
void setHasUnsafeAlgebra(bool B);
/// Set or clear the no-nans flag on this instruction, which must be an
/// operator which supports this flag. See LangRef.html for the meaning of
/// this flag.
void setHasNoNaNs(bool B);
/// Set or clear the no-infs flag on this instruction, which must be an
/// operator which supports this flag. See LangRef.html for the meaning of
/// this flag.
void setHasNoInfs(bool B);
/// Set or clear the no-signed-zeros flag on this instruction, which must be
/// an operator which supports this flag. See LangRef.html for the meaning of
/// this flag.
void setHasNoSignedZeros(bool B);
/// Set or clear the allow-reciprocal flag on this instruction, which must be
/// an operator which supports this flag. See LangRef.html for the meaning of
/// this flag.
void setHasAllowReciprocal(bool B);
/// Convenience function for setting all the fast-math flags on this
/// instruction, which must be an operator which supports these flags. See
/// LangRef.html for the meaning of these flats.
void setFastMathFlags(FastMathFlags FMF);
/// Determine whether the unsafe-algebra flag is set.
bool hasUnsafeAlgebra() const;
/// Determine whether the no-NaNs flag is set.
bool hasNoNaNs() const;
/// Determine whether the no-infs flag is set.
bool hasNoInfs() const;
/// Determine whether the no-signed-zeros flag is set.
bool hasNoSignedZeros() const;
/// Determine whether the allow-reciprocal flag is set.
bool hasAllowReciprocal() const;
/// Convenience function for getting all the fast-math flags, which must be an
/// operator which supports these flags. See LangRef.html for the meaning of
/// these flats.
FastMathFlags getFastMathFlags() const;
/// Copy I's fast-math flags
void copyFastMathFlags(const Instruction *I);
private:
/// hasMetadataHashEntry - Return true if we have an entry in the on-the-side
/// metadata hash.
bool hasMetadataHashEntry() const {
return (getSubclassDataFromValue() & HasMetadataBit) != 0;
}
// These are all implemented in Metadata.cpp.
MDNode *getMetadataImpl(unsigned KindID) const;
MDNode *getMetadataImpl(StringRef Kind) const;
void getAllMetadataImpl(SmallVectorImpl<std::pair<unsigned,MDNode*> > &)const;
void getAllMetadataOtherThanDebugLocImpl(SmallVectorImpl<std::pair<unsigned,
MDNode*> > &) const;
void clearMetadataHashEntries();
public:
//===--------------------------------------------------------------------===//
// Predicates and helper methods.
//===--------------------------------------------------------------------===//
/// isAssociative - Return true if the instruction is associative:
///
/// Associative operators satisfy: x op (y op z) === (x op y) op z
///
/// In LLVM, the Add, Mul, And, Or, and Xor operators are associative.
///
bool isAssociative() const;
static bool isAssociative(unsigned op);
/// isCommutative - Return true if the instruction is commutative:
///
/// Commutative operators satisfy: (x op y) === (y op x)
///
/// In LLVM, these are the associative operators, plus SetEQ and SetNE, when
/// applied to any type.
///
bool isCommutative() const { return isCommutative(getOpcode()); }
static bool isCommutative(unsigned op);
/// isIdempotent - Return true if the instruction is idempotent:
///
/// Idempotent operators satisfy: x op x === x
///
/// In LLVM, the And and Or operators are idempotent.
///
bool isIdempotent() const { return isIdempotent(getOpcode()); }
static bool isIdempotent(unsigned op);
/// isNilpotent - Return true if the instruction is nilpotent:
///
/// Nilpotent operators satisfy: x op x === Id,
///
/// where Id is the identity for the operator, i.e. a constant such that
/// x op Id === x and Id op x === x for all x.
///
/// In LLVM, the Xor operator is nilpotent.
///
bool isNilpotent() const { return isNilpotent(getOpcode()); }
static bool isNilpotent(unsigned op);
/// mayWriteToMemory - Return true if this instruction may modify memory.
///
bool mayWriteToMemory() const;
/// mayReadFromMemory - Return true if this instruction may read memory.
///
bool mayReadFromMemory() const;
/// mayReadOrWriteMemory - Return true if this instruction may read or
/// write memory.
///
bool mayReadOrWriteMemory() const {
return mayReadFromMemory() || mayWriteToMemory();
}
/// mayThrow - Return true if this instruction may throw an exception.
///
bool mayThrow() const;
/// mayReturn - Return true if this is a function that may return.
/// this is true for all normal instructions. The only exception
/// is functions that are marked with the 'noreturn' attribute.
///
bool mayReturn() const;
/// mayHaveSideEffects - Return true if the instruction may have side effects.
///
/// Note that this does not consider malloc and alloca to have side
/// effects because the newly allocated memory is completely invisible to
/// instructions which don't used the returned value. For cases where this
/// matters, isSafeToSpeculativelyExecute may be more appropriate.
bool mayHaveSideEffects() const {
return mayWriteToMemory() || mayThrow() || !mayReturn();
}
/// clone() - Create a copy of 'this' instruction that is identical in all
/// ways except the following:
/// * The instruction has no parent
/// * The instruction has no name
///
Instruction *clone() const;
/// isIdenticalTo - Return true if the specified instruction is exactly
/// identical to the current one. This means that all operands match and any
/// extra information (e.g. load is volatile) agree.
bool isIdenticalTo(const Instruction *I) const;
/// isIdenticalToWhenDefined - This is like isIdenticalTo, except that it
/// ignores the SubclassOptionalData flags, which specify conditions
/// under which the instruction's result is undefined.
bool isIdenticalToWhenDefined(const Instruction *I) const;
/// When checking for operation equivalence (using isSameOperationAs) it is
/// sometimes useful to ignore certain attributes.
enum OperationEquivalenceFlags {
/// Check for equivalence ignoring load/store alignment.
CompareIgnoringAlignment = 1<<0,
/// Check for equivalence treating a type and a vector of that type
/// as equivalent.
CompareUsingScalarTypes = 1<<1
};
/// This function determines if the specified instruction executes the same
/// operation as the current one. This means that the opcodes, type, operand
/// types and any other factors affecting the operation must be the same. This
/// is similar to isIdenticalTo except the operands themselves don't have to
/// be identical.
/// @returns true if the specified instruction is the same operation as
/// the current one.
/// @brief Determine if one instruction is the same operation as another.
bool isSameOperationAs(const Instruction *I, unsigned flags = 0) const;
/// isUsedOutsideOfBlock - Return true if there are any uses of this
/// instruction in blocks other than the specified block. Note that PHI nodes
/// are considered to evaluate their operands in the corresponding predecessor
/// block.
bool isUsedOutsideOfBlock(const BasicBlock *BB) const;
/// Methods for support type inquiry through isa, cast, and dyn_cast:
static inline bool classof(const Value *V) {
return V->getValueID() >= Value::InstructionVal;
}
//----------------------------------------------------------------------
// Exported enumerations.
//
enum TermOps { // These terminate basic blocks
#define FIRST_TERM_INST(N) TermOpsBegin = N,
#define HANDLE_TERM_INST(N, OPC, CLASS) OPC = N,
#define LAST_TERM_INST(N) TermOpsEnd = N+1
#include "llvm/IR/Instruction.def"
};
enum BinaryOps {
#define FIRST_BINARY_INST(N) BinaryOpsBegin = N,
#define HANDLE_BINARY_INST(N, OPC, CLASS) OPC = N,
#define LAST_BINARY_INST(N) BinaryOpsEnd = N+1
#include "llvm/IR/Instruction.def"
};
enum MemoryOps {
#define FIRST_MEMORY_INST(N) MemoryOpsBegin = N,
#define HANDLE_MEMORY_INST(N, OPC, CLASS) OPC = N,
#define LAST_MEMORY_INST(N) MemoryOpsEnd = N+1
#include "llvm/IR/Instruction.def"
};
enum CastOps {
#define FIRST_CAST_INST(N) CastOpsBegin = N,
#define HANDLE_CAST_INST(N, OPC, CLASS) OPC = N,
#define LAST_CAST_INST(N) CastOpsEnd = N+1
#include "llvm/IR/Instruction.def"
};
enum OtherOps {
#define FIRST_OTHER_INST(N) OtherOpsBegin = N,
#define HANDLE_OTHER_INST(N, OPC, CLASS) OPC = N,
#define LAST_OTHER_INST(N) OtherOpsEnd = N+1
#include "llvm/IR/Instruction.def"
};
private:
// Shadow Value::setValueSubclassData with a private forwarding method so that
// subclasses cannot accidentally use it.
void setValueSubclassData(unsigned short D) {
Value::setValueSubclassData(D);
}
unsigned short getSubclassDataFromValue() const {
return Value::getSubclassDataFromValue();
}
void setHasMetadataHashEntry(bool V) {
setValueSubclassData((getSubclassDataFromValue() & ~HasMetadataBit) |
(V ? HasMetadataBit : 0));
}
friend class SymbolTableListTraits<Instruction, BasicBlock>;
void setParent(BasicBlock *P);
protected:
// Instruction subclasses can stick up to 15 bits of stuff into the
// SubclassData field of instruction with these members.
// Verify that only the low 15 bits are used.
void setInstructionSubclassData(unsigned short D) {
assert((D & HasMetadataBit) == 0 && "Out of range value put into field");
setValueSubclassData((getSubclassDataFromValue() & HasMetadataBit) | D);
}
unsigned getSubclassDataFromInstruction() const {
return getSubclassDataFromValue() & ~HasMetadataBit;
}
Instruction(Type *Ty, unsigned iType, Use *Ops, unsigned NumOps,
Instruction *InsertBefore = 0);
Instruction(Type *Ty, unsigned iType, Use *Ops, unsigned NumOps,
BasicBlock *InsertAtEnd);
virtual Instruction *clone_impl() const = 0;
};
// Instruction* is only 4-byte aligned.
template<>
class PointerLikeTypeTraits<Instruction*> {
typedef Instruction* PT;
public:
static inline void *getAsVoidPointer(PT P) { return P; }
static inline PT getFromVoidPointer(void *P) {
return static_cast<PT>(P);
}
enum { NumLowBitsAvailable = 2 };
};
} // End llvm namespace
#endif

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,316 @@
//===-- llvm/IntrinsicInst.h - Intrinsic Instruction Wrappers ---*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines classes that make it really easy to deal with intrinsic
// functions with the isa/dyncast family of functions. In particular, this
// allows you to do things like:
//
// if (MemCpyInst *MCI = dyn_cast<MemCpyInst>(Inst))
// ... MCI->getDest() ... MCI->getSource() ...
//
// All intrinsic function calls are instances of the call instruction, so these
// are all subclasses of the CallInst class. Note that none of these classes
// has state or virtual methods, which is an important part of this gross/neat
// hack working.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_IR_INTRINSICINST_H
#define LLVM_IR_INTRINSICINST_H
#include "llvm/IR/Constants.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Intrinsics.h"
namespace llvm {
/// IntrinsicInst - A useful wrapper class for inspecting calls to intrinsic
/// functions. This allows the standard isa/dyncast/cast functionality to
/// work with calls to intrinsic functions.
class IntrinsicInst : public CallInst {
IntrinsicInst() LLVM_DELETED_FUNCTION;
IntrinsicInst(const IntrinsicInst&) LLVM_DELETED_FUNCTION;
void operator=(const IntrinsicInst&) LLVM_DELETED_FUNCTION;
public:
/// getIntrinsicID - Return the intrinsic ID of this intrinsic.
///
Intrinsic::ID getIntrinsicID() const {
return (Intrinsic::ID)getCalledFunction()->getIntrinsicID();
}
// Methods for support type inquiry through isa, cast, and dyn_cast:
static inline bool classof(const CallInst *I) {
if (const Function *CF = I->getCalledFunction())
return CF->isIntrinsic();
return false;
}
static inline bool classof(const Value *V) {
return isa<CallInst>(V) && classof(cast<CallInst>(V));
}
};
/// DbgInfoIntrinsic - This is the common base class for debug info intrinsics
///
class DbgInfoIntrinsic : public IntrinsicInst {
public:
// Methods for support type inquiry through isa, cast, and dyn_cast:
static inline bool classof(const IntrinsicInst *I) {
switch (I->getIntrinsicID()) {
case Intrinsic::dbg_declare:
case Intrinsic::dbg_value:
return true;
default: return false;
}
}
static inline bool classof(const Value *V) {
return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
}
static Value *StripCast(Value *C);
};
/// DbgDeclareInst - This represents the llvm.dbg.declare instruction.
///
class DbgDeclareInst : public DbgInfoIntrinsic {
public:
Value *getAddress() const;
MDNode *getVariable() const { return cast<MDNode>(getArgOperand(1)); }
// Methods for support type inquiry through isa, cast, and dyn_cast:
static inline bool classof(const IntrinsicInst *I) {
return I->getIntrinsicID() == Intrinsic::dbg_declare;
}
static inline bool classof(const Value *V) {
return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
}
};
/// DbgValueInst - This represents the llvm.dbg.value instruction.
///
class DbgValueInst : public DbgInfoIntrinsic {
public:
const Value *getValue() const;
Value *getValue();
uint64_t getOffset() const {
return cast<ConstantInt>(
const_cast<Value*>(getArgOperand(1)))->getZExtValue();
}
MDNode *getVariable() const { return cast<MDNode>(getArgOperand(2)); }
// Methods for support type inquiry through isa, cast, and dyn_cast:
static inline bool classof(const IntrinsicInst *I) {
return I->getIntrinsicID() == Intrinsic::dbg_value;
}
static inline bool classof(const Value *V) {
return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
}
};
/// MemIntrinsic - This is the common base class for memset/memcpy/memmove.
///
class MemIntrinsic : public IntrinsicInst {
public:
Value *getRawDest() const { return const_cast<Value*>(getArgOperand(0)); }
Value *getLength() const { return const_cast<Value*>(getArgOperand(2)); }
ConstantInt *getAlignmentCst() const {
return cast<ConstantInt>(const_cast<Value*>(getArgOperand(3)));
}
unsigned getAlignment() const {
return getAlignmentCst()->getZExtValue();
}
ConstantInt *getVolatileCst() const {
return cast<ConstantInt>(const_cast<Value*>(getArgOperand(4)));
}
bool isVolatile() const {
return !getVolatileCst()->isZero();
}
unsigned getDestAddressSpace() const {
return cast<PointerType>(getRawDest()->getType())->getAddressSpace();
}
/// getDest - This is just like getRawDest, but it strips off any cast
/// instructions that feed it, giving the original input. The returned
/// value is guaranteed to be a pointer.
Value *getDest() const { return getRawDest()->stripPointerCasts(); }
/// set* - Set the specified arguments of the instruction.
///
void setDest(Value *Ptr) {
assert(getRawDest()->getType() == Ptr->getType() &&
"setDest called with pointer of wrong type!");
setArgOperand(0, Ptr);
}
void setLength(Value *L) {
assert(getLength()->getType() == L->getType() &&
"setLength called with value of wrong type!");
setArgOperand(2, L);
}
void setAlignment(Constant* A) {
setArgOperand(3, A);
}
void setVolatile(Constant* V) {
setArgOperand(4, V);
}
Type *getAlignmentType() const {
return getArgOperand(3)->getType();
}
// Methods for support type inquiry through isa, cast, and dyn_cast:
static inline bool classof(const IntrinsicInst *I) {
switch (I->getIntrinsicID()) {
case Intrinsic::memcpy:
case Intrinsic::memmove:
case Intrinsic::memset:
return true;
default: return false;
}
}
static inline bool classof(const Value *V) {
return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
}
};
/// MemSetInst - This class wraps the llvm.memset intrinsic.
///
class MemSetInst : public MemIntrinsic {
public:
/// get* - Return the arguments to the instruction.
///
Value *getValue() const { return const_cast<Value*>(getArgOperand(1)); }
void setValue(Value *Val) {
assert(getValue()->getType() == Val->getType() &&
"setValue called with value of wrong type!");
setArgOperand(1, Val);
}
// Methods for support type inquiry through isa, cast, and dyn_cast:
static inline bool classof(const IntrinsicInst *I) {
return I->getIntrinsicID() == Intrinsic::memset;
}
static inline bool classof(const Value *V) {
return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
}
};
/// MemTransferInst - This class wraps the llvm.memcpy/memmove intrinsics.
///
class MemTransferInst : public MemIntrinsic {
public:
/// get* - Return the arguments to the instruction.
///
Value *getRawSource() const { return const_cast<Value*>(getArgOperand(1)); }
/// getSource - This is just like getRawSource, but it strips off any cast
/// instructions that feed it, giving the original input. The returned
/// value is guaranteed to be a pointer.
Value *getSource() const { return getRawSource()->stripPointerCasts(); }
unsigned getSourceAddressSpace() const {
return cast<PointerType>(getRawSource()->getType())->getAddressSpace();
}
void setSource(Value *Ptr) {
assert(getRawSource()->getType() == Ptr->getType() &&
"setSource called with pointer of wrong type!");
setArgOperand(1, Ptr);
}
// Methods for support type inquiry through isa, cast, and dyn_cast:
static inline bool classof(const IntrinsicInst *I) {
return I->getIntrinsicID() == Intrinsic::memcpy ||
I->getIntrinsicID() == Intrinsic::memmove;
}
static inline bool classof(const Value *V) {
return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
}
};
/// MemCpyInst - This class wraps the llvm.memcpy intrinsic.
///
class MemCpyInst : public MemTransferInst {
public:
// Methods for support type inquiry through isa, cast, and dyn_cast:
static inline bool classof(const IntrinsicInst *I) {
return I->getIntrinsicID() == Intrinsic::memcpy;
}
static inline bool classof(const Value *V) {
return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
}
};
/// MemMoveInst - This class wraps the llvm.memmove intrinsic.
///
class MemMoveInst : public MemTransferInst {
public:
// Methods for support type inquiry through isa, cast, and dyn_cast:
static inline bool classof(const IntrinsicInst *I) {
return I->getIntrinsicID() == Intrinsic::memmove;
}
static inline bool classof(const Value *V) {
return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
}
};
/// VAStartInst - This represents the llvm.va_start intrinsic.
///
class VAStartInst : public IntrinsicInst {
public:
static inline bool classof(const IntrinsicInst *I) {
return I->getIntrinsicID() == Intrinsic::vastart;
}
static inline bool classof(const Value *V) {
return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
}
Value *getArgList() const { return const_cast<Value*>(getArgOperand(0)); }
};
/// VAEndInst - This represents the llvm.va_end intrinsic.
///
class VAEndInst : public IntrinsicInst {
public:
static inline bool classof(const IntrinsicInst *I) {
return I->getIntrinsicID() == Intrinsic::vaend;
}
static inline bool classof(const Value *V) {
return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
}
Value *getArgList() const { return const_cast<Value*>(getArgOperand(0)); }
};
/// VACopyInst - This represents the llvm.va_copy intrinsic.
///
class VACopyInst : public IntrinsicInst {
public:
static inline bool classof(const IntrinsicInst *I) {
return I->getIntrinsicID() == Intrinsic::vacopy;
}
static inline bool classof(const Value *V) {
return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
}
Value *getDest() const { return const_cast<Value*>(getArgOperand(0)); }
Value *getSrc() const { return const_cast<Value*>(getArgOperand(1)); }
};
}
#endif

View File

@@ -0,0 +1,128 @@
//===-- llvm/Instrinsics.h - LLVM Intrinsic Function Handling ---*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines a set of enums which allow processing of intrinsic
// functions. Values of these enum types are returned by
// Function::getIntrinsicID.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_IR_INTRINSICS_H
#define LLVM_IR_INTRINSICS_H
#include "llvm/ADT/ArrayRef.h"
#include <string>
namespace llvm {
class Type;
class FunctionType;
class Function;
class LLVMContext;
class Module;
class AttributeSet;
/// Intrinsic Namespace - This namespace contains an enum with a value for
/// every intrinsic/builtin function known by LLVM. These enum values are
/// returned by Function::getIntrinsicID().
///
namespace Intrinsic {
enum ID {
not_intrinsic = 0, // Must be zero
// Get the intrinsic enums generated from Intrinsics.td
#define GET_INTRINSIC_ENUM_VALUES
#include "llvm/IR/Intrinsics.gen"
#undef GET_INTRINSIC_ENUM_VALUES
, num_intrinsics
};
/// Intrinsic::getName(ID) - Return the LLVM name for an intrinsic, such as
/// "llvm.ppc.altivec.lvx".
std::string getName(ID id, ArrayRef<Type*> Tys = ArrayRef<Type*>());
/// Intrinsic::getType(ID) - Return the function type for an intrinsic.
///
FunctionType *getType(LLVMContext &Context, ID id,
ArrayRef<Type*> Tys = ArrayRef<Type*>());
/// Intrinsic::isOverloaded(ID) - Returns true if the intrinsic can be
/// overloaded.
bool isOverloaded(ID id);
/// Intrinsic::getAttributes(ID) - Return the attributes for an intrinsic.
///
AttributeSet getAttributes(LLVMContext &C, ID id);
/// Intrinsic::getDeclaration(M, ID) - Create or insert an LLVM Function
/// declaration for an intrinsic, and return it.
///
/// The Tys and numTys parameters are for intrinsics with overloaded types
/// (e.g., those using iAny, fAny, vAny, or iPTRAny). For a declaration for an
/// overloaded intrinsic, Tys should point to an array of numTys pointers to
/// Type, and must provide exactly one type for each overloaded type in the
/// intrinsic.
Function *getDeclaration(Module *M, ID id,
ArrayRef<Type*> Tys = ArrayRef<Type*>());
/// Map a GCC builtin name to an intrinsic ID.
ID getIntrinsicForGCCBuiltin(const char *Prefix, const char *BuiltinName);
/// IITDescriptor - This is a type descriptor which explains the type
/// requirements of an intrinsic. This is returned by
/// getIntrinsicInfoTableEntries.
struct IITDescriptor {
enum IITDescriptorKind {
Void, MMX, Metadata, Half, Float, Double,
Integer, Vector, Pointer, Struct,
Argument, ExtendVecArgument, TruncVecArgument
} Kind;
union {
unsigned Integer_Width;
unsigned Float_Width;
unsigned Vector_Width;
unsigned Pointer_AddressSpace;
unsigned Struct_NumElements;
unsigned Argument_Info;
};
enum ArgKind {
AK_AnyInteger,
AK_AnyFloat,
AK_AnyVector,
AK_AnyPointer
};
unsigned getArgumentNumber() const {
assert(Kind == Argument || Kind == ExtendVecArgument ||
Kind == TruncVecArgument);
return Argument_Info >> 2;
}
ArgKind getArgumentKind() const {
assert(Kind == Argument || Kind == ExtendVecArgument ||
Kind == TruncVecArgument);
return (ArgKind)(Argument_Info&3);
}
static IITDescriptor get(IITDescriptorKind K, unsigned Field) {
IITDescriptor Result = { K, { Field } };
return Result;
}
};
/// getIntrinsicInfoTableEntries - Return the IIT table descriptor for the
/// specified intrinsic into an array of IITDescriptors.
///
void getIntrinsicInfoTableEntries(ID id, SmallVectorImpl<IITDescriptor> &T);
} // End Intrinsic namespace
} // End llvm namespace
#endif

View File

@@ -0,0 +1,114 @@
//===-- llvm/LLVMContext.h - Class for managing "global" state --*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file declares LLVMContext, a container of "global" state in LLVM, such
// as the global type and constant uniquing tables.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_IR_LLVMCONTEXT_H
#define LLVM_IR_LLVMCONTEXT_H
#include "llvm/Support/Compiler.h"
namespace llvm {
class LLVMContextImpl;
class StringRef;
class Twine;
class Instruction;
class Module;
class SMDiagnostic;
template <typename T> class SmallVectorImpl;
/// This is an important class for using LLVM in a threaded context. It
/// (opaquely) owns and manages the core "global" data of LLVM's core
/// infrastructure, including the type and constant uniquing tables.
/// LLVMContext itself provides no locking guarantees, so you should be careful
/// to have one context per thread.
class LLVMContext {
public:
LLVMContextImpl *const pImpl;
LLVMContext();
~LLVMContext();
// Pinned metadata names, which always have the same value. This is a
// compile-time performance optimization, not a correctness optimization.
enum {
MD_dbg = 0, // "dbg"
MD_tbaa = 1, // "tbaa"
MD_prof = 2, // "prof"
MD_fpmath = 3, // "fpmath"
MD_range = 4, // "range"
MD_tbaa_struct = 5, // "tbaa.struct"
MD_invariant_load = 6 // "invariant.load"
};
/// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
/// This ID is uniqued across modules in the current LLVMContext.
unsigned getMDKindID(StringRef Name) const;
/// getMDKindNames - Populate client supplied SmallVector with the name for
/// custom metadata IDs registered in this LLVMContext.
void getMDKindNames(SmallVectorImpl<StringRef> &Result) const;
typedef void (*InlineAsmDiagHandlerTy)(const SMDiagnostic&, void *Context,
unsigned LocCookie);
/// setInlineAsmDiagnosticHandler - This method sets a handler that is invoked
/// when problems with inline asm are detected by the backend. The first
/// argument is a function pointer and the second is a context pointer that
/// gets passed into the DiagHandler.
///
/// LLVMContext doesn't take ownership or interpret either of these
/// pointers.
void setInlineAsmDiagnosticHandler(InlineAsmDiagHandlerTy DiagHandler,
void *DiagContext = 0);
/// getInlineAsmDiagnosticHandler - Return the diagnostic handler set by
/// setInlineAsmDiagnosticHandler.
InlineAsmDiagHandlerTy getInlineAsmDiagnosticHandler() const;
/// getInlineAsmDiagnosticContext - Return the diagnostic context set by
/// setInlineAsmDiagnosticHandler.
void *getInlineAsmDiagnosticContext() const;
/// emitError - Emit an error message to the currently installed error handler
/// with optional location information. This function returns, so code should
/// be prepared to drop the erroneous construct on the floor and "not crash".
/// The generated code need not be correct. The error message will be
/// implicitly prefixed with "error: " and should not end with a ".".
void emitError(unsigned LocCookie, const Twine &ErrorStr);
void emitError(const Instruction *I, const Twine &ErrorStr);
void emitError(const Twine &ErrorStr);
private:
LLVMContext(LLVMContext&) LLVM_DELETED_FUNCTION;
void operator=(LLVMContext&) LLVM_DELETED_FUNCTION;
/// addModule - Register a module as being instantiated in this context. If
/// the context is deleted, the module will be deleted as well.
void addModule(Module*);
/// removeModule - Unregister a module from this context.
void removeModule(Module*);
// Module needs access to the add/removeModule methods.
friend class Module;
};
/// getGlobalContext - Returns a global context. This is for LLVM clients that
/// only care about operating on a single thread.
extern LLVMContext &getGlobalContext();
}
#endif

View File

@@ -0,0 +1,198 @@
//===---- llvm/MDBuilder.h - Builder for LLVM metadata ----------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the MDBuilder class, which is used as a convenient way to
// create LLVM metadata with a consistent and simplified interface.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_IR_MDBUILDER_H
#define LLVM_IR_MDBUILDER_H
#include "llvm/IR/Constants.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Metadata.h"
namespace llvm {
class APInt;
class LLVMContext;
class MDBuilder {
LLVMContext &Context;
public:
MDBuilder(LLVMContext &context) : Context(context) {}
/// \brief Return the given string as metadata.
MDString *createString(StringRef Str) {
return MDString::get(Context, Str);
}
//===------------------------------------------------------------------===//
// FPMath metadata.
//===------------------------------------------------------------------===//
/// \brief Return metadata with the given settings. The special value 0.0
/// for the Accuracy parameter indicates the default (maximal precision)
/// setting.
MDNode *createFPMath(float Accuracy) {
if (Accuracy == 0.0)
return 0;
assert(Accuracy > 0.0 && "Invalid fpmath accuracy!");
Value *Op = ConstantFP::get(Type::getFloatTy(Context), Accuracy);
return MDNode::get(Context, Op);
}
//===------------------------------------------------------------------===//
// Prof metadata.
//===------------------------------------------------------------------===//
/// \brief Return metadata containing two branch weights.
MDNode *createBranchWeights(uint32_t TrueWeight, uint32_t FalseWeight) {
uint32_t Weights[] = { TrueWeight, FalseWeight };
return createBranchWeights(Weights);
}
/// \brief Return metadata containing a number of branch weights.
MDNode *createBranchWeights(ArrayRef<uint32_t> Weights) {
assert(Weights.size() >= 2 && "Need at least two branch weights!");
SmallVector<Value *, 4> Vals(Weights.size()+1);
Vals[0] = createString("branch_weights");
Type *Int32Ty = Type::getInt32Ty(Context);
for (unsigned i = 0, e = Weights.size(); i != e; ++i)
Vals[i+1] = ConstantInt::get(Int32Ty, Weights[i]);
return MDNode::get(Context, Vals);
}
//===------------------------------------------------------------------===//
// Range metadata.
//===------------------------------------------------------------------===//
/// \brief Return metadata describing the range [Lo, Hi).
MDNode *createRange(const APInt &Lo, const APInt &Hi) {
assert(Lo.getBitWidth() == Hi.getBitWidth() && "Mismatched bitwidths!");
// If the range is everything then it is useless.
if (Hi == Lo)
return 0;
// Return the range [Lo, Hi).
Type *Ty = IntegerType::get(Context, Lo.getBitWidth());
Value *Range[2] = { ConstantInt::get(Ty, Lo), ConstantInt::get(Ty, Hi) };
return MDNode::get(Context, Range);
}
//===------------------------------------------------------------------===//
// TBAA metadata.
//===------------------------------------------------------------------===//
/// \brief Return metadata appropriate for a TBAA root node. Each returned
/// node is distinct from all other metadata and will never be identified
/// (uniqued) with anything else.
MDNode *createAnonymousTBAARoot() {
// To ensure uniqueness the root node is self-referential.
MDNode *Dummy = MDNode::getTemporary(Context, ArrayRef<Value*>());
MDNode *Root = MDNode::get(Context, Dummy);
// At this point we have
// !0 = metadata !{} <- dummy
// !1 = metadata !{metadata !0} <- root
// Replace the dummy operand with the root node itself and delete the dummy.
Root->replaceOperandWith(0, Root);
MDNode::deleteTemporary(Dummy);
// We now have
// !1 = metadata !{metadata !1} <- self-referential root
return Root;
}
/// \brief Return metadata appropriate for a TBAA root node with the given
/// name. This may be identified (uniqued) with other roots with the same
/// name.
MDNode *createTBAARoot(StringRef Name) {
return MDNode::get(Context, createString(Name));
}
/// \brief Return metadata for a non-root TBAA node with the given name,
/// parent in the TBAA tree, and value for 'pointsToConstantMemory'.
MDNode *createTBAANode(StringRef Name, MDNode *Parent,
bool isConstant = false) {
if (isConstant) {
Constant *Flags = ConstantInt::get(Type::getInt64Ty(Context), 1);
Value *Ops[3] = { createString(Name), Parent, Flags };
return MDNode::get(Context, Ops);
} else {
Value *Ops[2] = { createString(Name), Parent };
return MDNode::get(Context, Ops);
}
}
struct TBAAStructField {
uint64_t Offset;
uint64_t Size;
MDNode *TBAA;
TBAAStructField(uint64_t Offset, uint64_t Size, MDNode *TBAA) :
Offset(Offset), Size(Size), TBAA(TBAA) {}
};
/// \brief Return metadata for a tbaa.struct node with the given
/// struct field descriptions.
MDNode *createTBAAStructNode(ArrayRef<TBAAStructField> Fields) {
SmallVector<Value *, 4> Vals(Fields.size() * 3);
Type *Int64 = IntegerType::get(Context, 64);
for (unsigned i = 0, e = Fields.size(); i != e; ++i) {
Vals[i * 3 + 0] = ConstantInt::get(Int64, Fields[i].Offset);
Vals[i * 3 + 1] = ConstantInt::get(Int64, Fields[i].Size);
Vals[i * 3 + 2] = Fields[i].TBAA;
}
return MDNode::get(Context, Vals);
}
/// \brief Return metadata for a TBAA struct node in the type DAG
/// with the given name, a list of pairs (offset, field type in the type DAG).
MDNode *createTBAAStructTypeNode(StringRef Name,
ArrayRef<std::pair<uint64_t, MDNode*> > Fields) {
SmallVector<Value *, 4> Ops(Fields.size() * 2 + 1);
Type *Int64 = IntegerType::get(Context, 64);
Ops[0] = createString(Name);
for (unsigned i = 0, e = Fields.size(); i != e; ++i) {
Ops[i * 2 + 1] = ConstantInt::get(Int64, Fields[i].first);
Ops[i * 2 + 2] = Fields[i].second;
}
return MDNode::get(Context, Ops);
}
/// \brief Return metadata for a TBAA scalar type node with the
/// given name, an offset and a parent in the TBAA type DAG.
MDNode *createTBAAScalarTypeNode(StringRef Name, uint64_t Offset,
MDNode *Parent) {
SmallVector<Value *, 4> Ops(3);
Type *Int64 = IntegerType::get(Context, 64);
Ops[0] = createString(Name);
Ops[1] = ConstantInt::get(Int64, Offset);
Ops[2] = Parent;
return MDNode::get(Context, Ops);
}
/// \brief Return metadata for a TBAA tag node with the given
/// base type, access type and offset relative to the base type.
MDNode *createTBAAStructTagNode(MDNode *BaseType, MDNode *AccessType,
uint64_t Offset) {
Type *Int64 = IntegerType::get(Context, 64);
Value *Ops[3] = { BaseType, AccessType, ConstantInt::get(Int64, Offset) };
return MDNode::get(Context, Ops);
}
};
} // end namespace llvm
#endif

View File

@@ -0,0 +1,242 @@
//===-- llvm/Metadata.h - Metadata definitions ------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
/// @file
/// This file contains the declarations for metadata subclasses.
/// They represent the different flavors of metadata that live in LLVM.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_IR_METADATA_H
#define LLVM_IR_METADATA_H
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/FoldingSet.h"
#include "llvm/ADT/ilist_node.h"
#include "llvm/IR/Value.h"
namespace llvm {
class Constant;
class Instruction;
class LLVMContext;
class Module;
template <typename T> class SmallVectorImpl;
template<typename ValueSubClass, typename ItemParentClass>
class SymbolTableListTraits;
//===----------------------------------------------------------------------===//
/// MDString - a single uniqued string.
/// These are used to efficiently contain a byte sequence for metadata.
/// MDString is always unnamed.
class MDString : public Value {
virtual void anchor();
MDString(const MDString &) LLVM_DELETED_FUNCTION;
explicit MDString(LLVMContext &C);
public:
static MDString *get(LLVMContext &Context, StringRef Str);
static MDString *get(LLVMContext &Context, const char *Str) {
return get(Context, Str ? StringRef(Str) : StringRef());
}
StringRef getString() const { return getName(); }
unsigned getLength() const { return (unsigned)getName().size(); }
typedef StringRef::iterator iterator;
/// begin() - Pointer to the first byte of the string.
iterator begin() const { return getName().begin(); }
/// end() - Pointer to one byte past the end of the string.
iterator end() const { return getName().end(); }
/// Methods for support type inquiry through isa, cast, and dyn_cast:
static bool classof(const Value *V) {
return V->getValueID() == MDStringVal;
}
};
class MDNodeOperand;
//===----------------------------------------------------------------------===//
/// MDNode - a tuple of other values.
class MDNode : public Value, public FoldingSetNode {
MDNode(const MDNode &) LLVM_DELETED_FUNCTION;
void operator=(const MDNode &) LLVM_DELETED_FUNCTION;
friend class MDNodeOperand;
friend class LLVMContextImpl;
friend struct FoldingSetTrait<MDNode>;
/// Hash - If the MDNode is uniqued cache the hash to speed up lookup.
unsigned Hash;
/// NumOperands - This many 'MDNodeOperand' items are co-allocated onto the
/// end of this MDNode.
unsigned NumOperands;
// Subclass data enums.
enum {
/// FunctionLocalBit - This bit is set if this MDNode is function local.
/// This is true when it (potentially transitively) contains a reference to
/// something in a function, like an argument, basicblock, or instruction.
FunctionLocalBit = 1 << 0,
/// NotUniquedBit - This is set on MDNodes that are not uniqued because they
/// have a null operand.
NotUniquedBit = 1 << 1,
/// DestroyFlag - This bit is set by destroy() so the destructor can assert
/// that the node isn't being destroyed with a plain 'delete'.
DestroyFlag = 1 << 2
};
// FunctionLocal enums.
enum FunctionLocalness {
FL_Unknown = -1,
FL_No = 0,
FL_Yes = 1
};
/// replaceOperand - Replace each instance of F from the operand list of this
/// node with T.
void replaceOperand(MDNodeOperand *Op, Value *NewVal);
~MDNode();
MDNode(LLVMContext &C, ArrayRef<Value*> Vals, bool isFunctionLocal);
static MDNode *getMDNode(LLVMContext &C, ArrayRef<Value*> Vals,
FunctionLocalness FL, bool Insert = true);
public:
// Constructors and destructors.
static MDNode *get(LLVMContext &Context, ArrayRef<Value*> Vals);
// getWhenValsUnresolved - Construct MDNode determining function-localness
// from isFunctionLocal argument, not by analyzing Vals.
static MDNode *getWhenValsUnresolved(LLVMContext &Context,
ArrayRef<Value*> Vals,
bool isFunctionLocal);
static MDNode *getIfExists(LLVMContext &Context, ArrayRef<Value*> Vals);
/// getTemporary - Return a temporary MDNode, for use in constructing
/// cyclic MDNode structures. A temporary MDNode is not uniqued,
/// may be RAUW'd, and must be manually deleted with deleteTemporary.
static MDNode *getTemporary(LLVMContext &Context, ArrayRef<Value*> Vals);
/// deleteTemporary - Deallocate a node created by getTemporary. The
/// node must not have any users.
static void deleteTemporary(MDNode *N);
/// replaceOperandWith - Replace a specific operand.
void replaceOperandWith(unsigned i, Value *NewVal);
/// getOperand - Return specified operand.
Value *getOperand(unsigned i) const;
/// getNumOperands - Return number of MDNode operands.
unsigned getNumOperands() const { return NumOperands; }
/// isFunctionLocal - Return whether MDNode is local to a function.
bool isFunctionLocal() const {
return (getSubclassDataFromValue() & FunctionLocalBit) != 0;
}
// getFunction - If this metadata is function-local and recursively has a
// function-local operand, return the first such operand's parent function.
// Otherwise, return null. getFunction() should not be used for performance-
// critical code because it recursively visits all the MDNode's operands.
const Function *getFunction() const;
/// Profile - calculate a unique identifier for this MDNode to collapse
/// duplicates
void Profile(FoldingSetNodeID &ID) const;
/// Methods for support type inquiry through isa, cast, and dyn_cast:
static bool classof(const Value *V) {
return V->getValueID() == MDNodeVal;
}
/// Methods for metadata merging.
static MDNode *getMostGenericTBAA(MDNode *A, MDNode *B);
static MDNode *getMostGenericFPMath(MDNode *A, MDNode *B);
static MDNode *getMostGenericRange(MDNode *A, MDNode *B);
private:
// destroy - Delete this node. Only when there are no uses.
void destroy();
bool isNotUniqued() const {
return (getSubclassDataFromValue() & NotUniquedBit) != 0;
}
void setIsNotUniqued();
// Shadow Value::setValueSubclassData with a private forwarding method so that
// any future subclasses cannot accidentally use it.
void setValueSubclassData(unsigned short D) {
Value::setValueSubclassData(D);
}
};
//===----------------------------------------------------------------------===//
/// NamedMDNode - a tuple of MDNodes. Despite its name, a NamedMDNode isn't
/// itself an MDNode. NamedMDNodes belong to modules, have names, and contain
/// lists of MDNodes.
class NamedMDNode : public ilist_node<NamedMDNode> {
friend class SymbolTableListTraits<NamedMDNode, Module>;
friend struct ilist_traits<NamedMDNode>;
friend class LLVMContextImpl;
friend class Module;
NamedMDNode(const NamedMDNode &) LLVM_DELETED_FUNCTION;
std::string Name;
Module *Parent;
void *Operands; // SmallVector<TrackingVH<MDNode>, 4>
void setParent(Module *M) { Parent = M; }
explicit NamedMDNode(const Twine &N);
public:
/// eraseFromParent - Drop all references and remove the node from parent
/// module.
void eraseFromParent();
/// dropAllReferences - Remove all uses and clear node vector.
void dropAllReferences();
/// ~NamedMDNode - Destroy NamedMDNode.
~NamedMDNode();
/// getParent - Get the module that holds this named metadata collection.
inline Module *getParent() { return Parent; }
inline const Module *getParent() const { return Parent; }
/// getOperand - Return specified operand.
MDNode *getOperand(unsigned i) const;
/// getNumOperands - Return the number of NamedMDNode operands.
unsigned getNumOperands() const;
/// addOperand - Add metadata operand.
void addOperand(MDNode *M);
/// getName - Return a constant reference to this named metadata's name.
StringRef getName() const;
/// print - Implement operator<< on NamedMDNode.
void print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW = 0) const;
/// dump() - Allow printing of NamedMDNodes from the debugger.
void dump() const;
};
} // end llvm namespace
#endif

View File

@@ -0,0 +1,589 @@
//===-- llvm/Module.h - C++ class to represent a VM module ------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
/// @file
/// Module.h This file contains the declarations for the Module class.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_IR_MODULE_H
#define LLVM_IR_MODULE_H
#include "llvm/ADT/OwningPtr.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/GlobalAlias.h"
#include "llvm/IR/GlobalVariable.h"
#include "llvm/IR/Metadata.h"
#include "llvm/Support/DataTypes.h"
namespace llvm {
class FunctionType;
class GVMaterializer;
class LLVMContext;
class StructType;
template<typename T> struct DenseMapInfo;
template<typename KeyT, typename ValueT, typename KeyInfoT> class DenseMap;
template<> struct ilist_traits<Function>
: public SymbolTableListTraits<Function, Module> {
// createSentinel is used to get hold of the node that marks the end of the
// list... (same trick used here as in ilist_traits<Instruction>)
Function *createSentinel() const {
return static_cast<Function*>(&Sentinel);
}
static void destroySentinel(Function*) {}
Function *provideInitialHead() const { return createSentinel(); }
Function *ensureHead(Function*) const { return createSentinel(); }
static void noteHead(Function*, Function*) {}
private:
mutable ilist_node<Function> Sentinel;
};
template<> struct ilist_traits<GlobalVariable>
: public SymbolTableListTraits<GlobalVariable, Module> {
// createSentinel is used to create a node that marks the end of the list.
GlobalVariable *createSentinel() const {
return static_cast<GlobalVariable*>(&Sentinel);
}
static void destroySentinel(GlobalVariable*) {}
GlobalVariable *provideInitialHead() const { return createSentinel(); }
GlobalVariable *ensureHead(GlobalVariable*) const { return createSentinel(); }
static void noteHead(GlobalVariable*, GlobalVariable*) {}
private:
mutable ilist_node<GlobalVariable> Sentinel;
};
template<> struct ilist_traits<GlobalAlias>
: public SymbolTableListTraits<GlobalAlias, Module> {
// createSentinel is used to create a node that marks the end of the list.
GlobalAlias *createSentinel() const {
return static_cast<GlobalAlias*>(&Sentinel);
}
static void destroySentinel(GlobalAlias*) {}
GlobalAlias *provideInitialHead() const { return createSentinel(); }
GlobalAlias *ensureHead(GlobalAlias*) const { return createSentinel(); }
static void noteHead(GlobalAlias*, GlobalAlias*) {}
private:
mutable ilist_node<GlobalAlias> Sentinel;
};
template<> struct ilist_traits<NamedMDNode>
: public ilist_default_traits<NamedMDNode> {
// createSentinel is used to get hold of a node that marks the end of
// the list...
NamedMDNode *createSentinel() const {
return static_cast<NamedMDNode*>(&Sentinel);
}
static void destroySentinel(NamedMDNode*) {}
NamedMDNode *provideInitialHead() const { return createSentinel(); }
NamedMDNode *ensureHead(NamedMDNode*) const { return createSentinel(); }
static void noteHead(NamedMDNode*, NamedMDNode*) {}
void addNodeToList(NamedMDNode *) {}
void removeNodeFromList(NamedMDNode *) {}
private:
mutable ilist_node<NamedMDNode> Sentinel;
};
/// A Module instance is used to store all the information related to an
/// LLVM module. Modules are the top level container of all other LLVM
/// Intermediate Representation (IR) objects. Each module directly contains a
/// list of globals variables, a list of functions, a list of libraries (or
/// other modules) this module depends on, a symbol table, and various data
/// about the target's characteristics.
///
/// A module maintains a GlobalValRefMap object that is used to hold all
/// constant references to global variables in the module. When a global
/// variable is destroyed, it should have no entries in the GlobalValueRefMap.
/// @brief The main container class for the LLVM Intermediate Representation.
class Module {
/// @name Types And Enumerations
/// @{
public:
/// The type for the list of global variables.
typedef iplist<GlobalVariable> GlobalListType;
/// The type for the list of functions.
typedef iplist<Function> FunctionListType;
/// The type for the list of aliases.
typedef iplist<GlobalAlias> AliasListType;
/// The type for the list of named metadata.
typedef ilist<NamedMDNode> NamedMDListType;
/// The Global Variable iterator.
typedef GlobalListType::iterator global_iterator;
/// The Global Variable constant iterator.
typedef GlobalListType::const_iterator const_global_iterator;
/// The Function iterators.
typedef FunctionListType::iterator iterator;
/// The Function constant iterator
typedef FunctionListType::const_iterator const_iterator;
/// The Global Alias iterators.
typedef AliasListType::iterator alias_iterator;
/// The Global Alias constant iterator
typedef AliasListType::const_iterator const_alias_iterator;
/// The named metadata iterators.
typedef NamedMDListType::iterator named_metadata_iterator;
/// The named metadata constant interators.
typedef NamedMDListType::const_iterator const_named_metadata_iterator;
/// An enumeration for describing the endianess of the target machine.
enum Endianness { AnyEndianness, LittleEndian, BigEndian };
/// An enumeration for describing the size of a pointer on the target machine.
enum PointerSize { AnyPointerSize, Pointer32, Pointer64 };
/// This enumeration defines the supported behaviors of module flags.
enum ModFlagBehavior {
/// Emits an error if two values disagree, otherwise the resulting value is
/// that of the operands.
Error = 1,
/// Emits a warning if two values disagree. The result value will be the
/// operand for the flag from the first module being linked.
Warning = 2,
/// Adds a requirement that another module flag be present and have a
/// specified value after linking is performed. The value must be a metadata
/// pair, where the first element of the pair is the ID of the module flag
/// to be restricted, and the second element of the pair is the value the
/// module flag should be restricted to. This behavior can be used to
/// restrict the allowable results (via triggering of an error) of linking
/// IDs with the **Override** behavior.
Require = 3,
/// Uses the specified value, regardless of the behavior or value of the
/// other module. If both modules specify **Override**, but the values
/// differ, an error will be emitted.
Override = 4,
/// Appends the two values, which are required to be metadata nodes.
Append = 5,
/// Appends the two values, which are required to be metadata
/// nodes. However, duplicate entries in the second list are dropped
/// during the append operation.
AppendUnique = 6
};
struct ModuleFlagEntry {
ModFlagBehavior Behavior;
MDString *Key;
Value *Val;
ModuleFlagEntry(ModFlagBehavior B, MDString *K, Value *V)
: Behavior(B), Key(K), Val(V) {}
};
/// @}
/// @name Member Variables
/// @{
private:
LLVMContext &Context; ///< The LLVMContext from which types and
///< constants are allocated.
GlobalListType GlobalList; ///< The Global Variables in the module
FunctionListType FunctionList; ///< The Functions in the module
AliasListType AliasList; ///< The Aliases in the module
NamedMDListType NamedMDList; ///< The named metadata in the module
std::string GlobalScopeAsm; ///< Inline Asm at global scope.
ValueSymbolTable *ValSymTab; ///< Symbol table for values
OwningPtr<GVMaterializer> Materializer; ///< Used to materialize GlobalValues
std::string ModuleID; ///< Human readable identifier for the module
std::string TargetTriple; ///< Platform target triple Module compiled on
std::string DataLayout; ///< Target data description
void *NamedMDSymTab; ///< NamedMDNode names.
friend class Constant;
/// @}
/// @name Constructors
/// @{
public:
/// The Module constructor. Note that there is no default constructor. You
/// must provide a name for the module upon construction.
explicit Module(StringRef ModuleID, LLVMContext& C);
/// The module destructor. This will dropAllReferences.
~Module();
/// @}
/// @name Module Level Accessors
/// @{
/// Get the module identifier which is, essentially, the name of the module.
/// @returns the module identifier as a string
const std::string &getModuleIdentifier() const { return ModuleID; }
/// Get the data layout string for the module's target platform. This encodes
/// the type sizes and alignments expected by this module.
/// @returns the data layout as a string
const std::string &getDataLayout() const { return DataLayout; }
/// Get the target triple which is a string describing the target host.
/// @returns a string containing the target triple.
const std::string &getTargetTriple() const { return TargetTriple; }
/// Get the target endian information.
/// @returns Endianess - an enumeration for the endianess of the target
Endianness getEndianness() const;
/// Get the target pointer size.
/// @returns PointerSize - an enumeration for the size of the target's pointer
PointerSize getPointerSize() const;
/// Get the global data context.
/// @returns LLVMContext - a container for LLVM's global information
LLVMContext &getContext() const { return Context; }
/// Get any module-scope inline assembly blocks.
/// @returns a string containing the module-scope inline assembly blocks.
const std::string &getModuleInlineAsm() const { return GlobalScopeAsm; }
/// @}
/// @name Module Level Mutators
/// @{
/// Set the module identifier.
void setModuleIdentifier(StringRef ID) { ModuleID = ID; }
/// Set the data layout
void setDataLayout(StringRef DL) { DataLayout = DL; }
/// Set the target triple.
void setTargetTriple(StringRef T) { TargetTriple = T; }
/// Set the module-scope inline assembly blocks.
void setModuleInlineAsm(StringRef Asm) {
GlobalScopeAsm = Asm;
if (!GlobalScopeAsm.empty() &&
GlobalScopeAsm[GlobalScopeAsm.size()-1] != '\n')
GlobalScopeAsm += '\n';
}
/// Append to the module-scope inline assembly blocks, automatically inserting
/// a separating newline if necessary.
void appendModuleInlineAsm(StringRef Asm) {
GlobalScopeAsm += Asm;
if (!GlobalScopeAsm.empty() &&
GlobalScopeAsm[GlobalScopeAsm.size()-1] != '\n')
GlobalScopeAsm += '\n';
}
/// @}
/// @name Generic Value Accessors
/// @{
/// getNamedValue - Return the global value in the module with
/// the specified name, of arbitrary type. This method returns null
/// if a global with the specified name is not found.
GlobalValue *getNamedValue(StringRef Name) const;
/// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
/// This ID is uniqued across modules in the current LLVMContext.
unsigned getMDKindID(StringRef Name) const;
/// getMDKindNames - Populate client supplied SmallVector with the name for
/// custom metadata IDs registered in this LLVMContext.
void getMDKindNames(SmallVectorImpl<StringRef> &Result) const;
typedef DenseMap<StructType*, unsigned, DenseMapInfo<StructType*> >
NumeredTypesMapTy;
/// getTypeByName - Return the type with the specified name, or null if there
/// is none by that name.
StructType *getTypeByName(StringRef Name) const;
/// @}
/// @name Function Accessors
/// @{
/// getOrInsertFunction - Look up the specified function in the module symbol
/// table. Four possibilities:
/// 1. If it does not exist, add a prototype for the function and return it.
/// 2. If it exists, and has a local linkage, the existing function is
/// renamed and a new one is inserted.
/// 3. Otherwise, if the existing function has the correct prototype, return
/// the existing function.
/// 4. Finally, the function exists but has the wrong prototype: return the
/// function with a constantexpr cast to the right prototype.
Constant *getOrInsertFunction(StringRef Name, FunctionType *T,
AttributeSet AttributeList);
Constant *getOrInsertFunction(StringRef Name, FunctionType *T);
/// getOrInsertFunction - Look up the specified function in the module symbol
/// table. If it does not exist, add a prototype for the function and return
/// it. This function guarantees to return a constant of pointer to the
/// specified function type or a ConstantExpr BitCast of that type if the
/// named function has a different type. This version of the method takes a
/// null terminated list of function arguments, which makes it easier for
/// clients to use.
Constant *getOrInsertFunction(StringRef Name,
AttributeSet AttributeList,
Type *RetTy, ...) END_WITH_NULL;
/// getOrInsertFunction - Same as above, but without the attributes.
Constant *getOrInsertFunction(StringRef Name, Type *RetTy, ...)
END_WITH_NULL;
Constant *getOrInsertTargetIntrinsic(StringRef Name,
FunctionType *Ty,
AttributeSet AttributeList);
/// getFunction - Look up the specified function in the module symbol table.
/// If it does not exist, return null.
Function *getFunction(StringRef Name) const;
/// @}
/// @name Global Variable Accessors
/// @{
/// getGlobalVariable - Look up the specified global variable in the module
/// symbol table. If it does not exist, return null. If AllowInternal is set
/// to true, this function will return types that have InternalLinkage. By
/// default, these types are not returned.
GlobalVariable *getGlobalVariable(StringRef Name,
bool AllowInternal = false) const;
/// getNamedGlobal - Return the global variable in the module with the
/// specified name, of arbitrary type. This method returns null if a global
/// with the specified name is not found.
GlobalVariable *getNamedGlobal(StringRef Name) const {
return getGlobalVariable(Name, true);
}
/// getOrInsertGlobal - Look up the specified global in the module symbol
/// table.
/// 1. If it does not exist, add a declaration of the global and return it.
/// 2. Else, the global exists but has the wrong type: return the function
/// with a constantexpr cast to the right type.
/// 3. Finally, if the existing global is the correct declaration, return
/// the existing global.
Constant *getOrInsertGlobal(StringRef Name, Type *Ty);
/// @}
/// @name Global Alias Accessors
/// @{
/// getNamedAlias - Return the global alias in the module with the
/// specified name, of arbitrary type. This method returns null if a global
/// with the specified name is not found.
GlobalAlias *getNamedAlias(StringRef Name) const;
/// @}
/// @name Named Metadata Accessors
/// @{
/// getNamedMetadata - Return the NamedMDNode in the module with the
/// specified name. This method returns null if a NamedMDNode with the
/// specified name is not found.
NamedMDNode *getNamedMetadata(const Twine &Name) const;
/// getOrInsertNamedMetadata - Return the named MDNode in the module
/// with the specified name. This method returns a new NamedMDNode if a
/// NamedMDNode with the specified name is not found.
NamedMDNode *getOrInsertNamedMetadata(StringRef Name);
/// eraseNamedMetadata - Remove the given NamedMDNode from this module
/// and delete it.
void eraseNamedMetadata(NamedMDNode *NMD);
/// @}
/// @name Module Flags Accessors
/// @{
/// getModuleFlagsMetadata - Returns the module flags in the provided vector.
void getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> &Flags) const;
/// getModuleFlagsMetadata - Returns the NamedMDNode in the module that
/// represents module-level flags. This method returns null if there are no
/// module-level flags.
NamedMDNode *getModuleFlagsMetadata() const;
/// getOrInsertModuleFlagsMetadata - Returns the NamedMDNode in the module
/// that represents module-level flags. If module-level flags aren't found,
/// it creates the named metadata that contains them.
NamedMDNode *getOrInsertModuleFlagsMetadata();
/// addModuleFlag - Add a module-level flag to the module-level flags
/// metadata. It will create the module-level flags named metadata if it
/// doesn't already exist.
void addModuleFlag(ModFlagBehavior Behavior, StringRef Key, Value *Val);
void addModuleFlag(ModFlagBehavior Behavior, StringRef Key, uint32_t Val);
void addModuleFlag(MDNode *Node);
/// @}
/// @name Materialization
/// @{
/// setMaterializer - Sets the GVMaterializer to GVM. This module must not
/// yet have a Materializer. To reset the materializer for a module that
/// already has one, call MaterializeAllPermanently first. Destroying this
/// module will destroy its materializer without materializing any more
/// GlobalValues. Without destroying the Module, there is no way to detach or
/// destroy a materializer without materializing all the GVs it controls, to
/// avoid leaving orphan unmaterialized GVs.
void setMaterializer(GVMaterializer *GVM);
/// getMaterializer - Retrieves the GVMaterializer, if any, for this Module.
GVMaterializer *getMaterializer() const { return Materializer.get(); }
/// isMaterializable - True if the definition of GV has yet to be materialized
/// from the GVMaterializer.
bool isMaterializable(const GlobalValue *GV) const;
/// isDematerializable - Returns true if this GV was loaded from this Module's
/// GVMaterializer and the GVMaterializer knows how to dematerialize the GV.
bool isDematerializable(const GlobalValue *GV) const;
/// Materialize - Make sure the GlobalValue is fully read. If the module is
/// corrupt, this returns true and fills in the optional string with
/// information about the problem. If successful, this returns false.
bool Materialize(GlobalValue *GV, std::string *ErrInfo = 0);
/// Dematerialize - If the GlobalValue is read in, and if the GVMaterializer
/// supports it, release the memory for the function, and set it up to be
/// materialized lazily. If !isDematerializable(), this method is a noop.
void Dematerialize(GlobalValue *GV);
/// MaterializeAll - Make sure all GlobalValues in this Module are fully read.
/// If the module is corrupt, this returns true and fills in the optional
/// string with information about the problem. If successful, this returns
/// false.
bool MaterializeAll(std::string *ErrInfo = 0);
/// MaterializeAllPermanently - Make sure all GlobalValues in this Module are
/// fully read and clear the Materializer. If the module is corrupt, this
/// returns true, fills in the optional string with information about the
/// problem, and DOES NOT clear the old Materializer. If successful, this
/// returns false.
bool MaterializeAllPermanently(std::string *ErrInfo = 0);
/// @}
/// @name Direct access to the globals list, functions list, and symbol table
/// @{
/// Get the Module's list of global variables (constant).
const GlobalListType &getGlobalList() const { return GlobalList; }
/// Get the Module's list of global variables.
GlobalListType &getGlobalList() { return GlobalList; }
static iplist<GlobalVariable> Module::*getSublistAccess(GlobalVariable*) {
return &Module::GlobalList;
}
/// Get the Module's list of functions (constant).
const FunctionListType &getFunctionList() const { return FunctionList; }
/// Get the Module's list of functions.
FunctionListType &getFunctionList() { return FunctionList; }
static iplist<Function> Module::*getSublistAccess(Function*) {
return &Module::FunctionList;
}
/// Get the Module's list of aliases (constant).
const AliasListType &getAliasList() const { return AliasList; }
/// Get the Module's list of aliases.
AliasListType &getAliasList() { return AliasList; }
static iplist<GlobalAlias> Module::*getSublistAccess(GlobalAlias*) {
return &Module::AliasList;
}
/// Get the Module's list of named metadata (constant).
const NamedMDListType &getNamedMDList() const { return NamedMDList; }
/// Get the Module's list of named metadata.
NamedMDListType &getNamedMDList() { return NamedMDList; }
static ilist<NamedMDNode> Module::*getSublistAccess(NamedMDNode*) {
return &Module::NamedMDList;
}
/// Get the symbol table of global variable and function identifiers
const ValueSymbolTable &getValueSymbolTable() const { return *ValSymTab; }
/// Get the Module's symbol table of global variable and function identifiers.
ValueSymbolTable &getValueSymbolTable() { return *ValSymTab; }
/// @}
/// @name Global Variable Iteration
/// @{
global_iterator global_begin() { return GlobalList.begin(); }
const_global_iterator global_begin() const { return GlobalList.begin(); }
global_iterator global_end () { return GlobalList.end(); }
const_global_iterator global_end () const { return GlobalList.end(); }
bool global_empty() const { return GlobalList.empty(); }
/// @}
/// @name Function Iteration
/// @{
iterator begin() { return FunctionList.begin(); }
const_iterator begin() const { return FunctionList.begin(); }
iterator end () { return FunctionList.end(); }
const_iterator end () const { return FunctionList.end(); }
size_t size() const { return FunctionList.size(); }
bool empty() const { return FunctionList.empty(); }
/// @}
/// @name Alias Iteration
/// @{
alias_iterator alias_begin() { return AliasList.begin(); }
const_alias_iterator alias_begin() const { return AliasList.begin(); }
alias_iterator alias_end () { return AliasList.end(); }
const_alias_iterator alias_end () const { return AliasList.end(); }
size_t alias_size () const { return AliasList.size(); }
bool alias_empty() const { return AliasList.empty(); }
/// @}
/// @name Named Metadata Iteration
/// @{
named_metadata_iterator named_metadata_begin() { return NamedMDList.begin(); }
const_named_metadata_iterator named_metadata_begin() const {
return NamedMDList.begin();
}
named_metadata_iterator named_metadata_end() { return NamedMDList.end(); }
const_named_metadata_iterator named_metadata_end() const {
return NamedMDList.end();
}
size_t named_metadata_size() const { return NamedMDList.size(); }
bool named_metadata_empty() const { return NamedMDList.empty(); }
/// @}
/// @name Utility functions for printing and dumping Module objects
/// @{
/// Print the module to an output stream with an optional
/// AssemblyAnnotationWriter.
void print(raw_ostream &OS, AssemblyAnnotationWriter *AAW) const;
/// Dump the module to stderr (for debugging).
void dump() const;
/// This function causes all the subinstructions to "let go" of all references
/// that they are maintaining. This allows one to 'delete' a whole class at
/// a time, even though there may be circular references... first all
/// references are dropped, and all use counts go to zero. Then everything
/// is delete'd for real. Note that no operations are valid on an object
/// that has "dropped all references", except operator delete.
void dropAllReferences();
/// @}
};
/// An raw_ostream inserter for modules.
inline raw_ostream &operator<<(raw_ostream &O, const Module &M) {
M.print(O, 0);
return O;
}
} // End llvm namespace
#endif

View File

@@ -0,0 +1,160 @@
//===-- llvm/OperandTraits.h - OperandTraits class definition ---*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the traits classes that are handy for enforcing the correct
// layout of various User subclasses. It also provides the means for accessing
// the operands in the most efficient manner.
//
#ifndef LLVM_IR_OPERANDTRAITS_H
#define LLVM_IR_OPERANDTRAITS_H
#include "llvm/IR/User.h"
namespace llvm {
//===----------------------------------------------------------------------===//
// FixedNumOperand Trait Class
//===----------------------------------------------------------------------===//
/// FixedNumOperandTraits - determine the allocation regime of the Use array
/// when it is a prefix to the User object, and the number of Use objects is
/// known at compile time.
template <typename SubClass, unsigned ARITY>
struct FixedNumOperandTraits {
static Use *op_begin(SubClass* U) {
return reinterpret_cast<Use*>(U) - ARITY;
}
static Use *op_end(SubClass* U) {
return reinterpret_cast<Use*>(U);
}
static unsigned operands(const User*) {
return ARITY;
}
};
//===----------------------------------------------------------------------===//
// OptionalOperand Trait Class
//===----------------------------------------------------------------------===//
/// OptionalOperandTraits - when the number of operands may change at runtime.
/// Naturally it may only decrease, because the allocations may not change.
template <typename SubClass, unsigned ARITY = 1>
struct OptionalOperandTraits : public FixedNumOperandTraits<SubClass, ARITY> {
static unsigned operands(const User *U) {
return U->getNumOperands();
}
};
//===----------------------------------------------------------------------===//
// VariadicOperand Trait Class
//===----------------------------------------------------------------------===//
/// VariadicOperandTraits - determine the allocation regime of the Use array
/// when it is a prefix to the User object, and the number of Use objects is
/// only known at allocation time.
template <typename SubClass, unsigned MINARITY = 0>
struct VariadicOperandTraits {
static Use *op_begin(SubClass* U) {
return reinterpret_cast<Use*>(U) - static_cast<User*>(U)->getNumOperands();
}
static Use *op_end(SubClass* U) {
return reinterpret_cast<Use*>(U);
}
static unsigned operands(const User *U) {
return U->getNumOperands();
}
};
//===----------------------------------------------------------------------===//
// HungoffOperand Trait Class
//===----------------------------------------------------------------------===//
/// HungoffOperandTraits - determine the allocation regime of the Use array
/// when it is not a prefix to the User object, but allocated at an unrelated
/// heap address.
/// Assumes that the User subclass that is determined by this traits class
/// has an OperandList member of type User::op_iterator. [Note: this is now
/// trivially satisfied, because User has that member for historic reasons.]
///
/// This is the traits class that is needed when the Use array must be
/// resizable.
template <unsigned MINARITY = 1>
struct HungoffOperandTraits {
static Use *op_begin(User* U) {
return U->OperandList;
}
static Use *op_end(User* U) {
return U->OperandList + U->getNumOperands();
}
static unsigned operands(const User *U) {
return U->getNumOperands();
}
};
/// Macro for generating in-class operand accessor declarations.
/// It should only be called in the public section of the interface.
///
#define DECLARE_TRANSPARENT_OPERAND_ACCESSORS(VALUECLASS) \
public: \
inline VALUECLASS *getOperand(unsigned) const; \
inline void setOperand(unsigned, VALUECLASS*); \
inline op_iterator op_begin(); \
inline const_op_iterator op_begin() const; \
inline op_iterator op_end(); \
inline const_op_iterator op_end() const; \
protected: \
template <int> inline Use &Op(); \
template <int> inline const Use &Op() const; \
public: \
inline unsigned getNumOperands() const
/// Macro for generating out-of-class operand accessor definitions
#define DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CLASS, VALUECLASS) \
CLASS::op_iterator CLASS::op_begin() { \
return OperandTraits<CLASS>::op_begin(this); \
} \
CLASS::const_op_iterator CLASS::op_begin() const { \
return OperandTraits<CLASS>::op_begin(const_cast<CLASS*>(this)); \
} \
CLASS::op_iterator CLASS::op_end() { \
return OperandTraits<CLASS>::op_end(this); \
} \
CLASS::const_op_iterator CLASS::op_end() const { \
return OperandTraits<CLASS>::op_end(const_cast<CLASS*>(this)); \
} \
VALUECLASS *CLASS::getOperand(unsigned i_nocapture) const { \
assert(i_nocapture < OperandTraits<CLASS>::operands(this) \
&& "getOperand() out of range!"); \
return cast_or_null<VALUECLASS>( \
OperandTraits<CLASS>::op_begin(const_cast<CLASS*>(this))[i_nocapture].get()); \
} \
void CLASS::setOperand(unsigned i_nocapture, VALUECLASS *Val_nocapture) { \
assert(i_nocapture < OperandTraits<CLASS>::operands(this) \
&& "setOperand() out of range!"); \
OperandTraits<CLASS>::op_begin(this)[i_nocapture] = Val_nocapture; \
} \
unsigned CLASS::getNumOperands() const { \
return OperandTraits<CLASS>::operands(this); \
} \
template <int Idx_nocapture> Use &CLASS::Op() { \
return this->OpFrom<Idx_nocapture>(this); \
} \
template <int Idx_nocapture> const Use &CLASS::Op() const { \
return this->OpFrom<Idx_nocapture>(this); \
}
} // End llvm namespace
#endif

View File

@@ -0,0 +1,478 @@
//===-- llvm/Operator.h - Operator utility subclass -------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines various classes for working with Instructions and
// ConstantExprs.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_IR_OPERATOR_H
#define LLVM_IR_OPERATOR_H
#include "llvm/IR/Constants.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Instruction.h"
#include "llvm/IR/Type.h"
#include "llvm/Support/GetElementPtrTypeIterator.h"
namespace llvm {
class GetElementPtrInst;
class BinaryOperator;
class ConstantExpr;
/// Operator - This is a utility class that provides an abstraction for the
/// common functionality between Instructions and ConstantExprs.
///
class Operator : public User {
private:
// The Operator class is intended to be used as a utility, and is never itself
// instantiated.
void *operator new(size_t, unsigned) LLVM_DELETED_FUNCTION;
void *operator new(size_t s) LLVM_DELETED_FUNCTION;
Operator() LLVM_DELETED_FUNCTION;
protected:
// NOTE: Cannot use LLVM_DELETED_FUNCTION because it's not legal to delete
// an overridden method that's not deleted in the base class. Cannot leave
// this unimplemented because that leads to an ODR-violation.
~Operator();
public:
/// getOpcode - Return the opcode for this Instruction or ConstantExpr.
///
unsigned getOpcode() const {
if (const Instruction *I = dyn_cast<Instruction>(this))
return I->getOpcode();
return cast<ConstantExpr>(this)->getOpcode();
}
/// getOpcode - If V is an Instruction or ConstantExpr, return its
/// opcode. Otherwise return UserOp1.
///
static unsigned getOpcode(const Value *V) {
if (const Instruction *I = dyn_cast<Instruction>(V))
return I->getOpcode();
if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
return CE->getOpcode();
return Instruction::UserOp1;
}
static inline bool classof(const Instruction *) { return true; }
static inline bool classof(const ConstantExpr *) { return true; }
static inline bool classof(const Value *V) {
return isa<Instruction>(V) || isa<ConstantExpr>(V);
}
};
/// OverflowingBinaryOperator - Utility class for integer arithmetic operators
/// which may exhibit overflow - Add, Sub, and Mul. It does not include SDiv,
/// despite that operator having the potential for overflow.
///
class OverflowingBinaryOperator : public Operator {
public:
enum {
NoUnsignedWrap = (1 << 0),
NoSignedWrap = (1 << 1)
};
private:
friend class BinaryOperator;
friend class ConstantExpr;
void setHasNoUnsignedWrap(bool B) {
SubclassOptionalData =
(SubclassOptionalData & ~NoUnsignedWrap) | (B * NoUnsignedWrap);
}
void setHasNoSignedWrap(bool B) {
SubclassOptionalData =
(SubclassOptionalData & ~NoSignedWrap) | (B * NoSignedWrap);
}
public:
/// hasNoUnsignedWrap - Test whether this operation is known to never
/// undergo unsigned overflow, aka the nuw property.
bool hasNoUnsignedWrap() const {
return SubclassOptionalData & NoUnsignedWrap;
}
/// hasNoSignedWrap - Test whether this operation is known to never
/// undergo signed overflow, aka the nsw property.
bool hasNoSignedWrap() const {
return (SubclassOptionalData & NoSignedWrap) != 0;
}
static inline bool classof(const Instruction *I) {
return I->getOpcode() == Instruction::Add ||
I->getOpcode() == Instruction::Sub ||
I->getOpcode() == Instruction::Mul ||
I->getOpcode() == Instruction::Shl;
}
static inline bool classof(const ConstantExpr *CE) {
return CE->getOpcode() == Instruction::Add ||
CE->getOpcode() == Instruction::Sub ||
CE->getOpcode() == Instruction::Mul ||
CE->getOpcode() == Instruction::Shl;
}
static inline bool classof(const Value *V) {
return (isa<Instruction>(V) && classof(cast<Instruction>(V))) ||
(isa<ConstantExpr>(V) && classof(cast<ConstantExpr>(V)));
}
};
/// PossiblyExactOperator - A udiv or sdiv instruction, which can be marked as
/// "exact", indicating that no bits are destroyed.
class PossiblyExactOperator : public Operator {
public:
enum {
IsExact = (1 << 0)
};
private:
friend class BinaryOperator;
friend class ConstantExpr;
void setIsExact(bool B) {
SubclassOptionalData = (SubclassOptionalData & ~IsExact) | (B * IsExact);
}
public:
/// isExact - Test whether this division is known to be exact, with
/// zero remainder.
bool isExact() const {
return SubclassOptionalData & IsExact;
}
static bool isPossiblyExactOpcode(unsigned OpC) {
return OpC == Instruction::SDiv ||
OpC == Instruction::UDiv ||
OpC == Instruction::AShr ||
OpC == Instruction::LShr;
}
static inline bool classof(const ConstantExpr *CE) {
return isPossiblyExactOpcode(CE->getOpcode());
}
static inline bool classof(const Instruction *I) {
return isPossiblyExactOpcode(I->getOpcode());
}
static inline bool classof(const Value *V) {
return (isa<Instruction>(V) && classof(cast<Instruction>(V))) ||
(isa<ConstantExpr>(V) && classof(cast<ConstantExpr>(V)));
}
};
/// Convenience struct for specifying and reasoning about fast-math flags.
class FastMathFlags {
private:
friend class FPMathOperator;
unsigned Flags;
FastMathFlags(unsigned F) : Flags(F) { }
public:
enum {
UnsafeAlgebra = (1 << 0),
NoNaNs = (1 << 1),
NoInfs = (1 << 2),
NoSignedZeros = (1 << 3),
AllowReciprocal = (1 << 4)
};
FastMathFlags() : Flags(0)
{ }
/// Whether any flag is set
bool any() { return Flags != 0; }
/// Set all the flags to false
void clear() { Flags = 0; }
/// Flag queries
bool noNaNs() { return 0 != (Flags & NoNaNs); }
bool noInfs() { return 0 != (Flags & NoInfs); }
bool noSignedZeros() { return 0 != (Flags & NoSignedZeros); }
bool allowReciprocal() { return 0 != (Flags & AllowReciprocal); }
bool unsafeAlgebra() { return 0 != (Flags & UnsafeAlgebra); }
/// Flag setters
void setNoNaNs() { Flags |= NoNaNs; }
void setNoInfs() { Flags |= NoInfs; }
void setNoSignedZeros() { Flags |= NoSignedZeros; }
void setAllowReciprocal() { Flags |= AllowReciprocal; }
void setUnsafeAlgebra() {
Flags |= UnsafeAlgebra;
setNoNaNs();
setNoInfs();
setNoSignedZeros();
setAllowReciprocal();
}
};
/// FPMathOperator - Utility class for floating point operations which can have
/// information about relaxed accuracy requirements attached to them.
class FPMathOperator : public Operator {
private:
friend class Instruction;
void setHasUnsafeAlgebra(bool B) {
SubclassOptionalData =
(SubclassOptionalData & ~FastMathFlags::UnsafeAlgebra) |
(B * FastMathFlags::UnsafeAlgebra);
// Unsafe algebra implies all the others
if (B) {
setHasNoNaNs(true);
setHasNoInfs(true);
setHasNoSignedZeros(true);
setHasAllowReciprocal(true);
}
}
void setHasNoNaNs(bool B) {
SubclassOptionalData =
(SubclassOptionalData & ~FastMathFlags::NoNaNs) |
(B * FastMathFlags::NoNaNs);
}
void setHasNoInfs(bool B) {
SubclassOptionalData =
(SubclassOptionalData & ~FastMathFlags::NoInfs) |
(B * FastMathFlags::NoInfs);
}
void setHasNoSignedZeros(bool B) {
SubclassOptionalData =
(SubclassOptionalData & ~FastMathFlags::NoSignedZeros) |
(B * FastMathFlags::NoSignedZeros);
}
void setHasAllowReciprocal(bool B) {
SubclassOptionalData =
(SubclassOptionalData & ~FastMathFlags::AllowReciprocal) |
(B * FastMathFlags::AllowReciprocal);
}
/// Convenience function for setting all the fast-math flags
void setFastMathFlags(FastMathFlags FMF) {
SubclassOptionalData |= FMF.Flags;
}
public:
/// Test whether this operation is permitted to be
/// algebraically transformed, aka the 'A' fast-math property.
bool hasUnsafeAlgebra() const {
return (SubclassOptionalData & FastMathFlags::UnsafeAlgebra) != 0;
}
/// Test whether this operation's arguments and results are to be
/// treated as non-NaN, aka the 'N' fast-math property.
bool hasNoNaNs() const {
return (SubclassOptionalData & FastMathFlags::NoNaNs) != 0;
}
/// Test whether this operation's arguments and results are to be
/// treated as NoN-Inf, aka the 'I' fast-math property.
bool hasNoInfs() const {
return (SubclassOptionalData & FastMathFlags::NoInfs) != 0;
}
/// Test whether this operation can treat the sign of zero
/// as insignificant, aka the 'S' fast-math property.
bool hasNoSignedZeros() const {
return (SubclassOptionalData & FastMathFlags::NoSignedZeros) != 0;
}
/// Test whether this operation is permitted to use
/// reciprocal instead of division, aka the 'R' fast-math property.
bool hasAllowReciprocal() const {
return (SubclassOptionalData & FastMathFlags::AllowReciprocal) != 0;
}
/// Convenience function for getting all the fast-math flags
FastMathFlags getFastMathFlags() const {
return FastMathFlags(SubclassOptionalData);
}
/// \brief Get the maximum error permitted by this operation in ULPs. An
/// accuracy of 0.0 means that the operation should be performed with the
/// default precision.
float getFPAccuracy() const;
static inline bool classof(const Instruction *I) {
return I->getType()->isFPOrFPVectorTy();
}
static inline bool classof(const Value *V) {
return isa<Instruction>(V) && classof(cast<Instruction>(V));
}
};
/// ConcreteOperator - A helper template for defining operators for individual
/// opcodes.
template<typename SuperClass, unsigned Opc>
class ConcreteOperator : public SuperClass {
public:
static inline bool classof(const Instruction *I) {
return I->getOpcode() == Opc;
}
static inline bool classof(const ConstantExpr *CE) {
return CE->getOpcode() == Opc;
}
static inline bool classof(const Value *V) {
return (isa<Instruction>(V) && classof(cast<Instruction>(V))) ||
(isa<ConstantExpr>(V) && classof(cast<ConstantExpr>(V)));
}
};
class AddOperator
: public ConcreteOperator<OverflowingBinaryOperator, Instruction::Add> {
};
class SubOperator
: public ConcreteOperator<OverflowingBinaryOperator, Instruction::Sub> {
};
class MulOperator
: public ConcreteOperator<OverflowingBinaryOperator, Instruction::Mul> {
};
class ShlOperator
: public ConcreteOperator<OverflowingBinaryOperator, Instruction::Shl> {
};
class SDivOperator
: public ConcreteOperator<PossiblyExactOperator, Instruction::SDiv> {
};
class UDivOperator
: public ConcreteOperator<PossiblyExactOperator, Instruction::UDiv> {
};
class AShrOperator
: public ConcreteOperator<PossiblyExactOperator, Instruction::AShr> {
};
class LShrOperator
: public ConcreteOperator<PossiblyExactOperator, Instruction::LShr> {
};
class GEPOperator
: public ConcreteOperator<Operator, Instruction::GetElementPtr> {
enum {
IsInBounds = (1 << 0)
};
friend class GetElementPtrInst;
friend class ConstantExpr;
void setIsInBounds(bool B) {
SubclassOptionalData =
(SubclassOptionalData & ~IsInBounds) | (B * IsInBounds);
}
public:
/// isInBounds - Test whether this is an inbounds GEP, as defined
/// by LangRef.html.
bool isInBounds() const {
return SubclassOptionalData & IsInBounds;
}
inline op_iterator idx_begin() { return op_begin()+1; }
inline const_op_iterator idx_begin() const { return op_begin()+1; }
inline op_iterator idx_end() { return op_end(); }
inline const_op_iterator idx_end() const { return op_end(); }
Value *getPointerOperand() {
return getOperand(0);
}
const Value *getPointerOperand() const {
return getOperand(0);
}
static unsigned getPointerOperandIndex() {
return 0U; // get index for modifying correct operand
}
/// getPointerOperandType - Method to return the pointer operand as a
/// PointerType.
Type *getPointerOperandType() const {
return getPointerOperand()->getType();
}
/// getPointerAddressSpace - Method to return the address space of the
/// pointer operand.
unsigned getPointerAddressSpace() const {
return cast<PointerType>(getPointerOperandType())->getAddressSpace();
}
unsigned getNumIndices() const { // Note: always non-negative
return getNumOperands() - 1;
}
bool hasIndices() const {
return getNumOperands() > 1;
}
/// hasAllZeroIndices - Return true if all of the indices of this GEP are
/// zeros. If so, the result pointer and the first operand have the same
/// value, just potentially different types.
bool hasAllZeroIndices() const {
for (const_op_iterator I = idx_begin(), E = idx_end(); I != E; ++I) {
if (ConstantInt *C = dyn_cast<ConstantInt>(I))
if (C->isZero())
continue;
return false;
}
return true;
}
/// hasAllConstantIndices - Return true if all of the indices of this GEP are
/// constant integers. If so, the result pointer and the first operand have
/// a constant offset between them.
bool hasAllConstantIndices() const {
for (const_op_iterator I = idx_begin(), E = idx_end(); I != E; ++I) {
if (!isa<ConstantInt>(I))
return false;
}
return true;
}
/// \brief Accumulate the constant address offset of this GEP if possible.
///
/// This routine accepts an APInt into which it will accumulate the constant
/// offset of this GEP if the GEP is in fact constant. If the GEP is not
/// all-constant, it returns false and the value of the offset APInt is
/// undefined (it is *not* preserved!). The APInt passed into this routine
/// must be at least as wide as the IntPtr type for the address space of
/// the base GEP pointer.
bool accumulateConstantOffset(const DataLayout &DL, APInt &Offset) const {
assert(Offset.getBitWidth() ==
DL.getPointerSizeInBits(getPointerAddressSpace()) &&
"The offset must have exactly as many bits as our pointer.");
for (gep_type_iterator GTI = gep_type_begin(this), GTE = gep_type_end(this);
GTI != GTE; ++GTI) {
ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
if (!OpC)
return false;
if (OpC->isZero())
continue;
// Handle a struct index, which adds its field offset to the pointer.
if (StructType *STy = dyn_cast<StructType>(*GTI)) {
unsigned ElementIdx = OpC->getZExtValue();
const StructLayout *SL = DL.getStructLayout(STy);
Offset += APInt(Offset.getBitWidth(),
SL->getElementOffset(ElementIdx));
continue;
}
// For array or vector indices, scale the index by the size of the type.
APInt Index = OpC->getValue().sextOrTrunc(Offset.getBitWidth());
Offset += Index * APInt(Offset.getBitWidth(),
DL.getTypeAllocSize(GTI.getIndexedType()));
}
return true;
}
};
} // End llvm namespace
#endif

View File

@@ -0,0 +1,78 @@
//===-- llvm/SymbolTableListTraits.h - Traits for iplist --------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines a generic class that is used to implement the automatic
// symbol table manipulation that occurs when you put (for example) a named
// instruction into a basic block.
//
// The way that this is implemented is by using a special traits class with the
// intrusive list that makes up the list of instructions in a basic block. When
// a new element is added to the list of instructions, the traits class is
// notified, allowing the symbol table to be updated.
//
// This generic class implements the traits class. It must be generic so that
// it can work for all uses it, which include lists of instructions, basic
// blocks, arguments, functions, global variables, etc...
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_IR_SYMBOLTABLELISTTRAITS_H
#define LLVM_IR_SYMBOLTABLELISTTRAITS_H
#include "llvm/ADT/ilist.h"
namespace llvm {
class ValueSymbolTable;
template<typename NodeTy> class ilist_iterator;
template<typename NodeTy, typename Traits> class iplist;
template<typename Ty> struct ilist_traits;
// ValueSubClass - The type of objects that I hold, e.g. Instruction.
// ItemParentClass - The type of object that owns the list, e.g. BasicBlock.
//
template<typename ValueSubClass, typename ItemParentClass>
class SymbolTableListTraits : public ilist_default_traits<ValueSubClass> {
typedef ilist_traits<ValueSubClass> TraitsClass;
public:
SymbolTableListTraits() {}
/// getListOwner - Return the object that owns this list. If this is a list
/// of instructions, it returns the BasicBlock that owns them.
ItemParentClass *getListOwner() {
size_t Offset(size_t(&((ItemParentClass*)0->*ItemParentClass::
getSublistAccess(static_cast<ValueSubClass*>(0)))));
iplist<ValueSubClass>* Anchor(static_cast<iplist<ValueSubClass>*>(this));
return reinterpret_cast<ItemParentClass*>(reinterpret_cast<char*>(Anchor)-
Offset);
}
static iplist<ValueSubClass> &getList(ItemParentClass *Par) {
return Par->*(Par->getSublistAccess((ValueSubClass*)0));
}
static ValueSymbolTable *getSymTab(ItemParentClass *Par) {
return Par ? toPtr(Par->getValueSymbolTable()) : 0;
}
void addNodeToList(ValueSubClass *V);
void removeNodeFromList(ValueSubClass *V);
void transferNodesFromList(ilist_traits<ValueSubClass> &L2,
ilist_iterator<ValueSubClass> first,
ilist_iterator<ValueSubClass> last);
//private:
template<typename TPtr>
void setSymTabObject(TPtr *, TPtr);
static ValueSymbolTable *toPtr(ValueSymbolTable *P) { return P; }
static ValueSymbolTable *toPtr(ValueSymbolTable &R) { return &R; }
};
} // End llvm namespace
#endif

472
thirdparty/clang/include/llvm/IR/Type.h vendored Normal file
View File

@@ -0,0 +1,472 @@
//===-- llvm/Type.h - Classes for handling data types -----------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains the declaration of the Type class. For more "Type"
// stuff, look in DerivedTypes.h.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_IR_TYPE_H
#define LLVM_IR_TYPE_H
#include "llvm/ADT/APFloat.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/DataTypes.h"
#include "llvm/Support/ErrorHandling.h"
namespace llvm {
class PointerType;
class IntegerType;
class raw_ostream;
class Module;
class LLVMContext;
class LLVMContextImpl;
class StringRef;
template<class GraphType> struct GraphTraits;
/// The instances of the Type class are immutable: once they are created,
/// they are never changed. Also note that only one instance of a particular
/// type is ever created. Thus seeing if two types are equal is a matter of
/// doing a trivial pointer comparison. To enforce that no two equal instances
/// are created, Type instances can only be created via static factory methods
/// in class Type and in derived classes. Once allocated, Types are never
/// free'd.
///
class Type {
public:
//===--------------------------------------------------------------------===//
/// Definitions of all of the base types for the Type system. Based on this
/// value, you can cast to a class defined in DerivedTypes.h.
/// Note: If you add an element to this, you need to add an element to the
/// Type::getPrimitiveType function, or else things will break!
/// Also update LLVMTypeKind and LLVMGetTypeKind () in the C binding.
///
enum TypeID {
// PrimitiveTypes - make sure LastPrimitiveTyID stays up to date.
VoidTyID = 0, ///< 0: type with no size
HalfTyID, ///< 1: 16-bit floating point type
FloatTyID, ///< 2: 32-bit floating point type
DoubleTyID, ///< 3: 64-bit floating point type
X86_FP80TyID, ///< 4: 80-bit floating point type (X87)
FP128TyID, ///< 5: 128-bit floating point type (112-bit mantissa)
PPC_FP128TyID, ///< 6: 128-bit floating point type (two 64-bits, PowerPC)
LabelTyID, ///< 7: Labels
MetadataTyID, ///< 8: Metadata
X86_MMXTyID, ///< 9: MMX vectors (64 bits, X86 specific)
// Derived types... see DerivedTypes.h file.
// Make sure FirstDerivedTyID stays up to date!
IntegerTyID, ///< 10: Arbitrary bit width integers
FunctionTyID, ///< 11: Functions
StructTyID, ///< 12: Structures
ArrayTyID, ///< 13: Arrays
PointerTyID, ///< 14: Pointers
VectorTyID, ///< 15: SIMD 'packed' format, or other vector type
NumTypeIDs, // Must remain as last defined ID
LastPrimitiveTyID = X86_MMXTyID,
FirstDerivedTyID = IntegerTyID
};
private:
/// Context - This refers to the LLVMContext in which this type was uniqued.
LLVMContext &Context;
// Due to Ubuntu GCC bug 910363:
// https://bugs.launchpad.net/ubuntu/+source/gcc-4.5/+bug/910363
// Bitpack ID and SubclassData manually.
// Note: TypeID : low 8 bit; SubclassData : high 24 bit.
uint32_t IDAndSubclassData;
protected:
friend class LLVMContextImpl;
explicit Type(LLVMContext &C, TypeID tid)
: Context(C), IDAndSubclassData(0),
NumContainedTys(0), ContainedTys(0) {
setTypeID(tid);
}
~Type() {}
void setTypeID(TypeID ID) {
IDAndSubclassData = (ID & 0xFF) | (IDAndSubclassData & 0xFFFFFF00);
assert(getTypeID() == ID && "TypeID data too large for field");
}
unsigned getSubclassData() const { return IDAndSubclassData >> 8; }
void setSubclassData(unsigned val) {
IDAndSubclassData = (IDAndSubclassData & 0xFF) | (val << 8);
// Ensure we don't have any accidental truncation.
assert(getSubclassData() == val && "Subclass data too large for field");
}
/// NumContainedTys - Keeps track of how many Type*'s there are in the
/// ContainedTys list.
unsigned NumContainedTys;
/// ContainedTys - A pointer to the array of Types contained by this Type.
/// For example, this includes the arguments of a function type, the elements
/// of a structure, the pointee of a pointer, the element type of an array,
/// etc. This pointer may be 0 for types that don't contain other types
/// (Integer, Double, Float).
Type * const *ContainedTys;
public:
void print(raw_ostream &O) const;
void dump() const;
/// getContext - Return the LLVMContext in which this type was uniqued.
LLVMContext &getContext() const { return Context; }
//===--------------------------------------------------------------------===//
// Accessors for working with types.
//
/// getTypeID - Return the type id for the type. This will return one
/// of the TypeID enum elements defined above.
///
TypeID getTypeID() const { return (TypeID)(IDAndSubclassData & 0xFF); }
/// isVoidTy - Return true if this is 'void'.
bool isVoidTy() const { return getTypeID() == VoidTyID; }
/// isHalfTy - Return true if this is 'half', a 16-bit IEEE fp type.
bool isHalfTy() const { return getTypeID() == HalfTyID; }
/// isFloatTy - Return true if this is 'float', a 32-bit IEEE fp type.
bool isFloatTy() const { return getTypeID() == FloatTyID; }
/// isDoubleTy - Return true if this is 'double', a 64-bit IEEE fp type.
bool isDoubleTy() const { return getTypeID() == DoubleTyID; }
/// isX86_FP80Ty - Return true if this is x86 long double.
bool isX86_FP80Ty() const { return getTypeID() == X86_FP80TyID; }
/// isFP128Ty - Return true if this is 'fp128'.
bool isFP128Ty() const { return getTypeID() == FP128TyID; }
/// isPPC_FP128Ty - Return true if this is powerpc long double.
bool isPPC_FP128Ty() const { return getTypeID() == PPC_FP128TyID; }
/// isFloatingPointTy - Return true if this is one of the six floating point
/// types
bool isFloatingPointTy() const {
return getTypeID() == HalfTyID || getTypeID() == FloatTyID ||
getTypeID() == DoubleTyID ||
getTypeID() == X86_FP80TyID || getTypeID() == FP128TyID ||
getTypeID() == PPC_FP128TyID;
}
const fltSemantics &getFltSemantics() const {
switch (getTypeID()) {
case HalfTyID: return APFloat::IEEEhalf;
case FloatTyID: return APFloat::IEEEsingle;
case DoubleTyID: return APFloat::IEEEdouble;
case X86_FP80TyID: return APFloat::x87DoubleExtended;
case FP128TyID: return APFloat::IEEEquad;
case PPC_FP128TyID: return APFloat::PPCDoubleDouble;
default: llvm_unreachable("Invalid floating type");
}
}
/// isX86_MMXTy - Return true if this is X86 MMX.
bool isX86_MMXTy() const { return getTypeID() == X86_MMXTyID; }
/// isFPOrFPVectorTy - Return true if this is a FP type or a vector of FP.
///
bool isFPOrFPVectorTy() const { return getScalarType()->isFloatingPointTy(); }
/// isLabelTy - Return true if this is 'label'.
bool isLabelTy() const { return getTypeID() == LabelTyID; }
/// isMetadataTy - Return true if this is 'metadata'.
bool isMetadataTy() const { return getTypeID() == MetadataTyID; }
/// isIntegerTy - True if this is an instance of IntegerType.
///
bool isIntegerTy() const { return getTypeID() == IntegerTyID; }
/// isIntegerTy - Return true if this is an IntegerType of the given width.
bool isIntegerTy(unsigned Bitwidth) const;
/// isIntOrIntVectorTy - Return true if this is an integer type or a vector of
/// integer types.
///
bool isIntOrIntVectorTy() const { return getScalarType()->isIntegerTy(); }
/// isFunctionTy - True if this is an instance of FunctionType.
///
bool isFunctionTy() const { return getTypeID() == FunctionTyID; }
/// isStructTy - True if this is an instance of StructType.
///
bool isStructTy() const { return getTypeID() == StructTyID; }
/// isArrayTy - True if this is an instance of ArrayType.
///
bool isArrayTy() const { return getTypeID() == ArrayTyID; }
/// isPointerTy - True if this is an instance of PointerType.
///
bool isPointerTy() const { return getTypeID() == PointerTyID; }
/// isPtrOrPtrVectorTy - Return true if this is a pointer type or a vector of
/// pointer types.
///
bool isPtrOrPtrVectorTy() const { return getScalarType()->isPointerTy(); }
/// isVectorTy - True if this is an instance of VectorType.
///
bool isVectorTy() const { return getTypeID() == VectorTyID; }
/// canLosslesslyBitCastTo - Return true if this type could be converted
/// with a lossless BitCast to type 'Ty'. For example, i8* to i32*. BitCasts
/// are valid for types of the same size only where no re-interpretation of
/// the bits is done.
/// @brief Determine if this type could be losslessly bitcast to Ty
bool canLosslesslyBitCastTo(Type *Ty) const;
/// isEmptyTy - Return true if this type is empty, that is, it has no
/// elements or all its elements are empty.
bool isEmptyTy() const;
/// Here are some useful little methods to query what type derived types are
/// Note that all other types can just compare to see if this == Type::xxxTy;
///
bool isPrimitiveType() const { return getTypeID() <= LastPrimitiveTyID; }
bool isDerivedType() const { return getTypeID() >= FirstDerivedTyID; }
/// isFirstClassType - Return true if the type is "first class", meaning it
/// is a valid type for a Value.
///
bool isFirstClassType() const {
return getTypeID() != FunctionTyID && getTypeID() != VoidTyID;
}
/// isSingleValueType - Return true if the type is a valid type for a
/// register in codegen. This includes all first-class types except struct
/// and array types.
///
bool isSingleValueType() const {
return (getTypeID() != VoidTyID && isPrimitiveType()) ||
getTypeID() == IntegerTyID || getTypeID() == PointerTyID ||
getTypeID() == VectorTyID;
}
/// isAggregateType - Return true if the type is an aggregate type. This
/// means it is valid as the first operand of an insertvalue or
/// extractvalue instruction. This includes struct and array types, but
/// does not include vector types.
///
bool isAggregateType() const {
return getTypeID() == StructTyID || getTypeID() == ArrayTyID;
}
/// isSized - Return true if it makes sense to take the size of this type. To
/// get the actual size for a particular target, it is reasonable to use the
/// DataLayout subsystem to do this.
///
bool isSized() const {
// If it's a primitive, it is always sized.
if (getTypeID() == IntegerTyID || isFloatingPointTy() ||
getTypeID() == PointerTyID ||
getTypeID() == X86_MMXTyID)
return true;
// If it is not something that can have a size (e.g. a function or label),
// it doesn't have a size.
if (getTypeID() != StructTyID && getTypeID() != ArrayTyID &&
getTypeID() != VectorTyID)
return false;
// Otherwise we have to try harder to decide.
return isSizedDerivedType();
}
/// getPrimitiveSizeInBits - Return the basic size of this type if it is a
/// primitive type. These are fixed by LLVM and are not target dependent.
/// This will return zero if the type does not have a size or is not a
/// primitive type.
///
/// Note that this may not reflect the size of memory allocated for an
/// instance of the type or the number of bytes that are written when an
/// instance of the type is stored to memory. The DataLayout class provides
/// additional query functions to provide this information.
///
unsigned getPrimitiveSizeInBits() const;
/// getScalarSizeInBits - If this is a vector type, return the
/// getPrimitiveSizeInBits value for the element type. Otherwise return the
/// getPrimitiveSizeInBits value for this type.
unsigned getScalarSizeInBits();
/// getFPMantissaWidth - Return the width of the mantissa of this type. This
/// is only valid on floating point types. If the FP type does not
/// have a stable mantissa (e.g. ppc long double), this method returns -1.
int getFPMantissaWidth() const;
/// getScalarType - If this is a vector type, return the element type,
/// otherwise return 'this'.
const Type *getScalarType() const;
Type *getScalarType();
//===--------------------------------------------------------------------===//
// Type Iteration support.
//
typedef Type * const *subtype_iterator;
subtype_iterator subtype_begin() const { return ContainedTys; }
subtype_iterator subtype_end() const { return &ContainedTys[NumContainedTys];}
/// getContainedType - This method is used to implement the type iterator
/// (defined a the end of the file). For derived types, this returns the
/// types 'contained' in the derived type.
///
Type *getContainedType(unsigned i) const {
assert(i < NumContainedTys && "Index out of range!");
return ContainedTys[i];
}
/// getNumContainedTypes - Return the number of types in the derived type.
///
unsigned getNumContainedTypes() const { return NumContainedTys; }
//===--------------------------------------------------------------------===//
// Helper methods corresponding to subclass methods. This forces a cast to
// the specified subclass and calls its accessor. "getVectorNumElements" (for
// example) is shorthand for cast<VectorType>(Ty)->getNumElements(). This is
// only intended to cover the core methods that are frequently used, helper
// methods should not be added here.
unsigned getIntegerBitWidth() const;
Type *getFunctionParamType(unsigned i) const;
unsigned getFunctionNumParams() const;
bool isFunctionVarArg() const;
StringRef getStructName() const;
unsigned getStructNumElements() const;
Type *getStructElementType(unsigned N) const;
Type *getSequentialElementType() const;
uint64_t getArrayNumElements() const;
Type *getArrayElementType() const { return getSequentialElementType(); }
unsigned getVectorNumElements() const;
Type *getVectorElementType() const { return getSequentialElementType(); }
Type *getPointerElementType() const { return getSequentialElementType(); }
/// \brief Get the address space of this pointer or pointer vector type.
unsigned getPointerAddressSpace() const;
//===--------------------------------------------------------------------===//
// Static members exported by the Type class itself. Useful for getting
// instances of Type.
//
/// getPrimitiveType - Return a type based on an identifier.
static Type *getPrimitiveType(LLVMContext &C, TypeID IDNumber);
//===--------------------------------------------------------------------===//
// These are the builtin types that are always available.
//
static Type *getVoidTy(LLVMContext &C);
static Type *getLabelTy(LLVMContext &C);
static Type *getHalfTy(LLVMContext &C);
static Type *getFloatTy(LLVMContext &C);
static Type *getDoubleTy(LLVMContext &C);
static Type *getMetadataTy(LLVMContext &C);
static Type *getX86_FP80Ty(LLVMContext &C);
static Type *getFP128Ty(LLVMContext &C);
static Type *getPPC_FP128Ty(LLVMContext &C);
static Type *getX86_MMXTy(LLVMContext &C);
static IntegerType *getIntNTy(LLVMContext &C, unsigned N);
static IntegerType *getInt1Ty(LLVMContext &C);
static IntegerType *getInt8Ty(LLVMContext &C);
static IntegerType *getInt16Ty(LLVMContext &C);
static IntegerType *getInt32Ty(LLVMContext &C);
static IntegerType *getInt64Ty(LLVMContext &C);
//===--------------------------------------------------------------------===//
// Convenience methods for getting pointer types with one of the above builtin
// types as pointee.
//
static PointerType *getHalfPtrTy(LLVMContext &C, unsigned AS = 0);
static PointerType *getFloatPtrTy(LLVMContext &C, unsigned AS = 0);
static PointerType *getDoublePtrTy(LLVMContext &C, unsigned AS = 0);
static PointerType *getX86_FP80PtrTy(LLVMContext &C, unsigned AS = 0);
static PointerType *getFP128PtrTy(LLVMContext &C, unsigned AS = 0);
static PointerType *getPPC_FP128PtrTy(LLVMContext &C, unsigned AS = 0);
static PointerType *getX86_MMXPtrTy(LLVMContext &C, unsigned AS = 0);
static PointerType *getIntNPtrTy(LLVMContext &C, unsigned N, unsigned AS = 0);
static PointerType *getInt1PtrTy(LLVMContext &C, unsigned AS = 0);
static PointerType *getInt8PtrTy(LLVMContext &C, unsigned AS = 0);
static PointerType *getInt16PtrTy(LLVMContext &C, unsigned AS = 0);
static PointerType *getInt32PtrTy(LLVMContext &C, unsigned AS = 0);
static PointerType *getInt64PtrTy(LLVMContext &C, unsigned AS = 0);
/// getPointerTo - Return a pointer to the current type. This is equivalent
/// to PointerType::get(Foo, AddrSpace).
PointerType *getPointerTo(unsigned AddrSpace = 0);
private:
/// isSizedDerivedType - Derived types like structures and arrays are sized
/// iff all of the members of the type are sized as well. Since asking for
/// their size is relatively uncommon, move this operation out of line.
bool isSizedDerivedType() const;
};
// Printing of types.
static inline raw_ostream &operator<<(raw_ostream &OS, Type &T) {
T.print(OS);
return OS;
}
// allow isa<PointerType>(x) to work without DerivedTypes.h included.
template <> struct isa_impl<PointerType, Type> {
static inline bool doit(const Type &Ty) {
return Ty.getTypeID() == Type::PointerTyID;
}
};
//===----------------------------------------------------------------------===//
// Provide specializations of GraphTraits to be able to treat a type as a
// graph of sub types.
template <> struct GraphTraits<Type*> {
typedef Type NodeType;
typedef Type::subtype_iterator ChildIteratorType;
static inline NodeType *getEntryNode(Type *T) { return T; }
static inline ChildIteratorType child_begin(NodeType *N) {
return N->subtype_begin();
}
static inline ChildIteratorType child_end(NodeType *N) {
return N->subtype_end();
}
};
template <> struct GraphTraits<const Type*> {
typedef const Type NodeType;
typedef Type::subtype_iterator ChildIteratorType;
static inline NodeType *getEntryNode(NodeType *T) { return T; }
static inline ChildIteratorType child_begin(NodeType *N) {
return N->subtype_begin();
}
static inline ChildIteratorType child_end(NodeType *N) {
return N->subtype_end();
}
};
} // End llvm namespace
#endif

View File

@@ -0,0 +1,399 @@
//===---- llvm/TypeBuilder.h - Builder for LLVM types -----------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the TypeBuilder class, which is used as a convenient way to
// create LLVM types with a consistent and simplified interface.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_IR_TYPEBUILDER_H
#define LLVM_IR_TYPEBUILDER_H
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/LLVMContext.h"
#include <limits.h>
namespace llvm {
/// TypeBuilder - This provides a uniform API for looking up types
/// known at compile time. To support cross-compilation, we define a
/// series of tag types in the llvm::types namespace, like i<N>,
/// ieee_float, ppc_fp128, etc. TypeBuilder<T, false> allows T to be
/// any of these, a native C type (whose size may depend on the host
/// compiler), or a pointer, function, or struct type built out of
/// these. TypeBuilder<T, true> removes native C types from this set
/// to guarantee that its result is suitable for cross-compilation.
/// We define the primitive types, pointer types, and functions up to
/// 5 arguments here, but to use this class with your own types,
/// you'll need to specialize it. For example, say you want to call a
/// function defined externally as:
///
/// struct MyType {
/// int32 a;
/// int32 *b;
/// void *array[1]; // Intended as a flexible array.
/// };
/// int8 AFunction(struct MyType *value);
///
/// You'll want to use
/// Function::Create(TypeBuilder<types::i<8>(MyType*), true>::get(), ...)
/// to declare the function, but when you first try this, your compiler will
/// complain that TypeBuilder<MyType, true>::get() doesn't exist. To fix this,
/// write:
///
/// namespace llvm {
/// template<bool xcompile> class TypeBuilder<MyType, xcompile> {
/// public:
/// static StructType *get(LLVMContext &Context) {
/// // If you cache this result, be sure to cache it separately
/// // for each LLVMContext.
/// return StructType::get(
/// TypeBuilder<types::i<32>, xcompile>::get(Context),
/// TypeBuilder<types::i<32>*, xcompile>::get(Context),
/// TypeBuilder<types::i<8>*[], xcompile>::get(Context),
/// NULL);
/// }
///
/// // You may find this a convenient place to put some constants
/// // to help with getelementptr. They don't have any effect on
/// // the operation of TypeBuilder.
/// enum Fields {
/// FIELD_A,
/// FIELD_B,
/// FIELD_ARRAY
/// };
/// }
/// } // namespace llvm
///
/// TypeBuilder cannot handle recursive types or types you only know at runtime.
/// If you try to give it a recursive type, it will deadlock, infinitely
/// recurse, or do something similarly undesirable.
template<typename T, bool cross_compilable> class TypeBuilder {};
// Types for use with cross-compilable TypeBuilders. These correspond
// exactly with an LLVM-native type.
namespace types {
/// i<N> corresponds to the LLVM IntegerType with N bits.
template<uint32_t num_bits> class i {};
// The following classes represent the LLVM floating types.
class ieee_float {};
class ieee_double {};
class x86_fp80 {};
class fp128 {};
class ppc_fp128 {};
// X86 MMX.
class x86_mmx {};
} // namespace types
// LLVM doesn't have const or volatile types.
template<typename T, bool cross> class TypeBuilder<const T, cross>
: public TypeBuilder<T, cross> {};
template<typename T, bool cross> class TypeBuilder<volatile T, cross>
: public TypeBuilder<T, cross> {};
template<typename T, bool cross> class TypeBuilder<const volatile T, cross>
: public TypeBuilder<T, cross> {};
// Pointers
template<typename T, bool cross> class TypeBuilder<T*, cross> {
public:
static PointerType *get(LLVMContext &Context) {
return PointerType::getUnqual(TypeBuilder<T,cross>::get(Context));
}
};
/// There is no support for references
template<typename T, bool cross> class TypeBuilder<T&, cross> {};
// Arrays
template<typename T, size_t N, bool cross> class TypeBuilder<T[N], cross> {
public:
static ArrayType *get(LLVMContext &Context) {
return ArrayType::get(TypeBuilder<T, cross>::get(Context), N);
}
};
/// LLVM uses an array of length 0 to represent an unknown-length array.
template<typename T, bool cross> class TypeBuilder<T[], cross> {
public:
static ArrayType *get(LLVMContext &Context) {
return ArrayType::get(TypeBuilder<T, cross>::get(Context), 0);
}
};
// Define the C integral types only for TypeBuilder<T, false>.
//
// C integral types do not have a defined size. It would be nice to use the
// stdint.h-defined typedefs that do have defined sizes, but we'd run into the
// following problem:
//
// On an ILP32 machine, stdint.h might define:
//
// typedef int int32_t;
// typedef long long int64_t;
// typedef long size_t;
//
// If we defined TypeBuilder<int32_t> and TypeBuilder<int64_t>, then any use of
// TypeBuilder<size_t> would fail. We couldn't define TypeBuilder<size_t> in
// addition to the defined-size types because we'd get duplicate definitions on
// platforms where stdint.h instead defines:
//
// typedef int int32_t;
// typedef long long int64_t;
// typedef int size_t;
//
// So we define all the primitive C types and nothing else.
#define DEFINE_INTEGRAL_TYPEBUILDER(T) \
template<> class TypeBuilder<T, false> { \
public: \
static IntegerType *get(LLVMContext &Context) { \
return IntegerType::get(Context, sizeof(T) * CHAR_BIT); \
} \
}; \
template<> class TypeBuilder<T, true> { \
/* We provide a definition here so users don't accidentally */ \
/* define these types to work. */ \
}
DEFINE_INTEGRAL_TYPEBUILDER(char);
DEFINE_INTEGRAL_TYPEBUILDER(signed char);
DEFINE_INTEGRAL_TYPEBUILDER(unsigned char);
DEFINE_INTEGRAL_TYPEBUILDER(short);
DEFINE_INTEGRAL_TYPEBUILDER(unsigned short);
DEFINE_INTEGRAL_TYPEBUILDER(int);
DEFINE_INTEGRAL_TYPEBUILDER(unsigned int);
DEFINE_INTEGRAL_TYPEBUILDER(long);
DEFINE_INTEGRAL_TYPEBUILDER(unsigned long);
#ifdef _MSC_VER
DEFINE_INTEGRAL_TYPEBUILDER(__int64);
DEFINE_INTEGRAL_TYPEBUILDER(unsigned __int64);
#else /* _MSC_VER */
DEFINE_INTEGRAL_TYPEBUILDER(long long);
DEFINE_INTEGRAL_TYPEBUILDER(unsigned long long);
#endif /* _MSC_VER */
#undef DEFINE_INTEGRAL_TYPEBUILDER
template<uint32_t num_bits, bool cross>
class TypeBuilder<types::i<num_bits>, cross> {
public:
static IntegerType *get(LLVMContext &C) {
return IntegerType::get(C, num_bits);
}
};
template<> class TypeBuilder<float, false> {
public:
static Type *get(LLVMContext& C) {
return Type::getFloatTy(C);
}
};
template<> class TypeBuilder<float, true> {};
template<> class TypeBuilder<double, false> {
public:
static Type *get(LLVMContext& C) {
return Type::getDoubleTy(C);
}
};
template<> class TypeBuilder<double, true> {};
template<bool cross> class TypeBuilder<types::ieee_float, cross> {
public:
static Type *get(LLVMContext& C) { return Type::getFloatTy(C); }
};
template<bool cross> class TypeBuilder<types::ieee_double, cross> {
public:
static Type *get(LLVMContext& C) { return Type::getDoubleTy(C); }
};
template<bool cross> class TypeBuilder<types::x86_fp80, cross> {
public:
static Type *get(LLVMContext& C) { return Type::getX86_FP80Ty(C); }
};
template<bool cross> class TypeBuilder<types::fp128, cross> {
public:
static Type *get(LLVMContext& C) { return Type::getFP128Ty(C); }
};
template<bool cross> class TypeBuilder<types::ppc_fp128, cross> {
public:
static Type *get(LLVMContext& C) { return Type::getPPC_FP128Ty(C); }
};
template<bool cross> class TypeBuilder<types::x86_mmx, cross> {
public:
static Type *get(LLVMContext& C) { return Type::getX86_MMXTy(C); }
};
template<bool cross> class TypeBuilder<void, cross> {
public:
static Type *get(LLVMContext &C) {
return Type::getVoidTy(C);
}
};
/// void* is disallowed in LLVM types, but it occurs often enough in C code that
/// we special case it.
template<> class TypeBuilder<void*, false>
: public TypeBuilder<types::i<8>*, false> {};
template<> class TypeBuilder<const void*, false>
: public TypeBuilder<types::i<8>*, false> {};
template<> class TypeBuilder<volatile void*, false>
: public TypeBuilder<types::i<8>*, false> {};
template<> class TypeBuilder<const volatile void*, false>
: public TypeBuilder<types::i<8>*, false> {};
template<typename R, bool cross> class TypeBuilder<R(), cross> {
public:
static FunctionType *get(LLVMContext &Context) {
return FunctionType::get(TypeBuilder<R, cross>::get(Context), false);
}
};
template<typename R, typename A1, bool cross> class TypeBuilder<R(A1), cross> {
public:
static FunctionType *get(LLVMContext &Context) {
Type *params[] = {
TypeBuilder<A1, cross>::get(Context),
};
return FunctionType::get(TypeBuilder<R, cross>::get(Context),
params, false);
}
};
template<typename R, typename A1, typename A2, bool cross>
class TypeBuilder<R(A1, A2), cross> {
public:
static FunctionType *get(LLVMContext &Context) {
Type *params[] = {
TypeBuilder<A1, cross>::get(Context),
TypeBuilder<A2, cross>::get(Context),
};
return FunctionType::get(TypeBuilder<R, cross>::get(Context),
params, false);
}
};
template<typename R, typename A1, typename A2, typename A3, bool cross>
class TypeBuilder<R(A1, A2, A3), cross> {
public:
static FunctionType *get(LLVMContext &Context) {
Type *params[] = {
TypeBuilder<A1, cross>::get(Context),
TypeBuilder<A2, cross>::get(Context),
TypeBuilder<A3, cross>::get(Context),
};
return FunctionType::get(TypeBuilder<R, cross>::get(Context),
params, false);
}
};
template<typename R, typename A1, typename A2, typename A3, typename A4,
bool cross>
class TypeBuilder<R(A1, A2, A3, A4), cross> {
public:
static FunctionType *get(LLVMContext &Context) {
Type *params[] = {
TypeBuilder<A1, cross>::get(Context),
TypeBuilder<A2, cross>::get(Context),
TypeBuilder<A3, cross>::get(Context),
TypeBuilder<A4, cross>::get(Context),
};
return FunctionType::get(TypeBuilder<R, cross>::get(Context),
params, false);
}
};
template<typename R, typename A1, typename A2, typename A3, typename A4,
typename A5, bool cross>
class TypeBuilder<R(A1, A2, A3, A4, A5), cross> {
public:
static FunctionType *get(LLVMContext &Context) {
Type *params[] = {
TypeBuilder<A1, cross>::get(Context),
TypeBuilder<A2, cross>::get(Context),
TypeBuilder<A3, cross>::get(Context),
TypeBuilder<A4, cross>::get(Context),
TypeBuilder<A5, cross>::get(Context),
};
return FunctionType::get(TypeBuilder<R, cross>::get(Context),
params, false);
}
};
template<typename R, bool cross> class TypeBuilder<R(...), cross> {
public:
static FunctionType *get(LLVMContext &Context) {
return FunctionType::get(TypeBuilder<R, cross>::get(Context), true);
}
};
template<typename R, typename A1, bool cross>
class TypeBuilder<R(A1, ...), cross> {
public:
static FunctionType *get(LLVMContext &Context) {
Type *params[] = {
TypeBuilder<A1, cross>::get(Context),
};
return FunctionType::get(TypeBuilder<R, cross>::get(Context), params, true);
}
};
template<typename R, typename A1, typename A2, bool cross>
class TypeBuilder<R(A1, A2, ...), cross> {
public:
static FunctionType *get(LLVMContext &Context) {
Type *params[] = {
TypeBuilder<A1, cross>::get(Context),
TypeBuilder<A2, cross>::get(Context),
};
return FunctionType::get(TypeBuilder<R, cross>::get(Context),
params, true);
}
};
template<typename R, typename A1, typename A2, typename A3, bool cross>
class TypeBuilder<R(A1, A2, A3, ...), cross> {
public:
static FunctionType *get(LLVMContext &Context) {
Type *params[] = {
TypeBuilder<A1, cross>::get(Context),
TypeBuilder<A2, cross>::get(Context),
TypeBuilder<A3, cross>::get(Context),
};
return FunctionType::get(TypeBuilder<R, cross>::get(Context),
params, true);
}
};
template<typename R, typename A1, typename A2, typename A3, typename A4,
bool cross>
class TypeBuilder<R(A1, A2, A3, A4, ...), cross> {
public:
static FunctionType *get(LLVMContext &Context) {
Type *params[] = {
TypeBuilder<A1, cross>::get(Context),
TypeBuilder<A2, cross>::get(Context),
TypeBuilder<A3, cross>::get(Context),
TypeBuilder<A4, cross>::get(Context),
};
return FunctionType::get(TypeBuilder<R, cross>::get(Context),
params, true);
}
};
template<typename R, typename A1, typename A2, typename A3, typename A4,
typename A5, bool cross>
class TypeBuilder<R(A1, A2, A3, A4, A5, ...), cross> {
public:
static FunctionType *get(LLVMContext &Context) {
Type *params[] = {
TypeBuilder<A1, cross>::get(Context),
TypeBuilder<A2, cross>::get(Context),
TypeBuilder<A3, cross>::get(Context),
TypeBuilder<A4, cross>::get(Context),
TypeBuilder<A5, cross>::get(Context),
};
return FunctionType::get(TypeBuilder<R, cross>::get(Context),
params, true);
}
};
} // namespace llvm
#endif

View File

@@ -0,0 +1,78 @@
//===-- llvm/IR/TypeFinder.h - Class to find used struct types --*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains the declaration of the TypeFinder class.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_IR_TYPEFINDER_H
#define LLVM_IR_TYPEFINDER_H
#include "llvm/ADT/DenseSet.h"
#include <vector>
namespace llvm {
class MDNode;
class Module;
class StructType;
class Type;
class Value;
/// TypeFinder - Walk over a module, identifying all of the types that are
/// used by the module.
class TypeFinder {
// To avoid walking constant expressions multiple times and other IR
// objects, we keep several helper maps.
DenseSet<const Value*> VisitedConstants;
DenseSet<Type*> VisitedTypes;
std::vector<StructType*> StructTypes;
bool OnlyNamed;
public:
TypeFinder() : OnlyNamed(false) {}
void run(const Module &M, bool onlyNamed);
void clear();
typedef std::vector<StructType*>::iterator iterator;
typedef std::vector<StructType*>::const_iterator const_iterator;
iterator begin() { return StructTypes.begin(); }
iterator end() { return StructTypes.end(); }
const_iterator begin() const { return StructTypes.begin(); }
const_iterator end() const { return StructTypes.end(); }
bool empty() const { return StructTypes.empty(); }
size_t size() const { return StructTypes.size(); }
iterator erase(iterator I, iterator E) { return StructTypes.erase(I, E); }
StructType *&operator[](unsigned Idx) { return StructTypes[Idx]; }
private:
/// incorporateType - This method adds the type to the list of used
/// structures if it's not in there already.
void incorporateType(Type *Ty);
/// incorporateValue - This method is used to walk operand lists finding types
/// hiding in constant expressions and other operands that won't be walked in
/// other ways. GlobalValues, basic blocks, instructions, and inst operands
/// are all explicitly enumerated.
void incorporateValue(const Value *V);
/// incorporateMDNode - This method is used to walk the operands of an MDNode
/// to find types hiding within.
void incorporateMDNode(const MDNode *V);
};
} // end llvm namespace
#endif

219
thirdparty/clang/include/llvm/IR/Use.h vendored Normal file
View File

@@ -0,0 +1,219 @@
//===-- llvm/Use.h - Definition of the Use class ----------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This defines the Use class. The Use class represents the operand of an
// instruction or some other User instance which refers to a Value. The Use
// class keeps the "use list" of the referenced value up to date.
//
// Pointer tagging is used to efficiently find the User corresponding
// to a Use without having to store a User pointer in every Use. A
// User is preceded in memory by all the Uses corresponding to its
// operands, and the low bits of one of the fields (Prev) of the Use
// class are used to encode offsets to be able to find that User given
// a pointer to any Use. For details, see:
//
// http://www.llvm.org/docs/ProgrammersManual.html#UserLayout
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_IR_USE_H
#define LLVM_IR_USE_H
#include "llvm/ADT/PointerIntPair.h"
#include "llvm/Support/Compiler.h"
#include <cstddef>
#include <iterator>
namespace llvm {
class Value;
class User;
class Use;
template<typename>
struct simplify_type;
// Use** is only 4-byte aligned.
template<>
class PointerLikeTypeTraits<Use**> {
public:
static inline void *getAsVoidPointer(Use** P) { return P; }
static inline Use **getFromVoidPointer(void *P) {
return static_cast<Use**>(P);
}
enum { NumLowBitsAvailable = 2 };
};
//===----------------------------------------------------------------------===//
// Use Class
//===----------------------------------------------------------------------===//
/// Use is here to make keeping the "use" list of a Value up-to-date really
/// easy.
class Use {
public:
/// swap - provide a fast substitute to std::swap<Use>
/// that also works with less standard-compliant compilers
void swap(Use &RHS);
// A type for the word following an array of hung-off Uses in memory, which is
// a pointer back to their User with the bottom bit set.
typedef PointerIntPair<User*, 1, unsigned> UserRef;
private:
Use(const Use &U) LLVM_DELETED_FUNCTION;
/// Destructor - Only for zap()
~Use() {
if (Val) removeFromList();
}
enum PrevPtrTag { zeroDigitTag
, oneDigitTag
, stopTag
, fullStopTag };
/// Constructor
Use(PrevPtrTag tag) : Val(0) {
Prev.setInt(tag);
}
public:
/// Normally Use will just implicitly convert to a Value* that it holds.
operator Value*() const { return Val; }
/// If implicit conversion to Value* doesn't work, the get() method returns
/// the Value*.
Value *get() const { return Val; }
/// getUser - This returns the User that contains this Use. For an
/// instruction operand, for example, this will return the instruction.
User *getUser() const;
inline void set(Value *Val);
Value *operator=(Value *RHS) {
set(RHS);
return RHS;
}
const Use &operator=(const Use &RHS) {
set(RHS.Val);
return *this;
}
Value *operator->() { return Val; }
const Value *operator->() const { return Val; }
Use *getNext() const { return Next; }
/// initTags - initialize the waymarking tags on an array of Uses, so that
/// getUser() can find the User from any of those Uses.
static Use *initTags(Use *Start, Use *Stop);
/// zap - This is used to destroy Use operands when the number of operands of
/// a User changes.
static void zap(Use *Start, const Use *Stop, bool del = false);
private:
const Use* getImpliedUser() const;
Value *Val;
Use *Next;
PointerIntPair<Use**, 2, PrevPtrTag> Prev;
void setPrev(Use **NewPrev) {
Prev.setPointer(NewPrev);
}
void addToList(Use **List) {
Next = *List;
if (Next) Next->setPrev(&Next);
setPrev(List);
*List = this;
}
void removeFromList() {
Use **StrippedPrev = Prev.getPointer();
*StrippedPrev = Next;
if (Next) Next->setPrev(StrippedPrev);
}
friend class Value;
};
// simplify_type - Allow clients to treat uses just like values when using
// casting operators.
template<> struct simplify_type<Use> {
typedef Value* SimpleType;
static SimpleType getSimplifiedValue(Use &Val) {
return Val.get();
}
};
template<> struct simplify_type<const Use> {
typedef /*const*/ Value* SimpleType;
static SimpleType getSimplifiedValue(const Use &Val) {
return Val.get();
}
};
template<typename UserTy> // UserTy == 'User' or 'const User'
class value_use_iterator : public std::iterator<std::forward_iterator_tag,
UserTy*, ptrdiff_t> {
typedef std::iterator<std::forward_iterator_tag, UserTy*, ptrdiff_t> super;
typedef value_use_iterator<UserTy> _Self;
Use *U;
explicit value_use_iterator(Use *u) : U(u) {}
friend class Value;
public:
typedef typename super::reference reference;
typedef typename super::pointer pointer;
value_use_iterator(const _Self &I) : U(I.U) {}
value_use_iterator() {}
bool operator==(const _Self &x) const {
return U == x.U;
}
bool operator!=(const _Self &x) const {
return !operator==(x);
}
/// atEnd - return true if this iterator is equal to use_end() on the value.
bool atEnd() const { return U == 0; }
// Iterator traversal: forward iteration only
_Self &operator++() { // Preincrement
assert(U && "Cannot increment end iterator!");
U = U->getNext();
return *this;
}
_Self operator++(int) { // Postincrement
_Self tmp = *this; ++*this; return tmp;
}
// Retrieve a pointer to the current User.
UserTy *operator*() const {
assert(U && "Cannot dereference end iterator!");
return U->getUser();
}
UserTy *operator->() const { return operator*(); }
Use &getUse() const { return *U; }
/// getOperandNo - Return the operand # of this use in its User. Defined in
/// User.h
///
unsigned getOperandNo() const;
};
} // End llvm namespace
#endif

205
thirdparty/clang/include/llvm/IR/User.h vendored Normal file
View File

@@ -0,0 +1,205 @@
//===-- llvm/User.h - User class definition ---------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This class defines the interface that one who uses a Value must implement.
// Each instance of the Value class keeps track of what User's have handles
// to it.
//
// * Instructions are the largest class of Users.
// * Constants may be users of other constants (think arrays and stuff)
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_IR_USER_H
#define LLVM_IR_USER_H
#include "llvm/IR/Value.h"
#include "llvm/Support/ErrorHandling.h"
namespace llvm {
/// OperandTraits - Compile-time customization of
/// operand-related allocators and accessors
/// for use of the User class
template <class>
struct OperandTraits;
class User : public Value {
User(const User &) LLVM_DELETED_FUNCTION;
void *operator new(size_t) LLVM_DELETED_FUNCTION;
template <unsigned>
friend struct HungoffOperandTraits;
virtual void anchor();
protected:
/// OperandList - This is a pointer to the array of Uses for this User.
/// For nodes of fixed arity (e.g. a binary operator) this array will live
/// prefixed to some derived class instance. For nodes of resizable variable
/// arity (e.g. PHINodes, SwitchInst etc.), this memory will be dynamically
/// allocated and should be destroyed by the classes' virtual dtor.
Use *OperandList;
/// NumOperands - The number of values used by this User.
///
unsigned NumOperands;
void *operator new(size_t s, unsigned Us);
User(Type *ty, unsigned vty, Use *OpList, unsigned NumOps)
: Value(ty, vty), OperandList(OpList), NumOperands(NumOps) {}
Use *allocHungoffUses(unsigned) const;
void dropHungoffUses() {
Use::zap(OperandList, OperandList + NumOperands, true);
OperandList = 0;
// Reset NumOperands so User::operator delete() does the right thing.
NumOperands = 0;
}
public:
~User() {
Use::zap(OperandList, OperandList + NumOperands);
}
/// operator delete - free memory allocated for User and Use objects
void operator delete(void *Usr);
/// placement delete - required by std, but never called.
void operator delete(void*, unsigned) {
llvm_unreachable("Constructor throws?");
}
/// placement delete - required by std, but never called.
void operator delete(void*, unsigned, bool) {
llvm_unreachable("Constructor throws?");
}
protected:
template <int Idx, typename U> static Use &OpFrom(const U *that) {
return Idx < 0
? OperandTraits<U>::op_end(const_cast<U*>(that))[Idx]
: OperandTraits<U>::op_begin(const_cast<U*>(that))[Idx];
}
template <int Idx> Use &Op() {
return OpFrom<Idx>(this);
}
template <int Idx> const Use &Op() const {
return OpFrom<Idx>(this);
}
public:
Value *getOperand(unsigned i) const {
assert(i < NumOperands && "getOperand() out of range!");
return OperandList[i];
}
void setOperand(unsigned i, Value *Val) {
assert(i < NumOperands && "setOperand() out of range!");
assert((!isa<Constant>((const Value*)this) ||
isa<GlobalValue>((const Value*)this)) &&
"Cannot mutate a constant with setOperand!");
OperandList[i] = Val;
}
const Use &getOperandUse(unsigned i) const {
assert(i < NumOperands && "getOperandUse() out of range!");
return OperandList[i];
}
Use &getOperandUse(unsigned i) {
assert(i < NumOperands && "getOperandUse() out of range!");
return OperandList[i];
}
unsigned getNumOperands() const { return NumOperands; }
// ---------------------------------------------------------------------------
// Operand Iterator interface...
//
typedef Use* op_iterator;
typedef const Use* const_op_iterator;
inline op_iterator op_begin() { return OperandList; }
inline const_op_iterator op_begin() const { return OperandList; }
inline op_iterator op_end() { return OperandList+NumOperands; }
inline const_op_iterator op_end() const { return OperandList+NumOperands; }
/// Convenience iterator for directly iterating over the Values in the
/// OperandList
class value_op_iterator : public std::iterator<std::forward_iterator_tag,
Value*> {
op_iterator OI;
public:
explicit value_op_iterator(Use *U) : OI(U) {}
bool operator==(const value_op_iterator &x) const {
return OI == x.OI;
}
bool operator!=(const value_op_iterator &x) const {
return !operator==(x);
}
/// Iterator traversal: forward iteration only
value_op_iterator &operator++() { // Preincrement
++OI;
return *this;
}
value_op_iterator operator++(int) { // Postincrement
value_op_iterator tmp = *this; ++*this; return tmp;
}
/// Retrieve a pointer to the current Value.
Value *operator*() const {
return *OI;
}
Value *operator->() const { return operator*(); }
};
inline value_op_iterator value_op_begin() {
return value_op_iterator(op_begin());
}
inline value_op_iterator value_op_end() {
return value_op_iterator(op_end());
}
// dropAllReferences() - This function is in charge of "letting go" of all
// objects that this User refers to. This allows one to
// 'delete' a whole class at a time, even though there may be circular
// references... First all references are dropped, and all use counts go to
// zero. Then everything is deleted for real. Note that no operations are
// valid on an object that has "dropped all references", except operator
// delete.
//
void dropAllReferences() {
for (op_iterator i = op_begin(), e = op_end(); i != e; ++i)
i->set(0);
}
/// replaceUsesOfWith - Replaces all references to the "From" definition with
/// references to the "To" definition.
///
void replaceUsesOfWith(Value *From, Value *To);
// Methods for support type inquiry through isa, cast, and dyn_cast:
static inline bool classof(const Value *V) {
return isa<Instruction>(V) || isa<Constant>(V);
}
};
template<> struct simplify_type<User::op_iterator> {
typedef Value* SimpleType;
static SimpleType getSimplifiedValue(User::op_iterator &Val) {
return Val->get();
}
};
template<> struct simplify_type<User::const_op_iterator> {
typedef /*const*/ Value* SimpleType;
static SimpleType getSimplifiedValue(User::const_op_iterator &Val) {
return Val->get();
}
};
// value_use_iterator::getOperandNo - Requires the definition of the User class.
template<typename UserTy>
unsigned value_use_iterator<UserTy>::getOperandNo() const {
return U - U->getUser()->op_begin();
}
} // End llvm namespace
#endif

411
thirdparty/clang/include/llvm/IR/Value.h vendored Normal file
View File

@@ -0,0 +1,411 @@
//===-- llvm/Value.h - Definition of the Value class ------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file declares the Value class.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_IR_VALUE_H
#define LLVM_IR_VALUE_H
#include "llvm/IR/Use.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/Compiler.h"
namespace llvm {
class Constant;
class Argument;
class Instruction;
class BasicBlock;
class GlobalValue;
class Function;
class GlobalVariable;
class GlobalAlias;
class InlineAsm;
class ValueSymbolTable;
template<typename ValueTy> class StringMapEntry;
typedef StringMapEntry<Value*> ValueName;
class raw_ostream;
class AssemblyAnnotationWriter;
class ValueHandleBase;
class LLVMContext;
class Twine;
class MDNode;
class Type;
class StringRef;
//===----------------------------------------------------------------------===//
// Value Class
//===----------------------------------------------------------------------===//
/// This is a very important LLVM class. It is the base class of all values
/// computed by a program that may be used as operands to other values. Value is
/// the super class of other important classes such as Instruction and Function.
/// All Values have a Type. Type is not a subclass of Value. Some values can
/// have a name and they belong to some Module. Setting the name on the Value
/// automatically updates the module's symbol table.
///
/// Every value has a "use list" that keeps track of which other Values are
/// using this Value. A Value can also have an arbitrary number of ValueHandle
/// objects that watch it and listen to RAUW and Destroy events. See
/// llvm/Support/ValueHandle.h for details.
///
/// @brief LLVM Value Representation
class Value {
const unsigned char SubclassID; // Subclass identifier (for isa/dyn_cast)
unsigned char HasValueHandle : 1; // Has a ValueHandle pointing to this?
protected:
/// SubclassOptionalData - This member is similar to SubclassData, however it
/// is for holding information which may be used to aid optimization, but
/// which may be cleared to zero without affecting conservative
/// interpretation.
unsigned char SubclassOptionalData : 7;
private:
/// SubclassData - This member is defined by this class, but is not used for
/// anything. Subclasses can use it to hold whatever state they find useful.
/// This field is initialized to zero by the ctor.
unsigned short SubclassData;
Type *VTy;
Use *UseList;
friend class ValueSymbolTable; // Allow ValueSymbolTable to directly mod Name.
friend class ValueHandleBase;
ValueName *Name;
void operator=(const Value &) LLVM_DELETED_FUNCTION;
Value(const Value &) LLVM_DELETED_FUNCTION;
protected:
/// printCustom - Value subclasses can override this to implement custom
/// printing behavior.
virtual void printCustom(raw_ostream &O) const;
Value(Type *Ty, unsigned scid);
public:
virtual ~Value();
/// dump - Support for debugging, callable in GDB: V->dump()
//
void dump() const;
/// print - Implement operator<< on Value.
///
void print(raw_ostream &O, AssemblyAnnotationWriter *AAW = 0) const;
/// All values are typed, get the type of this value.
///
Type *getType() const { return VTy; }
/// All values hold a context through their type.
LLVMContext &getContext() const;
// All values can potentially be named.
bool hasName() const { return Name != 0 && SubclassID != MDStringVal; }
ValueName *getValueName() const { return Name; }
void setValueName(ValueName *VN) { Name = VN; }
/// getName() - Return a constant reference to the value's name. This is cheap
/// and guaranteed to return the same reference as long as the value is not
/// modified.
StringRef getName() const;
/// setName() - Change the name of the value, choosing a new unique name if
/// the provided name is taken.
///
/// \param Name The new name; or "" if the value's name should be removed.
void setName(const Twine &Name);
/// takeName - transfer the name from V to this value, setting V's name to
/// empty. It is an error to call V->takeName(V).
void takeName(Value *V);
/// replaceAllUsesWith - Go through the uses list for this definition and make
/// each use point to "V" instead of "this". After this completes, 'this's
/// use list is guaranteed to be empty.
///
void replaceAllUsesWith(Value *V);
//----------------------------------------------------------------------
// Methods for handling the chain of uses of this Value.
//
typedef value_use_iterator<User> use_iterator;
typedef value_use_iterator<const User> const_use_iterator;
bool use_empty() const { return UseList == 0; }
use_iterator use_begin() { return use_iterator(UseList); }
const_use_iterator use_begin() const { return const_use_iterator(UseList); }
use_iterator use_end() { return use_iterator(0); }
const_use_iterator use_end() const { return const_use_iterator(0); }
User *use_back() { return *use_begin(); }
const User *use_back() const { return *use_begin(); }
/// hasOneUse - Return true if there is exactly one user of this value. This
/// is specialized because it is a common request and does not require
/// traversing the whole use list.
///
bool hasOneUse() const {
const_use_iterator I = use_begin(), E = use_end();
if (I == E) return false;
return ++I == E;
}
/// hasNUses - Return true if this Value has exactly N users.
///
bool hasNUses(unsigned N) const;
/// hasNUsesOrMore - Return true if this value has N users or more. This is
/// logically equivalent to getNumUses() >= N.
///
bool hasNUsesOrMore(unsigned N) const;
bool isUsedInBasicBlock(const BasicBlock *BB) const;
/// getNumUses - This method computes the number of uses of this Value. This
/// is a linear time operation. Use hasOneUse, hasNUses, or hasNUsesOrMore
/// to check for specific values.
unsigned getNumUses() const;
/// addUse - This method should only be used by the Use class.
///
void addUse(Use &U) { U.addToList(&UseList); }
/// An enumeration for keeping track of the concrete subclass of Value that
/// is actually instantiated. Values of this enumeration are kept in the
/// Value classes SubclassID field. They are used for concrete type
/// identification.
enum ValueTy {
ArgumentVal, // This is an instance of Argument
BasicBlockVal, // This is an instance of BasicBlock
FunctionVal, // This is an instance of Function
GlobalAliasVal, // This is an instance of GlobalAlias
GlobalVariableVal, // This is an instance of GlobalVariable
UndefValueVal, // This is an instance of UndefValue
BlockAddressVal, // This is an instance of BlockAddress
ConstantExprVal, // This is an instance of ConstantExpr
ConstantAggregateZeroVal, // This is an instance of ConstantAggregateZero
ConstantDataArrayVal, // This is an instance of ConstantDataArray
ConstantDataVectorVal, // This is an instance of ConstantDataVector
ConstantIntVal, // This is an instance of ConstantInt
ConstantFPVal, // This is an instance of ConstantFP
ConstantArrayVal, // This is an instance of ConstantArray
ConstantStructVal, // This is an instance of ConstantStruct
ConstantVectorVal, // This is an instance of ConstantVector
ConstantPointerNullVal, // This is an instance of ConstantPointerNull
MDNodeVal, // This is an instance of MDNode
MDStringVal, // This is an instance of MDString
InlineAsmVal, // This is an instance of InlineAsm
PseudoSourceValueVal, // This is an instance of PseudoSourceValue
FixedStackPseudoSourceValueVal, // This is an instance of
// FixedStackPseudoSourceValue
InstructionVal, // This is an instance of Instruction
// Enum values starting at InstructionVal are used for Instructions;
// don't add new values here!
// Markers:
ConstantFirstVal = FunctionVal,
ConstantLastVal = ConstantPointerNullVal
};
/// getValueID - Return an ID for the concrete type of this object. This is
/// used to implement the classof checks. This should not be used for any
/// other purpose, as the values may change as LLVM evolves. Also, note that
/// for instructions, the Instruction's opcode is added to InstructionVal. So
/// this means three things:
/// # there is no value with code InstructionVal (no opcode==0).
/// # there are more possible values for the value type than in ValueTy enum.
/// # the InstructionVal enumerator must be the highest valued enumerator in
/// the ValueTy enum.
unsigned getValueID() const {
return SubclassID;
}
/// getRawSubclassOptionalData - Return the raw optional flags value
/// contained in this value. This should only be used when testing two
/// Values for equivalence.
unsigned getRawSubclassOptionalData() const {
return SubclassOptionalData;
}
/// clearSubclassOptionalData - Clear the optional flags contained in
/// this value.
void clearSubclassOptionalData() {
SubclassOptionalData = 0;
}
/// hasSameSubclassOptionalData - Test whether the optional flags contained
/// in this value are equal to the optional flags in the given value.
bool hasSameSubclassOptionalData(const Value *V) const {
return SubclassOptionalData == V->SubclassOptionalData;
}
/// intersectOptionalDataWith - Clear any optional flags in this value
/// that are not also set in the given value.
void intersectOptionalDataWith(const Value *V) {
SubclassOptionalData &= V->SubclassOptionalData;
}
/// hasValueHandle - Return true if there is a value handle associated with
/// this value.
bool hasValueHandle() const { return HasValueHandle; }
/// stripPointerCasts - This method strips off any unneeded pointer casts and
/// all-zero GEPs from the specified value, returning the original uncasted
/// value. If this is called on a non-pointer value, it returns 'this'.
Value *stripPointerCasts();
const Value *stripPointerCasts() const {
return const_cast<Value*>(this)->stripPointerCasts();
}
/// stripInBoundsConstantOffsets - This method strips off unneeded pointer casts and
/// all-constant GEPs from the specified value, returning the original
/// pointer value. If this is called on a non-pointer value, it returns
/// 'this'.
Value *stripInBoundsConstantOffsets();
const Value *stripInBoundsConstantOffsets() const {
return const_cast<Value*>(this)->stripInBoundsConstantOffsets();
}
/// stripInBoundsOffsets - This method strips off unneeded pointer casts and
/// any in-bounds Offsets from the specified value, returning the original
/// pointer value. If this is called on a non-pointer value, it returns
/// 'this'.
Value *stripInBoundsOffsets();
const Value *stripInBoundsOffsets() const {
return const_cast<Value*>(this)->stripInBoundsOffsets();
}
/// isDereferenceablePointer - Test if this value is always a pointer to
/// allocated and suitably aligned memory for a simple load or store.
bool isDereferenceablePointer() const;
/// DoPHITranslation - If this value is a PHI node with CurBB as its parent,
/// return the value in the PHI node corresponding to PredBB. If not, return
/// ourself. This is useful if you want to know the value something has in a
/// predecessor block.
Value *DoPHITranslation(const BasicBlock *CurBB, const BasicBlock *PredBB);
const Value *DoPHITranslation(const BasicBlock *CurBB,
const BasicBlock *PredBB) const{
return const_cast<Value*>(this)->DoPHITranslation(CurBB, PredBB);
}
/// MaximumAlignment - This is the greatest alignment value supported by
/// load, store, and alloca instructions, and global values.
static const unsigned MaximumAlignment = 1u << 29;
/// mutateType - Mutate the type of this Value to be of the specified type.
/// Note that this is an extremely dangerous operation which can create
/// completely invalid IR very easily. It is strongly recommended that you
/// recreate IR objects with the right types instead of mutating them in
/// place.
void mutateType(Type *Ty) {
VTy = Ty;
}
protected:
unsigned short getSubclassDataFromValue() const { return SubclassData; }
void setValueSubclassData(unsigned short D) { SubclassData = D; }
};
inline raw_ostream &operator<<(raw_ostream &OS, const Value &V) {
V.print(OS);
return OS;
}
void Use::set(Value *V) {
if (Val) removeFromList();
Val = V;
if (V) V->addUse(*this);
}
// isa - Provide some specializations of isa so that we don't have to include
// the subtype header files to test to see if the value is a subclass...
//
template <> struct isa_impl<Constant, Value> {
static inline bool doit(const Value &Val) {
return Val.getValueID() >= Value::ConstantFirstVal &&
Val.getValueID() <= Value::ConstantLastVal;
}
};
template <> struct isa_impl<Argument, Value> {
static inline bool doit (const Value &Val) {
return Val.getValueID() == Value::ArgumentVal;
}
};
template <> struct isa_impl<InlineAsm, Value> {
static inline bool doit(const Value &Val) {
return Val.getValueID() == Value::InlineAsmVal;
}
};
template <> struct isa_impl<Instruction, Value> {
static inline bool doit(const Value &Val) {
return Val.getValueID() >= Value::InstructionVal;
}
};
template <> struct isa_impl<BasicBlock, Value> {
static inline bool doit(const Value &Val) {
return Val.getValueID() == Value::BasicBlockVal;
}
};
template <> struct isa_impl<Function, Value> {
static inline bool doit(const Value &Val) {
return Val.getValueID() == Value::FunctionVal;
}
};
template <> struct isa_impl<GlobalVariable, Value> {
static inline bool doit(const Value &Val) {
return Val.getValueID() == Value::GlobalVariableVal;
}
};
template <> struct isa_impl<GlobalAlias, Value> {
static inline bool doit(const Value &Val) {
return Val.getValueID() == Value::GlobalAliasVal;
}
};
template <> struct isa_impl<GlobalValue, Value> {
static inline bool doit(const Value &Val) {
return isa<GlobalVariable>(Val) || isa<Function>(Val) ||
isa<GlobalAlias>(Val);
}
};
template <> struct isa_impl<MDNode, Value> {
static inline bool doit(const Value &Val) {
return Val.getValueID() == Value::MDNodeVal;
}
};
// Value* is only 4-byte aligned.
template<>
class PointerLikeTypeTraits<Value*> {
typedef Value* PT;
public:
static inline void *getAsVoidPointer(PT P) { return P; }
static inline PT getFromVoidPointer(void *P) {
return static_cast<PT>(P);
}
enum { NumLowBitsAvailable = 2 };
};
} // End llvm namespace
#endif

View File

@@ -0,0 +1,133 @@
//===-- llvm/ValueSymbolTable.h - Implement a Value Symtab ------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the name/Value symbol table for LLVM.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_IR_VALUESYMBOLTABLE_H
#define LLVM_IR_VALUESYMBOLTABLE_H
#include "llvm/ADT/StringMap.h"
#include "llvm/IR/Value.h"
#include "llvm/Support/DataTypes.h"
namespace llvm {
template<typename ValueSubClass, typename ItemParentClass>
class SymbolTableListTraits;
class BasicBlock;
class Function;
class NamedMDNode;
class Module;
class StringRef;
/// This class provides a symbol table of name/value pairs. It is essentially
/// a std::map<std::string,Value*> but has a controlled interface provided by
/// LLVM as well as ensuring uniqueness of names.
///
class ValueSymbolTable {
friend class Value;
friend class SymbolTableListTraits<Argument, Function>;
friend class SymbolTableListTraits<BasicBlock, Function>;
friend class SymbolTableListTraits<Instruction, BasicBlock>;
friend class SymbolTableListTraits<Function, Module>;
friend class SymbolTableListTraits<GlobalVariable, Module>;
friend class SymbolTableListTraits<GlobalAlias, Module>;
/// @name Types
/// @{
public:
/// @brief A mapping of names to values.
typedef StringMap<Value*> ValueMap;
/// @brief An iterator over a ValueMap.
typedef ValueMap::iterator iterator;
/// @brief A const_iterator over a ValueMap.
typedef ValueMap::const_iterator const_iterator;
/// @}
/// @name Constructors
/// @{
public:
ValueSymbolTable() : vmap(0), LastUnique(0) {}
~ValueSymbolTable();
/// @}
/// @name Accessors
/// @{
public:
/// This method finds the value with the given \p Name in the
/// the symbol table.
/// @returns the value associated with the \p Name
/// @brief Lookup a named Value.
Value *lookup(StringRef Name) const { return vmap.lookup(Name); }
/// @returns true iff the symbol table is empty
/// @brief Determine if the symbol table is empty
inline bool empty() const { return vmap.empty(); }
/// @brief The number of name/type pairs is returned.
inline unsigned size() const { return unsigned(vmap.size()); }
/// This function can be used from the debugger to display the
/// content of the symbol table while debugging.
/// @brief Print out symbol table on stderr
void dump() const;
/// @}
/// @name Iteration
/// @{
public:
/// @brief Get an iterator that from the beginning of the symbol table.
inline iterator begin() { return vmap.begin(); }
/// @brief Get a const_iterator that from the beginning of the symbol table.
inline const_iterator begin() const { return vmap.begin(); }
/// @brief Get an iterator to the end of the symbol table.
inline iterator end() { return vmap.end(); }
/// @brief Get a const_iterator to the end of the symbol table.
inline const_iterator end() const { return vmap.end(); }
/// @}
/// @name Mutators
/// @{
private:
/// This method adds the provided value \p N to the symbol table. The Value
/// must have a name which is used to place the value in the symbol table.
/// If the inserted name conflicts, this renames the value.
/// @brief Add a named value to the symbol table
void reinsertValue(Value *V);
/// createValueName - This method attempts to create a value name and insert
/// it into the symbol table with the specified name. If it conflicts, it
/// auto-renames the name and returns that instead.
ValueName *createValueName(StringRef Name, Value *V);
/// This method removes a value from the symbol table. It leaves the
/// ValueName attached to the value, but it is no longer inserted in the
/// symtab.
void removeValueName(ValueName *V);
/// @}
/// @name Internal Data
/// @{
private:
ValueMap vmap; ///< The map that holds the symbol table.
mutable uint32_t LastUnique; ///< Counter for tracking unique names
/// @}
};
} // End llvm namespace
#endif