#Prof = -pg
# TODO: Get rid of exceptions! : -fno-exceptions -fno-rtti
-CompileCommonOpts = $(Prof) -Wall -W -Wwrite-strings -Wno-unused -I$(LEVEL)/include
+CompileCommonOpts = $(Prof) -Wall -W -Wwrite-strings -Wno-unused-parameter -Wno-missing-braces -I$(LEVEL)/include
# Compile a file, don't link...
Compile = $(CXX) -c $(CPPFLAGS) $(CXXFLAGS) $(CompileCommonOpts)
#Prof = -pg
# TODO: Get rid of exceptions! : -fno-exceptions -fno-rtti
-CompileCommonOpts = $(Prof) -Wall -W -Wwrite-strings -Wno-unused -I$(LEVEL)/include
+CompileCommonOpts = $(Prof) -Wall -W -Wwrite-strings -Wno-unused-parameter -Wno-missing-braces -I$(LEVEL)/include
# Compile a file, don't link...
Compile = $(CXX) -c $(CPPFLAGS) $(CXXFLAGS) $(CompileCommonOpts)
//===--------------------------------------------------------------------===//
// Basic ID <-> Name map functionality
- static AnnotationID getID (const string &Name); // Name -> ID
- static const string &getName(AnnotationID ID); // ID -> Name
+ static AnnotationID getID(const std::string &Name); // Name -> ID
+ static const std::string &getName(AnnotationID ID); // ID -> Name
// getID - Name -> ID + registration of a factory function for demand driven
// annotation support.
- static AnnotationID getID (const string &Name, Factory Fact, void *Data=0);
+ static AnnotationID getID(const std::string &Name, Factory Fact,
+ void *Data = 0);
//===--------------------------------------------------------------------===//
// Annotation creation on demand support...
// an argument. Should return true if there was an error processing the
// argument and the program should exit.
//
- virtual bool handleOccurance(const char *ArgName, const string &Arg) = 0;
+ virtual bool handleOccurance(const char *ArgName, const std::string &Arg) = 0;
virtual enum NumOccurances getNumOccurancesFlagDefault() const {
return Optional;
// addOccurance - Wrapper around handleOccurance that enforces Flags
//
- bool addOccurance(const char *ArgName, const string &Value);
+ bool addOccurance(const char *ArgName, const std::string &Value);
// Prints option name followed by message. Always returns true.
- bool error(string Message, const char *ArgName = 0);
+ bool error(std::string Message, const char *ArgName = 0);
public:
inline int getNumOccurances() const { return NumOccurances; }
//
class Alias : public Option {
Option &AliasFor;
- virtual bool handleOccurance(const char *ArgName, const string &Arg) {
+ virtual bool handleOccurance(const char *ArgName, const std::string &Arg) {
return AliasFor.handleOccurance(AliasFor.ArgStr, Arg);
}
virtual enum OptionHidden getOptionHiddenFlagDefault() const {return Hidden;}
//
class Flag : public Option {
bool Value;
- virtual bool handleOccurance(const char *ArgName, const string &Arg);
+ virtual bool handleOccurance(const char *ArgName, const std::string &Arg);
public:
inline Flag(const char *ArgStr, const char *Message, int Flags = 0,
bool DefaultVal = 0) : Option(ArgStr, Message, Flags),
//
class Int : public Option {
int Value;
- virtual bool handleOccurance(const char *ArgName, const string &Arg);
+ virtual bool handleOccurance(const char *ArgName, const std::string &Arg);
virtual enum ValueExpected getValueExpectedFlagDefault() const {
return ValueRequired;
}
//===----------------------------------------------------------------------===//
// String valued command line option
//
-class String : public Option, public string {
- virtual bool handleOccurance(const char *ArgName, const string &Arg);
+class String : public Option, public std::string {
+ virtual bool handleOccurance(const char *ArgName, const std::string &Arg);
virtual enum ValueExpected getValueExpectedFlagDefault() const {
return ValueRequired;
}
public:
inline String(const char *ArgStr, const char *Help, int Flags = 0,
const char *DefaultVal = "")
- : Option(ArgStr, Help, Flags), string(DefaultVal) {}
+ : Option(ArgStr, Help, Flags), std::string(DefaultVal) {}
- inline const string &operator=(const string &Val) {
- return string::operator=(Val);
+ inline const std::string &operator=(const std::string &Val) {
+ return std::string::operator=(Val);
}
};
//===----------------------------------------------------------------------===//
// String list command line option
//
-class StringList : public Option, public vector<string> {
+class StringList : public Option, public std::vector<std::string> {
virtual enum NumOccurances getNumOccurancesFlagDefault() const {
return ZeroOrMore;
virtual enum ValueExpected getValueExpectedFlagDefault() const {
return ValueRequired;
}
- virtual bool handleOccurance(const char *ArgName, const string &Arg);
+ virtual bool handleOccurance(const char *ArgName, const std::string &Arg);
public:
inline StringList(const char *ArgStr, const char *Help, int Flags = 0)
// Use a vector instead of a map, because the lists should be short,
// the overhead is less, and most importantly, it keeps them in the order
// inserted so we can print our option out nicely.
- vector<pair<const char *, pair<int, const char *> > > ValueMap;
+ std::vector<std::pair<const char *, std::pair<int, const char *> > > ValueMap;
inline EnumBase(const char *ArgStr, const char *Help, int Flags)
: Option(ArgStr, Help, Flags) {}
inline EnumValueBase(int Flags) : EnumBase(Flags) {}
// handleOccurance - Set Value to the enum value specified by Arg
- virtual bool handleOccurance(const char *ArgName, const string &Arg);
+ virtual bool handleOccurance(const char *ArgName, const std::string &Arg);
// Return the width of the option tag for printing...
virtual unsigned getOptionWidth() const;
return ValueDisallowed;
}
protected:
- virtual bool handleOccurance(const char *ArgName, const string &Arg);
+ virtual bool handleOccurance(const char *ArgName, const std::string &Arg);
inline EnumFlagsBase(int Flags) : EnumValueBase(Flags) {}
// Return the width of the option tag for printing...
return ValueDisallowed;
}
protected:
- vector<int> Values; // The options specified so far.
+ std::vector<int> Values; // The options specified so far.
inline EnumListBase(int Flags)
: EnumBase(Flags) {}
- virtual bool handleOccurance(const char *ArgName, const string &Arg);
+ virtual bool handleOccurance(const char *ArgName, const std::string &Arg);
// Return the width of the option tag for printing...
virtual unsigned getOptionWidth() const;
typedef typename GT::NodeType NodeType;
typedef typename GT::ChildIteratorType ChildItTy;
- set<NodeType *> Visited; // All of the blocks visited so far...
+ std::set<NodeType *> Visited; // All of the blocks visited so far...
// VisitStack - Used to maintain the ordering. Top = current block
// First element is node pointer, second is the 'next child' to visit
- stack<pair<NodeType *, ChildItTy> > VisitStack;
+ std::stack<std::pair<NodeType *, ChildItTy> > VisitStack;
const bool Reverse; // Iterate over children before self?
private:
void reverseEnterNode() {
- pair<NodeType *, ChildItTy> &Top = VisitStack.top();
+ std::pair<NodeType *, ChildItTy> &Top = VisitStack.top();
NodeType *Node = Top.first;
ChildItTy &It = Top.second;
for (; It != GT::child_end(Node); ++It) {
NodeType *Child = *It;
if (!Visited.count(Child)) {
Visited.insert(Child);
- VisitStack.push(make_pair(Child, GT::child_begin(Child)));
+ VisitStack.push(std::make_pair(Child, GT::child_begin(Child)));
reverseEnterNode();
return;
}
inline df_iterator(NodeType *Node, bool reverse) : Reverse(reverse) {
Visited.insert(Node);
- VisitStack.push(make_pair(Node, GT::child_begin(Node)));
+ VisitStack.push(std::make_pair(Node, GT::child_begin(Node)));
if (Reverse) reverseEnterNode();
}
inline df_iterator() { /* End is when stack is empty */ }
reverseEnterNode();
} else { // Normal Depth First Iterator
do {
- pair<NodeType *, ChildItTy> &Top = VisitStack.top();
+ std::pair<NodeType *, ChildItTy> &Top = VisitStack.top();
NodeType *Node = Top.first;
ChildItTy &It = Top.second;
if (!Visited.count(Next)) { // Has our next sibling been visited?
// No, do it now.
Visited.insert(Next);
- VisitStack.push(make_pair(Next, GT::child_begin(Next)));
+ VisitStack.push(std::make_pair(Next, GT::child_begin(Next)));
return *this;
}
}
#define LLVM_SUPPORT_HASHEXTRAS_H
#include <string>
-#include <hash_map>
+#include <ext/hash_map>
+
+// Cannot specialize hash template from outside of the std namespace.
+namespace std {
template <> struct hash<string> {
size_t operator()(string const &str) const {
inline size_t operator()(const T *Val) const { return (size_t)Val; }
};
+} // End namespace std
+
#endif
typedef typename GT::NodeType NodeType;
typedef typename GT::ChildIteratorType ChildItTy;
- set<NodeType *> Visited; // All of the blocks visited so far...
+ std::set<NodeType *> Visited; // All of the blocks visited so far...
// VisitStack - Used to maintain the ordering. Top = current block
// First element is basic block pointer, second is the 'next child' to visit
- stack<pair<NodeType *, ChildItTy> > VisitStack;
+ std::stack<std::pair<NodeType *, ChildItTy> > VisitStack;
void traverseChild() {
while (VisitStack.top().second != GT::child_end(VisitStack.top().first)) {
// }
//
-typedef reverse_iterator<vector<BasicBlock*>::iterator> rpo_iterator;
+typedef std::vector<BasicBlock*>::reverse_iterator rpo_iterator;
// TODO: FIXME: ReversePostOrderTraversal is not generic!
class ReversePostOrderTraversal {
- vector<BasicBlock*> Blocks; // Block list in normal PO order
+ std::vector<BasicBlock*> Blocks; // Block list in normal PO order
inline void Initialize(BasicBlock *BB) {
copy(po_begin(BB), po_end(BB), back_inserter(Blocks));
}
// arguments to get a boolean result.
//
template<class Ty>
-struct bitwise_or : public binary_function<Ty, Ty, bool> {
+struct bitwise_or : public std::binary_function<Ty, Ty, bool> {
bool operator()(const Ty& left, const Ty& right) const {
return left | right;
}
RootIt current;
UnaryFunc Fn;
public:
- typedef typename iterator_traits<RootIt>::iterator_category
+ typedef typename std::iterator_traits<RootIt>::iterator_category
iterator_category;
- typedef typename iterator_traits<RootIt>::difference_type
+ typedef typename std::iterator_traits<RootIt>::difference_type
difference_type;
typedef typename UnaryFunc::result_type value_type;
typedef typename UnaryFunc::result_type *pointer;
_Self& operator-= (difference_type n) { current -= n; return *this; }
reference operator[](difference_type n) const { return *(*this + n); }
+ inline bool operator!=(const _Self &X) const { return !operator==(X); }
inline bool operator==(const _Self &X) const { return current == X.current; }
inline bool operator< (const _Self &X) const { return current < X.current; }
#include <string>
#include <stdio.h>
-static inline string utostr(uint64_t X, bool isNeg = false) {
+static inline std::string utostr(uint64_t X, bool isNeg = false) {
char Buffer[40];
char *BufPtr = Buffer+39;
if (isNeg) *--BufPtr = '-'; // Add negative sign...
- return string(BufPtr);
+ return std::string(BufPtr);
}
-static inline string itostr(int64_t X) {
+static inline std::string itostr(int64_t X) {
if (X < 0)
return utostr((uint64_t)-X, true);
else
}
-static inline string utostr(unsigned X, bool isNeg = false) {
+static inline std::string utostr(unsigned X, bool isNeg = false) {
char Buffer[20];
char *BufPtr = Buffer+19;
if (isNeg) *--BufPtr = '-'; // Add negative sign...
- return string(BufPtr);
+ return std::string(BufPtr);
}
-static inline string itostr(int X) {
+static inline std::string itostr(int X) {
if (X < 0)
return utostr((unsigned)-X, true);
else
return utostr((unsigned)X);
}
-static inline string ftostr(double V) {
+static inline std::string ftostr(double V) {
char Buffer[200];
snprintf(Buffer, 200, "%e", V);
return Buffer;
template<class ConcreteTreeNode, class Payload>
class Tree {
- vector<ConcreteTreeNode*> Children; // This nodes children, if any
- ConcreteTreeNode *Parent; // Parent of this node...
- Payload Data; // Data held in this node...
+ std::vector<ConcreteTreeNode*> Children; // This nodes children, if any
+ ConcreteTreeNode *Parent; // Parent of this node...
+ Payload Data; // Data held in this node...
protected:
- void setChildren(const vector<ConcreteTreeNode*> &children) {
+ void setChildren(const std::vector<ConcreteTreeNode*> &children) {
Children = children;
}
public:
inline Tree(ConcreteTreeNode *parent) : Parent(parent) {}
- inline Tree(const vector<ConcreteTreeNode*> &children, ConcreteTreeNode *par)
- : Children(children), Parent(par) {}
+ inline Tree(const std::vector<ConcreteTreeNode*> &children,
+ ConcreteTreeNode *par) : Children(children), Parent(par) {}
- inline Tree(const vector<ConcreteTreeNode*> &children, ConcreteTreeNode *par,
- const Payload &data)
+ inline Tree(const std::vector<ConcreteTreeNode*> &children,
+ ConcreteTreeNode *par, const Payload &data)
: Children(children), Parent(parent), Data(data) {}
// Tree dtor - Free all children
typedef typename GT::NodeType NodeType;
typedef typename GT::ChildIteratorType ChildItTy;
- set<NodeType *> Visited; // All of the blocks visited so far...
+ std::set<NodeType *> Visited; // All of the blocks visited so far...
// VisitStack - Used to maintain the ordering. Top = current block
// First element is node pointer, second is the 'next child' to visit
- stack<pair<NodeType *, ChildItTy> > VisitStack;
+ std::stack<std::pair<NodeType *, ChildItTy> > VisitStack;
const bool Reverse; // Iterate over children before self?
private:
void reverseEnterNode() {
- pair<NodeType *, ChildItTy> &Top = VisitStack.top();
+ std::pair<NodeType *, ChildItTy> &Top = VisitStack.top();
NodeType *Node = Top.first;
ChildItTy &It = Top.second;
for (; It != GT::child_end(Node); ++It) {
NodeType *Child = *It;
if (!Visited.count(Child)) {
Visited.insert(Child);
- VisitStack.push(make_pair(Child, GT::child_begin(Child)));
+ VisitStack.push(std::make_pair(Child, GT::child_begin(Child)));
reverseEnterNode();
return;
}
inline df_iterator(NodeType *Node, bool reverse) : Reverse(reverse) {
Visited.insert(Node);
- VisitStack.push(make_pair(Node, GT::child_begin(Node)));
+ VisitStack.push(std::make_pair(Node, GT::child_begin(Node)));
if (Reverse) reverseEnterNode();
}
inline df_iterator() { /* End is when stack is empty */ }
reverseEnterNode();
} else { // Normal Depth First Iterator
do {
- pair<NodeType *, ChildItTy> &Top = VisitStack.top();
+ std::pair<NodeType *, ChildItTy> &Top = VisitStack.top();
NodeType *Node = Top.first;
ChildItTy &It = Top.second;
if (!Visited.count(Next)) { // Has our next sibling been visited?
// No, do it now.
Visited.insert(Next);
- VisitStack.push(make_pair(Next, GT::child_begin(Next)));
+ VisitStack.push(std::make_pair(Next, GT::child_begin(Next)));
return *this;
}
}
#define LLVM_SUPPORT_HASHEXTRAS_H
#include <string>
-#include <hash_map>
+#include <ext/hash_map>
+
+// Cannot specialize hash template from outside of the std namespace.
+namespace std {
template <> struct hash<string> {
size_t operator()(string const &str) const {
inline size_t operator()(const T *Val) const { return (size_t)Val; }
};
+} // End namespace std
+
#endif
typedef typename GT::NodeType NodeType;
typedef typename GT::ChildIteratorType ChildItTy;
- set<NodeType *> Visited; // All of the blocks visited so far...
+ std::set<NodeType *> Visited; // All of the blocks visited so far...
// VisitStack - Used to maintain the ordering. Top = current block
// First element is basic block pointer, second is the 'next child' to visit
- stack<pair<NodeType *, ChildItTy> > VisitStack;
+ std::stack<std::pair<NodeType *, ChildItTy> > VisitStack;
void traverseChild() {
while (VisitStack.top().second != GT::child_end(VisitStack.top().first)) {
// }
//
-typedef reverse_iterator<vector<BasicBlock*>::iterator> rpo_iterator;
+typedef std::vector<BasicBlock*>::reverse_iterator rpo_iterator;
// TODO: FIXME: ReversePostOrderTraversal is not generic!
class ReversePostOrderTraversal {
- vector<BasicBlock*> Blocks; // Block list in normal PO order
+ std::vector<BasicBlock*> Blocks; // Block list in normal PO order
inline void Initialize(BasicBlock *BB) {
copy(po_begin(BB), po_end(BB), back_inserter(Blocks));
}
// arguments to get a boolean result.
//
template<class Ty>
-struct bitwise_or : public binary_function<Ty, Ty, bool> {
+struct bitwise_or : public std::binary_function<Ty, Ty, bool> {
bool operator()(const Ty& left, const Ty& right) const {
return left | right;
}
RootIt current;
UnaryFunc Fn;
public:
- typedef typename iterator_traits<RootIt>::iterator_category
+ typedef typename std::iterator_traits<RootIt>::iterator_category
iterator_category;
- typedef typename iterator_traits<RootIt>::difference_type
+ typedef typename std::iterator_traits<RootIt>::difference_type
difference_type;
typedef typename UnaryFunc::result_type value_type;
typedef typename UnaryFunc::result_type *pointer;
_Self& operator-= (difference_type n) { current -= n; return *this; }
reference operator[](difference_type n) const { return *(*this + n); }
+ inline bool operator!=(const _Self &X) const { return !operator==(X); }
inline bool operator==(const _Self &X) const { return current == X.current; }
inline bool operator< (const _Self &X) const { return current < X.current; }
#include <string>
#include <stdio.h>
-static inline string utostr(uint64_t X, bool isNeg = false) {
+static inline std::string utostr(uint64_t X, bool isNeg = false) {
char Buffer[40];
char *BufPtr = Buffer+39;
if (isNeg) *--BufPtr = '-'; // Add negative sign...
- return string(BufPtr);
+ return std::string(BufPtr);
}
-static inline string itostr(int64_t X) {
+static inline std::string itostr(int64_t X) {
if (X < 0)
return utostr((uint64_t)-X, true);
else
}
-static inline string utostr(unsigned X, bool isNeg = false) {
+static inline std::string utostr(unsigned X, bool isNeg = false) {
char Buffer[20];
char *BufPtr = Buffer+19;
if (isNeg) *--BufPtr = '-'; // Add negative sign...
- return string(BufPtr);
+ return std::string(BufPtr);
}
-static inline string itostr(int X) {
+static inline std::string itostr(int X) {
if (X < 0)
return utostr((unsigned)-X, true);
else
return utostr((unsigned)X);
}
-static inline string ftostr(double V) {
+static inline std::string ftostr(double V) {
char Buffer[200];
snprintf(Buffer, 200, "%e", V);
return Buffer;
template<class ConcreteTreeNode, class Payload>
class Tree {
- vector<ConcreteTreeNode*> Children; // This nodes children, if any
- ConcreteTreeNode *Parent; // Parent of this node...
- Payload Data; // Data held in this node...
+ std::vector<ConcreteTreeNode*> Children; // This nodes children, if any
+ ConcreteTreeNode *Parent; // Parent of this node...
+ Payload Data; // Data held in this node...
protected:
- void setChildren(const vector<ConcreteTreeNode*> &children) {
+ void setChildren(const std::vector<ConcreteTreeNode*> &children) {
Children = children;
}
public:
inline Tree(ConcreteTreeNode *parent) : Parent(parent) {}
- inline Tree(const vector<ConcreteTreeNode*> &children, ConcreteTreeNode *par)
- : Children(children), Parent(par) {}
+ inline Tree(const std::vector<ConcreteTreeNode*> &children,
+ ConcreteTreeNode *par) : Children(children), Parent(par) {}
- inline Tree(const vector<ConcreteTreeNode*> &children, ConcreteTreeNode *par,
- const Payload &data)
+ inline Tree(const std::vector<ConcreteTreeNode*> &children,
+ ConcreteTreeNode *par, const Payload &data)
: Children(children), Parent(parent), Data(data) {}
// Tree dtor - Free all children
class CallGraph;
class CallGraphNode {
Method *Meth;
- vector<CallGraphNode*> CalledMethods;
+ std::vector<CallGraphNode*> CalledMethods;
CallGraphNode(const CallGraphNode &); // Do not implement
public:
- typedef vector<CallGraphNode*>::iterator iterator;
- typedef vector<CallGraphNode*>::const_iterator const_iterator;
+ typedef std::vector<CallGraphNode*>::iterator iterator;
+ typedef std::vector<CallGraphNode*>::const_iterator const_iterator;
// getMethod - Return the method that this call graph node represents...
Method *getMethod() const { return Meth; }
class CallGraph {
Module *Mod; // The module this call graph represents
- typedef map<const Method *, CallGraphNode *> MethodMapTy;
+ typedef std::map<const Method *, CallGraphNode *> MethodMapTy;
MethodMapTy MethodMap; // Map from a method to its node
CallGraphNode *Root;
//
class DominatorSet : public DominatorBase {
public:
- typedef set<const BasicBlock*> DomSetType; // Dom set for a bb
- typedef map<const BasicBlock *, DomSetType> DomSetMapType; // Map of dom sets
+ typedef std::set<const BasicBlock*> DomSetType; // Dom set for a bb
+ // Map of dom sets
+ typedef std::map<const BasicBlock*, DomSetType> DomSetMapType;
private:
DomSetMapType Doms;
// method.
//
class ImmediateDominators : public DominatorBase {
- map<const BasicBlock*, const BasicBlock*> IDoms;
+ std::map<const BasicBlock*, const BasicBlock*> IDoms;
void calcIDoms(const DominatorSet &DS);
public:
}
// Accessor interface:
- typedef map<const BasicBlock*, const BasicBlock*> IDomMapType;
+ typedef std::map<const BasicBlock*, const BasicBlock*> IDomMapType;
typedef IDomMapType::const_iterator const_iterator;
inline const_iterator begin() const { return IDoms.begin(); }
inline const_iterator end() const { return IDoms.end(); }
// node returns null, because it does not have an immediate dominator.
//
inline const BasicBlock *operator[](const BasicBlock *BB) const {
- map<const BasicBlock*, const BasicBlock*>::const_iterator I =
+ std::map<const BasicBlock*, const BasicBlock*>::const_iterator I =
IDoms.find(BB);
return I != IDoms.end() ? I->second : 0;
}
public:
typedef Node2 Node;
private:
- map<const BasicBlock*, Node*> Nodes;
+ std::map<const BasicBlock*, Node*> Nodes;
void calculate(const DominatorSet &DS);
- typedef map<const BasicBlock*, Node*> NodeMapType;
+ typedef std::map<const BasicBlock*, Node*> NodeMapType;
public:
- class Node2 : public vector<Node*> {
+ class Node2 : public std::vector<Node*> {
friend class DominatorTree;
const BasicBlock *TheNode;
Node2 * const IDom;
public:
inline const BasicBlock *getNode() const { return TheNode; }
inline Node2 *getIDom() const { return IDom; }
- inline const vector<Node*> &getChildren() const { return *this; }
+ inline const std::vector<Node*> &getChildren() const { return *this; }
// dominates - Returns true iff this dominates N. Note that this is not a
// constant time operation!
//
class DominanceFrontier : public DominatorBase {
public:
- typedef set<const BasicBlock*> DomSetType; // Dom set for a bb
- typedef map<const BasicBlock *, DomSetType> DomSetMapType; // Map of dom sets
+ typedef std::set<const BasicBlock*> DomSetType; // Dom set for a bb
+ typedef std::map<const BasicBlock*, DomSetType> DomSetMapType; // Dom set map
private:
DomSetMapType Frontiers;
const DomSetType &calcDomFrontier(const DominatorTree &DT,
struct FindUnsafePointerTypes : public Pass {
// UnsafeTypes - Set of types that are not safe to transform.
- set<PointerType*> UnsafeTypes;
+ std::set<PointerType*> UnsafeTypes;
public:
// Accessor for underlying type set...
- inline const set<PointerType*> &getUnsafeTypes() const {
+ inline const std::set<PointerType*> &getUnsafeTypes() const {
return UnsafeTypes;
}
// printResults - Loop over the results of the analysis, printing out unsafe
// types.
//
- void printResults(const Module *Mod, ostream &o);
+ void printResults(const Module *Mod, std::ostream &o);
};
#endif
class SymbolTable;
class FindUsedTypes : public Pass {
- set<const Type *> UsedTypes;
+ std::set<const Type *> UsedTypes;
bool IncludeSymbolTables;
public:
// getTypes - After the pass has been run, return the set containing all of
// the types used in the module.
//
- inline const set<const Type *> &getTypes() const { return UsedTypes; }
+ inline const std::set<const Type *> &getTypes() const { return UsedTypes; }
// Print the types found in the module. If the optional Module parameter is
// passed in, then the types are printed symbolically if possible, using the
// symbol table from the module.
//
- void printTypes(ostream &o, const Module *M = 0) const;
+ void printTypes(std::ostream &o, const Module *M = 0) const;
private:
// IncorporateType - Incorporate one type and all of its subtypes into the
//
template<class Payload>
class InstTreeNode :
- public Tree<InstTreeNode<Payload>, pair<pair<Value*, char>, Payload> > {
+ public Tree<InstTreeNode<Payload>,
+ std::pair<std::pair<Value*, char>, Payload> > {
friend class InstForest<Payload>;
- typedef Tree<InstTreeNode<Payload>, pair<pair<Value*, char>, Payload> > super;
+ typedef Tree<InstTreeNode<Payload>,
+ std::pair<std::pair<Value*, char>, Payload> > super;
// Constants used for the node type value
enum NodeTypeTy {
public:
// print - Called by operator<< below...
- void print(ostream &o, unsigned Indent) const {
- o << string(Indent*2, ' ');
+ void print(std::ostream &o, unsigned Indent) const {
+ o << std::string(Indent*2, ' ');
switch (getNodeType()) {
case ConstNode : o << "Constant : "; break;
- case BasicBlockNode : o << "BasicBlock : " << getValue()->getName() << endl;
+ case BasicBlockNode : o << "BasicBlock : " << getValue()->getName() << "\n";
return;
case InstructionNode: o << "Instruction: "; break;
case TemporaryNode : o << "Temporary : "; break;
- default: o << "UNKNOWN NODE TYPE: " << getNodeType() << endl; abort();
+ default: o << "UNKNOWN NODE TYPE: " << getNodeType() << "\n"; abort();
}
o << getValue();
};
template<class Payload>
-inline ostream &operator<<(ostream &o, const InstTreeNode<Payload> *N) {
+inline std::ostream &operator<<(std::ostream &o,
+ const InstTreeNode<Payload> *N) {
N->print(o, 0); return o;
}
// guaranteed to be an instruction node. The constructor builds the forest.
//
template<class Payload>
-class InstForest : public vector<InstTreeNode<Payload> *> {
+class InstForest : public std::vector<InstTreeNode<Payload> *> {
friend class InstTreeNode<Payload>;
// InstMap - Map contains entries for ALL instructions in the method and the
// InstTreeNode that they correspond to.
//
- map<Instruction*, InstTreeNode<Payload> *> InstMap;
+ std::map<Instruction*, InstTreeNode<Payload> *> InstMap;
void addInstMapping(Instruction *I, InstTreeNode<Payload> *IN) {
- InstMap.insert(make_pair(I, IN));
+ InstMap.insert(std::make_pair(I, IN));
}
void removeInstFromRootList(Instruction *I) {
// the parent pointer can be used to find the root of the tree.
//
inline InstTreeNode<Payload> *getInstNode(Instruction *Inst) {
- map<Instruction*, InstTreeNode<Payload> *>::iterator I = InstMap.find(Inst);
+ std::map<Instruction*, InstTreeNode<Payload> *>::iterator I =
+ InstMap.find(Inst);
if (I != InstMap.end()) return I->second;
return 0;
}
inline const InstTreeNode<Payload> *getInstNode(const Instruction *Inst)const{
- map<Instruction*, InstTreeNode<Payload>*>::const_iterator I =
+ std::map<Instruction*, InstTreeNode<Payload>*>::const_iterator I =
InstMap.find(Inst);
if (I != InstMap.end()) return I->second;
return 0;
}
// print - Called by operator<< below...
- void print(ostream &out) const {
+ void print(std::ostream &out) const {
for (const_iterator I = begin(), E = end(); I != E; ++I)
out << *I;
}
};
template<class Payload>
-inline ostream &operator<<(ostream &o, const InstForest<Payload> &IF) {
+inline std::ostream &operator<<(std::ostream &o, const InstForest<Payload> &IF){
IF.print(o); return o;
}
// Otherwise, we are an internal instruction node. We must process our
// uses and add them as children of this node.
//
- vector<InstTreeNode*> Children;
+ std::vector<InstTreeNode*> Children;
// Make sure that the forest knows about us!
IF.addInstMapping(I, this);
//
BasicBlock *HeaderNode;
public:
- typedef vector<BasicBlock*>::iterator succ_iterator;
- typedef vector<BasicBlock*>::iterator pred_iterator;
- typedef vector<BasicBlock*>::iterator node_iterator;
+ typedef std::vector<BasicBlock*>::iterator succ_iterator;
+ typedef std::vector<BasicBlock*>::iterator pred_iterator;
+ typedef std::vector<BasicBlock*>::iterator node_iterator;
inline Interval(BasicBlock *Header) : HeaderNode(Header) {
Nodes.push_back(Header);
// Nodes - The basic blocks in this interval.
//
- vector<BasicBlock*> Nodes;
+ std::vector<BasicBlock*> Nodes;
// Successors - List of BasicBlocks that are reachable directly from nodes in
// this interval, but are not in the interval themselves.
// These nodes neccesarily must be header nodes for other intervals.
//
- vector<BasicBlock*> Successors;
+ std::vector<BasicBlock*> Successors;
// Predecessors - List of BasicBlocks that have this Interval's header block
// as one of their successors.
//
- vector<BasicBlock*> Predecessors;
+ std::vector<BasicBlock*> Predecessors;
// contains - Find out if a basic block is in this interval
inline bool contains(BasicBlock *BB) const {
template<class NodeTy, class OrigContainer_t>
class IntervalIterator {
- stack<pair<Interval*, typename Interval::succ_iterator> > IntStack;
- set<BasicBlock*> Visited;
+ std::stack<std::pair<Interval*, typename Interval::succ_iterator> > IntStack;
+ std::set<BasicBlock*> Visited;
OrigContainer_t *OrigContainer;
bool IOwnMem; // If True, delete intervals when done with them
// See file header for conditions of use
typedef BasicBlock* _BB;
typedef IntervalIterator<NodeTy, OrigContainer_t> _Self;
- typedef forward_iterator_tag iterator_category;
+ typedef std::forward_iterator_tag iterator_category;
IntervalIterator() {} // End iterator, empty stack
IntervalIterator(Method *M, bool OwnMemory) : IOwnMem(OwnMemory) {
// BasicBlock is a (possibly nonexistent) loop with a "tail" of non looping
// nodes following it.
//
-class IntervalPartition : public vector<Interval*> {
- typedef map<BasicBlock*, Interval*> IntervalMapTy;
+class IntervalPartition : public std::vector<Interval*> {
+ typedef std::map<BasicBlock*, Interval*> IntervalMapTy;
IntervalMapTy IntervalMap;
- typedef vector<Interval*> IntervalListTy;
+ typedef std::vector<Interval*> IntervalListTy;
Interval *RootInterval;
public:
#ifndef LIVE_VAR_MAP_H
#define LIVE_VAR_MAP_H
-#include <hash_map>
+#include <ext/hash_map>
class BasicBlock;
class BBLiveVar;
-typedef hash_map<const BasicBlock *,
- BBLiveVar *, hashFuncBB > BBToBBLiveVarMapType;
+typedef std::hash_map<const BasicBlock *,
+ BBLiveVar *, hashFuncBB > BBToBBLiveVarMapType;
-typedef hash_map<const MachineInstr *, const LiveVarSet *,
- hashFuncMInst> MInstToLiveVarSetMapType;
+typedef std::hash_map<const MachineInstr *, const LiveVarSet *,
+ hashFuncMInst> MInstToLiveVarSetMapType;
#endif
#ifndef LIVE_VAR_SET_H
#define LIVE_VAR_SET_H
-#include "ValueSet.h"
+#include "llvm/Analysis/LiveVar/ValueSet.h"
#include "llvm/Instruction.h"
#include "llvm/Type.h"
-/* Title: ValueSet.h
+/* Title: ValueSet.h -*- C++ -*-
Author: Ruchira Sasanka
Date: Jun 30, 01
Purpose: Contains a mathematical set of Values. LiveVarSet is derived from
#ifndef VALUE_SET_H
#define VALUE_SET_H
-#include <stdlib.h>
-
-#include <hash_set>
-#include <algorithm>
-//#include <fstream>
-#include <iostream>
-
-#include "llvm/Value.h"
-
-
-//------------------------ Support functions ---------------------------------
-
-struct hashFuncValue { // sturcture containing the hash func
- inline size_t operator () (const Value *const val) const
- { return (size_t) val; }
-};
-
-
+class Value;
+#include "Support/HashExtras.h"
+#include <ext/hash_set>
//------------------- Class Definition for ValueSet --------------------------
-class ValueSet : public hash_set<const Value *, hashFuncValue >
-{
-
+class ValueSet : public std::hash_set<const Value *> {
public:
- ValueSet(); // constructor
-
inline void add(const Value *const val)
{ assert( val ); insert(val);} // for adding a live variable to set
namespace cfg {class Interval; }
class LoopDepthCalculator {
- map<const BasicBlock*, unsigned> LoopDepth;
+ std::map<const BasicBlock*, unsigned> LoopDepth;
inline void AddBB(const BasicBlock *BB); // Increment count for this block
inline void ProcessInterval(cfg::Interval *I);
public:
LoopDepthCalculator(Method *M);
inline unsigned getLoopDepth(const BasicBlock *BB) const {
- map<const BasicBlock*, unsigned>::const_iterator I = LoopDepth.find(BB);
+ std::map<const BasicBlock*,unsigned>::const_iterator I = LoopDepth.find(BB);
return I != LoopDepth.end() ? I->second : 0;
}
};
//
class Loop {
Loop *ParentLoop;
- vector<const BasicBlock *> Blocks; // First entry is the header node
- vector<Loop*> SubLoops; // Loops contained entirely within this one
+ std::vector<const BasicBlock *> Blocks; // First entry is the header node
+ std::vector<Loop*> SubLoops; // Loops contained entirely within this one
unsigned LoopDepth; // Nesting depth of this loop
Loop(const Loop &); // DO NOT IMPLEMENT
bool contains(const BasicBlock *BB) const;
// getSubLoops - Return the loops contained entirely within this loop
- inline const vector<Loop*> &getSubLoops() const { return SubLoops; }
- inline const vector<const BasicBlock*> &getBlocks() const { return Blocks; }
+ inline const std::vector<Loop*> &getSubLoops() const { return SubLoops; }
+ inline const std::vector<const BasicBlock*> &getBlocks() const {
+ return Blocks;
+ }
private:
friend class LoopInfo;
//
class LoopInfo {
// BBMap - Mapping of basic blocks to the inner most loop they occur in
- map<const BasicBlock *, Loop*> BBMap;
- vector<Loop*> TopLevelLoops;
+ std::map<const BasicBlock *, Loop*> BBMap;
+ std::vector<Loop*> TopLevelLoops;
public:
// LoopInfo ctor - Calculate the natural loop information for a CFG
LoopInfo(const DominatorSet &DS);
- const vector<Loop*> &getTopLevelLoops() const { return TopLevelLoops; }
+ const std::vector<Loop*> &getTopLevelLoops() const { return TopLevelLoops; }
// getLoopFor - Return the inner most loop that BB lives in. If a basic block
// is in no loop (for example the entry node), null is returned.
//
const Loop *getLoopFor(const BasicBlock *BB) const {
- map<const BasicBlock *, Loop*>::const_iterator I = BBMap.find(BB);
+ std::map<const BasicBlock *, Loop*>::const_iterator I = BBMap.find(BB);
return I != BBMap.end() ? I->second : 0;
}
inline const Loop *operator[](const BasicBlock *BB) const {
virtual bool processInstruction(const Instruction *I) { return false; }
private:
- bool handleType(set<const Type *> &TypeSet, const Type *T);
+ bool handleType(std::set<const Type *> &TypeSet, const Type *T);
};
#endif
const Module *TheModule;
bool IgnoreNamedNodes; // Shall we not count named nodes?
- typedef vector<const Value*> TypePlane;
- vector<TypePlane> Table;
- map<const Value *, unsigned> NodeMap;
+ typedef std::vector<const Value*> TypePlane;
+ std::vector<TypePlane> Table;
+ std::map<const Value *, unsigned> NodeMap;
// ModuleLevel - Used to keep track of which values belong to the module,
// and which values belong to the currently incorporated method.
//
- vector<unsigned> ModuleLevel;
+ std::vector<unsigned> ModuleLevel;
public:
SlotCalculator(const Module *M, bool IgnoreNamed);
// error messages corresponding to the problem are added to the errorMsgs
// vectors, and a value of true is returned.
//
-bool verify(const Module *M, vector<string> &ErrorMsgs);
-bool verify(const Method *M, vector<string> &ErrorMsgs);
+bool verify(const Module *M, std::vector<std::string> &ErrorMsgs);
+bool verify(const Method *M, std::vector<std::string> &ErrorMsgs);
#endif
class Interval;
class IntervalPartition;
- void WriteToOutput(const Interval *I, ostream &o);
- inline ostream &operator <<(ostream &o, const Interval *I) {
+ void WriteToOutput(const Interval *I, std::ostream &o);
+ inline std::ostream &operator <<(std::ostream &o, const Interval *I) {
WriteToOutput(I, o); return o;
}
- void WriteToOutput(const IntervalPartition &IP, ostream &o);
- inline ostream &operator <<(ostream &o, const IntervalPartition &IP) {
+ void WriteToOutput(const IntervalPartition &IP, std::ostream &o);
+ inline std::ostream &operator <<(std::ostream &o,
+ const IntervalPartition &IP) {
WriteToOutput(IP, o); return o;
}
class DominatorTree;
class DominanceFrontier;
- void WriteToOutput(const DominatorSet &, ostream &o);
- inline ostream &operator <<(ostream &o, const DominatorSet &DS) {
+ void WriteToOutput(const DominatorSet &, std::ostream &o);
+ inline std::ostream &operator <<(std::ostream &o, const DominatorSet &DS) {
WriteToOutput(DS, o); return o;
}
- void WriteToOutput(const ImmediateDominators &, ostream &o);
- inline ostream &operator <<(ostream &o, const ImmediateDominators &ID) {
+ void WriteToOutput(const ImmediateDominators &, std::ostream &o);
+ inline std::ostream &operator <<(std::ostream &o,
+ const ImmediateDominators &ID) {
WriteToOutput(ID, o); return o;
}
- void WriteToOutput(const DominatorTree &, ostream &o);
- inline ostream &operator <<(ostream &o, const DominatorTree &DT) {
+ void WriteToOutput(const DominatorTree &, std::ostream &o);
+ inline std::ostream &operator <<(std::ostream &o, const DominatorTree &DT) {
WriteToOutput(DT, o); return o;
}
- void WriteToOutput(const DominanceFrontier &, ostream &o);
- inline ostream &operator <<(ostream &o, const DominanceFrontier &DF) {
+ void WriteToOutput(const DominanceFrontier &, std::ostream &o);
+ inline std::ostream &operator <<(std::ostream &o,
+ const DominanceFrontier &DF) {
WriteToOutput(DF, o); return o;
}
class CallGraph;
class CallGraphNode;
- void WriteToOutput(const CallGraph &, ostream &o);
- inline ostream &operator <<(ostream &o, const CallGraph &CG) {
+ void WriteToOutput(const CallGraph &, std::ostream &o);
+ inline std::ostream &operator <<(std::ostream &o, const CallGraph &CG) {
WriteToOutput(CG, o); return o;
}
- void WriteToOutput(const CallGraphNode *, ostream &o);
- inline ostream &operator <<(ostream &o, const CallGraphNode *CGN) {
+ void WriteToOutput(const CallGraphNode *, std::ostream &o);
+ inline std::ostream &operator <<(std::ostream &o, const CallGraphNode *CGN) {
WriteToOutput(CGN, o); return o;
}
class Loop;
class LoopInfo;
- void WriteToOutput(const LoopInfo &, ostream &o);
- inline ostream &operator <<(ostream &o, const LoopInfo &LI) {
+ void WriteToOutput(const LoopInfo &, std::ostream &o);
+ inline std::ostream &operator <<(std::ostream &o, const LoopInfo &LI) {
WriteToOutput(LI, o); return o;
}
- void WriteToOutput(const Loop *, ostream &o);
- inline ostream &operator <<(ostream &o, const Loop *L) {
+ void WriteToOutput(const Loop *, std::ostream &o);
+ inline std::ostream &operator <<(std::ostream &o, const Loop *L) {
WriteToOutput(L, o); return o;
}
} // End namespace CFG
class InductionVariable;
-void WriteToOutput(const InductionVariable &, ostream &o);
-inline ostream &operator <<(ostream &o, const InductionVariable &IV) {
+void WriteToOutput(const InductionVariable &, std::ostream &o);
+inline std::ostream &operator <<(std::ostream &o, const InductionVariable &IV) {
WriteToOutput(IV, o); return o;
}
//===--------------------------------------------------------------------===//
// Basic ID <-> Name map functionality
- static AnnotationID getID (const string &Name); // Name -> ID
- static const string &getName(AnnotationID ID); // ID -> Name
+ static AnnotationID getID(const std::string &Name); // Name -> ID
+ static const std::string &getName(AnnotationID ID); // ID -> Name
// getID - Name -> ID + registration of a factory function for demand driven
// annotation support.
- static AnnotationID getID (const string &Name, Factory Fact, void *Data=0);
+ static AnnotationID getID(const std::string &Name, Factory Fact,
+ void *Data = 0);
//===--------------------------------------------------------------------===//
// Annotation creation on demand support...
#define LLVM_ASSEMBLY_CACHED_WRITER_H
#include "llvm/Assembly/Writer.h"
+#include <iostream>
class AssemblyWriter; // Internal private class
class SlotCalculator;
AssemblyWriter *AW;
SlotCalculator *SC;
public:
- ostream &Out;
+ std::ostream &Out;
public:
- CachedWriter(ostream &O = cout) : AW(0), SC(0), Out(O) { }
- CachedWriter(const Module *M, ostream &O = cout) : AW(0), SC(0), Out(O) {
+ CachedWriter(std::ostream &O = std::cout) : AW(0), SC(0), Out(O) { }
+ CachedWriter(const Module *M, std::ostream &O = std::cout)
+ : AW(0), SC(0), Out(O) {
setModule(M);
}
~CachedWriter();
return *this << (const Value*)X;
}
- inline CachedWriter &operator<<(ostream &(&Manip)(ostream &)) {
+ inline CachedWriter &operator<<(std::ostream &(&Manip)(std::ostream &)) {
Out << Manip; return *this;
}
// The useful interface defined by this file... Parse an ascii file, and return
// the internal representation in a nice slice'n'dice'able representation.
//
-Module *ParseAssemblyFile(const string &Filename);// throw (ParseException);
+Module *ParseAssemblyFile(const std::string &Filename);// throw (ParseException)
//===------------------------------------------------------------------------===
// Helper Classes
//
class ParseException {
public:
- ParseException(const string &filename, const string &message,
+ ParseException(const std::string &filename, const std::string &message,
int LineNo = -1, int ColNo = -1);
ParseException(const ParseException &E);
// getMessage - Return the message passed in at construction time plus extra
// information extracted from the options used to parse with...
//
- const string getMessage() const;
+ const std::string getMessage() const;
- inline const string getRawMessage() const { // Just the raw message...
+ inline const std::string &getRawMessage() const { // Just the raw message...
return Message;
}
- inline const string &getFilename() const {
+ inline const std::string &getFilename() const {
return Filename;
}
}
private :
- string Filename;
- string Message;
+ std::string Filename;
+ std::string Message;
int LineNo, ColumnNo; // -1 if not relevant
ParseException &operator=(const ParseException &E); // objects by reference
#include "llvm/Pass.h"
#include "llvm/Assembly/Writer.h"
+#include <iostream>
class PrintModulePass : public Pass {
- string Banner; // String to print before each method
- ostream *Out; // ostream to print on
+ std::string Banner; // String to print before each method
+ std::ostream *Out; // ostream to print on
bool DeleteStream; // Delete the ostream in our dtor?
bool PrintPerMethod; // Print one method at a time rather than the whole?
public:
- inline PrintModulePass(const string &B, ostream *o = &cout,
+ inline PrintModulePass(const std::string &B, std::ostream *o = &std::cout,
bool DS = false,
bool printPerMethod = true)
: Banner(B), Out(o), DeleteStream(DS), PrintPerMethod(printPerMethod) {
// representation of an object into an ascii bytestream that the parser can
// understand later... (the parser only understands whole classes though)
//
-void WriteToAssembly(const Module *Module, ostream &o);
-void WriteToAssembly(const GlobalVariable *G, ostream &o);
-void WriteToAssembly(const Method *Method, ostream &o);
-void WriteToAssembly(const BasicBlock *BB, ostream &o);
-void WriteToAssembly(const Instruction *In, ostream &o);
-void WriteToAssembly(const Constant *V, ostream &o);
+void WriteToAssembly(const Module *Module, std::ostream &o);
+void WriteToAssembly(const GlobalVariable *G, std::ostream &o);
+void WriteToAssembly(const Method *Method, std::ostream &o);
+void WriteToAssembly(const BasicBlock *BB, std::ostream &o);
+void WriteToAssembly(const Instruction *In, std::ostream &o);
+void WriteToAssembly(const Constant *V, std::ostream &o);
// WriteTypeSymbolic - This attempts to write the specified type as a symbolic
// type, iff there is an entry in the modules symbol table for the specified
// type or one of it's component types. This is slower than a simple x << Type;
//
-ostream &WriteTypeSymbolic(ostream &o, const Type *Ty, const Module *Module);
+std::ostream &WriteTypeSymbolic(std::ostream &, const Type *, const Module *M);
// WriteAsOperand - Write the name of the specified value out to the specified
// ostream. This can be useful when you just want to print int %reg126, not the
// whole instruction that generated it.
//
-ostream &WriteAsOperand(ostream &o, const Value *V, bool PrintType = true,
- bool PrintName = true, SlotCalculator *Table = 0);
+std::ostream &WriteAsOperand(std::ostream &, const Value *, bool PrintTy = true,
+ bool PrintName = true, SlotCalculator *Table = 0);
// WriteToVCG - Dump the specified structure to a VCG file. If method is
// family of files with a common base name is created, with a method name
// suffix.
//
-void WriteToVCG(const Module *Module, const string &Filename);
-void WriteToVCG(const Method *Method, const string &Filename);
+void WriteToVCG(const Module *Module, const std::string &Filename);
+void WriteToVCG(const Method *Method, const std::string &Filename);
// Define operator<< to work on the various classes that we can send to an
// ostream...
//
-inline ostream &operator<<(ostream &o, const Module *C) {
+inline std::ostream &operator<<(std::ostream &o, const Module *C) {
WriteToAssembly(C, o); return o;
}
-inline ostream &operator<<(ostream &o, const GlobalVariable *G) {
+inline std::ostream &operator<<(std::ostream &o, const GlobalVariable *G) {
WriteToAssembly(G, o); return o;
}
-inline ostream &operator<<(ostream &o, const Method *M) {
+inline std::ostream &operator<<(std::ostream &o, const Method *M) {
WriteToAssembly(M, o); return o;
}
-inline ostream &operator<<(ostream &o, const BasicBlock *B) {
+inline std::ostream &operator<<(std::ostream &o, const BasicBlock *B) {
WriteToAssembly(B, o); return o;
}
-inline ostream &operator<<(ostream &o, const Instruction *I) {
+inline std::ostream &operator<<(std::ostream &o, const Instruction *I) {
WriteToAssembly(I, o); return o;
}
-inline ostream &operator<<(ostream &o, const Constant *I) {
+inline std::ostream &operator<<(std::ostream &o, const Constant *I) {
WriteToAssembly(I, o); return o;
}
-inline ostream &operator<<(ostream &o, const Type *T) {
+inline std::ostream &operator<<(std::ostream &o, const Type *T) {
if (!T) return o << "<null Type>";
return o << T->getDescription();
}
-inline ostream &operator<<(ostream &o, const Value *I) {
+inline std::ostream &operator<<(std::ostream &o, const Value *I) {
switch (I->getValueType()) {
case Value::TypeVal: return o << cast<const Type>(I);
case Value::ConstantVal: WriteToAssembly(cast<Constant>(I) , o); break;
// Instruction iterators...
typedef InstListType::iterator iterator;
typedef InstListType::const_iterator const_iterator;
- typedef reverse_iterator<const_iterator> const_reverse_iterator;
- typedef reverse_iterator<iterator> reverse_iterator;
+ typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
+ typedef std::reverse_iterator<iterator> reverse_iterator;
// Predecessor and successor iterators...
typedef PredIterator<BasicBlock, Value::use_iterator> pred_iterator;
const BasicBlock> succ_const_iterator;
// Ctor, dtor
- BasicBlock(const string &Name = "", Method *Parent = 0);
+ BasicBlock(const std::string &Name = "", Method *Parent = 0);
~BasicBlock();
// Specialize setName to take care of symbol table majik
- virtual void setName(const string &name, SymbolTable *ST = 0);
+ virtual void setName(const std::string &name, SymbolTable *ST = 0);
// getParent - Return the enclosing method, or null if none
const Method *getParent() const { return InstList.getParent(); }
}
static inline bool read(const unsigned char *&Buf, const unsigned char *EndBuf,
- string &Result, bool Aligned = true) {
+ std::string &Result, bool Aligned = true) {
unsigned Size;
if (read_vbr(Buf, EndBuf, Size)) return true; // Failure reading size?
if (Buf+Size > EndBuf) return true; // Size invalid?
- Result = string((char*)Buf, Size);
+ Result = std::string((char*)Buf, Size);
Buf += Size;
if (Aligned) // If we should stay aligned do so...
// string... note that this should be inlined always so only the relevant IF
// body should be included...
//
-static inline void output(unsigned i, deque<unsigned char> &Out, int pos = -1){
+static inline void output(unsigned i, std::deque<unsigned char> &Out,
+ int pos = -1) {
#ifdef LITTLE_ENDIAN
if (pos == -1)
Out.insert(Out.end(), (unsigned char*)&i, (unsigned char*)&i+4);
#endif
}
-static inline void output(int i, deque<unsigned char> &Out) {
+static inline void output(int i, std::deque<unsigned char> &Out) {
output((unsigned)i, Out);
}
//
// Note that using this may cause the output buffer to become unaligned...
//
-static inline void output_vbr(uint64_t i, deque<unsigned char> &out) {
+static inline void output_vbr(uint64_t i, std::deque<unsigned char> &out) {
while (1) {
if (i < 0x80) { // done?
out.push_back((unsigned char)i); // We know the high bit is clear...
}
}
-static inline void output_vbr(unsigned i, deque<unsigned char> &out) {
+static inline void output_vbr(unsigned i, std::deque<unsigned char> &out) {
while (1) {
if (i < 0x80) { // done?
out.push_back((unsigned char)i); // We know the high bit is clear...
}
}
-static inline void output_vbr(int64_t i, deque<unsigned char> &out) {
+static inline void output_vbr(int64_t i, std::deque<unsigned char> &out) {
if (i < 0)
output_vbr(((uint64_t)(-i) << 1) | 1, out); // Set low order sign bit...
else
}
-static inline void output_vbr(int i, deque<unsigned char> &out) {
+static inline void output_vbr(int i, std::deque<unsigned char> &out) {
if (i < 0)
output_vbr(((unsigned)(-i) << 1) | 1, out); // Set low order sign bit...
else
// align32 - emit the minimal number of bytes that will bring us to 32 bit
// alignment...
//
-static inline void align32(deque<unsigned char> &Out) {
+static inline void align32(std::deque<unsigned char> &Out) {
int NumPads = (4-(Out.size() & 3)) & 3; // Bytes to get padding to 32 bits
while (NumPads--) Out.push_back((unsigned char)0xAB);
}
-static inline void output(const string &s, deque<unsigned char> &Out,
+static inline void output(const std::string &s, std::deque<unsigned char> &Out,
bool Aligned = true) {
unsigned Len = s.length();
output_vbr(Len, Out); // Strings may have an arbitrary length...
}
static inline void output_data(void *Ptr, void *End,
- deque<unsigned char> &Out, bool Align = false) {
+ std::deque<unsigned char> &Out,
+ bool Align = false) {
#ifdef LITTLE_ENDIAN
Out.insert(Out.end(), (unsigned char*)Ptr, (unsigned char*)End);
#else
// Parse and return a class...
//
-Module *ParseBytecodeFile(const string &Filename, string *ErrorStr = 0);
+Module *ParseBytecodeFile(const std::string &Filename,
+ std::string *ErrorStr = 0);
Module *ParseBytecodeBuffer(const char *Buffer, unsigned BufferSize,
- string *ErrorStr = 0);
+ std::string *ErrorStr = 0);
#endif
#include "llvm/Instruction.h"
#include "Support/NonCopyable.h"
#include "Support/HashExtras.h"
-#include <hash_map>
-#include <hash_set>
+#include <ext/hash_set>
class Constant;
class BasicBlock;
//
//------------------------------------------------------------------------
-class InstrForest : private hash_map<const Instruction *, InstructionNode*> {
+class InstrForest : private std::hash_map<const Instruction *, InstructionNode*> {
private:
- hash_set<InstructionNode*> treeRoots;
+ std::hash_set<InstructionNode*> treeRoots;
public:
/*ctor*/ InstrForest (Method *M);
return (*this)[instr];
}
- inline const hash_set<InstructionNode*> &getRootSet() const {
+ inline const std::hash_set<InstructionNode*> &getRootSet() const {
return treeRoots;
}
public:
// Constructor that uses the type of S1 as the type of the temporary.
// s1 must be a valid value. s2 may be NULL.
- TmpInstruction(OtherOps opcode, Value *s1, Value* s2, const string &name="")
+ TmpInstruction(OtherOps opcode, Value *s1, Value* s2,
+ const std::string &name = "")
: Instruction(s1->getType(), opcode, name)
{
assert(s1 != NULL && "Use different constructor if both operands are 0");
// Constructor that allows the type of the temporary to be specified.
// Both S1 and S2 may be NULL.
TmpInstruction(OtherOps opcode, const Type* tmpType,
- Value *s1, Value* s2, const string &name = "")
+ Value *s1, Value* s2, const std::string &name = "")
: Instruction(tmpType, opcode, name)
{
Initialize(opcode, s1, s2);
class Constant;
class TargetMachine;
-//************************ Exported Functions ******************************/
-
//---------------------------------------------------------------------------
// Function GetConstantValueAsSignedInt
//---------------------------------------------------------------------------
Value* FoldGetElemChain (const InstructionNode* getElemInstrNode,
- vector<Value*>& chainIdxVec);
+ std::vector<Value*>& chainIdxVec);
//------------------------------------------------------------------------
// fall under case 3; these must be inserted before `minstr'.
//---------------------------------------------------------------------------
-vector<MachineInstr*> FixConstantOperandsForInstr (Instruction* vmInstr,
- MachineInstr* minstr,
- TargetMachine& target);
-
-
-//**************************************************************************/
+std::vector<MachineInstr*> FixConstantOperandsForInstr (Instruction* vmInstr,
+ MachineInstr* minstr,
+ TargetMachine& target);
#endif
-/* Title: InterferenceGraph.h
+/* Title: InterferenceGraph.h -*- C++ -*-
Author: Ruchira Sasanka
Date: July 20, 01
Purpose: Interference Graph used for register coloring.
#include "llvm/CodeGen/IGNode.h"
-typedef vector <IGNode *> IGNodeListType;
+typedef std::vector <IGNode *> IGNodeListType;
class InterferenceGraph
// to create it after adding all IGNodes to the IGNodeList
InterferenceGraph(RegClass *const RC);
+ ~InterferenceGraph();
+
void createGraph();
void addLRToIG(LiveRange *const LR);
void printIG() const;
void printIGNodeList() const;
-
- ~InterferenceGraph();
-
-
};
-
#endif
-
#include "llvm/Annotation.h"
#include "llvm/Method.h"
#include <iterator>
-#include <hash_map>
-#include <hash_set>
#include <values.h>
template<class _MI, class _V> class ValOpIterator;
}
public:
- friend ostream& operator<<(ostream& os, const MachineOperand& mop);
+ friend std::ostream& operator<<(std::ostream& os, const MachineOperand& mop);
private:
private:
MachineOpCode opCode;
OpCodeMask opCodeMask; // extra bits for variants of an opcode
- vector<MachineOperand> operands;
- vector<Value*> implicitRefs; // values implicitly referenced by this
- vector<bool> implicitIsDef; // machine instruction (eg, call args)
+ std::vector<MachineOperand> operands;
+ std::vector<Value*> implicitRefs; // values implicitly referenced by this
+ std::vector<bool> implicitIsDef; // machine instruction (eg, call args)
public:
typedef ValOpIterator<const MachineInstr, const Value> val_const_op_iterator;
public:
- friend ostream& operator<<(ostream& os, const MachineInstr& minstr);
- friend val_const_op_iterator;
- friend val_op_iterator;
+ friend std::ostream& operator<<(std::ostream& os, const MachineInstr& minstr);
+ friend class val_const_op_iterator;
+ friend class val_op_iterator;
public:
// Access to set the operands when building the machine instruction
//
//---------------------------------------------------------------------------
-class MachineCodeForVMInstr: public vector<MachineInstr*>
+class MachineCodeForVMInstr: public std::vector<MachineInstr*>
{
private:
- vector<Value*> tempVec; // used by m/c instr but not VM instr
+ std::vector<Value*> tempVec; // used by m/c instr but not VM instr
public:
/*ctor*/ MachineCodeForVMInstr () {}
/*ctor*/ ~MachineCodeForVMInstr ();
- const vector<Value*>& getTempValues () const { return tempVec; }
- vector<Value*>& getTempValues () { return tempVec; }
+ const std::vector<Value*>& getTempValues () const { return tempVec; }
+ std::vector<Value*>& getTempValues () { return tempVec; }
void addTempValue (Value* val) { tempVec.push_back(val); }
//---------------------------------------------------------------------------
-class MachineCodeForBasicBlock: public vector<MachineInstr*> {
+class MachineCodeForBasicBlock: public std::vector<MachineInstr*> {
public:
- typedef vector<MachineInstr*>::iterator iterator;
- typedef vector<const MachineInstr*>::const_iterator const_iterator;
+ typedef std::vector<MachineInstr*>::iterator iterator;
+ typedef std::vector<MachineInstr*>::const_iterator const_iterator;
};
unsigned currentOptionalArgsSize;
unsigned maxOptionalArgsSize;
unsigned currentTmpValuesSize;
- hash_set<const Constant*> constantsForConstPool;
- hash_map<const Value*, int> offsets;
+ std::hash_set<const Constant*> constantsForConstPool;
+ std::hash_map<const Value*, int> offsets;
// hash_map<const Value*, int> offsetsFromSP;
public:
inline unsigned getMaxOptionalArgsSize() const { return maxOptionalArgsSize;}
inline unsigned getCurrentOptionalArgsSize() const
{ return currentOptionalArgsSize;}
- inline const hash_set<const Constant*>&
+ inline const std::hash_set<const Constant*>&
getConstantPoolValues() const {return constantsForConstPool;}
//
//---------------------------------------------------------------------------
-ostream& operator<< (ostream& os, const MachineInstr& minstr);
+std::ostream& operator<< (std::ostream& os, const MachineInstr& minstr);
-ostream& operator<< (ostream& os, const MachineOperand& mop);
+std::ostream& operator<< (std::ostream& os, const MachineOperand& mop);
void PrintMachineInstructions(const Method *method);
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/MachineRegInfo.h"
#include <stack>
+#include <iostream>
-typedef vector<unsigned int> ReservedColorListType;
+typedef std::vector<unsigned int> ReservedColorListType;
//-----------------------------------------------------------------------------
InterferenceGraph IG; // Interference graph - constructed by
// buildInterferenceGraph
- stack <IGNode *> IGNodeStack; // the stack used for coloring
+ std::stack<IGNode *> IGNodeStack; // the stack used for coloring
const ReservedColorListType *const ReservedColorList;
//
inline void printIGNodeList() const {
- cerr << "IG Nodes for Register Class " << RegClassID << ":" << endl;
+ std::cerr << "IG Nodes for Register Class " << RegClassID << ":" << "\n";
IG.printIGNodeList();
}
inline void printIG() {
- cerr << "IG for Register Class " << RegClassID << ":" << endl;
+ std::cerr << "IG for Register Class " << RegClassID << ":" << "\n";
IG.printIG();
}
-
};
-
-
-
-
-
-
#endif
-/* Title: ValueSet.h
+/* Title: ValueSet.h -*- C++ -*-
Author: Ruchira Sasanka
Date: Jun 30, 01
Purpose: Contains a mathematical set of Values. LiveVarSet is derived from
#ifndef VALUE_SET_H
#define VALUE_SET_H
-#include <stdlib.h>
-
-#include <hash_set>
-#include <algorithm>
-//#include <fstream>
-#include <iostream>
-
-#include "llvm/Value.h"
-
-
-//------------------------ Support functions ---------------------------------
-
-struct hashFuncValue { // sturcture containing the hash func
- inline size_t operator () (const Value *const val) const
- { return (size_t) val; }
-};
-
-
+class Value;
+#include "Support/HashExtras.h"
+#include <ext/hash_set>
//------------------- Class Definition for ValueSet --------------------------
-class ValueSet : public hash_set<const Value *, hashFuncValue >
-{
-
+class ValueSet : public std::hash_set<const Value *> {
public:
- ValueSet(); // constructor
-
inline void add(const Value *const val)
{ assert( val ); insert(val);} // for adding a live variable to set
void destroyConstantImpl();
public:
// Specialize setName to handle symbol table majik...
- virtual void setName(const string &name, SymbolTable *ST = 0);
+ virtual void setName(const std::string &name, SymbolTable *ST = 0);
- virtual string getStrValue() const = 0;
+ virtual std::string getStrValue() const = 0;
// Static constructor to get a '0' constant of arbitrary type...
static Constant *getNullConstant(const Type *Ty);
// inverted - Return the opposite value of the current value.
inline ConstantBool *inverted() const { return (this==True) ? False : True; }
- virtual string getStrValue() const;
+ virtual std::string getStrValue() const;
inline bool getValue() const { return Val; }
// isNullValue - Return true if this is the value that would be returned by
public:
static ConstantSInt *get(const Type *Ty, int64_t V);
- virtual string getStrValue() const;
+ virtual std::string getStrValue() const;
static bool isValueValidForType(const Type *Ty, int64_t V);
inline int64_t getValue() const { return Val.Signed; }
public:
static ConstantUInt *get(const Type *Ty, uint64_t V);
- virtual string getStrValue() const;
+ virtual std::string getStrValue() const;
static bool isValueValidForType(const Type *Ty, uint64_t V);
inline uint64_t getValue() const { return Val.Unsigned; }
public:
static ConstantFP *get(const Type *Ty, double V);
- virtual string getStrValue() const;
+ virtual std::string getStrValue() const;
static bool isValueValidForType(const Type *Ty, double V);
inline double getValue() const { return Val; }
class ConstantArray : public Constant {
ConstantArray(const ConstantArray &); // DO NOT IMPLEMENT
protected:
- ConstantArray(const ArrayType *T, const vector<Constant*> &Val);
+ ConstantArray(const ArrayType *T, const std::vector<Constant*> &Val);
~ConstantArray() {}
virtual void destroyConstant();
public:
- static ConstantArray *get(const ArrayType *T, const vector<Constant*> &);
- static ConstantArray *get(const string &Initializer);
+ static ConstantArray *get(const ArrayType *T, const std::vector<Constant*> &);
+ static ConstantArray *get(const std::string &Initializer);
- virtual string getStrValue() const;
+ virtual std::string getStrValue() const;
inline const ArrayType *getType() const {
return (ArrayType*)Value::getType();
}
- inline const vector<Use> &getValues() const { return Operands; }
+ inline const std::vector<Use> &getValues() const { return Operands; }
// isNullValue - Return true if this is the value that would be returned by
// getNullConstant.
class ConstantStruct : public Constant {
ConstantStruct(const ConstantStruct &); // DO NOT IMPLEMENT
protected:
- ConstantStruct(const StructType *T, const vector<Constant*> &Val);
+ ConstantStruct(const StructType *T, const std::vector<Constant*> &Val);
~ConstantStruct() {}
virtual void destroyConstant();
public:
static ConstantStruct *get(const StructType *T,
- const vector<Constant*> &V);
+ const std::vector<Constant*> &V);
- virtual string getStrValue() const;
+ virtual std::string getStrValue() const;
inline const StructType *getType() const {
return (StructType*)Value::getType();
}
- inline const vector<Use> &getValues() const { return Operands; }
+ inline const std::vector<Use> &getValues() const { return Operands; }
// isNullValue - Return true if this is the value that would be returned by
// getNullConstant.
inline ConstantPointer(const PointerType *T) : Constant((const Type*)T){}
~ConstantPointer() {}
public:
- virtual string getStrValue() const = 0;
+ virtual std::string getStrValue() const = 0;
inline const PointerType *getType() const {
return (PointerType*)Value::getType();
}
inline ConstantPointerNull(const PointerType *T) : ConstantPointer(T) {}
inline ~ConstantPointerNull() {}
public:
- virtual string getStrValue() const;
+ virtual std::string getStrValue() const;
static ConstantPointerNull *get(const PointerType *T);
public:
static ConstantPointerRef *get(GlobalValue *GV);
- virtual string getStrValue() const;
+ virtual std::string getStrValue() const;
const GlobalValue *getValue() const {
return cast<GlobalValue>(Operands[0].get());
// if I am a type, and I get resolved into a more concrete type.
//
///// FIXME: kill mutable nonsense when Type's are not const
- mutable vector<AbstractTypeUser *> AbstractTypeUsers;
+ mutable std::vector<AbstractTypeUser *> AbstractTypeUsers;
char isRefining; // Used for recursive types
class MethodType : public DerivedType {
public:
- typedef vector<PATypeHandle<Type> > ParamTypes;
+ typedef std::vector<PATypeHandle<Type> > ParamTypes;
private:
PATypeHandle<Type> ResultType;
ParamTypes ParamTys;
// defines private constructors and has no friends
// Private ctor - Only can be created by a static member...
- MethodType(const Type *Result, const vector<const Type*> &Params,
+ MethodType(const Type *Result, const std::vector<const Type*> &Params,
bool IsVarArgs);
public:
//
virtual void refineAbstractType(const DerivedType *OldTy, const Type *NewTy);
- static MethodType *get(const Type *Result, const vector<const Type*> &Params,
+ static MethodType *get(const Type *Result,
+ const std::vector<const Type*> &Params,
bool isVarArg);
class StructType : public CompositeType {
public:
- typedef vector<PATypeHandle<Type> > ElementTypes;
+ typedef std::vector<PATypeHandle<Type> > ElementTypes;
private:
ElementTypes ETypes; // Element types of struct
// defines private constructors and has no friends
// Private ctor - Only can be created by a static member...
- StructType(const vector<const Type*> &Types);
+ StructType(const std::vector<const Type*> &Types);
public:
inline const ElementTypes &getElementTypes() const { return ETypes; }
//
virtual void refineAbstractType(const DerivedType *OldTy, const Type *NewTy);
- static StructType *get(const vector<const Type*> &Params);
+ static StructType *get(const std::vector<const Type*> &Params);
// Methods for support type inquiry through isa, cast, and dyn_cast:
static inline bool classof(const StructType *T) { return true; }
// BasicBlock iterators...
typedef BasicBlocksType::iterator iterator;
typedef BasicBlocksType::const_iterator const_iterator;
- typedef reverse_iterator<const_iterator> const_reverse_iterator;
- typedef reverse_iterator<iterator> reverse_iterator;
+ typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
+ typedef std::reverse_iterator<iterator> reverse_iterator;
private:
void setParent(Module *parent);
public:
- Method(const MethodType *Ty, bool isInternal, const string &Name = "");
+ Method(const MethodType *Ty, bool isInternal, const std::string &Name = "");
~Method();
// Specialize setName to handle symbol table majik...
- virtual void setName(const string &name, SymbolTable *ST = 0);
+ virtual void setName(const std::string &name, SymbolTable *ST = 0);
const Type *getReturnType() const; // Return the return type of method
const MethodType *getMethodType() const; // Return the MethodType for me
_BB_i_t BB; // BasicBlocksType::iterator
_BI_t BI; // BasicBlock::iterator
public:
- typedef bidirectional_iterator_tag iterator_category;
- typedef IIty value_type;
- typedef unsigned difference_type;
- typedef BIty pointer;
- typedef IIty reference;
+ typedef std::bidirectional_iterator_tag iterator_category;
+ typedef IIty value_type;
+ typedef unsigned difference_type;
+ typedef BIty pointer;
+ typedef IIty reference;
template<class M> InstIterator(M &m)
: BBs(m.getBasicBlocks()), BB(BBs.begin()) { // begin ctor
GlobalValue(const GlobalValue &); // do not implement
protected:
GlobalValue(const Type *Ty, ValueTy vty, bool hasInternalLinkage,
- const string &name = "")
+ const std::string &name = "")
: User(Ty, vty, name), HasInternalLinkage(hasInternalLinkage), Parent(0) {}
bool HasInternalLinkage; // Is this value accessable externally?
bool isConstantGlobal; // Is this a global constant?
public:
GlobalVariable(const Type *Ty, bool isConstant, bool isInternal,
- Constant *Initializer = 0, const string &Name = "");
+ Constant *Initializer = 0, const std::string &Name = "");
~GlobalVariable() {}
// Specialize setName to handle symbol table majik...
- virtual void setName(const string &name, SymbolTable *ST = 0);
+ virtual void setName(const std::string &name, SymbolTable *ST = 0);
// The initializer for the global variable/constant is held by Operands[0] if
// an initializer is specified.
public:
TerminatorInst(Instruction::TermOps iType);
TerminatorInst(const Type *Ty, Instruction::TermOps iType,
- const string &Name = "");
+ const std::string &Name = "");
inline ~TerminatorInst() {}
// Terminators must implement the methods required by Instruction...
//
static UnaryOperator *create(UnaryOps Op, Value *Source);
- UnaryOperator(Value *S, UnaryOps iType, const string &Name = "")
+ UnaryOperator(Value *S, UnaryOps iType, const std::string &Name = "")
: Instruction(S->getType(), iType, Name) {
Operands.reserve(1);
Operands.push_back(Use(S, this));
// and the two operands.
//
static BinaryOperator *create(BinaryOps Op, Value *S1, Value *S2,
- const string &Name = "");
+ const std::string &Name = "");
BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
- const string &Name = "")
+ const std::string &Name = "")
: Instruction(S1->getType(), iType, Name) {
Operands.reserve(2);
Operands.push_back(Use(S1, this));
protected:
unsigned iType; // InstructionType
public:
- Instruction(const Type *Ty, unsigned iType, const string &Name = "");
+ Instruction(const Type *Ty, unsigned iType, const std::string &Name = "");
virtual ~Instruction(); // Virtual dtor == good.
// Specialize setName to handle symbol table majik...
- virtual void setName(const string &name, SymbolTable *ST = 0);
+ virtual void setName(const std::string &name, SymbolTable *ST = 0);
// clone() - Create a copy of 'this' instruction that is identical in all ways
// except the following:
// error occurs, true is returned and ErrorMsg (if not null) is set to indicate
// the problem.
//
-bool LinkModules(Module *Dest, const Module *Src, string *ErrorMsg = 0);
+bool LinkModules(Module *Dest, const Module *Src, std::string *ErrorMsg = 0);
#endif
typedef ValueHolder<Method, Module, Module> MethodListType;
// Global Variable iterators...
- typedef GlobalListType::iterator giterator;
- typedef GlobalListType::const_iterator const_giterator;
- typedef reverse_iterator<giterator> reverse_giterator;
- typedef reverse_iterator<const_giterator> const_reverse_giterator;
+ typedef GlobalListType::iterator giterator;
+ typedef GlobalListType::const_iterator const_giterator;
+ typedef std::reverse_iterator<giterator> reverse_giterator;
+ typedef std::reverse_iterator<const_giterator> const_reverse_giterator;
// Method iterators...
- typedef MethodListType::iterator iterator;
- typedef MethodListType::const_iterator const_iterator;
- typedef reverse_iterator<const_iterator> const_reverse_iterator;
- typedef reverse_iterator<iterator> reverse_iterator;
+ typedef MethodListType::iterator iterator;
+ typedef MethodListType::const_iterator const_iterator;
+ typedef std::reverse_iterator<iterator> reverse_iterator;
+ typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
private:
GlobalListType GlobalList; // The Global Variables
//
// runAllPasses - Run a bunch of passes on the specified module, efficiently.
- static bool runAllPasses(Module *M, vector<Pass*> &Passes) {
+ static bool runAllPasses(Module *M, std::vector<Pass*> &Passes) {
bool MadeChanges = false;
// Run all of the pass initializers
for (unsigned i = 0; i < Passes.size(); ++i)
// runAllPassesAndFree - Run a bunch of passes on the specified module,
// efficiently. When done, delete all of the passes.
//
- static bool runAllPassesAndFree(Module *M, vector<Pass*> &Passes) {
+ static bool runAllPassesAndFree(Module *M, std::vector<Pass*> &Passes) {
// First run all of the passes
bool MadeChanges = runAllPasses(M, Passes);
const Module *TheModule;
bool IgnoreNamedNodes; // Shall we not count named nodes?
- typedef vector<const Value*> TypePlane;
- vector<TypePlane> Table;
- map<const Value *, unsigned> NodeMap;
+ typedef std::vector<const Value*> TypePlane;
+ std::vector<TypePlane> Table;
+ std::map<const Value *, unsigned> NodeMap;
// ModuleLevel - Used to keep track of which values belong to the module,
// and which values belong to the currently incorporated method.
//
- vector<unsigned> ModuleLevel;
+ std::vector<unsigned> ModuleLevel;
public:
SlotCalculator(const Module *M, bool IgnoreNamed);
//===--------------------------------------------------------------------===//
// Basic ID <-> Name map functionality
- static AnnotationID getID (const string &Name); // Name -> ID
- static const string &getName(AnnotationID ID); // ID -> Name
+ static AnnotationID getID(const std::string &Name); // Name -> ID
+ static const std::string &getName(AnnotationID ID); // ID -> Name
// getID - Name -> ID + registration of a factory function for demand driven
// annotation support.
- static AnnotationID getID (const string &Name, Factory Fact, void *Data=0);
+ static AnnotationID getID(const std::string &Name, Factory Fact,
+ void *Data = 0);
//===--------------------------------------------------------------------===//
// Annotation creation on demand support...
// an argument. Should return true if there was an error processing the
// argument and the program should exit.
//
- virtual bool handleOccurance(const char *ArgName, const string &Arg) = 0;
+ virtual bool handleOccurance(const char *ArgName, const std::string &Arg) = 0;
virtual enum NumOccurances getNumOccurancesFlagDefault() const {
return Optional;
// addOccurance - Wrapper around handleOccurance that enforces Flags
//
- bool addOccurance(const char *ArgName, const string &Value);
+ bool addOccurance(const char *ArgName, const std::string &Value);
// Prints option name followed by message. Always returns true.
- bool error(string Message, const char *ArgName = 0);
+ bool error(std::string Message, const char *ArgName = 0);
public:
inline int getNumOccurances() const { return NumOccurances; }
//
class Alias : public Option {
Option &AliasFor;
- virtual bool handleOccurance(const char *ArgName, const string &Arg) {
+ virtual bool handleOccurance(const char *ArgName, const std::string &Arg) {
return AliasFor.handleOccurance(AliasFor.ArgStr, Arg);
}
virtual enum OptionHidden getOptionHiddenFlagDefault() const {return Hidden;}
//
class Flag : public Option {
bool Value;
- virtual bool handleOccurance(const char *ArgName, const string &Arg);
+ virtual bool handleOccurance(const char *ArgName, const std::string &Arg);
public:
inline Flag(const char *ArgStr, const char *Message, int Flags = 0,
bool DefaultVal = 0) : Option(ArgStr, Message, Flags),
//
class Int : public Option {
int Value;
- virtual bool handleOccurance(const char *ArgName, const string &Arg);
+ virtual bool handleOccurance(const char *ArgName, const std::string &Arg);
virtual enum ValueExpected getValueExpectedFlagDefault() const {
return ValueRequired;
}
//===----------------------------------------------------------------------===//
// String valued command line option
//
-class String : public Option, public string {
- virtual bool handleOccurance(const char *ArgName, const string &Arg);
+class String : public Option, public std::string {
+ virtual bool handleOccurance(const char *ArgName, const std::string &Arg);
virtual enum ValueExpected getValueExpectedFlagDefault() const {
return ValueRequired;
}
public:
inline String(const char *ArgStr, const char *Help, int Flags = 0,
const char *DefaultVal = "")
- : Option(ArgStr, Help, Flags), string(DefaultVal) {}
+ : Option(ArgStr, Help, Flags), std::string(DefaultVal) {}
- inline const string &operator=(const string &Val) {
- return string::operator=(Val);
+ inline const std::string &operator=(const std::string &Val) {
+ return std::string::operator=(Val);
}
};
//===----------------------------------------------------------------------===//
// String list command line option
//
-class StringList : public Option, public vector<string> {
+class StringList : public Option, public std::vector<std::string> {
virtual enum NumOccurances getNumOccurancesFlagDefault() const {
return ZeroOrMore;
virtual enum ValueExpected getValueExpectedFlagDefault() const {
return ValueRequired;
}
- virtual bool handleOccurance(const char *ArgName, const string &Arg);
+ virtual bool handleOccurance(const char *ArgName, const std::string &Arg);
public:
inline StringList(const char *ArgStr, const char *Help, int Flags = 0)
// Use a vector instead of a map, because the lists should be short,
// the overhead is less, and most importantly, it keeps them in the order
// inserted so we can print our option out nicely.
- vector<pair<const char *, pair<int, const char *> > > ValueMap;
+ std::vector<std::pair<const char *, std::pair<int, const char *> > > ValueMap;
inline EnumBase(const char *ArgStr, const char *Help, int Flags)
: Option(ArgStr, Help, Flags) {}
inline EnumValueBase(int Flags) : EnumBase(Flags) {}
// handleOccurance - Set Value to the enum value specified by Arg
- virtual bool handleOccurance(const char *ArgName, const string &Arg);
+ virtual bool handleOccurance(const char *ArgName, const std::string &Arg);
// Return the width of the option tag for printing...
virtual unsigned getOptionWidth() const;
return ValueDisallowed;
}
protected:
- virtual bool handleOccurance(const char *ArgName, const string &Arg);
+ virtual bool handleOccurance(const char *ArgName, const std::string &Arg);
inline EnumFlagsBase(int Flags) : EnumValueBase(Flags) {}
// Return the width of the option tag for printing...
return ValueDisallowed;
}
protected:
- vector<int> Values; // The options specified so far.
+ std::vector<int> Values; // The options specified so far.
inline EnumListBase(int Flags)
: EnumBase(Flags) {}
- virtual bool handleOccurance(const char *ArgName, const string &Arg);
+ virtual bool handleOccurance(const char *ArgName, const std::string &Arg);
// Return the width of the option tag for printing...
virtual unsigned getOptionWidth() const;
// error occurs, true is returned and ErrorMsg (if not null) is set to indicate
// the problem.
//
-bool LinkModules(Module *Dest, const Module *Src, string *ErrorMsg = 0);
+bool LinkModules(Module *Dest, const Module *Src, std::string *ErrorMsg = 0);
#endif
// MangleTypeName - Implement a consistent name-mangling scheme for
// a given type.
//
-string MangleTypeName(const Type *type);
+std::string MangleTypeName(const Type *type);
// MangleName - implement a consistent name-mangling scheme for all
// externally visible (i.e., global) objects.
//
// privateName should be unique within the module.
//
-string MangleName(const string &privateName, const Value *V);
+std::string MangleName(const std::string &privateName, const Value *V);
#endif
class Type;
class SymbolTable : public AbstractTypeUser,
- public map<const Type *, map<const string, Value *> > {
+ public std::map<const Type *,
+ std::map<const std::string, Value *> > {
public:
- typedef map<const string, Value *> VarMap;
- typedef map<const Type *, VarMap> super;
+ typedef std::map<const std::string, Value *> VarMap;
+ typedef std::map<const Type *, VarMap> super;
private:
SymbolTable *ParentSymTab;
SymbolTable *getParentSymTab() { return ParentSymTab; }
// lookup - Returns null on failure...
- Value *lookup(const Type *Ty, const string &name);
+ Value *lookup(const Type *Ty, const std::string &name);
// insert - Add named definition to the symbol table...
inline void insert(Value *N) {
// name... There can be a many to one mapping between names and
// (constant/type)s.
//
- inline void insert(const string &Name, Value *V) {
+ inline void insert(const std::string &Name, Value *V) {
assert((isa<Type>(V) || isa<Constant>(V)) &&
"Can only insert types and constants here!");
insertEntry(Name, V->getType(), V);
// it (or derived from it) that does not already occur in the symbol table for
// the specified type.
//
- string getUniqueName(const Type *Ty, const string &BaseName);
+ std::string getUniqueName(const Type *Ty, const std::string &BaseName);
inline unsigned type_size(const Type *TypeID) const {
return find(TypeID)->second.size();
// insertEntry - Insert a value into the symbol table with the specified
// name...
//
- void insertEntry(const string &Name, const Type *Ty, Value *V);
+ void insertEntry(const std::string &Name, const Type *Ty, Value *V);
// removeEntry - Remove a value from the symbol table...
//
struct MachineInstrDescriptor {
- string opCodeString; // Assembly language mnemonic for the opcode.
- int numOperands; // Number of args; -1 if variable #args
- int resultPos; // Position of the result; -1 if no result
+ std::string opCodeString; // Assembly language mnemonic for the opcode.
+ int numOperands; // Number of args; -1 if variable #args
+ int resultPos; // Position of the result; -1 if no result
unsigned int maxImmedConst; // Largest +ve constant in IMMMED field or 0.
- bool immedIsSignExtended; // Is IMMED field sign-extended? If so,
+ bool immedIsSignExtended; // Is IMMED field sign-extended? If so,
// smallest -ve value is -(maxImmedConst+1).
unsigned int numDelaySlots; // Number of delay slots after instruction
unsigned int latency; // Latency in machine cycles
//
virtual void CreateCodeToLoadConst(Value* val,
Instruction* dest,
- vector<MachineInstr*>& minstrVec,
- vector<TmpInstruction*>& temps) const =0;
+ std::vector<MachineInstr*>& minstrVec,
+ std::vector<TmpInstruction*> &) const = 0;
// Create an instruction sequence to copy an integer value `val'
// to a floating point value `dest' by copying to memory and back.
virtual void CreateCodeToCopyIntToFloat(Method* method,
Value* val,
Instruction* dest,
- vector<MachineInstr*>& minstrVec,
- vector<TmpInstruction*>& tempVec,
+ std::vector<MachineInstr*>& minstVec,
+ std::vector<TmpInstruction*>& tmpVec,
TargetMachine& target) const = 0;
// Similarly, create an instruction sequence to copy an FP value
virtual void CreateCodeToCopyFloatToInt(Method* method,
Value* val,
Instruction* dest,
- vector<MachineInstr*>& minstrVec,
- vector<TmpInstruction*>& tempVec,
+ std::vector<MachineInstr*>& minstVec,
+ std::vector<TmpInstruction*>& tmpVec,
TargetMachine& target) const = 0;
CreateCopyInstructionsByType(const TargetMachine& target,
Value* src,
Instruction* dest,
- vector<MachineInstr*>& minstrVec) const = 0;
-
-
-
+ std::vector<MachineInstr*>& minstrVec) const = 0;
};
#endif
protected:
unsigned int numLevels;
- vector<unsigned short> cacheLineSizes;
- vector<unsigned int> cacheSizes;
- vector<unsigned short> cacheAssoc;
+ std::vector<unsigned short> cacheLineSizes;
+ std::vector<unsigned int> cacheSizes;
+ std::vector<unsigned short> cacheAssoc;
public:
/*ctor*/ MachineCacheInfo (const TargetMachine& tgt);
static Annotation *TypeAnFactory(AnnotationID, const Annotable *, void *);
public:
- TargetData(const string &TargetName, unsigned char PtrSize = 8,
+ TargetData(const std::string &TargetName, unsigned char PtrSize = 8,
unsigned char PtrAl = 8, unsigned char DoubleAl = 8,
unsigned char FloatAl = 4, unsigned char LongAl = 8,
unsigned char IntAl = 4, unsigned char ShortAl = 2,
// stores that include the implicit form of getelementptr.
//
unsigned getIndexedOffset(const Type *Ty,
- const vector<Value*> &Indices) const;
+ const std::vector<Value*> &Indices) const;
inline const StructLayout *getStructLayout(const StructType *Ty) const {
return (const StructLayout*)((const Type*)Ty)->getOrCreateAnnotation(AID);
// TargetData structure.
//
struct StructLayout : public Annotation {
- vector<unsigned> MemberOffsets;
+ std::vector<unsigned> MemberOffsets;
unsigned StructSize;
unsigned StructAlignment;
private:
struct MachineInstrDescriptor {
- string opCodeString; // Assembly language mnemonic for the opcode.
- int numOperands; // Number of args; -1 if variable #args
- int resultPos; // Position of the result; -1 if no result
+ std::string opCodeString; // Assembly language mnemonic for the opcode.
+ int numOperands; // Number of args; -1 if variable #args
+ int resultPos; // Position of the result; -1 if no result
unsigned int maxImmedConst; // Largest +ve constant in IMMMED field or 0.
- bool immedIsSignExtended; // Is IMMED field sign-extended? If so,
+ bool immedIsSignExtended; // Is IMMED field sign-extended? If so,
// smallest -ve value is -(maxImmedConst+1).
unsigned int numDelaySlots; // Number of delay slots after instruction
unsigned int latency; // Latency in machine cycles
//
virtual void CreateCodeToLoadConst(Value* val,
Instruction* dest,
- vector<MachineInstr*>& minstrVec,
- vector<TmpInstruction*>& temps) const =0;
+ std::vector<MachineInstr*>& minstrVec,
+ std::vector<TmpInstruction*> &) const = 0;
// Create an instruction sequence to copy an integer value `val'
// to a floating point value `dest' by copying to memory and back.
virtual void CreateCodeToCopyIntToFloat(Method* method,
Value* val,
Instruction* dest,
- vector<MachineInstr*>& minstrVec,
- vector<TmpInstruction*>& tempVec,
+ std::vector<MachineInstr*>& minstVec,
+ std::vector<TmpInstruction*>& tmpVec,
TargetMachine& target) const = 0;
// Similarly, create an instruction sequence to copy an FP value
virtual void CreateCodeToCopyFloatToInt(Method* method,
Value* val,
Instruction* dest,
- vector<MachineInstr*>& minstrVec,
- vector<TmpInstruction*>& tempVec,
+ std::vector<MachineInstr*>& minstVec,
+ std::vector<TmpInstruction*>& tmpVec,
TargetMachine& target) const = 0;
CreateCopyInstructionsByType(const TargetMachine& target,
Value* src,
Instruction* dest,
- vector<MachineInstr*>& minstrVec) const = 0;
-
-
-
+ std::vector<MachineInstr*>& minstrVec) const = 0;
};
#endif
class TargetMachine : public NonCopyableV {
public:
- const string TargetName;
+ const std::string TargetName;
const TargetData DataLayout; // Calculates type size & alignment
int optSizeForSubWordData;
int minMemOpWordSize;
int maxAtomicMemOpWordSize;
protected:
- TargetMachine(const string &targetname, // Can only create subclasses...
+ TargetMachine(const std::string &targetname, // Can only create subclasses...
unsigned char PtrSize = 8, unsigned char PtrAl = 8,
unsigned char DoubleAl = 8, unsigned char FloatAl = 4,
unsigned char LongAl = 8, unsigned char IntAl = 4,
// method. The specified method must have been compiled before this may be
// used.
//
- virtual void emitAssembly(const Module *M, ostream &OutStr) const = 0;
+ virtual void emitAssembly(const Module *M, std::ostream &OutStr) const = 0;
};
#endif
#define LLVM_TARGET_MACHINEREGINFO_H
#include "Support/NonCopyable.h"
-#include <hash_map>
+#include <ext/hash_map>
#include <string>
class TargetMachine;
-typedef hash_map<const MachineInstr *, AddedInstrns *> AddedInstrMapType;
+typedef std::hash_map<const MachineInstr *, AddedInstrns *> AddedInstrMapType;
// A vector of all machine register classes
//
-typedef vector<const MachineRegClassInfo *> MachineRegClassArrayType;
+typedef std::vector<const MachineRegClassInfo *> MachineRegClassArrayType;
class MachineRegInfo : public NonCopyableV {
LiveRangeInfo & LRI) const = 0;
virtual void suggestRegs4CallArgs(const MachineInstr *const CallI,
- LiveRangeInfo& LRI, vector<RegClass *> RCL) const = 0;
+ LiveRangeInfo& LRI, std::vector<RegClass *> RCL) const = 0;
virtual void suggestReg4RetValue(const MachineInstr *const RetI,
LiveRangeInfo& LRI) const = 0;
//
virtual int getUnifiedRegNum(int RegClassID, int reg) const = 0;
- virtual const string getUnifiedRegName(int UnifiedRegNum) const = 0;
+ virtual const std::string getUnifiedRegName(int UnifiedRegNum) const = 0;
// Gives the type of a register based on the type of the LR
#define LLVM_TARGET_MACHINESCHEDINFO_H
#include "llvm/Target/MachineInstrInfo.h"
-#include <hash_map>
+#include <ext/hash_map>
typedef long long cycles_t;
-const cycles_t HUGE_LATENCY = ~((unsigned long long) 1 << sizeof(cycles_t)-1);
+const cycles_t HUGE_LATENCY = ~((unsigned long long) 1 << sizeof(cycles_t)-2);
const cycles_t INVALID_LATENCY = -HUGE_LATENCY;
static const unsigned MAX_OPCODE_SIZE = 16;
OpCodePair(); // disable for now
};
-
+namespace std {
template <> struct hash<OpCodePair> {
size_t operator()(const OpCodePair& pair) const {
return hash<long>()(pair.val);
}
};
-
+}
//---------------------------------------------------------------------------
// class MachineResource
class MachineResource {
public:
- const string rname;
+ const std::string rname;
resourceId_t rid;
- /*ctor*/ MachineResource(const string& resourceName)
+ /*ctor*/ MachineResource(const std::string& resourceName)
: rname(resourceName), rid(nextId++) {}
private:
public:
int maxNumUsers; // MAXINT if no restriction
- /*ctor*/ CPUResource(const string& rname, int maxUsers)
+ /*ctor*/ CPUResource(const std::string& rname, int maxUsers)
: MachineResource(rname), maxNumUsers(maxUsers) {}
};
cycles_t numBubbles;
// Feasible slots to use for this instruction.
- vector<bool> feasibleSlots;
+ std::vector<bool> feasibleSlots;
// Resource usages for this instruction, with one resource vector per cycle.
cycles_t numCycles;
- vector<vector<resourceId_t> > resourcesByCycle;
+ std::vector<std::vector<resourceId_t> > resourcesByCycle;
private:
// Conveniences for initializing this structure
// resize the resources vector if more cycles are specified
unsigned maxCycles = this->numCycles;
- maxCycles = max(maxCycles, delta.startCycle + abs(NC) - 1);
+ maxCycles = std::max(maxCycles, delta.startCycle + abs(NC) - 1);
if (maxCycles > this->numCycles)
{
this->resourcesByCycle.resize(maxCycles);
{
// Look for the resource backwards so we remove the last entry
// for that resource in each cycle.
- vector<resourceId_t>& rvec = this->resourcesByCycle[c];
+ std::vector<resourceId_t>& rvec = this->resourcesByCycle[c];
int r;
for (r = (int) rvec.size(); r >= 0; r--)
if (rvec[r] == delta.resourceId)
inline int getMinIssueGap (MachineOpCode fromOp,
MachineOpCode toOp) const {
- hash_map<OpCodePair,int>::const_iterator
+ std::hash_map<OpCodePair,int>::const_iterator
I = issueGaps.find(OpCodePair(fromOp, toOp));
return (I == issueGaps.end())? 0 : (*I).second;
}
- inline const vector<MachineOpCode>*
+ inline const std::vector<MachineOpCode>*
getConflictList(MachineOpCode opCode) const {
- hash_map<MachineOpCode,vector<MachineOpCode> >::const_iterator
+ std::hash_map<MachineOpCode, std::vector<MachineOpCode> >::const_iterator
I = conflictLists.find(opCode);
return (I == conflictLists.end())? NULL : & (*I).second;
}
virtual void initializeResources ();
private:
- void computeInstrResources(const vector<InstrRUsage>& instrRUForClasses);
- void computeIssueGaps(const vector<InstrRUsage>& instrRUForClasses);
+ void computeInstrResources(const std::vector<InstrRUsage>& instrRUForClasses);
+ void computeIssueGaps(const std::vector<InstrRUsage>& instrRUForClasses);
protected:
int numSchedClasses;
const MachineInstrInfo* mii;
- const InstrClassRUsage* classRUsages; // raw array by sclass
- const InstrRUsageDelta* usageDeltas; // raw array [1:numUsageDeltas]
- const InstrIssueDelta* issueDeltas; // raw array [1:numIssueDeltas]
+ const InstrClassRUsage* classRUsages; // raw array by sclass
+ const InstrRUsageDelta* usageDeltas; // raw array [1:numUsageDeltas]
+ const InstrIssueDelta* issueDeltas; // raw array [1:numIssueDeltas]
unsigned int numUsageDeltas;
unsigned int numIssueDeltas;
- vector<InstrRUsage> instrRUsages; // indexed by opcode
- hash_map<OpCodePair,int> issueGaps; // indexed by opcode pair
- hash_map<MachineOpCode,vector<MachineOpCode> >
- conflictLists; // indexed by opcode
+ std::vector<InstrRUsage> instrRUsages; // indexed by opcode
+ std::hash_map<OpCodePair,int> issueGaps; // indexed by opcode pair
+ std::hash_map<MachineOpCode, std::vector<MachineOpCode> >
+ conflictLists; // indexed by opcode
};
#endif
class ConstantMerge : public Pass {
protected:
- map<Constant*, GlobalVariable*> Constants;
+ std::map<Constant*, GlobalVariable*> Constants;
unsigned LastConstantSeen;
public:
inline ConstantMerge() : LastConstantSeen(0) {}
// incoming slot [or negative if the specified incoming slot should be
// removed].
//
- typedef pair<const StructType*, vector<int> > TransformType;
+ typedef std::pair<const StructType*, std::vector<int> > TransformType;
// Transforms to do for each structure type...
- map<const StructType*, TransformType> Transforms;
+ std::map<const StructType*, TransformType> Transforms;
// Mapping of old type to new types...
- map<const Type *, PATypeHolder<Type> > TypeMap;
+ std::map<const Type *, PATypeHolder<Type> > TypeMap;
// Mapping from global value of old type, to a global value of the new type...
- map<const GlobalValue*, GlobalValue*> GlobalMap;
+ std::map<const GlobalValue*, GlobalValue*> GlobalMap;
// Mapping from intra method value to intra method value
- map<const Value*, Value*> LocalValueMap;
+ std::map<const Value*, Value*> LocalValueMap;
public:
// Ctor - Take a map that specifies what transformation to do for each field
// the destination structure the field should end up in. A negative value
// indicates that the field should be deleted entirely.
//
- typedef map<const StructType*, vector<int> > TransformsType;
+ typedef std::map<const StructType*, std::vector<int> > TransformsType;
MutateStructTypes(const TransformsType &Transforms);
// AdjustIndices - Convert the indexes specifed by Idx to the new changed form
// using the specified OldTy as the base type being indexed into.
//
- void AdjustIndices(const CompositeType *OldTy, vector<Value*> &Idx,
+ void AdjustIndices(const CompositeType *OldTy, std::vector<Value*> &Idx,
unsigned idx = 0);
};
// error occurs, true is returned and ErrorMsg (if not null) is set to indicate
// the problem.
//
-bool LinkModules(Module *Dest, const Module *Src, string *ErrorMsg = 0);
+bool LinkModules(Module *Dest, const Module *Src, std::string *ErrorMsg = 0);
#endif
private:
PrimitiveID ID; // The current base type of this type...
unsigned UID; // The unique ID number for this class
- string Desc; // The printed name of the string...
+ std::string Desc; // The printed name of the string...
bool Abstract; // True if type contains an OpaqueType
bool Recursive; // True if the type is recursive
protected:
// ctor is protected, so only subclasses can create Type objects...
- Type(const string &Name, PrimitiveID id);
+ Type(const std::string &Name, PrimitiveID id);
virtual ~Type() {}
// When types are refined, they update their description to be more concrete.
//
- inline void setDescription(const string &D) { Desc = D; }
+ inline void setDescription(const std::string &D) { Desc = D; }
// setName - Associate the name with this type in the symbol table, but don't
// set the local name to be equal specified name.
//
- virtual void setName(const string &Name, SymbolTable *ST = 0);
+ virtual void setName(const std::string &Name, SymbolTable *ST = 0);
// Types can become nonabstract later, if they are refined.
//
inline unsigned getUniqueID() const { return UID; }
// getDescription - Return the string representation of the type...
- inline const string &getDescription() const { return Desc; }
+ inline const std::string &getDescription() const { return Desc; }
// isSigned - Return whether a numeric type is signed.
virtual bool isSigned() const { return 0; }
class User : public Value {
User(const User &); // Do not implement
protected:
- vector<Use> Operands;
+ std::vector<Use> Operands;
public:
- User(const Type *Ty, ValueTy vty, const string &name = "");
+ User(const Type *Ty, ValueTy vty, const std::string &name = "");
virtual ~User() { dropAllReferences(); }
inline Value *getOperand(unsigned i) {
// ---------------------------------------------------------------------------
// Operand Iterator interface...
//
- typedef vector<Use>::iterator op_iterator;
- typedef vector<Use>::const_iterator const_op_iterator;
+ typedef std::vector<Use>::iterator op_iterator;
+ typedef std::vector<Use>::const_iterator const_op_iterator;
inline op_iterator op_begin() { return Operands.begin(); }
inline const_op_iterator op_begin() const { return Operands.begin(); }
};
private:
- vector<User *> Uses;
- string Name;
+ std::vector<User *> Uses;
+ std::string Name;
PATypeHandle<Type> Ty;
ValueTy VTy;
protected:
inline void setType(const Type *ty) { Ty = ty; }
public:
- Value(const Type *Ty, ValueTy vty, const string &name = "");
+ Value(const Type *Ty, ValueTy vty, const std::string &name = "");
virtual ~Value();
// Support for debugging
inline const Type *getType() const { return Ty; }
// All values can potentially be named...
- inline bool hasName() const { return Name != ""; }
- inline const string &getName() const { return Name; }
+ inline bool hasName() const { return Name != ""; }
+ inline const std::string &getName() const { return Name; }
- virtual void setName(const string &name, SymbolTable * = 0) {
+ virtual void setName(const std::string &name, SymbolTable * = 0) {
Name = name;
}
//----------------------------------------------------------------------
// Methods for handling the vector of uses of this Value.
//
- typedef vector<User*>::iterator use_iterator;
- typedef vector<User*>::const_iterator use_const_iterator;
+ typedef std::vector<User*>::iterator use_iterator;
+ typedef std::vector<User*>::const_iterator use_const_iterator;
inline unsigned use_size() const { return Uses.size(); }
inline bool use_empty() const { return Uses.empty(); }
//
template<class ValueSubclass, class ItemParentType, class SymTabType>
class ValueHolder {
- vector<ValueSubclass*> ValueList;
+ std::vector<ValueSubclass*> ValueList;
ItemParentType *ItemParent;
SymTabType *Parent;
// sub-Definition iterator code
//===--------------------------------------------------------------------===//
//
- typedef vector<ValueSubclass*>::iterator iterator;
- typedef vector<ValueSubclass*>::const_iterator const_iterator;
- typedef reverse_iterator<const_iterator> const_reverse_iterator;
- typedef reverse_iterator<iterator> reverse_iterator;
+ typedef std::vector<ValueSubclass*>::iterator iterator;
+ typedef std::vector<ValueSubclass*>::const_iterator const_iterator;
+ typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
+ typedef std::reverse_iterator<iterator> reverse_iterator;
inline iterator begin() { return ValueList.begin(); }
inline const_iterator begin() const { return ValueList.begin(); }
class AllocationInst : public Instruction {
public:
AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
- const string &Name = "")
+ const std::string &Name = "")
: Instruction(Ty, iTy, Name) {
assert(Ty->isPointerType() && "Can't allocate a non pointer type!");
class MallocInst : public AllocationInst {
public:
- MallocInst(const Type *Ty, Value *ArraySize = 0, const string &Name = "")
+ MallocInst(const Type *Ty, Value *ArraySize = 0, const std::string &Name = "")
: AllocationInst(Ty, ArraySize, Malloc, Name) {}
virtual Instruction *clone() const {
class AllocaInst : public AllocationInst {
public:
- AllocaInst(const Type *Ty, Value *ArraySize = 0, const string &Name = "")
+ AllocaInst(const Type *Ty, Value *ArraySize = 0, const std::string &Name = "")
: AllocationInst(Ty, ArraySize, Alloca, Name) {}
virtual Instruction *clone() const {
class MemAccessInst : public Instruction {
protected:
inline MemAccessInst(const Type *Ty, unsigned Opcode,
- const string &Nam = "")
+ const std::string &Nam = "")
: Instruction(Ty, Opcode, Nam) {}
public:
// getIndexedType - Returns the type of the element that would be loaded with
// pointer type.
//
static const Type *getIndexedType(const Type *Ptr,
- const vector<Value*> &Indices,
+ const std::vector<Value*> &Indices,
bool AllowStructLeaf = false);
inline op_iterator idx_begin() {
inline const_op_iterator idx_end() const { return op_end(); }
- vector<Value*> copyIndices() const {
- return vector<Value*>(idx_begin(), idx_end());
+ std::vector<Value*> copyIndices() const {
+ return std::vector<Value*>(idx_begin(), idx_end());
}
Value *getPointerOperand() {
Operands.push_back(Use(LI.Operands[i], this));
}
public:
- LoadInst(Value *Ptr, const vector<Value*> &Idx, const string &Name = "");
- LoadInst(Value *Ptr, const string &Name = "");
+ LoadInst(Value *Ptr, const std::vector<Value*> &Ix, const std::string & = "");
+ LoadInst(Value *Ptr, const std::string &Name = "");
virtual Instruction *clone() const { return new LoadInst(*this); }
virtual const char *getOpcodeName() const { return "load"; }
Operands.push_back(Use(SI.Operands[i], this));
}
public:
- StoreInst(Value *Val, Value *Ptr, const vector<Value*> &Idx,
- const string &Name = "");
- StoreInst(Value *Val, Value *Ptr, const string &Name = "");
+ StoreInst(Value *Val, Value *Ptr, const std::vector<Value*> &Idx,
+ const std::string &Name = "");
+ StoreInst(Value *Val, Value *Ptr, const std::string &Name = "");
virtual Instruction *clone() const { return new StoreInst(*this); }
virtual const char *getOpcodeName() const { return "store"; }
Operands.push_back(Use(EPI.Operands[i], this));
}
public:
- GetElementPtrInst(Value *Ptr, const vector<Value*> &Idx,
- const string &Name = "");
+ GetElementPtrInst(Value *Ptr, const std::vector<Value*> &Idx,
+ const std::string &Name = "");
virtual Instruction *clone() const { return new GetElementPtrInst(*this); }
virtual const char *getOpcodeName() const { return "getelementptr"; }
virtual unsigned getFirstIndexOperandNumber() const { return 1; }
//
class GenericUnaryInst : public UnaryOperator {
public:
- GenericUnaryInst(UnaryOps Opcode, Value *S1, const string &Name = "")
+ GenericUnaryInst(UnaryOps Opcode, Value *S1, const std::string &Name = "")
: UnaryOperator(S1, Opcode, Name) {
}
class GenericBinaryInst : public BinaryOperator {
public:
GenericBinaryInst(BinaryOps Opcode, Value *S1, Value *S2,
- const string &Name = "")
+ const std::string &Name = "")
: BinaryOperator(Opcode, S1, S2, Name) {
}
BinaryOps OpType;
public:
SetCondInst(BinaryOps opType, Value *S1, Value *S2,
- const string &Name = "");
+ const std::string &Name = "");
virtual const char *getOpcodeName() const;
};
Operands.push_back(Use(CI.Operands[0], this));
}
public:
- CastInst(Value *S, const Type *Ty, const string &Name = "")
+ CastInst(Value *S, const Type *Ty, const std::string &Name = "")
: Instruction(Ty, Cast, Name) {
Operands.reserve(1);
Operands.push_back(Use(S, this));
inline void setParent(Method *parent) { Parent = parent; }
public:
- MethodArgument(const Type *Ty, const string &Name = "")
+ MethodArgument(const Type *Ty, const std::string &Name = "")
: Value(Ty, Value::MethodArgumentVal, Name) {
Parent = 0;
}
// Specialize setName to handle symbol table majik...
- virtual void setName(const string &name, SymbolTable *ST = 0);
+ virtual void setName(const std::string &name, SymbolTable *ST = 0);
inline const Method *getParent() const { return Parent; }
inline Method *getParent() { return Parent; }
class CallInst : public Instruction {
CallInst(const CallInst &CI);
public:
- CallInst(Value *Meth, const vector<Value*> ¶ms, const string &Name = "");
+ CallInst(Value *M, const std::vector<Value*> &Par, const std::string & = "");
virtual const char *getOpcodeName() const { return "call"; }
Operands.push_back(Use(SI.Operands[1], this));
}
public:
- ShiftInst(OtherOps Opcode, Value *S, Value *SA, const string &Name = "")
+ ShiftInst(OtherOps Opcode, Value *S, Value *SA, const std::string &Name = "")
: Instruction(S->getType(), Opcode, Name) {
assert((Opcode == Shl || Opcode == Shr) && "ShiftInst Opcode invalid!");
Operands.reserve(2);
class PHINode : public Instruction {
PHINode(const PHINode &PN);
public:
- PHINode(const Type *Ty, const string &Name = "");
+ PHINode(const Type *Ty, const std::string &Name = "");
virtual Instruction *clone() const { return new PHINode(*this); }
virtual const char *getOpcodeName() const { return "phi"; }
InvokeInst(const InvokeInst &BI);
public:
InvokeInst(Value *Meth, BasicBlock *IfNormal, BasicBlock *IfException,
- const vector<Value*> &Params, const string &Name = "");
+ const std::vector<Value*> &Params, const std::string &Name = "");
virtual Instruction *clone() const { return new InvokeInst(*this); }
#include "llvm/Optimizations/ConstantHandling.h"
#include "llvm/Method.h"
#include "llvm/BasicBlock.h"
+#include <iostream>
using namespace opt; // Get all the constant handling stuff
using namespace analysis;
static ExprType handleAddition(ExprType Left, ExprType Right, Value *V) {
const Type *Ty = V->getType();
if (Left.ExprTy > Right.ExprTy)
- swap(Left, Right); // Make left be simpler than right
+ std::swap(Left, Right); // Make left be simpler than right
switch (Left.ExprTy) {
case ExprType::Constant:
case Value::TypeVal: case Value::BasicBlockVal:
case Value::MethodVal: case Value::ModuleVal: default:
//assert(0 && "Unexpected expression type to classify!");
- cerr << "Bizarre thing to expr classify: " << Expr << endl;
+ std::cerr << "Bizarre thing to expr classify: " << Expr << "\n";
return Expr;
case Value::GlobalVariableVal: // Global Variable & Method argument:
case Value::MethodArgumentVal: // nothing known, return variable itself
ExprType Left (ClassifyExpression(I->getOperand(0)));
ExprType Right(ClassifyExpression(I->getOperand(1)));
if (Left.ExprTy > Right.ExprTy)
- swap(Left, Right); // Make left be simpler than right
+ std::swap(Left, Right); // Make left be simpler than right
if (Left.ExprTy != ExprType::Constant) // RHS must be > constant
return I; // Quadratic eqn! :(
assert(M->getParent() == Mod && "Method not in current module!");
CallGraphNode *New = new CallGraphNode(M);
- MethodMap.insert(pair<const Method*, CallGraphNode*>(M, New));
+ MethodMap.insert(std::make_pair(M, New));
return New;
}
}
-void cfg::WriteToOutput(const CallGraphNode *CGN, ostream &o) {
+void cfg::WriteToOutput(const CallGraphNode *CGN, std::ostream &o) {
if (CGN->getMethod())
o << "Call graph node for method: '" << CGN->getMethod()->getName() <<"'\n";
else
for (unsigned i = 0; i < CGN->size(); ++i)
o << " Calls method '" << (*CGN)[i]->getMethod()->getName() << "'\n";
- o << endl;
+ o << "\n";
}
-void cfg::WriteToOutput(const CallGraph &CG, ostream &o) {
+void cfg::WriteToOutput(const CallGraph &CG, std::ostream &o) {
WriteToOutput(CG.getRoot(), o);
for (CallGraph::const_iterator I = CG.begin(), E = CG.end(); I != E; ++I)
o << I->second;
UnsafeTypes.insert((PointerType*)ITy);
if (PrintFailures) {
- CachedWriter CW(M->getParent(), cerr);
+ CachedWriter CW(M->getParent(), std::cerr);
CW << "FindUnsafePointerTypes: Type '" << ITy
<< "' marked unsafe in '" << Meth->getName() << "' by:\n" << Inst;
}
// printResults - Loop over the results of the analysis, printing out unsafe
// types.
//
-void FindUnsafePointerTypes::printResults(const Module *M, ostream &o) {
+void FindUnsafePointerTypes::printResults(const Module *M, std::ostream &o) {
if (UnsafeTypes.empty()) {
o << "SafePointerAccess Analysis: No unsafe types found!\n";
return;
CW << "SafePointerAccess Analysis: Found these unsafe types:\n";
unsigned Counter = 1;
- for (set<PointerType*>::const_iterator I = getUnsafeTypes().begin(),
+ for (std::set<PointerType*>::const_iterator I = getUnsafeTypes().begin(),
E = getUnsafeTypes().end(); I != E; ++I, ++Counter) {
- CW << " #" << Counter << ". " << (Value*)*I << endl;
+ CW << " #" << Counter << ". " << (Value*)*I << "\n";
}
}
// passed in, then the types are printed symbolically if possible, using the
// symbol table from the module.
//
-void FindUsedTypes::printTypes(ostream &o, const Module *M = 0) const {
+void FindUsedTypes::printTypes(std::ostream &o, const Module *M = 0) const {
o << "Types in use by this module:\n";
if (M) {
CachedWriter CW(M, o);
- for (set<const Type *>::const_iterator I = UsedTypes.begin(),
+ for (std::set<const Type *>::const_iterator I = UsedTypes.begin(),
E = UsedTypes.end(); I != E; ++I)
- CW << " " << *I << endl;
+ CW << " " << *I << "\n";
} else
- for (set<const Type *>::const_iterator I = UsedTypes.begin(),
+ for (std::set<const Type *>::const_iterator I = UsedTypes.begin(),
E = UsedTypes.end(); I != E; ++I)
- o << " " << *I << endl;
+ o << " " << *I << "\n";
}
ExprType E2 = analysis::ClassifyExpression(V2);
if (E1.ExprTy > E2.ExprTy) // Make E1 be the simpler expression
- swap(E1, E2);
+ std::swap(E1, E2);
// E1 must be a constant incoming value, and E2 must be a linear expression
// with respect to the PHI node.
// Make sure that V1 is the incoming value, and V2 is from the backedge of
// the loop.
if (L->contains(Phi->getIncomingBlock(0))) // Wrong order. Swap now.
- swap(V1, V2);
+ std::swap(V1, V2);
Start = V1; // We know that Start has to be loop invariant...
Step = 0;
#include "Support/STLExtras.h"
using namespace cfg;
+using std::make_pair;
//===----------------------------------------------------------------------===//
// IntervalPartition Implementation
#include "llvm/Analysis/LiveVar/BBLiveVar.h"
#include "llvm/Analysis/LiveVar/MethodLiveVarInfo.h"
#include "llvm/CodeGen/MachineInstr.h"
+
+/// BROKEN: Should not include sparc stuff directly into here
#include "../../Target/Sparc/SparcInternals.h" // Only for PHI defn
+using std::cerr;
+using std::endl;
+using std::pair;
//-----------------------------------------------------------------------------
// Constructor
if( DEBUG_LV > 1) { // debug msg
cerr << " *Iterating over machine instr ";
MInst->dump();
- cerr << endl;
+ cerr << "\n";
}
// iterate over MI operands to find defs
if( DEBUG_LV > 1) { // debug msg of level 2
cerr << " - phi operand ";
printValue( ArgVal );
- cerr << " came from BB ";
+ cerr << " came from BB ";
printValue( PhiArgMap[ ArgVal ]);
- cerr<<endl;
+ cerr << "\n";
}
} // if( IsPhi )
InSetChanged = true;
if( DEBUG_LV > 1) {
- cerr << " +Def: "; printValue( Op ); cerr << endl;
+ cerr << " +Def: "; printValue( Op ); cerr << "\n";
}
}
// map that contains phi args->BB they came
// set by calcDefUseSets & used by setPropagate
- hash_map<const Value *, const BasicBlock *, hashFuncValue> PhiArgMap;
+ std::hash_map<const Value *, const BasicBlock *> PhiArgMap;
// method to propogate an InSet to OutSet of a predecessor
bool setPropagate( LiveVarSet *const OutSetOfPred,
#include "llvm/Analysis/LiveVar/MethodLiveVarInfo.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "Support/PostOrderIterator.h"
-
+#include <iostream>
+using std::cout;
+using std::endl;
//************************** Constructor/Destructor ***************************
-MethodLiveVarInfo::MethodLiveVarInfo(const Method *const M) : Meth(M),
- BB2BBLVMap()
-{
- assert(! M->isExternal() ); // cannot be a prototype decleration
+MethodLiveVarInfo::MethodLiveVarInfo(const Method *const M) : Meth(M) {
+ assert(!M->isExternal() && "Cannot be a prototype declaration");
HasAnalyzed = false; // still we haven't called analyze()
}
if( (*MI).first ) // delete all LiveVarSets in MInst2LVSetBI
delete (*MI).second;
}
-
-
}
#include "llvm/Analysis/LiveVar/ValueSet.h"
#include "llvm/ConstantVals.h"
-
+#include <iostream>
+using std::cerr;
+using std::endl;
+using std::pair;
+using std::hash_set;
void printValue( const Value *const v) // func to print a Value
{
-
if (v->hasName())
cerr << v << "(" << ((*v).getName()) << ") ";
else if (Constant *C = dyn_cast<Constant>(v))
//---------------- Method implementations --------------------------
-
-
-ValueSet:: ValueSet() : hash_set<const Value *, hashFuncValue> () { }
-
// for performing two set unions
bool ValueSet::setUnion( const ValueSet *const set1) {
const_iterator set1it;
pair<iterator, bool> result;
bool changed = false;
- for( set1it = set1->begin() ; set1it != set1->end(); set1it++) {
+ for( set1it = set1->begin() ; set1it != set1->end(); ++set1it) {
// for all all elements in set1
result = insert( *set1it ); // insert to this set
if( result.second == true) changed = true;
const ValueSet *const set2) {
const_iterator set1it, set2it;
- for( set1it = set1->begin() ; set1it != set1->end(); set1it++) {
+ for( set1it = set1->begin() ; set1it != set1->end(); ++set1it) {
// for all elements in set1
iterator set2it = set2->find( *set1it ); // find wether the elem is in set2
if( set2it == set2->end() ) // if the element is not in set2
// for performing set subtraction
void ValueSet::setSubtract( const ValueSet *const set1) {
const_iterator set1it;
- for( set1it = set1->begin() ; set1it != set1->end(); set1it++)
+ for( set1it = set1->begin() ; set1it != set1->end(); ++set1it)
// for all elements in set1
erase( *set1it ); // erase that element from this set
}
void ValueSet::printSet() const { // for printing a live variable set
- const_iterator it;
- for( it = begin() ; it != end(); it++)
- printValue( *it );
+ for_each(begin(), end(), printValue);
}
}
LoopDepthCalculator::LoopDepthCalculator(Method *M) {
- //map<const BasicBlock*, unsigned> LoopDepth;
-
cfg::IntervalPartition *IP = new cfg::IntervalPartition(M);
while (!IP->isDegeneratePartition()) {
for_each(IP->begin(), IP->end(),
//
cfg::IntervalPartition *NewIP = new cfg::IntervalPartition(*IP, true);
if (NewIP->size() == IP->size()) {
- cerr << "IRREDUCIBLE GRAPH FOUND!!!\n";
+ assert(0 && "IRREDUCIBLE GRAPH FOUND!!!\n");
// TODO: fix irreducible graph
return;
}
const DominatorSet &DS) {
if (BBMap.find(BB) != BBMap.end()) return 0; // Havn't processed this node?
- vector<const BasicBlock *> TodoStack;
+ std::vector<const BasicBlock *> TodoStack;
// Scan the predecessors of BB, checking to see if BB dominates any of
// them.
// loop can be found for them. Also check subsidary basic blocks to see if
// they start subloops of their own.
//
- for (vector<const BasicBlock*>::reverse_iterator I = L->Blocks.rbegin(),
+ for (std::vector<const BasicBlock*>::reverse_iterator I = L->Blocks.rbegin(),
E = L->Blocks.rend(); I != E; ++I) {
// Check to see if this block starts a new loop
}
if (BBMap.find(*I) == BBMap.end())
- BBMap.insert(make_pair(*I, L));
+ BBMap.insert(std::make_pair(*I, L));
}
return L;
#include "llvm/DerivedTypes.h"
#include "Support/STLExtras.h"
#include <map>
+#include <iostream>
+using std::set;
// processModule - Driver function to call all of my subclasses virtual methods.
//
break;
default:
- cerr << "ModuleAnalyzer::handleType, type unknown: '"
- << T->getName() << "'\n";
+ std::cerr << "ModuleAnalyzer::handleType, type unknown: '"
+ << T->getName() << "'\n";
break;
}
#include "Support/DepthFirstIterator.h"
#include "Support/STLExtras.h"
#include <algorithm>
+using std::set;
+
//===----------------------------------------------------------------------===//
// Helper Template
#include "llvm/Analysis/InductionVariable.h"
#include <iterator>
#include <algorithm>
+using std::ostream;
+using std::set;
+using std::vector;
+using std::string;
//===----------------------------------------------------------------------===//
// Interval Printing Routines
// Print out all of the basic blocks in the interval...
copy(I->Nodes.begin(), I->Nodes.end(),
- ostream_iterator<BasicBlock*>(o, "\n"));
+ std::ostream_iterator<BasicBlock*>(o, "\n"));
o << "Interval Predecessors:\n";
copy(I->Predecessors.begin(), I->Predecessors.end(),
- ostream_iterator<BasicBlock*>(o, "\n"));
+ std::ostream_iterator<BasicBlock*>(o, "\n"));
o << "Interval Successors:\n";
copy(I->Successors.begin(), I->Successors.end(),
- ostream_iterator<BasicBlock*>(o, "\n"));
+ std::ostream_iterator<BasicBlock*>(o, "\n"));
}
void cfg::WriteToOutput(const IntervalPartition &IP, ostream &o) {
- copy(IP.begin(), IP.end(), ostream_iterator<const Interval *>(o, "\n"));
+ copy(IP.begin(), IP.end(), std::ostream_iterator<const Interval *>(o, "\n"));
}
//===----------------------------------------------------------------------===//
ostream &operator<<(ostream &o, const set<const BasicBlock*> &BBs) {
- copy(BBs.begin(), BBs.end(), ostream_iterator<const BasicBlock*>(o, "\n"));
+ copy(BBs.begin(),BBs.end(), std::ostream_iterator<const BasicBlock*>(o,"\n"));
return o;
}
for (DominatorSet::const_iterator I = DS.begin(), E = DS.end(); I != E; ++I) {
o << "=============================--------------------------------\n"
<< "\nDominator Set For Basic Block\n" << I->first
- << "-------------------------------\n" << I->second << endl;
+ << "-------------------------------\n" << I->second << "\n";
}
}
I != E; ++I) {
o << "=============================--------------------------------\n"
<< "\nImmediate Dominator For Basic Block\n" << I->first
- << "is: \n" << I->second << endl;
+ << "is: \n" << I->second << "\n";
}
}
I != E; ++I) {
o << "=============================--------------------------------\n"
<< "\nDominance Frontier For Basic Block\n" << I->first
- << "is: \n" << I->second << endl;
+ << "is: \n" << I->second << "\n";
}
}
if (i) o << ",";
WriteAsOperand(o, (const Value*)L->getBlocks()[i]);
}
- o << endl;
+ o << "\n";
copy(L->getSubLoops().begin(), L->getSubLoops().end(),
- ostream_iterator<const Loop*>(o, "\n"));
+ std::ostream_iterator<const Loop*>(o, "\n"));
}
void cfg::WriteToOutput(const LoopInfo &LI, ostream &o) {
copy(LI.getTopLevelLoops().begin(), LI.getTopLevelLoops().end(),
- ostream_iterator<const Loop*>(o, "\n"));
+ std::ostream_iterator<const Loop*>(o, "\n"));
}
WriteAsOperand(o, (const Value*)IV.Phi);
o << ":\n" << (const Value*)IV.Phi;
} else {
- o << endl;
+ o << "\n";
}
if (IV.InductionType == InductionVariable::Unknown) return;
o << " Start ="; WriteAsOperand(o, IV.Start);
o << " Step =" ; WriteAsOperand(o, IV.Step);
- o << endl;
+ o << "\n";
}
#include "llvm/Module.h"
#include "ParserInternals.h"
#include <stdio.h> // for sprintf
+using std::string;
// The useful interface defined by this file... Parse an ascii file, and return
// the internal representation in a nice slice'n'dice'able representation.
fclose(F);
if (Result) { // Check to see that it is valid...
- vector<string> Errors;
+ std::vector<string> Errors;
if (verify(Result, Errors)) {
delete Result; Result = 0;
string Message;
class Module;
// Global variables exported from the lexer...
-extern FILE *llvmAsmin;
+extern std::FILE *llvmAsmin;
extern int llvmAsmlineno;
// Globals exported by the parser...
-extern string CurFilename;
-Module *RunVMAsmParser(const string &Filename, FILE *F);
+extern std::string CurFilename;
+Module *RunVMAsmParser(const std::string &Filename, FILE *F);
// UnEscapeLexed - Run through the specified buffer and change \xx codes to the
// This also helps me because I keep typing 'throw new ParseException' instead
// of just 'throw ParseException'... sigh...
//
-static inline void ThrowException(const string &message,
+static inline void ThrowException(const std::string &message,
int LineNo = -1) {
if (LineNo == -1) LineNo = llvmAsmlineno;
// TODO: column number in exception
return Result;
}
- inline string getName() const {
+ inline std::string getName() const {
switch (Type) {
- case NumberVal : return string("#") + itostr(Num);
+ case NumberVal : return std::string("#") + itostr(Num);
case NameVal : return Name;
- case ConstStringVal: return string("\"") + Name + string("\"");
+ case ConstStringVal: return std::string("\"") + Name + std::string("\"");
case ConstFPVal : return ftostr(ConstPoolFP);
case ConstNullVal : return "null";
case ConstUIntVal :
- case ConstSIntVal : return string("%") + itostr(ConstPool64);
+ case ConstSIntVal : return std::string("%") + itostr(ConstPool64);
default:
assert(0 && "Unknown value!");
abort();
+ return "";
}
}
struct InstPlaceHolderHelper : public Instruction {
InstPlaceHolderHelper(const Type *Ty) : Instruction(Ty, UserOp1, "") {}
- virtual Instruction *clone() const { abort(); }
+ virtual Instruction *clone() const { abort(); return 0; }
virtual const char *getOpcodeName() const { return "placeholder"; }
};
#include <utility> // Get definition of pair class
#include <algorithm>
#include <stdio.h> // This embarasment is due to our flex lexer...
+#include <iostream>
+using std::list;
+using std::vector;
+using std::pair;
+using std::map;
+using std::pair;
+using std::make_pair;
+using std::cerr;
+using std::string;
int yyerror(const char *ErrorMsg); // Forward declarations to prevent "implicit
int yylex(); // declaration" of xxx warnings.
typedef vector<Value *> ValueList; // Numbered defs
static void ResolveDefinitions(vector<ValueList> &LateResolvers,
vector<ValueList> *FutureLateResolvers = 0);
-static void ResolveTypes (vector<PATypeHolder<Type> > &LateResolveTypes);
static struct PerModuleInfo {
Module *CurrentModule;
LateResolvers.clear();
}
-// ResolveType - Take a specified unresolved type and resolve it. If there is
-// nothing to resolve it to yet, return true. Otherwise resolve it and return
-// false.
-//
-static bool ResolveType(PATypeHolder<Type> &T) {
- const Type *Ty = T;
- ValID &DID = getValIDFromPlaceHolder(Ty);
-
- const Type *TheRealType = getTypeVal(DID, true);
- if (TheRealType == 0 || TheRealType == Ty) return true;
-
- // Refine the opaque type we had to the new type we are getting.
- cast<DerivedType>(Ty)->refineAbstractTypeTo(TheRealType);
- return false;
-}
-
// ResolveTypeTo - A brand new type was just declared. This means that (if
// name is not null) things referencing Name can be resolved. Otherwise, things
// refering to the number can be resolved. Do this now.
PATypeHolder<Type> *TypeVal;
Value *ValueVal;
- list<MethodArgument*> *MethodArgList;
- vector<Value*> *ValueList;
- list<PATypeHolder<Type> > *TypeList;
- list<pair<Value*, BasicBlock*> > *PHIList; // Represent the RHS of PHI node
- list<pair<Constant*, BasicBlock*> > *JumpTable;
- vector<Constant*> *ConstVector;
+ std::list<MethodArgument*> *MethodArgList;
+ std::vector<Value*> *ValueList;
+ std::list<PATypeHolder<Type> > *TypeList;
+ std::list<std::pair<Value*,
+ BasicBlock*> > *PHIList; // Represent the RHS of PHI node
+ std::list<std::pair<Constant*, BasicBlock*> > *JumpTable;
+ std::vector<Constant*> *ConstVector;
int64_t SInt64Val;
uint64_t UInt64Val;
}
| UpRTypesV '(' ArgTypeListI ')' { // Method derived type?
vector<const Type*> Params;
- mapto($3->begin(), $3->end(), back_inserter(Params),
- mem_fun_ref(&PATypeHandle<Type>::get));
+ mapto($3->begin(), $3->end(), std::back_inserter(Params),
+ std::mem_fun_ref(&PATypeHandle<Type>::get));
bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
if (isVarArg) Params.pop_back();
}
| '{' TypeListI '}' { // Structure type?
vector<const Type*> Elements;
- mapto($2->begin(), $2->end(), back_inserter(Elements),
- mem_fun_ref(&PATypeHandle<Type>::get));
+ mapto($2->begin(), $2->end(), std::back_inserter(Elements),
+ std::mem_fun_ref(&PATypeHandle<Type>::get));
$$ = newTH<Type>(HandleUpRefs(StructType::get(Elements)));
delete $2;
#include "llvm/ConstantVals.h"
#include "llvm/GlobalVariable.h"
#include <algorithm>
-
-
+#include <iostream>
+using std::make_pair;
+using std::cerr;
const Type *BytecodeParser::parseTypeConstant(const uchar *&Buf,
const uchar *EndBuf) {
unsigned NumParams;
if (read_vbr(Buf, EndBuf, NumParams)) return failure(Val);
- vector<const Type*> Params;
+ std::vector<const Type*> Params;
while (NumParams--) {
if (read_vbr(Buf, EndBuf, Typ)) return failure(Val);
const Type *Ty = getType(Typ);
if (read_vbr(Buf, EndBuf, NumElements)) return failure(Val);
BCR_TRACE(5, "Array Type Constant #" << ElTyp << " size="
- << NumElements << endl);
+ << NumElements << "\n");
return ArrayType::get(ElementType, NumElements);
}
case Type::StructTyID: {
unsigned Typ;
- vector<const Type*> Elements;
+ std::vector<const Type*> Elements;
if (read_vbr(Buf, EndBuf, Typ)) return failure(Val);
while (Typ) { // List is terminated by void/0 typeid
case Type::PointerTyID: {
unsigned ElTyp;
if (read_vbr(Buf, EndBuf, ElTyp)) return failure(Val);
- BCR_TRACE(5, "Pointer Type Constant #" << (ElTyp-14) << endl);
+ BCR_TRACE(5, "Pointer Type Constant #" << (ElTyp-14) << "\n");
const Type *ElementType = getType(ElTyp);
if (ElementType == 0) return failure(Val);
return PointerType::get(ElementType);
const ArrayType *AT = cast<const ArrayType>(Ty);
unsigned NumElements = AT->getNumElements();
- vector<Constant*> Elements;
+ std::vector<Constant*> Elements;
while (NumElements--) { // Read all of the elements of the constant.
unsigned Slot;
if (read_vbr(Buf, EndBuf, Slot)) return failure(true);
const StructType *ST = cast<StructType>(Ty);
const StructType::ElementTypes &ET = ST->getElementTypes();
- vector<Constant *> Elements;
+ std::vector<Constant *> Elements;
for (unsigned i = 0; i < ET.size(); ++i) {
unsigned Slot;
if (read_vbr(Buf, EndBuf, Slot)) return failure(true);
#include "llvm/iMemory.h"
#include "llvm/iPHINode.h"
#include "llvm/iOther.h"
+#include <iostream>
+using std::vector;
+using std::cerr;
bool BytecodeParser::ParseRawInst(const uchar *&Buf, const uchar *EndBuf,
RawInst &Result) {
#if 0
cerr << "NO: " << Result.NumOperands << " opcode: " << Result.Opcode
<< " Ty: " << Result.Ty->getDescription() << " arg1: " << Result.Arg1
- << " arg2: " << Result.Arg2 << " arg3: " << Result.Arg3 << endl;
+ << " arg2: " << Result.Arg2 << " arg3: " << Result.Arg3 << "\n";
#endif
return false;
}
} // end switch(Raw.Opcode)
cerr << "Unrecognized instruction! " << Raw.Opcode
- << " ADDR = 0x" << (void*)Buf << endl;
+ << " ADDR = 0x" << (void*)Buf << "\n";
return failure(true);
}
#include "llvm/iPHINode.h"
#include "llvm/iOther.h"
#include <sys/types.h>
-#include <sys/mman.h>
+typedef int blksize_t;
#include <sys/stat.h>
+#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>
#include <algorithm>
+#include <iostream>
+using std::cerr;
+using std::make_pair;
bool BytecodeParser::getTypeSlot(const Type *Ty, unsigned &Slot) {
if (Ty->isPrimitiveType()) {
Slot = FirstDerivedTyID + (&*I - &ModuleTypeValues[0]);
}
}
- //cerr << "getTypeSlot '" << Ty->getName() << "' = " << Slot << endl;
+ //cerr << "getTypeSlot '" << Ty->getName() << "' = " << Slot << "\n";
return false;
}
const Type *T = Type::getPrimitiveType((Type::PrimitiveID)ID);
if (T) return T;
- //cerr << "Looking up Type ID: " << ID << endl;
+ //cerr << "Looking up Type ID: " << ID << "\n";
const Value *D = getValue(Type::TypeTy, ID, false);
if (D == 0) return failure<const Type*>(0);
return cast<Type>(D);
}
-int BytecodeParser::insertValue(Value *Val, vector<ValueList> &ValueTab) {
+int BytecodeParser::insertValue(Value *Val, std::vector<ValueList> &ValueTab) {
unsigned type;
if (getTypeSlot(Val->getType(), type)) return failure<int>(-1);
assert(type != Type::TypeTyID && "Types should never be insertValue'd!");
ValueTab.resize(type+1, ValueList());
//cerr << "insertValue Values[" << type << "][" << ValueTab[type].size()
- // << "] = " << Val << endl;
+ // << "] = " << Val << "\n";
ValueTab[type].push_back(Val);
return ValueTab[type].size()-1;
case Type::LabelTyID: d = new BBPHolder(Ty, oNum); break;
case Type::MethodTyID:
cerr << "Creating method pholder! : " << type << ":" << oNum << " "
- << Ty->getName() << endl;
+ << Ty->getName() << "\n";
d = new MethPHolder(Ty, oNum);
if (insertValue(d, LateResolveModuleValues) ==-1) return failure<Value*>(0);
return d;
// Symtab entry: [def slot #][name]
unsigned slot;
if (read_vbr(Buf, EndBuf, slot)) return failure(true);
- string Name;
+ std::string Name;
if (read(Buf, EndBuf, Name, false)) // Not aligned...
return failure(true);
Value *D = getValue(Ty, slot, false); // Find mapping...
if (D == 0) {
- BCR_TRACE(3, "FAILED LOOKUP: Slot #" << slot << endl);
+ BCR_TRACE(3, "FAILED LOOKUP: Slot #" << slot << "\n");
return failure(true);
}
BCR_TRACE(4, "Map: '" << Name << "' to #" << slot << ":" << D;
- if (!isa<Instruction>(D)) cerr << endl);
+ if (!isa<Instruction>(D)) cerr << "\n");
D->setName(Name, ST);
}
MethodSignatureList.pop_front();
Method *M = new Method(MTy, isInternal != 0);
- BCR_TRACE(2, "METHOD TYPE: " << MTy << endl);
+ BCR_TRACE(2, "METHOD TYPE: " << MTy << "\n");
const MethodType::ParamTypes &Params = MTy->getParamTypes();
for (MethodType::ParamTypes::const_iterator It = Params.begin();
DeclareNewGlobalValue(GV, unsigned(DestSlot));
BCR_TRACE(2, "Global Variable of type: " << PTy->getDescription()
- << " into slot #" << DestSlot << endl);
+ << " into slot #" << DestSlot << "\n");
if (read_vbr(Buf, End, VarType)) return failure(true);
}
MethodSignatureList.push_back(
make_pair(cast<const PointerType>(Val->getType()), SlotNo));
if (read_vbr(Buf, End, MethSignature)) return failure(true);
- BCR_TRACE(2, "Method of type: " << Ty << endl);
+ BCR_TRACE(2, "Method of type: " << Ty << "\n");
}
if (align32(Buf, End)) return failure(true);
// Parse and return a class file...
//
-Module *ParseBytecodeFile(const string &Filename, string *ErrorStr) {
+Module *ParseBytecodeFile(const std::string &Filename, std::string *ErrorStr) {
struct stat StatBuf;
Module *Result = 0;
- if (Filename != string("-")) { // Read from a file...
+ if (Filename != std::string("-")) { // Read from a file...
int FD = open(Filename.c_str(), O_RDONLY);
if (FD == -1) {
if (ErrorStr) *ErrorStr = "Error opening file!";
#if TRACE_LEVEL // ByteCodeReading_TRACEer
#include "llvm/Assembly/Writer.h"
-#define BCR_TRACE(n, X) if (n < TRACE_LEVEL) cerr << string(n*2, ' ') << X
+#define BCR_TRACE(n, X) if (n < TRACE_LEVEL) cerr << std::string(n*2, ' ') << X
#else
#define BCR_TRACE(n, X)
#endif
unsigned Arg1, Arg2;
union {
unsigned Arg3;
- vector<unsigned> *VarArgs; // Contains arg #3,4,5... if NumOperands > 3
+ std::vector<unsigned> *VarArgs; // Contains arg #3,4,5... if NumOperands > 3
};
};
class BytecodeParser : public AbstractTypeUser {
- string Error; // Error message string goes here...
+ std::string Error; // Error message string goes here...
public:
BytecodeParser() {
// Define this in case we don't see a ModuleGlobalInfo block.
Module *ParseBytecode(const uchar *Buf, const uchar *EndBuf);
- string getError() const { return Error; }
+ std::string getError() const { return Error; }
private: // All of this data is transient across calls to ParseBytecode
Module *TheModule; // Current Module being read into...
- typedef vector<Value *> ValueList;
- typedef vector<ValueList> ValueTable;
+ typedef std::vector<Value *> ValueList;
+ typedef std::vector<ValueList> ValueTable;
ValueTable Values, LateResolveValues;
ValueTable ModuleValues, LateResolveModuleValues;
// are defined, and if so, the temporary object that they represent is held
// here.
//
- typedef map<pair<const PointerType *, unsigned>, GlobalVariable*>
- GlobalRefsType;
+ typedef std::map<std::pair<const PointerType *, unsigned>,
+ GlobalVariable*> GlobalRefsType;
GlobalRefsType GlobalRefs;
// TypesLoaded - This vector mirrors the Values[TypeTyID] plane. It is used
// to deal with forward references to types.
//
- typedef vector<PATypeHandle<Type> > TypeValuesListTy;
+ typedef std::vector<PATypeHandle<Type> > TypeValuesListTy;
TypeValuesListTy ModuleTypeValues;
TypeValuesListTy MethodTypeValues;
// into its slot to reserve it. When the method is loaded, this placeholder
// is replaced.
//
- list<pair<const PointerType *, unsigned> > MethodSignatureList;
+ std::list<std::pair<const PointerType *, unsigned> > MethodSignatureList;
private:
- bool ParseModule (const uchar * Buf, const uchar *End, Module *&);
- bool ParseModuleGlobalInfo (const uchar *&Buf, const uchar *End, Module *);
+ bool ParseModule (const uchar * Buf, const uchar *End, Module *&);
+ bool ParseModuleGlobalInfo(const uchar *&Buf, const uchar *End, Module *);
bool ParseSymbolTable (const uchar *&Buf, const uchar *End, SymbolTable *);
bool ParseMethod (const uchar *&Buf, const uchar *End, Module *);
bool ParseBasicBlock (const uchar *&Buf, const uchar *End, BasicBlock *&);
Value *getValue(const Type *Ty, unsigned num, bool Create = true);
const Type *getType(unsigned ID);
- int insertValue(Value *D, vector<ValueList> &D); // -1 = Failure
+ int insertValue(Value *D, std::vector<ValueList> &D); // -1 = Failure
bool postResolveValues(ValueTable &ValTab);
bool getTypeSlot(const Type *Ty, unsigned &Slot);
#include "llvm/ConstantVals.h"
#include "llvm/SymbolTable.h"
#include "llvm/DerivedTypes.h"
+#include <iostream>
+using std::cerr;
void BytecodeWriter::outputType(const Type *T) {
output_vbr((unsigned)T->getPrimitiveID(), Out);
case Type::StructTyID: {
const ConstantStruct *CPS = cast<const ConstantStruct>(CPV);
- const vector<Use> &Vals = CPS->getValues();
+ const std::vector<Use> &Vals = CPS->getValues();
for (unsigned i = 0; i < Vals.size(); ++i) {
int Slot = Table.getValSlot(Vals[i]);
//
static void outputInstructionFormat0(const Instruction *I,
const SlotCalculator &Table,
- unsigned Type, deque<uchar> &Out) {
+ unsigned Type, std::deque<uchar> &Out) {
// Opcode must have top two bits clear...
output_vbr(I->getOpcode() << 2, Out); // Instruction Opcode ID
output_vbr(Type, Out); // Result type
//
static void outputInstrVarArgsCall(const Instruction *I,
const SlotCalculator &Table, unsigned Type,
- deque<uchar> &Out) {
+ std::deque<uchar> &Out) {
assert(isa<CallInst>(I) || isa<InvokeInst>(I));
// Opcode must have top two bits clear...
output_vbr(I->getOpcode() << 2, Out); // Instruction Opcode ID
//
static void outputInstructionFormat1(const Instruction *I,
const SlotCalculator &Table, int *Slots,
- unsigned Type, deque<uchar> &Out) {
+ unsigned Type, std::deque<uchar> &Out) {
unsigned Opcode = I->getOpcode(); // Instruction Opcode ID
// bits Instruction format:
//
static void outputInstructionFormat2(const Instruction *I,
const SlotCalculator &Table, int *Slots,
- unsigned Type, deque<uchar> &Out) {
+ unsigned Type, std::deque<uchar> &Out) {
unsigned Opcode = I->getOpcode(); // Instruction Opcode ID
// bits Instruction format:
//
static void outputInstructionFormat3(const Instruction *I,
const SlotCalculator &Table, int *Slots,
- unsigned Type, deque<uchar> &Out) {
+ unsigned Type, std::deque<uchar> &Out) {
unsigned Opcode = I->getOpcode(); // Instruction Opcode ID
// bits Instruction format:
while (CurPlane.size() != ModuleSize) {
//SC_DEBUG(" Removing [" << i << "] Value=" << CurPlane.back() << "\n");
- map<const Value *, unsigned>::iterator NI = NodeMap.find(CurPlane.back());
+ std::map<const Value *, unsigned>::iterator NI =
+ NodeMap.find(CurPlane.back());
assert(NI != NodeMap.end() && "Node not in nodemap?");
NodeMap.erase(NI); // Erase from nodemap
CurPlane.pop_back(); // Shrink plane
}
int SlotCalculator::getValSlot(const Value *D) const {
- map<const Value*, unsigned>::const_iterator I = NodeMap.find(D);
+ std::map<const Value*, unsigned>::const_iterator I = NodeMap.find(D);
if (I == NodeMap.end()) return -1;
return (int)I->second;
const Module *TheModule;
bool IgnoreNamedNodes; // Shall we not count named nodes?
- typedef vector<const Value*> TypePlane;
- vector<TypePlane> Table;
- map<const Value *, unsigned> NodeMap;
+ typedef std::vector<const Value*> TypePlane;
+ std::vector<TypePlane> Table;
+ std::map<const Value *, unsigned> NodeMap;
// ModuleLevel - Used to keep track of which values belong to the module,
// and which values belong to the currently incorporated method.
//
- vector<unsigned> ModuleLevel;
+ std::vector<unsigned> ModuleLevel;
public:
SlotCalculator(const Module *M, bool IgnoreNamed);
#include <string.h>
#include <algorithm>
-BytecodeWriter::BytecodeWriter(deque<unsigned char> &o, const Module *M)
+BytecodeWriter::BytecodeWriter(std::deque<unsigned char> &o, const Module *M)
: Out(o), Table(M, false) {
outputSignature();
unsigned NumPlanes = Table.getNumPlanes();
for (unsigned pno = 0; pno < NumPlanes; pno++) {
- const vector<const Value*> &Plane = Table.getPlane(pno);
+ const std::vector<const Value*> &Plane = Table.getPlane(pno);
if (Plane.empty()) continue; // Skip empty type planes...
unsigned ValNo = 0;
assert (Slot != -1 && "Type in constant pool but not in method!!");
output_vbr((unsigned)Slot, Out);
- //cout << "Emitting " << NC << " constants of type '"
- // << Plane.front()->getType()->getName() << "' = Slot #" << Slot << endl;
+ //cerr << "Emitting " << NC << " constants of type '"
+ // << Plane.front()->getType()->getName() << "' = Slot #" << Slot << "\n";
for (unsigned i = ValNo; i < ValNo+NC; ++i) {
const Value *V = Plane[i];
void WriteBytecodeToFile(const Module *C, ostream &Out) {
assert(C && "You can't write a null module!!");
- deque<unsigned char> Buffer;
+ std::deque<unsigned char> Buffer;
// This object populates buffer for us...
BytecodeWriter BCW(Buffer, C);
// sequential in memory, however, so write out as much as possible in big
// chunks, until we're done.
//
- deque<unsigned char>::const_iterator I = Buffer.begin(), E = Buffer.end();
+ std::deque<unsigned char>::const_iterator I = Buffer.begin(),E = Buffer.end();
while (I != E) { // Loop until it's all written
// Scan to see how big this chunk is...
const unsigned char *ChunkPtr = &*I;
}
// Write out the chunk...
- Out.write(ChunkPtr, LastPtr-ChunkPtr);
+ Out.write((char*)ChunkPtr, LastPtr-ChunkPtr);
}
Out.flush();
#include <deque>
class BytecodeWriter {
- deque<unsigned char> &Out;
+ std::deque<unsigned char> &Out;
SlotCalculator Table;
public:
- BytecodeWriter(deque<unsigned char> &o, const Module *M);
+ BytecodeWriter(std::deque<unsigned char> &o, const Module *M);
protected:
void outputConstants(bool isMethod);
//
class BytecodeBlock {
unsigned Loc;
- deque<unsigned char> &Out;
+ std::deque<unsigned char> &Out;
BytecodeBlock(const BytecodeBlock &); // do not implement
void operator=(const BytecodeBlock &); // do not implement
public:
- inline BytecodeBlock(unsigned ID, deque<unsigned char> &o) : Out(o) {
+ inline BytecodeBlock(unsigned ID, std::deque<unsigned char> &o) : Out(o) {
output(ID, Out);
output((unsigned)0, Out); // Reserve the space for the block size...
Loc = Out.size();
#include "llvm/Instruction.h"
#include "Support/CommandLine.h"
#include "SchedPriorities.h"
-#include <hash_set>
#include <algorithm>
#include <iterator>
-
+#include <ext/hash_set>
+#include <iostream>
+using std::cerr;
+using std::vector;
//************************* External Data Types *****************************/
unsigned int totalInstrCount;
cycles_t curTime;
cycles_t nextEarliestIssueTime; // next cycle we can issue
- vector<hash_set<const SchedGraphNode*> > choicesForSlot; // indexed by slot#
+ vector<std::hash_set<const SchedGraphNode*> > choicesForSlot; // indexed by slot#
vector<const SchedGraphNode*> choiceVec; // indexed by node ptr
vector<int> numInClass; // indexed by sched class
vector<cycles_t> nextEarliestStartTime; // indexed by opCode
- hash_map<const SchedGraphNode*, DelaySlotInfo*> delaySlotInfoForBranches;
+ std::hash_map<const SchedGraphNode*, DelaySlotInfo*> delaySlotInfoForBranches;
// indexed by branch node ptr
public:
return choiceVec[i];
}
- inline hash_set<const SchedGraphNode*>& getChoicesForSlot(unsigned slotNum) {
+ inline std::hash_set<const SchedGraphNode*>& getChoicesForSlot(unsigned slotNum) {
assert(slotNum < nslots);
return choicesForSlot[slotNum];
}
bool createIfMissing=false)
{
DelaySlotInfo* dinfo;
- hash_map<const SchedGraphNode*, DelaySlotInfo* >::const_iterator
+ std::hash_map<const SchedGraphNode*, DelaySlotInfo* >::const_iterator
I = delaySlotInfoForBranches.find(bn);
if (I == delaySlotInfoForBranches.end())
{
{
if (schedInfo.numBubblesAfter(node->getOpCode()) > 0)
{ // Update next earliest time before which *nothing* can issue.
- nextEarliestIssueTime = max(nextEarliestIssueTime,
+ nextEarliestIssueTime = std::max(nextEarliestIssueTime,
curTime + 1 + schedInfo.numBubblesAfter(node->getOpCode()));
}
unsigned numIssued;
for (numIssued = 0; numIssued < maxIssue; numIssued++)
{
- int chosenSlot = -1, chosenNodeIndex = -1;
+ int chosenSlot = -1;
for (unsigned s=startSlot; s < S.nslots; s++)
if ((*igroup)[s] == NULL && S.getChoicesForSlot(s).size() == 1)
{
assert(s < S.nslots && "No feasible slot for instruction?");
- highestSlotUsed = max(highestSlotUsed, (int) s);
+ highestSlotUsed = std::max(highestSlotUsed, (int) s);
}
assert(highestSlotUsed <= (int) S.nslots-1 && "Invalid slot used?");
// Otherwise, just ignore the instruction.
for (unsigned i=indexForBreakingNode+1; i < S.getNumChoices(); i++)
{
- bool foundLowerSlot = false;
MachineOpCode opCode = S.getChoice(i)->getOpCode();
for (unsigned int s=startSlot; s < nslotsToUse; s++)
if (S.schedInfo.instrCanUseSlot(opCode, s))
{
for (cycles_t c = firstCycle; c <= S.getTime(); c++)
{
- cout << " Cycle " << c << " : Scheduled instructions:\n";
+ cerr << " Cycle " << (long)c << " : Scheduled instructions:\n";
const InstrGroup* igroup = S.isched.getIGroup(c);
for (unsigned int s=0; s < S.nslots; s++)
{
- cout << " ";
+ cerr << " ";
if ((*igroup)[s] != NULL)
- cout << * ((*igroup)[s])->getMachineInstr() << endl;
+ cerr << * ((*igroup)[s])->getMachineInstr() << "\n";
else
- cout << "<none>" << endl;
+ cerr << "<none>\n";
}
}
}
// an instruction can be issued, or the next earliest in which
// one will be ready, or to the next cycle, whichever is latest.
//
- S.updateTime(max(S.getTime() + 1,
- max(S.getEarliestIssueTime(),
- S.schedPrio.getEarliestReadyTime())));
+ S.updateTime(std::max(S.getTime() + 1,
+ std::max(S.getEarliestIssueTime(),
+ S.schedPrio.getEarliestReadyTime())));
}
}
if (SchedDebugLevel >= Sched_PrintSchedGraphs)
{
- cout << endl << "*** SCHEDULING GRAPHS FOR INSTRUCTION SCHEDULING"
- << endl;
+ cerr << "\n*** SCHEDULING GRAPHS FOR INSTRUCTION SCHEDULING\n";
graphSet.dump();
}
const BasicBlock* bb = bbvec[0];
if (SchedDebugLevel >= Sched_PrintSchedTrace)
- cout << endl << "*** TRACE OF INSTRUCTION SCHEDULING OPERATIONS\n\n";
+ cerr << "\n*** TRACE OF INSTRUCTION SCHEDULING OPERATIONS\n\n";
SchedPriorities schedPrio(method, graph); // expensive!
SchedulingManager S(target, graph, schedPrio);
if (SchedDebugLevel >= Sched_PrintMachineCode)
{
- cout << endl
- << "*** Machine instructions after INSTRUCTION SCHEDULING" << endl;
+ cerr << "\n*** Machine instructions after INSTRUCTION SCHEDULING\n";
MachineCodeForMethod::get(method).dump();
}
#include "llvm/Target/MachineRegInfo.h"
#include "llvm/iOther.h"
#include "Support/StringExtras.h"
+#include "Support/STLExtras.h"
#include <algorithm>
-#include <hash_map>
#include <vector>
+#include <iostream>
+#include <ext/hash_map>
+using std::vector;
+using std::pair;
+using std::hash_map;
+using std::cerr;
//*********************** Internal Data Structures *************************/
}
void SchedGraphEdge::dump(int indent=0) const {
- cout << string(indent*2, ' ') << *this;
+ cerr << std::string(indent*2, ' ') << *this;
}
}
void SchedGraphNode::dump(int indent=0) const {
- cout << string(indent*2, ' ') << *this;
+ cerr << std::string(indent*2, ' ') << *this;
}
const TargetMachine& target)
{
bbVec.push_back(bb);
- this->buildGraph(target);
+ buildGraph(target);
}
/*dtor*/
SchedGraph::~SchedGraph()
{
- for (iterator I=begin(); I != end(); ++I)
+ for (const_iterator I = begin(); I != end(); ++I)
{
- SchedGraphNode* node = (*I).second;
+ SchedGraphNode *node = I->second;
// for each node, delete its out-edges
- for (SchedGraphNode::iterator I = node->beginOutEdges();
- I != node->endOutEdges(); ++I)
- delete *I;
+ std::for_each(node->beginOutEdges(), node->endOutEdges(),
+ deleter<SchedGraphEdge>);
// then delete the node itself.
delete node;
void
SchedGraph::dump() const
{
- cout << " Sched Graph for Basic Blocks: ";
+ cerr << " Sched Graph for Basic Blocks: ";
for (unsigned i=0, N=bbVec.size(); i < N; i++)
{
- cout << (bbVec[i]->hasName()? bbVec[i]->getName() : "block")
+ cerr << (bbVec[i]->hasName()? bbVec[i]->getName() : "block")
<< " (" << bbVec[i] << ")"
<< ((i == N-1)? "" : ", ");
}
- cout << endl << endl << " Actual Root nodes : ";
+ cerr << "\n\n Actual Root nodes : ";
for (unsigned i=0, N=graphRoot->outEdges.size(); i < N; i++)
- cout << graphRoot->outEdges[i]->getSink()->getNodeId()
+ cerr << graphRoot->outEdges[i]->getSink()->getNodeId()
<< ((i == N-1)? "" : ", ");
- cout << endl << " Graph Nodes:" << endl;
+ cerr << "\n Graph Nodes:\n";
for (const_iterator I=begin(); I != end(); ++I)
- cout << endl << * (*I).second;
+ cerr << "\n" << *I->second;
- cout << endl;
+ cerr << "\n";
}
// this operand is a definition or use of value `instr'
SchedGraphNode* node = this->getGraphNodeForInstr(mvec[i]);
assert(node && "No node for machine instruction in this BB?");
- refVec.push_back(make_pair(node, o));
+ refVec.push_back(std::make_pair(node, o));
}
}
{
int regNum = mop.getMachineRegNum();
if (regNum != target.getRegInfo().getZeroRegNum())
- regToRefVecMap[mop.getMachineRegNum()].push_back(make_pair(node,
- i));
+ regToRefVecMap[mop.getMachineRegNum()].push_back(
+ std::make_pair(node, i));
continue; // nothing more to do
}
&& "Do not expect any other kind of operand to be defined!");
const Instruction* defInstr = cast<Instruction>(mop.getVRegValue());
- valueToDefVecMap[defInstr].push_back(make_pair(node, i));
+ valueToDefVecMap[defInstr].push_back(std::make_pair(node, i));
}
//
if (const Instruction* defInstr =
dyn_cast_or_null<Instruction>(minstr.getImplicitRef(i)))
{
- valueToDefVecMap[defInstr].push_back(make_pair(node, -i));
+ valueToDefVecMap[defInstr].push_back(std::make_pair(node, -i));
}
}
void
SchedGraph::buildGraph(const TargetMachine& target)
{
- const MachineInstrInfo& mii = target.getInstrInfo();
const BasicBlock* bb = bbVec[0];
assert(bbVec.size() == 1 && "Only handling a single basic block here");
SchedGraphSet::~SchedGraphSet()
{
// delete all the graphs
- for (iterator I=begin(); I != end(); ++I)
- delete (*I).second;
+ for (const_iterator I = begin(); I != end(); ++I)
+ delete I->second;
}
void
SchedGraphSet::dump() const
{
- cout << "======== Sched graphs for method `"
- << (method->hasName()? method->getName() : "???")
- << "' ========" << endl << endl;
+ cerr << "======== Sched graphs for method `" << method->getName()
+ << "' ========\n\n";
for (const_iterator I=begin(); I != end(); ++I)
- (*I).second->dump();
+ I->second->dump();
- cout << endl << "====== End graphs for method `"
- << (method->hasName()? method->getName() : "")
- << "' ========" << endl << endl;
+ cerr << "\n====== End graphs for method `" << method->getName()
+ << "' ========\n\n";
}
-ostream&
-operator<<(ostream& os, const SchedGraphEdge& edge)
+std::ostream &operator<<(std::ostream &os, const SchedGraphEdge& edge)
{
os << "edge [" << edge.src->getNodeId() << "] -> ["
<< edge.sink->getNodeId() << "] : ";
default: assert(0); break;
}
- os << " : delay = " << edge.minDelay << endl;
+ os << " : delay = " << edge.minDelay << "\n";
return os;
}
-ostream&
-operator<<(ostream& os, const SchedGraphNode& node)
+std::ostream &operator<<(std::ostream &os, const SchedGraphNode& node)
{
- os << string(8, ' ')
+ os << std::string(8, ' ')
<< "Node " << node.nodeId << " : "
- << "latency = " << node.latency << endl << string(12, ' ');
+ << "latency = " << node.latency << "\n" << std::string(12, ' ');
if (node.getMachineInstr() == NULL)
- os << "(Dummy node)" << endl;
+ os << "(Dummy node)\n";
else
{
- os << *node.getMachineInstr() << endl << string(12, ' ');
- os << node.inEdges.size() << " Incoming Edges:" << endl;
+ os << *node.getMachineInstr() << "\n" << std::string(12, ' ');
+ os << node.inEdges.size() << " Incoming Edges:\n";
for (unsigned i=0, N=node.inEdges.size(); i < N; i++)
- os << string(16, ' ') << *node.inEdges[i];
+ os << std::string(16, ' ') << *node.inEdges[i];
- os << string(12, ' ') << node.outEdges.size()
- << " Outgoing Edges:" << endl;
+ os << std::string(12, ' ') << node.outEdges.size()
+ << " Outgoing Edges:\n";
for (unsigned i=0, N=node.outEdges.size(); i < N; i++)
- {
- os << string(16, ' ') << * node.outEdges[i];
- }
+ os << std::string(16, ' ') << *node.outEdges[i];
}
return os;
#include "Support/NonCopyable.h"
#include "Support/HashExtras.h"
#include "Support/GraphTraits.h"
-#include <hash_map>
+#include <ext/hash_map>
class Value;
class Instruction;
//
// Debugging support
//
- friend ostream& operator<<(ostream& os, const SchedGraphEdge& edge);
+ friend std::ostream& operator<<(std::ostream& os, const SchedGraphEdge& edge);
void dump (int indent=0) const;
unsigned int nodeId;
const BasicBlock* bb;
const MachineInstr* minstr;
- vector<SchedGraphEdge*> inEdges;
- vector<SchedGraphEdge*> outEdges;
+ std::vector<SchedGraphEdge*> inEdges;
+ std::vector<SchedGraphEdge*> outEdges;
int origIndexInBB; // original position of machine instr in BB
int latency;
public:
- typedef vector<SchedGraphEdge*>:: iterator iterator;
- typedef vector<SchedGraphEdge*>::const_iterator const_iterator;
- typedef vector<SchedGraphEdge*>:: reverse_iterator reverse_iterator;
- typedef vector<SchedGraphEdge*>::const_reverse_iterator const_reverse_iterator;
+ typedef std::vector<SchedGraphEdge*>:: iterator iterator;
+ typedef std::vector<SchedGraphEdge*>::const_iterator const_iterator;
+ typedef std::vector<SchedGraphEdge*>:: reverse_iterator reverse_iterator;
+ typedef std::vector<SchedGraphEdge*>::const_reverse_iterator const_reverse_iterator;
public:
//
//
// Debugging support
//
- friend ostream& operator<<(ostream& os, const SchedGraphNode& node);
+ friend std::ostream& operator<<(std::ostream& os, const SchedGraphNode& node);
void dump (int indent=0) const;
class SchedGraph :
public NonCopyable,
- private hash_map<const MachineInstr*, SchedGraphNode*>
+ private std::hash_map<const MachineInstr*, SchedGraphNode*>
{
private:
- vector<const BasicBlock*> bbVec; // basic blocks included in the graph
+ std::vector<const BasicBlock*> bbVec; // basic blocks included in the graph
SchedGraphNode* graphRoot; // the root and leaf are not inserted
SchedGraphNode* graphLeaf; // in the hash_map (see getNumNodes())
+ typedef std::hash_map<const MachineInstr*, SchedGraphNode*> map_base;
public:
- typedef hash_map<const MachineInstr*, SchedGraphNode*>::iterator iterator;
- typedef hash_map<const MachineInstr*, SchedGraphNode*>::const_iterator const_iterator;
+ using map_base::iterator;
+ using map_base::const_iterator;
public:
//
// Accessor methods
//
- const vector<const BasicBlock*>& getBasicBlocks() const { return bbVec; }
+ const std::vector<const BasicBlock*>& getBasicBlocks() const { return bbVec; }
const unsigned int getNumNodes() const { return size()+2; }
SchedGraphNode* getRoot() const { return graphRoot; }
SchedGraphNode* getLeaf() const { return graphLeaf; }
// Unordered iterators.
// Return values is pair<const MachineIntr*,SchedGraphNode*>.
//
- iterator begin() {
- return hash_map<const MachineInstr*, SchedGraphNode*>::begin();
- }
- iterator end() {
- return hash_map<const MachineInstr*, SchedGraphNode*>::end();
- }
- const_iterator begin() const {
- return hash_map<const MachineInstr*, SchedGraphNode*>::begin();
- }
- const_iterator end() const {
- return hash_map<const MachineInstr*, SchedGraphNode*>::end();
- }
-
+ using map_base::begin;
+ using map_base::end;
+
//
// Ordered iterators.
// Return values is pair<const MachineIntr*,SchedGraphNode*>.
void buildNodesforBB (const TargetMachine& target,
const BasicBlock* bb,
- vector<SchedGraphNode*>& memNodeVec,
+ std::vector<SchedGraphNode*>& memNod,
RegToRefVecMap& regToRefVecMap,
ValueToDefVecMap& valueToDefVecMap);
void findDefUseInfoAtInstr (const TargetMachine& target,
SchedGraphNode* node,
- vector<SchedGraphNode*>& memNodeVec,
+ std::vector<SchedGraphNode*>& memNode,
RegToRefVecMap& regToRefVecMap,
ValueToDefVecMap& valueToDefVecMap);
void addCDEdges (const TerminatorInst* term,
const TargetMachine& target);
- void addMemEdges (const vector<SchedGraphNode*>& memNodeVec,
+ void addMemEdges (const std::vector<SchedGraphNode*>& memNod,
const TargetMachine& target);
- void addCallCCEdges (const vector<SchedGraphNode*>& memNodeVec,
+ void addCallCCEdges (const std::vector<SchedGraphNode*>& memNod,
MachineCodeForBasicBlock& bbMvec,
const TargetMachine& target);
class SchedGraphSet :
public NonCopyable,
- private hash_map<const BasicBlock*, SchedGraph*>
+ private std::hash_map<const BasicBlock*, SchedGraph*>
{
private:
const Method* method;
public:
- typedef hash_map<const BasicBlock*, SchedGraph*>::iterator iterator;
- typedef hash_map<const BasicBlock*, SchedGraph*>::const_iterator const_iterator;
+ typedef std::hash_map<const BasicBlock*, SchedGraph*> map_base;
+ using map_base::iterator;
+ using map_base::const_iterator;
public:
/*ctor*/ SchedGraphSet (const Method* _method,
//
// Iterators
//
- iterator begin() {
- return hash_map<const BasicBlock*, SchedGraph*>::begin();
- }
- iterator end() {
- return hash_map<const BasicBlock*, SchedGraph*>::end();
- }
- const_iterator begin() const {
- return hash_map<const BasicBlock*, SchedGraph*>::begin();
- }
- const_iterator end() const {
- return hash_map<const BasicBlock*, SchedGraph*>::end();
- }
+ using map_base::begin;
+ using map_base::end;
//
// Debugging support
};
-//************************ External Functions *****************************/
-
-
-ostream& operator<<(ostream& os, const SchedGraphEdge& edge);
-
-ostream& operator<<(ostream& os, const SchedGraphNode& node);
-
-
-/***************************************************************************/
+std::ostream &operator<<(std::ostream& os, const SchedGraphEdge& edge);
+std::ostream &operator<<(std::ostream &os, const SchedGraphNode& node);
#endif
#include "SchedPriorities.h"
#include "Support/PostOrderIterator.h"
-
+#include <iostream>
+using std::cerr;
SchedPriorities::SchedPriorities(const Method* method,
const SchedGraph* _graph)
: curTime(0),
graph(_graph),
- methodLiveVarInfo(method), // expensive!
- lastUseMap(),
- nodeDelayVec(_graph->getNumNodes(),INVALID_LATENCY), //make errors obvious
+ methodLiveVarInfo(method), // expensive!
+ nodeDelayVec(_graph->getNumNodes(), INVALID_LATENCY), // make errors obvious
earliestForNode(_graph->getNumNodes(), 0),
earliestReadyTime(0),
- candsAsHeap(),
- candsAsSet(),
- mcands(),
nextToTry(candsAsHeap.begin())
{
methodLiveVarInfo.analyze();
E != node->endOutEdges(); ++E)
{
cycles_t sinkDelay = getNodeDelayRef((*E)->getSink());
- nodeDelay = max(nodeDelay, sinkDelay + (*E)->getMinDelay());
+ nodeDelay = std::max(nodeDelay, sinkDelay + (*E)->getMinDelay());
}
}
getNodeDelayRef(node) = nodeDelay;
#undef TEST_HEAP_CONVERSION
#ifdef TEST_HEAP_CONVERSION
- cout << "Before heap conversion:" << endl;
+ cerr << "Before heap conversion:\n";
copy(candsAsHeap.begin(), candsAsHeap.end(),
- ostream_iterator<NodeDelayPair*>(cout,"\n"));
+ ostream_iterator<NodeDelayPair*>(cerr,"\n"));
#endif
candsAsHeap.makeHeap();
#ifdef TEST_HEAP_CONVERSION
- cout << "After heap conversion:" << endl;
+ cerr << "After heap conversion:\n";
copy(candsAsHeap.begin(), candsAsHeap.end(),
- ostream_iterator<NodeDelayPair*>(cout,"\n"));
+ ostream_iterator<NodeDelayPair*>(cerr,"\n"));
#endif
}
+void
+SchedPriorities::insertReady(const SchedGraphNode* node)
+{
+ candsAsHeap.insert(node, nodeDelayVec[node->getNodeId()]);
+ candsAsSet.insert(node);
+ mcands.clear(); // ensure reset choices is called before any more choices
+ earliestReadyTime = std::min(earliestReadyTime,
+ earliestForNode[node->getNodeId()]);
+
+ if (SchedDebugLevel >= Sched_PrintSchedTrace)
+ {
+ cerr << " Cycle " << (long)getTime() << ": "
+ << " Node " << node->getNodeId() << " is ready; "
+ << " Delay = " << (long)getNodeDelayRef(node) << "; Instruction: \n";
+ cerr << " " << *node->getMachineInstr() << "\n";
+ }
+}
void
SchedPriorities::issuedReadyNodeAt(cycles_t curTime,
for (NodeHeap::const_iterator I=candsAsHeap.begin();
I != candsAsHeap.end(); ++I)
if (candsAsHeap.getNode(I))
- earliestReadyTime = min(earliestReadyTime,
+ earliestReadyTime = std::min(earliestReadyTime,
getEarliestForNodeRef(candsAsHeap.getNode(I)));
}
E != node->endOutEdges(); ++E)
{
cycles_t& etime = getEarliestForNodeRef((*E)->getSink());
- etime = max(etime, curTime + (*E)->getMinDelay());
+ etime = std::max(etime, curTime + (*E)->getMinDelay());
}
}
//----------------------------------------------------------------------
inline int
-SchedPriorities::chooseByRule1(vector<candIndex>& mcands)
+SchedPriorities::chooseByRule1(std::vector<candIndex>& mcands)
{
return (mcands.size() == 1)? 0 // only one choice exists so take it
: -1; // -1 indicates multiple choices
}
inline int
-SchedPriorities::chooseByRule2(vector<candIndex>& mcands)
+SchedPriorities::chooseByRule2(std::vector<candIndex>& mcands)
{
assert(mcands.size() >= 1 && "Should have at least one candidate here.");
for (unsigned i=0, N = mcands.size(); i < N; i++)
}
inline int
-SchedPriorities::chooseByRule3(vector<candIndex>& mcands)
+SchedPriorities::chooseByRule3(std::vector<candIndex>& mcands)
{
assert(mcands.size() >= 1 && "Should have at least one candidate here.");
int maxUses = candsAsHeap.getNode(mcands[0])->getNumOutEdges();
void
-SchedPriorities::findSetWithMaxDelay(vector<candIndex>& mcands,
+SchedPriorities::findSetWithMaxDelay(std::vector<candIndex>& mcands,
const SchedulingManager& S)
{
if (mcands.size() == 0 && nextToTry != candsAsHeap.end())
if (SchedDebugLevel >= Sched_PrintSchedTrace)
{
- cout << " Cycle " << this->getTime() << ": "
- << "Next highest delay = " << maxDelay << " : "
+ cerr << " Cycle " << (long)getTime() << ": "
+ << "Next highest delay = " << (long)maxDelay << " : "
<< mcands.size() << " Nodes with this delay: ";
for (unsigned i=0; i < mcands.size(); i++)
- cout << candsAsHeap.getNode(mcands[i])->getNodeId() << ", ";
- cout << endl;
+ cerr << candsAsHeap.getNode(mcands[i])->getNodeId() << ", ";
+ cerr << "\n";
}
}
}
{
const MachineInstr* minstr = graphNode->getMachineInstr();
- hash_map<const MachineInstr*, bool>::const_iterator
+ std::hash_map<const MachineInstr*, bool>::const_iterator
ui = lastUseMap.find(minstr);
if (ui != lastUseMap.end())
- return (*ui).second;
+ return ui->second;
// else check if instruction is a last use and save it in the hash_map
bool hasLastUse = false;
#include "llvm/Analysis/LiveVar/MethodLiveVarInfo.h"
#include "llvm/Target/MachineSchedInfo.h"
#include <list>
+#include <ostream>
class Method;
class MachineInstr;
const SchedGraphNode* node;
cycles_t delay;
NodeDelayPair(const SchedGraphNode* n, cycles_t d) : node(n), delay(d) {}
- inline bool operator< (const NodeDelayPair& np) { return delay < np.delay; }
+ inline bool operator<(const NodeDelayPair& np) { return delay < np.delay; }
};
inline bool
NDPLessThan(const NodeDelayPair* np1, const NodeDelayPair* np2)
{
- return (np1->delay < np2->delay);
+ return np1->delay < np2->delay;
}
-class NodeHeap: public list<NodeDelayPair*>, public NonCopyable {
+class NodeHeap: public std::list<NodeDelayPair*>, public NonCopyable {
public:
- typedef list<NodeDelayPair*>::iterator iterator;
- typedef list<NodeDelayPair*>::const_iterator const_iterator;
+ typedef std::list<NodeDelayPair*>::iterator iterator;
+ typedef std::list<NodeDelayPair*>::const_iterator const_iterator;
public:
- /*ctor*/ NodeHeap () : list<NodeDelayPair*>(), _size(0) {}
+ /*ctor*/ NodeHeap () : std::list<NodeDelayPair*>(), _size(0) {}
/*dtor*/ ~NodeHeap () {}
inline unsigned int size () const { return _size; }
iterator I=begin();
for ( ; I != end() && getDelay(I) >= delay; ++I)
;
- list<NodeDelayPair*>::insert(I, ndp);
+ std::list<NodeDelayPair*>::insert(I, ndp);
}
_size++;
}
cycles_t curTime;
const SchedGraph* graph;
MethodLiveVarInfo methodLiveVarInfo;
- hash_map<const MachineInstr*, bool> lastUseMap;
- vector<cycles_t> nodeDelayVec;
- vector<cycles_t> earliestForNode;
+ std::hash_map<const MachineInstr*, bool> lastUseMap;
+ std::vector<cycles_t> nodeDelayVec;
+ std::vector<cycles_t> earliestForNode;
cycles_t earliestReadyTime;
NodeHeap candsAsHeap; // candidate nodes, ready to go
- hash_set<const SchedGraphNode*> candsAsSet; // same entries as candsAsHeap,
+ std::hash_set<const SchedGraphNode*> candsAsSet;//same entries as candsAsHeap,
// but as set for fast lookup
- vector<candIndex> mcands; // holds pointers into cands
+ std::vector<candIndex> mcands; // holds pointers into cands
candIndex nextToTry; // next cand after the last
// one tried in this cycle
- int chooseByRule1 (vector<candIndex>& mcands);
- int chooseByRule2 (vector<candIndex>& mcands);
- int chooseByRule3 (vector<candIndex>& mcands);
+ int chooseByRule1 (std::vector<candIndex>& mcands);
+ int chooseByRule2 (std::vector<candIndex>& mcands);
+ int chooseByRule3 (std::vector<candIndex>& mcands);
- void findSetWithMaxDelay (vector<candIndex>& mcands,
+ void findSetWithMaxDelay (std::vector<candIndex>& mcands,
const SchedulingManager& S);
void computeDelays (const SchedGraph* graph);
};
-inline void
-SchedPriorities::insertReady(const SchedGraphNode* node)
-{
- candsAsHeap.insert(node, nodeDelayVec[node->getNodeId()]);
- candsAsSet.insert(node);
- mcands.clear(); // ensure reset choices is called before any more choices
- earliestReadyTime = min(earliestReadyTime,
- earliestForNode[node->getNodeId()]);
-
- if (SchedDebugLevel >= Sched_PrintSchedTrace)
- {
- cout << " Cycle " << this->getTime() << ": "
- << " Node " << node->getNodeId() << " is ready; "
- << " Delay = " << this->getNodeDelayRef(node) << "; Instruction: "
- << endl;
- cout << " " << *node->getMachineInstr() << endl;
- }
-}
-
inline void SchedPriorities::updateTime(cycles_t c) {
curTime = c;
nextToTry = candsAsHeap.begin();
mcands.clear();
}
-inline ostream& operator<< (ostream& os, const NodeDelayPair* nd) {
+inline std::ostream &operator<<(std::ostream &os, const NodeDelayPair* nd) {
return os << "Delay for node " << nd->node->getNodeId()
- << " = " << nd->delay << endl;
+ << " = " << (long)nd->delay << "\n";
}
-/***************************************************************************/
-
#endif
#include "llvm/BasicBlock.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "Support/STLExtras.h"
+#include <iostream>
+using std::cerr;
+using std::vector;
//------------------------------------------------------------------------
// class InstrTreeNode
InstructionNode::dumpNode(int indent) const
{
for (int i=0; i < indent; i++)
- cout << " ";
+ cerr << " ";
- cout << getInstruction()->getOpcodeName();
+ cerr << getInstruction()->getOpcodeName();
const vector<MachineInstr*> &mvec = getInstruction()->getMachineInstrVec();
if (mvec.size() > 0)
- cout << "\tMachine Instructions: ";
+ cerr << "\tMachine Instructions: ";
for (unsigned int i=0; i < mvec.size(); i++)
{
mvec[i]->dump(0);
if (i < mvec.size() - 1)
- cout << "; ";
+ cerr << "; ";
}
- cout << endl;
+ cerr << "\n";
}
VRegListNode::dumpNode(int indent) const
{
for (int i=0; i < indent; i++)
- cout << " ";
+ cerr << " ";
- cout << "List" << endl;
+ cerr << "List" << "\n";
}
VRegNode::dumpNode(int indent) const
{
for (int i=0; i < indent; i++)
- cout << " ";
+ cerr << " ";
- cout << "VReg " << getValue() << "\t(type "
- << (int) getValue()->getValueType() << ")" << endl;
+ cerr << "VReg " << getValue() << "\t(type "
+ << (int) getValue()->getValueType() << ")" << "\n";
}
void
ConstantNode::dumpNode(int indent) const
{
for (int i=0; i < indent; i++)
- cout << " ";
+ cerr << " ";
- cout << "Constant " << getValue() << "\t(type "
- << (int) getValue()->getValueType() << ")" << endl;
+ cerr << "Constant " << getValue() << "\t(type "
+ << (int) getValue()->getValueType() << ")" << "\n";
}
void
LabelNode::dumpNode(int indent) const
{
for (int i=0; i < indent; i++)
- cout << " ";
+ cerr << " ";
- cout << "Label " << getValue() << endl;
+ cerr << "Label " << getValue() << "\n";
}
//------------------------------------------------------------------------
InstrForest::~InstrForest()
{
- for (hash_map<const Instruction*, InstructionNode*>:: iterator I = begin();
+ for (std::hash_map<const Instruction*,InstructionNode*>::iterator I = begin();
I != end(); ++I)
delete (*I).second;
}
void
InstrForest::dump() const
{
- for (hash_set<InstructionNode*>::const_iterator I = treeRoots.begin();
+ for (std::hash_set<InstructionNode*>::const_iterator I = treeRoots.begin();
I != treeRoots.end(); ++I)
(*I)->dump(/*dumpChildren*/ 1, /*indent*/ 0);
}
#include "llvm/iPHINode.h"
#include "llvm/Target/MachineRegInfo.h"
#include "Support/CommandLine.h"
-#include <string.h>
-
+#include <iostream>
+using std::cerr;
//******************** Internal Data Declarations ************************/
if (SelectDebugLevel >= Select_DebugInstTrees)
{
- cout << "\n\n*** Instruction trees for method "
+ cerr << "\n\n*** Instruction trees for method "
<< (method->hasName()? method->getName() : "")
- << endl << endl;
+ << "\n\n";
instrForest.dump();
}
//
// Invoke BURG instruction selection for each tree
//
- const hash_set<InstructionNode*> &treeRoots = instrForest.getRootSet();
- for (hash_set<InstructionNode*>::const_iterator
+ const std::hash_set<InstructionNode*> &treeRoots = instrForest.getRootSet();
+ for (std::hash_set<InstructionNode*>::const_iterator
treeRootIter = treeRoots.begin(); treeRootIter != treeRoots.end();
++treeRootIter)
{
if (SelectDebugLevel >= Select_PrintMachineCode)
{
- cout << endl
- << "*** Machine instructions after INSTRUCTION SELECTION" << endl;
+ cerr << "\n*** Machine instructions after INSTRUCTION SELECTION\n";
MachineCodeForMethod::get(method).dump();
}
// insert the copy instruction to the predecessor BB
- vector<MachineInstr*> CopyInstVec;
+ std::vector<MachineInstr*> CopyInstVec;
MachineInstr *CpMI =
target.getRegInfo().cpValue2Value(PN->getIncomingValue(i), PN);
PHINode *PN = (PHINode *) (*IIt);
- Value *PhiCpRes = new Value(PN->getType(), PN->getValueType());
-
- string *Name = new string("PhiCp:");
- (*Name) += (int) PhiCpRes;
- PhiCpRes->setName( *Name );
-
+ Value *PhiCpRes = new Value(PN->getType(), PN->getValueType(),"PhiCp:");
// for each incoming value of the phi, insert phi elimination
//
for (unsigned i = 0; i < PN->getNumIncomingValues(); ++i) {
// insert the copy instruction to the predecessor BB
-
MachineInstr *CpMI =
target.getRegInfo().cpValue2Value(PN->getIncomingValue(i),
PhiCpRes);
InsertPhiElimInst(PN->getIncomingBlock(i), CpMI);
-
}
MachineCodeForBasicBlock& bbMvec = BB->getMachineInstrVec();
bbMvec.insert( bbMvec.begin(), CpMI2);
-
-
}
else break; // since PHI nodes can only be at the top
MachineCodeForVMInstr& mvec = vmInstr->getMachineInstrVec();
for (int i = (int) mvec.size()-1; i >= 0; i--)
{
- vector<MachineInstr*> loadConstVec =
+ std::vector<MachineInstr*> loadConstVec =
FixConstantOperandsForInstr(vmInstr, mvec[i], target);
if (loadConstVec.size() > 0)
if (ruleForNode == 0)
{
- cerr << "Could not match instruction tree for instr selection" << endl;
+ cerr << "Could not match instruction tree for instr selection\n";
assert(0);
return true;
}
#include "llvm/Instruction.h"
#include "llvm/Type.h"
#include "llvm/iMemory.h"
-
+using std::vector;
//*************************** Local Functions ******************************/
#include "llvm/Method.h"
#include "llvm/iOther.h"
#include "llvm/Instruction.h"
+#include <iostream>
+using std::cerr;
AnnotationID MachineCodeForMethod::AID(
AnnotationManager::getID("MachineCodeForMethodAnnotation"));
MachineInstr::dump(unsigned int indent) const
{
for (unsigned i=0; i < indent; i++)
- cout << " ";
+ cerr << " ";
- cout << *this;
+ cerr << *this;
}
-ostream&
-operator<< (ostream& os, const MachineInstr& minstr)
+std::ostream &operator<<(std::ostream& os, const MachineInstr& minstr)
{
os << TargetInstrDescriptors[minstr.opCode].opCodeString;
#undef DEBUG_VAL_OP_ITERATOR
#ifdef DEBUG_VAL_OP_ITERATOR
- os << endl << "\tValue operands are: ";
+ os << "\n\tValue operands are: ";
for (MachineInstr::val_const_op_iterator vo(&minstr); ! vo.done(); ++vo)
{
const Value* val = *vo;
}
#endif
-
-
- os << endl;
-
- return os;
+ return os << "\n";
}
-static inline ostream&
-OutputOperand(ostream &os, const MachineOperand &mop)
+static inline std::ostream &OutputOperand(std::ostream &os,
+ const MachineOperand &mop)
{
Value* val;
switch (mop.getOperandType())
val = mop.getVRegValue();
os << "(val ";
if (val && val->hasName())
- os << val->getName().c_str();
+ os << val->getName();
else
os << val;
return os << ")";
}
-ostream&
-operator<<(ostream &os, const MachineOperand &mop)
+std::ostream &operator<<(std::ostream &os, const MachineOperand &mop)
{
switch(mop.opType)
{
os << "%ccreg";
return OutputOperand(os, mop);
case MachineOperand::MO_SignExtendedImmed:
- return os << mop.immedVal;
+ return os << (long)mop.immedVal;
case MachineOperand::MO_UnextendedImmed:
- return os << mop.immedVal;
+ return os << (long)mop.immedVal;
case MachineOperand::MO_PCRelativeDisp:
{
const Value* opVal = mop.getVRegValue();
bool isLabel = isa<Method>(opVal) || isa<BasicBlock>(opVal);
os << "%disp(" << (isLabel? "label " : "addr-of-val ");
if (opVal->hasName())
- os << opVal->getName().c_str();
+ os << opVal->getName();
else
os << opVal;
return os << ")";
size += align - mod;
}
- offset = growUp? firstTmpOffset + offset
- : firstTmpOffset - offset;
+ offset = growUp ? firstTmpOffset + offset : firstTmpOffset - offset;
currentTmpValuesSize += size;
return offset;
int
MachineCodeForMethod::getOffset(const Value* val) const
{
- hash_map<const Value*, int>::const_iterator pair = offsets.find(val);
- return (pair == offsets.end())? INVALID_FRAME_OFFSET : (*pair).second;
+ std::hash_map<const Value*, int>::const_iterator pair = offsets.find(val);
+ return (pair == offsets.end())? INVALID_FRAME_OFFSET : pair->second;
}
void
MachineCodeForMethod::dump() const
{
- cout << "\n" << method->getReturnType()
- << " \"" << method->getName() << "\"" << endl;
+ cerr << "\n" << method->getReturnType()
+ << " \"" << method->getName() << "\"\n";
for (Method::const_iterator BI = method->begin(); BI != method->end(); ++BI)
{
BasicBlock* bb = *BI;
- cout << "\n"
+ cerr << "\n"
<< (bb->hasName()? bb->getName() : "Label")
- << " (" << bb << ")" << ":"
- << endl;
+ << " (" << bb << ")" << ":\n";
MachineCodeForBasicBlock& mvec = bb->getMachineInstrVec();
for (unsigned i=0; i < mvec.size(); i++)
- cout << "\t" << *mvec[i];
+ cerr << "\t" << *mvec[i];
}
- cout << endl << "End method \"" << method->getName() << "\""
- << endl << endl;
+ cerr << "\nEnd method \"" << method->getName() << "\"\n\n";
}
#include "llvm/CodeGen/IGNode.h"
-
+#include <algorithm>
+#include <iostream>
+using std::cerr;
//-----------------------------------------------------------------------------
// Constructor
//-----------------------------------------------------------------------------
-IGNode::IGNode(LiveRange *const PLR, unsigned int Ind): Index(Ind),
- AdjList(),
- ParentLR(PLR)
+IGNode::IGNode(LiveRange *const PLR, unsigned int Ind) : Index(Ind),
+ ParentLR(PLR)
{
OnStack = false;
CurDegree = -1 ;
int neighs = AdjList.size();
if( neighs < 0) {
- cout << "\nAdj List size = " << neighs;
+ cerr << "\nAdj List size = " << neighs;
assert(0 && "Invalid adj list size");
}
- for(int i=0; i < neighs; i++) (AdjList[i])->decCurDegree();
+ for(int i=0; i < neighs; i++)
+ AdjList[i]->decCurDegree();
}
//-----------------------------------------------------------------------------
// two IGNodes together.
//-----------------------------------------------------------------------------
void IGNode::delAdjIGNode(const IGNode *const Node) {
- vector <IGNode *>::iterator It = AdjList.begin();
-
- // find Node
- for( ; It != AdjList.end() && (*It != Node); It++ ) ;
+ std::vector<IGNode *>::iterator It =
+ find(AdjList.begin(), AdjList.end(), Node);
assert( It != AdjList.end() ); // the node must be there
-
- AdjList.erase( It );
+
+ AdjList.erase(It);
}
#include "llvm/CodeGen/RegAllocCommon.h"
#include "llvm/CodeGen/LiveRange.h"
-
-
//----------------------------------------------------------------------------
// Class IGNode
//
class IGNode
{
- private:
-
const int Index; // index within IGNodeList
bool OnStack; // this has been pushed on to stack for coloring
- vector<IGNode *> AdjList; // adjacency list for this live range
+ std::vector<IGNode *> AdjList; // adjacency list for this live range
int CurDegree;
//
// Decremented when a neighbor is pushed on to the stack.
// After that, never incremented/set again nor used.
-
LiveRange *const ParentLR; // parent LR (cannot be a const)
};
-
-
-
-
-
-
#endif
#include "llvm/CodeGen/InterferenceGraph.h"
+#include "Support/STLExtras.h"
+#include <iostream>
+using std::cerr;
//-----------------------------------------------------------------------------
// Constructor: Records the RegClass and initalizes IGNodeList.
IG = NULL;
Size = 0;
if( DEBUG_RA) {
- cout << "Interference graph created!" << endl;
+ cerr << "Interference graph created!\n";
}
}
InterferenceGraph:: ~InterferenceGraph() {
// delete the matrix
- //
- if( IG )
- delete []IG;
+ for(unsigned int r=0; r < IGNodeList.size(); ++r)
+ delete[] IG[r];
+ delete[] IG;
// delete all IGNodes in the IGNodeList
- //
- vector<IGNode *>::const_iterator IGIt = IGNodeList.begin();
- for(unsigned i=0; i < IGNodeList.size() ; ++i) {
-
- const IGNode *const Node = IGNodeList[i];
- if( Node ) delete Node;
- }
-
+ for_each(IGNodeList.begin(), IGNodeList.end(), deleter<IGNode>);
}
void InterferenceGraph::createGraph()
{
Size = IGNodeList.size();
- IG = (char **) new char *[Size];
+ IG = new char*[Size];
for( unsigned int r=0; r < Size; ++r)
IG[r] = new char[Size];
// init IG matrix
for(unsigned int i=0; i < Size; i++)
- for( unsigned int j=0; j < Size ; j++)
+ for(unsigned int j=0; j < Size; j++)
IG[i][j] = 0;
}
//-----------------------------------------------------------------------------
void InterferenceGraph::addLRToIG(LiveRange *const LR)
{
- IGNode *Node = new IGNode(LR, IGNodeList.size() );
- IGNodeList.push_back( Node );
-
+ IGNodeList.push_back(new IGNode(LR, IGNodeList.size()));
}
char *val;
if( DEBUG_RA > 1)
- cout << "setting intf for: [" << row << "][" << col << "]" << endl;
+ cerr << "setting intf for: [" << row << "][" << col << "]\n";
( row > col) ? val = &IG[row][col]: val = &IG[col][row];
if( ! (*val) ) { // if this interf is not previously set
-
*val = 1; // add edges between nodes
IGNode1->addAdjIGNode( IGNode2 );
IGNode2->addAdjIGNode( IGNode1 );
const unsigned int col = LR2->getUserIGNode()->getIndex();
char ret;
- ( row > col) ? (ret = IG[row][col]) : (ret = IG[col][row]) ;
+ if (row > col)
+ ret = IG[row][col];
+ else
+ ret = IG[col][row];
return ret;
}
assertIGNode( SrcNode );
if( DEBUG_RA > 1) {
- cout << "Merging LRs: \""; LR1->printSet();
- cout << "\" and \""; LR2->printSet();
- cout << "\"" << endl;
+ cerr << "Merging LRs: \""; LR1->printSet();
+ cerr << "\" and \""; LR2->printSet();
+ cerr << "\"\n";
}
unsigned SrcDegree = SrcNode->getNumOfNeighbors();
for(unsigned int i=0; i < Size; i++) {
const IGNode *const Node = IGNodeList[i];
- if( ! Node )
- continue; // skip empty rows
-
- cout << " [" << i << "] ";
+ if(Node) {
+ cerr << " [" << i << "] ";
- for( unsigned int j=0; j < Size; j++) {
- if( j >= i) break;
- if( IG[i][j] ) cout << "(" << i << "," << j << ") ";
+ for( unsigned int j=0; j < i; j++) {
+ if(IG[i][j])
+ cerr << "(" << i << "," << j << ") ";
}
- cout << endl;
+ cerr << "\n";
}
+ }
}
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
void InterferenceGraph::printIGNodeList() const
{
- vector<IGNode *>::const_iterator IGIt = IGNodeList.begin(); // hash map iter
-
for(unsigned i=0; i < IGNodeList.size() ; ++i) {
-
const IGNode *const Node = IGNodeList[i];
- if( ! Node )
- continue;
-
- cout << " [" << Node->getIndex() << "] ";
- (Node->getParentLR())->printSet();
- //int Deg = Node->getCurDegree();
- cout << "\t <# of Neighs: " << Node->getNumOfNeighbors() << ">" << endl;
-
+ if (Node) {
+ cerr << " [" << Node->getIndex() << "] ";
+ Node->getParentLR()->printSet();
+ //int Deg = Node->getCurDegree();
+ cerr << "\t <# of Neighs: " << Node->getNumOfNeighbors() << ">\n";
+ }
}
}
-
-
-/* Title: InterferenceGraph.h
+/* Title: InterferenceGraph.h -*- C++ -*-
Author: Ruchira Sasanka
Date: July 20, 01
Purpose: Interference Graph used for register coloring.
#include "llvm/CodeGen/IGNode.h"
-typedef vector <IGNode *> IGNodeListType;
+typedef std::vector <IGNode *> IGNodeListType;
class InterferenceGraph
// to create it after adding all IGNodes to the IGNodeList
InterferenceGraph(RegClass *const RC);
+ ~InterferenceGraph();
+
void createGraph();
void addLRToIG(LiveRange *const LR);
void printIG() const;
void printIGNodeList() const;
-
- ~InterferenceGraph();
-
-
};
-
#endif
-
-/* Title: LiveRange.h
+/* Title: LiveRange.h -*- C++ -*-
Author: Ruchira Sasanka
Date: July 25, 01
Purpose: To keep info about a live range.
#include "llvm/Analysis/LiveVar/ValueSet.h"
#include "llvm/Type.h"
+#include <iostream>
class RegClass;
class IGNode;
if(SuggestedColor == -1 )
SuggestedColor = Col;
else if (DEBUG_RA)
- cerr << "Already has a suggested color " << Col << endl;
+ std::cerr << "Already has a suggested color " << Col << "\n";
}
inline unsigned getSuggestedColor() const {
#include "llvm/CodeGen/LiveRangeInfo.h"
+#include <iostream>
+using std::cerr;
//---------------------------------------------------------------------------
// Constructor
//---------------------------------------------------------------------------
LiveRangeInfo::LiveRangeInfo(const Method *const M,
const TargetMachine& tm,
- vector<RegClass *> &RCL)
- : Meth(M), LiveRangeMap(),
- TM(tm), RegClassList(RCL),
- MRI( tm.getRegInfo()),
- CallRetInstrList()
+ std::vector<RegClass *> &RCL)
+ : Meth(M), LiveRangeMap(), TM(tm),
+ RegClassList(RCL), MRI(tm.getRegInfo())
{ }
// Destructor: Deletes all LiveRanges in the LiveRangeMap
//---------------------------------------------------------------------------
LiveRangeInfo::~LiveRangeInfo() {
-
LiveRangeMapType::iterator MI = LiveRangeMap.begin();
for( ; MI != LiveRangeMap.end() ; ++MI) {
- if( (*MI).first ) {
-
- LiveRange *LR = (*MI).second;
-
- if( LR ) {
-
- // we need to be careful in deleting LiveRanges in LiveRangeMap
- // since two/more Values in the live range map can point to the same
- // live range. We have to make the other entries NULL when we delete
- // a live range.
-
- LiveRange::iterator LI = LR->begin();
-
- for( ; LI != LR->end() ; ++LI) {
- LiveRangeMap[*LI] = NULL;
- }
+ if (MI->first && MI->second) {
+ LiveRange *LR = MI->second;
- delete LR;
+ // we need to be careful in deleting LiveRanges in LiveRangeMap
+ // since two/more Values in the live range map can point to the same
+ // live range. We have to make the other entries NULL when we delete
+ // a live range.
- }
+ LiveRange::iterator LI = LR->begin();
+
+ for( ; LI != LR->end() ; ++LI)
+ LiveRangeMap[*LI] = 0;
+
+ delete LR;
}
}
-
}
L1->addSpillCost( L2->getSpillCost() ); // add the spill costs
- delete ( L2 ); // delete L2 as it is no longer needed
+ delete L2; // delete L2 as it is no longer needed
}
{
if( DEBUG_RA)
- cout << "Consturcting Live Ranges ..." << endl;
+ cerr << "Consturcting Live Ranges ...\n";
// first find the live ranges for all incoming args of the method since
// those LRs start from the start of the method
for( ; ArgIt != ArgList.end() ; ++ArgIt) { // for each argument
-
LiveRange * ArgRange = new LiveRange(); // creates a new LR and
const Value *const Val = (const Value *) *ArgIt;
assert( Val);
- ArgRange->add( Val ); // add the arg (def) to it
- LiveRangeMap[ Val ] = ArgRange;
+ ArgRange->add(Val); // add the arg (def) to it
+ LiveRangeMap[Val] = ArgRange;
// create a temp machine op to find the register class of value
//const MachineOperand Op(MachineOperand::MO_VirtualRegister);
if( DEBUG_RA > 1) {
- cout << " adding LiveRange for argument ";
- printValue( (const Value *) *ArgIt); cout << endl;
+ cerr << " adding LiveRange for argument ";
+ printValue((const Value *) *ArgIt); cerr << "\n";
}
}
Method::const_iterator BBI = Meth->begin(); // random iterator for BBs
-
for( ; BBI != Meth->end(); ++BBI) { // go thru BBs in random order
// Now find all LRs for machine the instructions. A new LR will be created
// get the iterator for machine instructions
const MachineCodeForBasicBlock& MIVec = (*BBI)->getMachineInstrVec();
- MachineCodeForBasicBlock::const_iterator
- MInstIterator = MIVec.begin();
+ MachineCodeForBasicBlock::const_iterator MInstIterator = MIVec.begin();
// iterate over all the machine instructions in BB
for( ; MInstIterator != MIVec.end(); MInstIterator++) {
// Now if the machine instruction is a call/return instruction,
// add it to CallRetInstrList for processing its implicit operands
- if( (TM.getInstrInfo()).isReturn( MInst->getOpCode()) ||
- (TM.getInstrInfo()).isCall( MInst->getOpCode()) )
+ if(TM.getInstrInfo().isReturn(MInst->getOpCode()) ||
+ TM.getInstrInfo().isCall(MInst->getOpCode()))
CallRetInstrList.push_back( MInst );
// iterate over MI operands to find defs
- for( MachineInstr::val_const_op_iterator OpI(MInst);!OpI.done(); ++OpI) {
-
- if( DEBUG_RA) {
+ for (MachineInstr::val_const_op_iterator OpI(MInst); !OpI.done(); ++OpI) {
+ if(DEBUG_RA) {
MachineOperand::MachineOperandType OpTyp =
OpI.getMachineOperand().getOperandType();
- if ( OpTyp == MachineOperand::MO_CCRegister) {
- cout << "\n**CC reg found. Is Def=" << OpI.isDef() << " Val:";
+ if (OpTyp == MachineOperand::MO_CCRegister) {
+ cerr << "\n**CC reg found. Is Def=" << OpI.isDef() << " Val:";
printValue( OpI.getMachineOperand().getVRegValue() );
- cout << endl;
+ cerr << "\n";
}
}
// create a new LR iff this operand is a def
if( OpI.isDef() ) {
-
const Value *const Def = *OpI;
-
// Only instruction values are accepted for live ranges here
-
if( Def->getValueType() != Value::InstructionVal ) {
- cout << "\n**%%Error: Def is not an instruction val. Def=";
- printValue( Def ); cout << endl;
+ cerr << "\n**%%Error: Def is not an instruction val. Def=";
+ printValue( Def ); cerr << "\n";
continue;
}
-
LiveRange *DefRange = LiveRangeMap[Def];
// see LR already there (because of multiple defs)
-
if( !DefRange) { // if it is not in LiveRangeMap
-
DefRange = new LiveRange(); // creates a new live range and
DefRange->add( Def ); // add the instruction (def) to it
LiveRangeMap[ Def ] = DefRange; // update the map
if( DEBUG_RA > 1) {
- cout << " creating a LR for def: ";
- printValue(Def); cout << endl;
+ cerr << " creating a LR for def: ";
+ printValue(Def); cerr << "\n";
}
// set the register class of the new live range
if(isCC && DEBUG_RA) {
- cout << "\a**created a LR for a CC reg:";
+ cerr << "\a**created a LR for a CC reg:";
printValue( OpI.getMachineOperand().getVRegValue() );
}
LiveRangeMap[ Def ] = DefRange;
if( DEBUG_RA > 1) {
- cout << " added to an existing LR for def: ";
- printValue( Def ); cout << endl;
+ cerr << " added to an existing LR for def: ";
+ printValue( Def ); cerr << "\n";
}
}
suggestRegs4CallRets();
if( DEBUG_RA)
- cout << "Initial Live Ranges constructed!" << endl;
+ cerr << "Initial Live Ranges constructed!\n";
}
//---------------------------------------------------------------------------
void LiveRangeInfo::coalesceLRs()
{
-
-
-
if( DEBUG_RA)
- cout << endl << "Coalscing LRs ..." << endl;
+ cerr << "\nCoalscing LRs ...\n";
Method::const_iterator BBI = Meth->begin(); // random iterator for BBs
// get the iterator for machine instructions
const MachineCodeForBasicBlock& MIVec = (*BBI)->getMachineInstrVec();
- MachineCodeForBasicBlock::const_iterator
- MInstIterator = MIVec.begin();
+ MachineCodeForBasicBlock::const_iterator MInstIterator = MIVec.begin();
// iterate over all the machine instructions in BB
for( ; MInstIterator != MIVec.end(); ++MInstIterator) {
const MachineInstr * MInst = *MInstIterator;
if( DEBUG_RA > 1) {
- cout << " *Iterating over machine instr ";
+ cerr << " *Iterating over machine instr ";
MInst->dump();
- cout << endl;
+ cerr << "\n";
}
//don't warn about labels
if (!((*UseI)->getType())->isLabelType() && DEBUG_RA) {
- cout<<" !! Warning: No LR for use "; printValue(*UseI);
- cout << endl;
+ cerr<<" !! Warning: No LR for use "; printValue(*UseI);
+ cerr << "\n";
}
continue; // ignore and continue
}
} // for all BBs
if( DEBUG_RA)
- cout << endl << "Coalscing Done!" << endl;
+ cerr << "\nCoalscing Done!\n";
}
void LiveRangeInfo::printLiveRanges()
{
LiveRangeMapType::iterator HMI = LiveRangeMap.begin(); // hash map iterator
- cout << endl << "Printing Live Ranges from Hash Map:" << endl;
- for( ; HMI != LiveRangeMap.end() ; HMI ++ ) {
- if( (*HMI).first && (*HMI).second ) {
- cout <<" "; printValue((*HMI).first); cout << "\t: ";
- ((*HMI).second)->printSet(); cout << endl;
+ cerr << "\nPrinting Live Ranges from Hash Map:\n";
+ for( ; HMI != LiveRangeMap.end() ; ++HMI) {
+ if( HMI->first && HMI->second ) {
+ cerr <<" "; printValue((*HMI).first); cerr << "\t: ";
+ HMI->second->printSet(); cerr << "\n";
}
}
}
-/* Title: LiveRangeInfo.h
+/* Title: LiveRangeInfo.h -*- C++ -*-
Author: Ruchira Sasanka
Date: Jun 30, 01
Purpose:
#include "llvm/CodeGen/RegClass.h"
-typedef hash_map <const Value *, LiveRange *, hashFuncValue> LiveRangeMapType;
-typedef vector <const MachineInstr *> CallRetInstrListType;
+typedef std::hash_map<const Value*, LiveRange*> LiveRangeMapType;
+typedef std::vector<const MachineInstr*> CallRetInstrListType;
const TargetMachine& TM; // target machine description
- vector<RegClass *> & RegClassList;// a vector containing register classess
+ std::vector<RegClass *> & RegClassList;// vector containing register classess
const MachineRegInfo& MRI; // machine reg info
LiveRangeInfo(const Method *const M,
const TargetMachine& tm,
- vector<RegClass *> & RCList);
+ std::vector<RegClass *> & RCList);
// Destructor to destroy all LiveRanges in the LiveRange Map
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/MachineFrameInfo.h"
+#include <iostream>
#include <math.h>
+using std::cerr;
// ***TODO: There are several places we add instructions. Validate the order
PhyRegAlloc::PhyRegAlloc(Method *M,
const TargetMachine& tm,
MethodLiveVarInfo *const Lvi)
- : RegClassList(),
- TM(tm),
- Meth(M),
+ : TM(tm), Meth(M),
mcInfo(MachineCodeForMethod::get(M)),
LVI(Lvi), LRI(M, tm, RegClassList),
MRI( tm.getRegInfo() ),
NumOfRegClasses(MRI.getNumOfRegClasses()),
- AddedInstrMap(), LoopDepthCalc(M), ResColList() {
+ LoopDepthCalc(M) {
// create each RegisterClass and put in RegClassList
//
- for( unsigned int rc=0; rc < NumOfRegClasses; rc++)
+ for(unsigned int rc=0; rc < NumOfRegClasses; rc++)
RegClassList.push_back( new RegClass(M, MRI.getMachineRegClass(rc),
&ResColList) );
}
//----------------------------------------------------------------------------
void PhyRegAlloc::createIGNodeListsAndIGs()
{
- if(DEBUG_RA ) cout << "Creating LR lists ..." << endl;
+ if(DEBUG_RA ) cerr << "Creating LR lists ...\n";
// hash map iterator
LiveRangeMapType::const_iterator HMI = (LRI.getLiveRangeMap())->begin();
if( !L) {
if( DEBUG_RA) {
- cout << "\n*?!?Warning: Null liver range found for: ";
- printValue( (*HMI).first) ; cout << endl;
+ cerr << "\n*?!?Warning: Null liver range found for: ";
+ printValue(HMI->first); cerr << "\n";
}
continue;
}
RegClassList[ rc ]->createInterferenceGraph();
if( DEBUG_RA)
- cout << "LRLists Created!" << endl;
+ cerr << "LRLists Created!\n";
}
for( ; LIt != LVSet->end(); ++LIt) {
if( DEBUG_RA > 1) {
- cout << "< Def="; printValue(Def);
- cout << ", Lvar="; printValue( *LIt); cout << "> ";
+ cerr << "< Def="; printValue(Def);
+ cerr << ", Lvar="; printValue( *LIt); cerr << "> ";
}
// get the live range corresponding to live var
else if(DEBUG_RA > 1) {
// we will not have LRs for values not explicitly allocated in the
// instruction stream (e.g., constants)
- cout << " warning: no live range for " ;
- printValue( *LIt); cout << endl; }
+ cerr << " warning: no live range for " ;
+ printValue(*LIt); cerr << "\n"; }
}
}
if( DEBUG_RA)
- cout << "\n For call inst: " << *MInst;
+ cerr << "\n For call inst: " << *MInst;
LiveVarSet::const_iterator LIt = LVSetAft->begin();
LiveRange *const LR = LRI.getLiveRangeForValue(*LIt );
if( LR && DEBUG_RA) {
- cout << "\n\tLR Aft Call: ";
+ cerr << "\n\tLR Aft Call: ";
LR->printSet();
}
if( LR && (LR != RetValLR) ) {
LR->setCallInterference();
if( DEBUG_RA) {
- cout << "\n ++Added call interf for LR: " ;
+ cerr << "\n ++Added call interf for LR: " ;
LR->printSet();
}
}
void PhyRegAlloc::buildInterferenceGraphs()
{
- if(DEBUG_RA) cout << "Creating interference graphs ..." << endl;
+ if(DEBUG_RA) cerr << "Creating interference graphs ...\n";
unsigned BBLoopDepthCost;
Method::const_iterator BBI = Meth->begin(); // random iterator for BBs
addInterferencesForArgs();
if( DEBUG_RA)
- cout << "Interference graphs calculted!" << endl;
+ cerr << "Interference graphs calculted!\n";
}
addInterference( *ArgIt, InSet, false ); // add interferences between
// args and LVars at start
if( DEBUG_RA > 1) {
- cout << " - %% adding interference for argument ";
- printValue( (const Value *) *ArgIt); cout << endl;
+ cerr << " - %% adding interference for argument ";
+ printValue((const Value *)*ArgIt); cerr << "\n";
}
}
}
// delete this condition checking later (must assert if Val is null)
if( !Val) {
if (DEBUG_RA)
- cout << "Warning: NULL Value found for operand" << endl;
+ cerr << "Warning: NULL Value found for operand\n";
continue;
}
assert( Val && "Value is NULL");
// nothing to worry if it's a const or a label
if (DEBUG_RA) {
- cout << "*NO LR for operand : " << Op ;
- cout << " [reg:" << Op.getAllocatedRegNum() << "]";
- cout << " in inst:\t" << *MInst << endl;
+ cerr << "*NO LR for operand : " << Op ;
+ cerr << " [reg:" << Op.getAllocatedRegNum() << "]";
+ cerr << " in inst:\t" << *MInst << "\n";
}
// if register is not allocated, mark register as invalid
// instruction, add them now.
//
if( AddedInstrMap[ MInst ] ) {
-
- deque<MachineInstr *> &IBef = (AddedInstrMap[MInst])->InstrnsBefore;
+ std::deque<MachineInstr *> &IBef = AddedInstrMap[MInst]->InstrnsBefore;
if( ! IBef.empty() ) {
-
- deque<MachineInstr *>::iterator AdIt;
+ std::deque<MachineInstr *>::iterator AdIt;
for( AdIt = IBef.begin(); AdIt != IBef.end() ; ++AdIt ) {
if( DEBUG_RA) {
cerr << "For inst " << *MInst;
- cerr << " PREPENDed instr: " << **AdIt << endl;
+ cerr << " PREPENDed instr: " << **AdIt << "\n";
}
MInstIterator = MIVec.insert( MInstIterator, *AdIt );
if((delay=TM.getInstrInfo().getNumDelaySlots(MInst->getOpCode())) >0){
move2DelayedInstr(MInst, *(MInstIterator+delay) );
- if(DEBUG_RA) cout<< "\nMoved an added instr after the delay slot";
+ if(DEBUG_RA) cerr<< "\nMoved an added instr after the delay slot";
}
else {
// Here we can add the "instructions after" to the current
// instruction since there are no delay slots for this instruction
- deque<MachineInstr *> &IAft = (AddedInstrMap[MInst])->InstrnsAfter;
+ std::deque<MachineInstr *> &IAft = AddedInstrMap[MInst]->InstrnsAfter;
if( ! IAft.empty() ) {
- deque<MachineInstr *>::iterator AdIt;
+ std::deque<MachineInstr *>::iterator AdIt;
++MInstIterator; // advance to the next instruction
if(DEBUG_RA) {
cerr << "For inst " << *MInst;
- cerr << " APPENDed instr: " << **AdIt << endl;
+ cerr << " APPENDed instr: " << **AdIt << "\n";
}
MInstIterator = MIVec.insert( MInstIterator, *AdIt );
RegClass *RC = LR->getRegClass();
const LiveVarSet *LVSetBef = LVI->getLiveVarSetBeforeMInst(MInst, BB);
-
- int TmpOff =
- mcInfo.pushTempValue(TM, MRI.getSpilledRegSize(RegType) );
+ mcInfo.pushTempValue(TM, MRI.getSpilledRegSize(RegType) );
MachineInstr *MIBef=NULL, *AdIMid=NULL, *MIAft=NULL;
return MRI.getUnifiedRegNum(RC->getID(), c);
else
assert( 0 && "FATAL: No free register could be found in reg class!!");
-
+ return 0;
}
-
-
-
//----------------------------------------------------------------------------
// This method modifies the IsColorUsedArr of the register class passed to it.
// It sets the bits corresponding to the registers used by this machine
LiveRange *const LRofImpRef =
LRI.getLiveRangeForValue( MInst->getImplicitRef(z) );
-
- if( LRofImpRef )
- if( LRofImpRef->hasColor() )
- IsColorUsedArr[ LRofImpRef->getColor() ] = true;
+
+ if(LRofImpRef && LRofImpRef->hasColor())
+ IsColorUsedArr[LRofImpRef->getColor()] = true;
}
-
-
-
}
void PhyRegAlloc:: move2DelayedInstr(const MachineInstr *OrigMI,
const MachineInstr *DelayedMI) {
-
// "added after" instructions of the original instr
- deque<MachineInstr *> &OrigAft = (AddedInstrMap[OrigMI])->InstrnsAfter;
+ std::deque<MachineInstr *> &OrigAft = AddedInstrMap[OrigMI]->InstrnsAfter;
// "added instructions" of the delayed instr
AddedInstrns *DelayAdI = AddedInstrMap[DelayedMI];
}
// "added after" instructions of the delayed instr
- deque<MachineInstr *> &DelayedAft = DelayAdI->InstrnsAfter;
+ std::deque<MachineInstr *> &DelayedAft = DelayAdI->InstrnsAfter;
// go thru all the "added after instructions" of the original instruction
// and append them to the "addded after instructions" of the delayed
// instructions
-
- deque<MachineInstr *>::iterator OrigAdIt;
-
- for( OrigAdIt = OrigAft.begin(); OrigAdIt != OrigAft.end() ; ++OrigAdIt ) {
- DelayedAft.push_back( *OrigAdIt );
- }
+ DelayedAft.insert(DelayedAft.end(), OrigAft.begin(), OrigAft.end());
// empty the "added after instructions" of the original instruction
OrigAft.clear();
-
}
//----------------------------------------------------------------------------
void PhyRegAlloc::printMachineCode()
{
- cout << endl << ";************** Method ";
- cout << Meth->getName() << " *****************" << endl;
+ cerr << "\n;************** Method " << Meth->getName()
+ << " *****************\n";
Method::const_iterator BBI = Meth->begin(); // random iterator for BBs
for( ; BBI != Meth->end(); ++BBI) { // traverse BBs in random order
- cout << endl ; printLabel( *BBI); cout << ": ";
+ cerr << "\n"; printLabel( *BBI); cerr << ": ";
// get the iterator for machine instructions
MachineCodeForBasicBlock& MIVec = (*BBI)->getMachineInstrVec();
MachineInstr *const MInst = *MInstIterator;
- cout << endl << "\t";
- cout << TargetInstrDescriptors[MInst->getOpCode()].opCodeString;
+ cerr << "\n\t";
+ cerr << TargetInstrDescriptors[MInst->getOpCode()].opCodeString;
//for(MachineInstr::val_const_op_iterator OpI(MInst);!OpI.done();++OpI) {
const Value *const Val = Op.getVRegValue () ;
// ****this code is temporary till NULL Values are fixed
if( ! Val ) {
- cout << "\t<*NULL*>";
+ cerr << "\t<*NULL*>";
continue;
}
// if a label or a constant
- if( (Val->getValueType() == Value::BasicBlockVal) ) {
-
- cout << "\t"; printLabel( Op.getVRegValue () );
- }
- else {
+ if(isa<BasicBlock>(Val) {
+ cerr << "\t"; printLabel( Op.getVRegValue () );
+ } else {
// else it must be a register value
const int RegNum = Op.getAllocatedRegNum();
- cout << "\t" << "%" << MRI.getUnifiedRegName( RegNum );
+ cerr << "\t" << "%" << MRI.getUnifiedRegName( RegNum );
if (Val->hasName() )
- cout << "(" << Val->getName() << ")";
+ cerr << "(" << Val->getName() << ")";
else
- cout << "(" << Val << ")";
+ cerr << "(" << Val << ")";
if( Op.opIsDef() )
- cout << "*";
+ cerr << "*";
const LiveRange *LROfVal = LRI.getLiveRangeForValue(Val);
if( LROfVal )
if( LROfVal->hasSpillOffset() )
- cout << "$";
+ cerr << "$";
}
}
else if(Op.getOperandType() == MachineOperand::MO_MachineRegister) {
- cout << "\t" << "%" << MRI.getUnifiedRegName(Op.getMachineRegNum());
+ cerr << "\t" << "%" << MRI.getUnifiedRegName(Op.getMachineRegNum());
}
else
- cout << "\t" << Op; // use dump field
+ cerr << "\t" << Op; // use dump field
}
unsigned NumOfImpRefs = MInst->getNumImplicitRefs();
if( NumOfImpRefs > 0 ) {
- cout << "\tImplicit:";
+ cerr << "\tImplicit:";
for(unsigned z=0; z < NumOfImpRefs; z++) {
printValue( MInst->getImplicitRef(z) );
- cout << "\t";
+ cerr << "\t";
}
}
} // for all machine instructions
-
- cout << endl;
+ cerr << "\n";
} // for all BBs
- cout << endl;
+ cerr << "\n";
}
assert( FirstMI && "No machine instruction in entry BB");
AddedInstrns *AI = AddedInstrMap[ FirstMI ];
- if ( !AI ) {
+ if (!AI) {
AI = new AddedInstrns();
- AddedInstrMap[ FirstMI ] = AI;
+ AddedInstrMap[FirstMI] = AI;
}
MRI.colorMethodArgs(Meth, LRI, AI );
//----------------------------------------------------------------------------
// Used to generate a label for a basic block
//----------------------------------------------------------------------------
-void PhyRegAlloc::printLabel(const Value *const Val)
-{
- if( Val->hasName() )
- cout << Val->getName();
+void PhyRegAlloc::printLabel(const Value *const Val) {
+ if (Val->hasName())
+ cerr << Val->getName();
else
- cout << "Label" << Val;
+ cerr << "Label" << Val;
}
void PhyRegAlloc::markUnusableSugColors()
{
- if(DEBUG_RA ) cout << "\nmarking unusable suggested colors ..." << endl;
+ if(DEBUG_RA ) cerr << "\nmarking unusable suggested colors ...\n";
// hash map iterator
LiveRangeMapType::const_iterator HMI = (LRI.getLiveRangeMap())->begin();
void PhyRegAlloc::allocateStackSpace4SpilledLRs()
{
- if(DEBUG_RA ) cout << "\nsetting LR stack offsets ..." << endl;
+ if(DEBUG_RA ) cerr << "\nsetting LR stack offsets ...\n";
// hash map iterator
LiveRangeMapType::const_iterator HMI = (LRI.getLiveRangeMap())->begin();
LiveRangeMapType::const_iterator HMIEnd = (LRI.getLiveRangeMap())->end();
for( ; HMI != HMIEnd ; ++HMI ) {
- if( (*HMI).first ) {
- LiveRange *L = (*HMI).second; // get the LiveRange
- if(L)
- if( ! L->hasColor() )
-
- // NOTE: ** allocating the size of long Type **
- L->setSpillOffFromFP(mcInfo.allocateSpilledValue(TM,
- Type::LongTy));
-
+ if(HMI->first && HMI->second) {
+ LiveRange *L = HMI->second; // get the LiveRange
+ if( ! L->hasColor() )
+ // NOTE: ** allocating the size of long Type **
+ L->setSpillOffFromFP(mcInfo.allocateSpilledValue(TM, Type::LongTy));
}
} // for all LR's in hash map
}
-/* Title: PhyRegAlloc.h
+/* Title: PhyRegAlloc.h -*- C++ -*-
Author: Ruchira Sasanka
Date: Aug 20, 01
Purpose: This is the main entry point for register allocation.
class AddedInstrns
{
public:
- deque<MachineInstr *> InstrnsBefore; // Added insts BEFORE an existing inst
- deque<MachineInstr *> InstrnsAfter; // Added insts AFTER an existing inst
-
- AddedInstrns() : InstrnsBefore(), InstrnsAfter() { }
+ std::deque<MachineInstr*> InstrnsBefore;// Added insts BEFORE an existing inst
+ std::deque<MachineInstr*> InstrnsAfter; // Added insts AFTER an existing inst
};
-typedef hash_map<const MachineInstr *, AddedInstrns *> AddedInstrMapType;
+typedef std::hash_map<const MachineInstr *, AddedInstrns *> AddedInstrMapType;
class PhyRegAlloc: public NonCopyable
{
- vector<RegClass *> RegClassList ; // vector of register classes
+ std::vector<RegClass *> RegClassList; // vector of register classes
const TargetMachine &TM; // target machine
const Method* Meth; // name of the method we work on
MachineCodeForMethod& mcInfo; // descriptor for method's native code
const BasicBlock *BB,
const unsigned OpNum);
- inline void constructLiveRanges()
- { LRI.constructLiveRanges(); }
+ inline void constructLiveRanges() { LRI.constructLiveRanges(); }
void colorIncomingArgs();
void colorCallRetArgs();
void addInterf4PseudoInstr(const MachineInstr *MInst);
-
public:
-
PhyRegAlloc(Method *const M, const TargetMachine& TM,
MethodLiveVarInfo *const Lvi);
-
~PhyRegAlloc();
// main method called for allocating registers
#include "llvm/CodeGen/RegClass.h"
-
+#include <iostream>
+using std::cerr;
//----------------------------------------------------------------------------
// This constructor inits IG. The actual matrix is created by a call to
: Meth(M), MRC(Mrc), RegClassID( Mrc->getRegClassID() ),
IG(this), IGNodeStack(), ReservedColorList(RCL) {
if( DEBUG_RA)
- cout << "Created Reg Class: " << RegClassID << endl;
+ cerr << "Created Reg Class: " << RegClassID << "\n";
IsColorUsedArr = new bool[ Mrc->getNumOfAllRegs() ];
}
//----------------------------------------------------------------------------
void RegClass::colorAllRegs()
{
- if(DEBUG_RA) cout << "Coloring IG of reg class " << RegClassID << " ...\n";
+ if(DEBUG_RA) cerr << "Coloring IG of reg class " << RegClassID << " ...\n";
// pre-color IGNodes
pushAllIGNodes(); // push all IG Nodes
bool PushedAll = pushUnconstrainedIGNodes();
if( DEBUG_RA) {
- cout << " Puhsed all-unconstrained IGNodes. ";
- if( PushedAll ) cout << " No constrained nodes left.";
- cout << endl;
+ cerr << " Puhsed all-unconstrained IGNodes. ";
+ if( PushedAll ) cerr << " No constrained nodes left.";
+ cerr << "\n";
}
if( PushedAll ) // if NO constrained nodes left
IGNode->pushOnStack(); // set OnStack and dec deg of neighs
if (DEBUG_RA > 1) {
- cout << " pushed un-constrained IGNode " << IGNode->getIndex() ;
- cout << " on to stack" << endl;
+ cerr << " pushed un-constrained IGNode " << IGNode->getIndex() ;
+ cerr << " on to stack\n";
}
}
else pushedall = false; // we didn't push all live ranges
}
else {
if( DEBUG_RA ) {
- cout << " Node " << Node->getIndex();
- cout << " already colored with color " << Node->getColor() << endl;
+ cerr << " Node " << Node->getIndex();
+ cerr << " already colored with color " << Node->getColor() << "\n";
}
}
if( !Node->hasColor() ) {
if( DEBUG_RA ) {
- cout << " Node " << Node->getIndex();
- cout << " - could not find a color (needs spilling)" << endl;
+ cerr << " Node " << Node->getIndex();
+ cerr << " - could not find a color (needs spilling)\n";
}
}
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/MachineRegInfo.h"
#include <stack>
+#include <iostream>
-typedef vector<unsigned int> ReservedColorListType;
+typedef std::vector<unsigned int> ReservedColorListType;
//-----------------------------------------------------------------------------
InterferenceGraph IG; // Interference graph - constructed by
// buildInterferenceGraph
- stack <IGNode *> IGNodeStack; // the stack used for coloring
+ std::stack<IGNode *> IGNodeStack; // the stack used for coloring
const ReservedColorListType *const ReservedColorList;
//
inline void printIGNodeList() const {
- cerr << "IG Nodes for Register Class " << RegClassID << ":" << endl;
+ std::cerr << "IG Nodes for Register Class " << RegClassID << ":" << "\n";
IG.printIGNodeList();
}
inline void printIG() {
- cerr << "IG for Register Class " << RegClassID << ":" << endl;
+ std::cerr << "IG for Register Class " << RegClassID << ":" << "\n";
IG.printIG();
}
-
};
-
-
-
-
-
-
#endif
#include <math.h> // For fmod
#include <signal.h>
#include <setjmp.h>
+#include <iostream>
+using std::vector;
+using std::cout;
+using std::cerr;
cl::Flag QuietMode ("quiet" , "Do not emit any non-program output");
cl::Alias QuietModeA("q" , "Alias for -quiet", cl::NoFlags, QuietMode);
static cl::Flag ProfileStructureFields("profilestructfields",
"Profile Structure Field Accesses");
#include <map>
-static map<const StructType *, vector<unsigned> > FieldAccessCounts;
+static std::map<const StructType *, vector<unsigned> > FieldAccessCounts;
#endif
sigjmp_buf SignalRecoverBuffer;
case Type::PointerTyID:
if (isa<ConstantPointerNull>(CPV)) {
Result.PointerVal = 0;
- } else if (ConstantPointerRef *CPR =dyn_cast<ConstantPointerRef>(CPV)) {
+ } else if (isa<ConstantPointerRef>(CPV)) {
assert(0 && "Not implemented!");
} else {
assert(0 && "Unknown constant pointer type!");
}
break;
default:
- cout << "ERROR: Constant unimp for type: " << CPV->getType() << endl;
+ cout << "ERROR: Constant unimp for type: " << CPV->getType() << "\n";
}
return Result;
} else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
cout << ( Cur >= 160? char((Cur>>4)+'A'-10) : char((Cur>>4) + '0'))
<< ((Cur&15) >= 10? char((Cur&15)+'A'-10) : char((Cur&15) + '0'));
}
- cout << endl;
+ cout << "\n";
}
}
static void SetValue(Value *V, GenericValue Val, ExecutionContext &SF) {
unsigned TyP = V->getType()->getUniqueID(); // TypePlane for value
- //cout << "Setting value: " << &SF.Values[TyP][getOperandSlot(V)] << endl;
+ //cout << "Setting value: " << &SF.Values[TyP][getOperandSlot(V)] << "\n";
SF.Values[TyP][getOperandSlot(V)] = Val;
}
return;
default:
- CW << "Bad Type: " << Init->getType() << endl;
+ CW << "Bad Type: " << Init->getType() << "\n";
assert(0 && "Unknown constant type to initialize memory with!");
}
}
IMPLEMENT_BINARY_OPERATOR(+, Double);
IMPLEMENT_BINARY_OPERATOR(+, Pointer);
default:
- cout << "Unhandled type for Add instruction: " << Ty << endl;
+ cout << "Unhandled type for Add instruction: " << Ty << "\n";
}
return Dest;
}
IMPLEMENT_BINARY_OPERATOR(-, Double);
IMPLEMENT_BINARY_OPERATOR(-, Pointer);
default:
- cout << "Unhandled type for Sub instruction: " << Ty << endl;
+ cout << "Unhandled type for Sub instruction: " << Ty << "\n";
}
return Dest;
}
IMPLEMENT_BINARY_OPERATOR(*, Double);
IMPLEMENT_BINARY_OPERATOR(*, Pointer);
default:
- cout << "Unhandled type for Mul instruction: " << Ty << endl;
+ cout << "Unhandled type for Mul instruction: " << Ty << "\n";
}
return Dest;
}
IMPLEMENT_BINARY_OPERATOR(/, Double);
IMPLEMENT_BINARY_OPERATOR(/, Pointer);
default:
- cout << "Unhandled type for Div instruction: " << Ty << endl;
+ cout << "Unhandled type for Div instruction: " << Ty << "\n";
}
return Dest;
}
Dest.DoubleVal = fmod(Src1.DoubleVal, Src2.DoubleVal);
break;
default:
- cout << "Unhandled type for Rem instruction: " << Ty << endl;
+ cout << "Unhandled type for Rem instruction: " << Ty << "\n";
}
return Dest;
}
IMPLEMENT_BINARY_OPERATOR(&, Long);
IMPLEMENT_BINARY_OPERATOR(&, Pointer);
default:
- cout << "Unhandled type for And instruction: " << Ty << endl;
+ cout << "Unhandled type for And instruction: " << Ty << "\n";
}
return Dest;
}
IMPLEMENT_BINARY_OPERATOR(|, Long);
IMPLEMENT_BINARY_OPERATOR(|, Pointer);
default:
- cout << "Unhandled type for Or instruction: " << Ty << endl;
+ cout << "Unhandled type for Or instruction: " << Ty << "\n";
}
return Dest;
}
IMPLEMENT_BINARY_OPERATOR(^, Long);
IMPLEMENT_BINARY_OPERATOR(^, Pointer);
default:
- cout << "Unhandled type for Xor instruction: " << Ty << endl;
+ cout << "Unhandled type for Xor instruction: " << Ty << "\n";
}
return Dest;
}
IMPLEMENT_SETCC(==, Double);
IMPLEMENT_SETCC(==, Pointer);
default:
- cout << "Unhandled type for SetEQ instruction: " << Ty << endl;
+ cout << "Unhandled type for SetEQ instruction: " << Ty << "\n";
}
return Dest;
}
IMPLEMENT_SETCC(!=, Pointer);
default:
- cout << "Unhandled type for SetNE instruction: " << Ty << endl;
+ cout << "Unhandled type for SetNE instruction: " << Ty << "\n";
}
return Dest;
}
IMPLEMENT_SETCC(<=, Double);
IMPLEMENT_SETCC(<=, Pointer);
default:
- cout << "Unhandled type for SetLE instruction: " << Ty << endl;
+ cout << "Unhandled type for SetLE instruction: " << Ty << "\n";
}
return Dest;
}
IMPLEMENT_SETCC(>=, Double);
IMPLEMENT_SETCC(>=, Pointer);
default:
- cout << "Unhandled type for SetGE instruction: " << Ty << endl;
+ cout << "Unhandled type for SetGE instruction: " << Ty << "\n";
}
return Dest;
}
IMPLEMENT_SETCC(<, Double);
IMPLEMENT_SETCC(<, Pointer);
default:
- cout << "Unhandled type for SetLT instruction: " << Ty << endl;
+ cout << "Unhandled type for SetLT instruction: " << Ty << "\n";
}
return Dest;
}
IMPLEMENT_SETCC(>, Double);
IMPLEMENT_SETCC(>, Pointer);
default:
- cout << "Unhandled type for SetGT instruction: " << Ty << endl;
+ cout << "Unhandled type for SetGT instruction: " << Ty << "\n";
}
return Dest;
}
// Print out structure field accounting information...
if (!FieldAccessCounts.empty()) {
CW << "Profile Field Access Counts:\n";
- map<const StructType *, vector<unsigned> >::iterator
+ std::map<const StructType *, vector<unsigned> >::iterator
I = FieldAccessCounts.begin(), E = FieldAccessCounts.end();
for (; I != E; ++I) {
vector<unsigned> &OfC = I->second;
if (i) CW << ", ";
CW << OfC[i];
}
- CW << endl;
+ CW << "\n";
}
- CW << endl;
+ CW << "\n";
CW << "Profile Field Access Percentages:\n";
cout.precision(3);
if (i) CW << ", ";
CW << double(OfC[i])/Sum;
}
- CW << endl;
+ CW << "\n";
}
- CW << endl;
+ CW << "\n";
FieldAccessCounts.clear();
}
CW << "Method " << M->getType() << " \"" << M->getName()
<< "\" returned ";
print(RetTy, Result);
- cout << endl;
+ cout << "\n";
}
if (RetTy->isIntegral())
CW << "Method " << M->getType() << " \"" << M->getName()
<< "\" returned ";
print(RetTy, Result);
- cout << endl;
+ cout << "\n";
}
}
IMPLEMENT_SHIFT(<<, ULong);
IMPLEMENT_SHIFT(<<, Long);
default:
- cout << "Unhandled type for Shl instruction: " << Ty << endl;
+ cout << "Unhandled type for Shl instruction: " << Ty << "\n";
}
SetValue(I, Dest, SF);
}
IMPLEMENT_SHIFT(>>, ULong);
IMPLEMENT_SHIFT(>>, Long);
default:
- cout << "Unhandled type for Shr instruction: " << Ty << endl;
+ cout << "Unhandled type for Shr instruction: " << Ty << "\n";
}
SetValue(I, Dest, SF);
}
IMPLEMENT_CAST(DESTTY, DESTCTY, Double)
#define IMPLEMENT_CAST_CASE_END() \
- default: cout << "Unhandled cast: " << SrcTy << " to " << Ty << endl; \
+ default: cout << "Unhandled cast: " << SrcTy << " to " << Ty << "\n"; \
break; \
} \
break
IMPLEMENT_CAST_CASE(Float , (float));
IMPLEMENT_CAST_CASE(Double , (double));
default:
- cout << "Unhandled dest type for cast instruction: " << Ty << endl;
+ cout << "Unhandled dest type for cast instruction: " << Ty << "\n";
}
SetValue(I, Dest, SF);
}
if (RetTy != Type::VoidTy) {
if (!ECStack.empty() && ECStack.back().Caller) {
ExecutionContext &SF = ECStack.back();
- CallInst *Caller = SF.Caller;
SetValue(SF.Caller, Result, SF);
SF.Caller = 0; // We returned from the call...
CW << "Method " << M->getType() << " \"" << M->getName()
<< "\" returned ";
print(RetTy, Result);
- cout << endl;
+ cout << "\n";
if (RetTy->isIntegral())
ExitCode = Result.SByteVal; // Capture the exit code of the program
case Type::UShortTyID: cout << V.UShortVal; break;
case Type::IntTyID: cout << V.IntVal; break;
case Type::UIntTyID: cout << V.UIntVal; break;
- case Type::LongTyID: cout << V.LongVal; break;
- case Type::ULongTyID: cout << V.ULongVal; break;
+ case Type::LongTyID: cout << (long)V.LongVal; break;
+ case Type::ULongTyID: cout << (unsigned long)V.ULongVal; break;
case Type::FloatTyID: cout << V.FloatVal; break;
case Type::DoubleTyID: cout << V.DoubleVal; break;
case Type::PointerTyID:cout << (void*)V.PointerVal; break;
printValue(Ty, V);
}
-void Interpreter::print(const string &Name) {
+void Interpreter::print(const std::string &Name) {
Value *PickedVal = ChooseOneOption(Name, LookupMatchingNames(Name));
if (!PickedVal) return;
if (const Method *M = dyn_cast<const Method>(PickedVal)) {
CW << M; // Print the method
} else if (const Type *Ty = dyn_cast<const Type>(PickedVal)) {
- CW << "type %" << Name << " = " << Ty->getDescription() << endl;
+ CW << "type %" << Name << " = " << Ty->getDescription() << "\n";
} else if (const BasicBlock *BB = dyn_cast<const BasicBlock>(PickedVal)) {
CW << BB; // Print the basic block
} else { // Otherwise there should be an annotation for the slot#
print(PickedVal->getType(),
getOperandValue(PickedVal, ECStack[CurFrame]));
- cout << endl;
+ cout << "\n";
}
}
-void Interpreter::infoValue(const string &Name) {
+void Interpreter::infoValue(const std::string &Name) {
Value *PickedVal = ChooseOneOption(Name, LookupMatchingNames(Name));
if (!PickedVal) return;
cout << "Value: ";
print(PickedVal->getType(),
getOperandValue(PickedVal, ECStack[CurFrame]));
- cout << endl;
+ cout << "\n";
printOperandInfo(PickedVal, ECStack[CurFrame]);
}
printValue(Args[i]->getType(), getOperandValue(Args[i], ECStack[FrameNo]));
}
- cout << ")" << endl;
+ cout << ")\n";
CW << *(ECStack[FrameNo].CurInst-(FrameNo != int(ECStack.size()-1)));
}
struct MethodInfo : public Annotation {
MethodInfo(Method *M);
- vector<unsigned> NumPlaneElements;
+ std::vector<unsigned> NumPlaneElements;
// Create - Factory function to allow MethodInfo annotations to be
#include "llvm/DerivedTypes.h"
#include <map>
#include <dlfcn.h>
+#include <iostream>
#include <link.h>
#include <math.h>
#include <stdio.h>
+using std::vector;
+using std::cout;
typedef GenericValue (*ExFunc)(MethodType *, const vector<GenericValue> &);
-static map<const Method *, ExFunc> Functions;
-static map<string, ExFunc> FuncNames;
+static std::map<const Method *, ExFunc> Functions;
+static std::map<std::string, ExFunc> FuncNames;
static Interpreter *TheInterpreter;
// getCurrentExecutablePath() - Return the directory that the lli executable
// lives in.
//
-string Interpreter::getCurrentExecutablePath() const {
+std::string Interpreter::getCurrentExecutablePath() const {
Dl_info Info;
if (dladdr(&TheInterpreter, &Info) == 0) return "";
- string LinkAddr(Info.dli_fname);
+ std::string LinkAddr(Info.dli_fname);
unsigned SlashPos = LinkAddr.rfind('/');
- if (SlashPos != string::npos)
+ if (SlashPos != std::string::npos)
LinkAddr.resize(SlashPos); // Trim the executable name off...
return LinkAddr;
static ExFunc lookupMethod(const Method *M) {
// Function not found, look it up... start by figuring out what the
// composite function name should be.
- string ExtName = "lle_";
+ std::string ExtName = "lle_";
const MethodType *MT = M->getMethodType();
for (unsigned i = 0; const Type *Ty = MT->getContainedType(i); ++i)
ExtName += getTypeID(Ty);
if (FnPtr == 0) // Try calling a generic function... if it exists...
FnPtr = (ExFunc)dlsym(RTLD_DEFAULT, ("lle_X_"+M->getName()).c_str());
if (FnPtr != 0)
- Functions.insert(make_pair(M, FnPtr)); // Cache for later
+ Functions.insert(std::make_pair(M, FnPtr)); // Cache for later
return FnPtr;
}
// Do a lookup to see if the method is in our cache... this should just be a
// defered annotation!
- map<const Method *, ExFunc>::iterator FI = Functions.find(M);
+ std::map<const Method *, ExFunc>::iterator FI = Functions.find(M);
ExFunc Fn = (FI == Functions.end()) ? lookupMethod(M) : FI->second;
if (Fn == 0) {
cout << "Tried to execute an unknown external method: "
- << M->getType()->getDescription() << " " << M->getName() << endl;
+ << M->getType()->getDescription() << " " << M->getName() << "\n";
return GenericValue();
}
// int "putchar"(int)
GenericValue lle_ii_putchar(MethodType *M, const vector<GenericValue> &Args) {
- cout << ((char)Args[0].IntVal) << flush;
+ cout << ((char)Args[0].IntVal) << std::flush;
return Args[0];
}
// void "putchar"(ubyte)
GenericValue lle_VB_putchar(MethodType *M, const vector<GenericValue> &Args) {
- cout << Args[0].SByteVal << flush;
+ cout << Args[0].SByteVal << std::flush;
return Args[0];
}
PointerTy PointerVal;
};
-typedef vector<GenericValue> ValuePlaneTy;
+typedef std::vector<GenericValue> ValuePlaneTy;
// ExecutionContext struct - This struct represents one stack frame currently
// executing.
BasicBlock *CurBB; // The currently executing BB
BasicBlock::iterator CurInst; // The next instruction to execute
MethodInfo *MethInfo; // The MethInfo annotation for the method
- vector<ValuePlaneTy> Values; // ValuePlanes for each type
+ std::vector<ValuePlaneTy> Values;// ValuePlanes for each type
BasicBlock *PrevBB; // The previous BB or null if in first BB
CallInst *Caller; // Holds the call that called subframes.
// The runtime stack of executing code. The top of the stack is the current
// method record.
- vector<ExecutionContext> ECStack;
+ std::vector<ExecutionContext> ECStack;
public:
Interpreter();
void handleUserInput();
// User Interation Methods...
- void loadModule(const string &Filename);
+ void loadModule(const std::string &Filename);
bool flushModule();
- bool callMethod(const string &Name); // return true on failure
- void setBreakpoint(const string &Name);
- void infoValue(const string &Name);
- void print(const string &Name);
+ bool callMethod(const std::string &Name); // return true on failure
+ void setBreakpoint(const std::string &Name);
+ void infoValue(const std::string &Name);
+ void print(const std::string &Name);
static void print(const Type *Ty, GenericValue V);
static void printValue(const Type *Ty, GenericValue V);
// Hack until we can parse command line args...
- bool callMainMethod(const string &MainName,
- const vector<string> &InputFilename);
+ bool callMainMethod(const std::string &MainName,
+ const std::vector<std::string> &InputFilename);
void list(); // Do the 'list' command
void printStackTrace(); // Do the 'backtrace' command
// Code execution methods...
- void callMethod (Method *Meth, const vector<GenericValue> &ArgVals);
+ void callMethod(Method *Meth, const std::vector<GenericValue> &ArgVals);
bool executeInstruction(); // Execute one instruction...
void stepInstruction(); // Do the 'step' command
void executeBrInst(BranchInst *I, ExecutionContext &SF);
void executeAllocInst(AllocationInst *I, ExecutionContext &SF);
GenericValue callExternalMethod(Method *Meth,
- const vector<GenericValue> &ArgVals);
+ const std::vector<GenericValue> &ArgVals);
void exitCalled(GenericValue GV);
// getCurrentMethod - Return the currently executing method
// getCurrentExecutablePath() - Return the directory that the lli executable
// lives in.
//
- string getCurrentExecutablePath() const;
+ std::string getCurrentExecutablePath() const;
// printCurrentInstruction - Print out the instruction that the virtual PC is
// at, or fail silently if no program is running.
// matches to that name. This is obviously slow, and should only be used for
// user interaction.
//
- vector<Value*> LookupMatchingNames(const string &Name);
+ std::vector<Value*> LookupMatchingNames(const std::string &Name);
// ChooseOneOption - Prompt the user to choose among the specified options to
// pick one value. If no options are provided, emit an error. If a single
// option is provided, just return that option.
//
- Value *ChooseOneOption(const string &Name, const vector<Value*> &Opts);
+ Value *ChooseOneOption(const std::string &Name,
+ const std::vector<Value*> &Opts);
void initializeExecutionEngine();
#include "Interpreter.h"
#include "llvm/SymbolTable.h"
#include "llvm/Assembly/Writer.h"
+#include <iostream>
+using std::cout;
//===----------------------------------------------------------------------===//
//
// LookupMatchingNames helper - Search a symbol table for values matching Name.
//
-static inline void LookupMatchingNames(const string &Name, SymTabValue &STV,
- vector<Value*> &Results) {
+static inline void LookupMatchingNames(const std::string &Name,SymTabValue &STV,
+ std::vector<Value*> &Results) {
SymbolTable *SymTab = STV.getSymbolTable();
if (SymTab == 0) return; // No symbolic values :(
// matches to that name. This is obviously slow, and should only be used for
// user interaction.
//
-vector<Value*> Interpreter::LookupMatchingNames(const string &Name) {
- vector<Value*> Results;
+std::vector<Value*> Interpreter::LookupMatchingNames(const std::string &Name) {
+ std::vector<Value*> Results;
Method *CurMeth = getCurrentMethod();
if (CurMeth) ::LookupMatchingNames(Name, *CurMeth, Results);
// pick one value. If no options are provided, emit an error. If a single
// option is provided, just return that option.
//
-Value *Interpreter::ChooseOneOption(const string &Name,
- const vector<Value*> &Opts) {
+Value *Interpreter::ChooseOneOption(const std::string &Name,
+ const std::vector<Value*> &Opts) {
switch (Opts.size()) {
case 1: return Opts[0];
case 0:
cout << " 0. Cancel operation\n";
for (unsigned i = 0; i < Opts.size(); ++i) {
cout << " " << (i+1) << ".";
- WriteAsOperand(cout, Opts[i]) << endl;
+ WriteAsOperand(cout, Opts[i]) << "\n";
}
unsigned Option;
do {
- cout << "lli> " << flush;
- cin >> Option;
+ cout << "lli> " << std::flush;
+ std::cin >> Option;
if (Option > Opts.size())
cout << "Invalid selection: Please choose from 0 to " << Opts.size()
- << endl;
+ << "\n";
} while (Option > Opts.size());
if (Option == 0) return 0;
#include "llvm/DerivedTypes.h"
#include "llvm/Transforms/Linker.h"
#include <algorithm>
+using std::string;
+using std::cout;
+using std::cin;
enum CommandID {
Quit, Help, // Basics
bool UserQuit = false;
// Sort the table...
- sort(CommandTable, CommandTableEnd);
+ std::sort(CommandTable, CommandTableEnd);
// Print the instruction that we are stopped at...
printCurrentInstruction();
do {
string Command;
- cout << "lli> " << flush;
+ cout << "lli> " << std::flush;
cin >> Command;
CommandTableElement *E = find(CommandTable, CommandTableEnd, Command);
if (Module *SupportLib = ParseBytecodeFile(RuntimeLib, &ErrorMsg)) {
if (LinkModules(CurMod, SupportLib, &ErrorMsg))
- cerr << "Error Linking runtime library into current module: "
- << ErrorMsg << endl;
+ std::cerr << "Error Linking runtime library into current module: "
+ << ErrorMsg << "\n";
} else {
- cerr << "Error loading runtime library '"+RuntimeLib+"': "
- << ErrorMsg << "\n";
+ std::cerr << "Error loading runtime library '"+RuntimeLib+"': "
+ << ErrorMsg << "\n";
}
}
// callMethod - Enter the specified method...
//
bool Interpreter::callMethod(const string &Name) {
- vector<Value*> Options = LookupMatchingNames(Name);
+ std::vector<Value*> Options = LookupMatchingNames(Name);
for (unsigned i = 0; i < Options.size(); ++i) { // Remove nonmethod matches...
if (!isa<Method>(Options[i])) {
Method *M = cast<Method>(PickedMeth);
- vector<GenericValue> Args;
+ std::vector<GenericValue> Args;
// TODO, get args from user...
callMethod(M, Args); // Start executing it...
return false;
}
-static void *CreateArgv(const vector<string> &InputArgv) {
+static void *CreateArgv(const std::vector<string> &InputArgv) {
// Pointers are 64 bits...
uint64_t *Result = new PointerTy[InputArgv.size()+1];
// callMethod can parse command line options and stuff for us.
//
bool Interpreter::callMainMethod(const string &Name,
- const vector<string> &InputArgv) {
- vector<Value*> Options = LookupMatchingNames(Name);
+ const std::vector<string> &InputArgv) {
+ std::vector<Value*> Options = LookupMatchingNames(Name);
for (unsigned i = 0; i < Options.size(); ++i) { // Remove nonmethod matches...
if (!isa<Method>(Options[i])) {
Method *M = cast<Method>(PickedMeth);
const MethodType *MT = M->getMethodType();
- vector<GenericValue> Args;
+ std::vector<GenericValue> Args;
switch (MT->getParamTypes().size()) {
default:
cout << "Unknown number of arguments to synthesize for '" << Name << "'!\n";
#include "llvm/DerivedTypes.h"
#include "llvm/iOther.h"
#include "llvm/ConstantVals.h"
+#include <iostream>
+using std::cerr;
+using std::string;
+using std::map;
// Error - Simple wrapper function to conditionally assign to E and return true.
// This just makes error return conditions a little bit simpler...
for (map<const Value*, Value*>::const_iterator I = M.begin(), E = M.end();
I != E; ++I) {
cerr << " Fr: " << (void*)I->first << " " << I->first
- << " To: " << (void*)I->second << " " << I->second << endl;
+ << " To: " << (void*)I->second << " " << I->second << "\n";
}
}
Constant *Result = 0;
if (ConstantArray *CPA = dyn_cast<ConstantArray>(CPV)) {
- const vector<Use> &Ops = CPA->getValues();
- vector<Constant*> Operands(Ops.size());
+ const std::vector<Use> &Ops = CPA->getValues();
+ std::vector<Constant*> Operands(Ops.size());
for (unsigned i = 0; i < Ops.size(); ++i)
Operands[i] =
cast<Constant>(RemapOperand(Ops[i], LocalMap, GlobalMap));
Result = ConstantArray::get(cast<ArrayType>(CPA->getType()), Operands);
} else if (ConstantStruct *CPS = dyn_cast<ConstantStruct>(CPV)) {
- const vector<Use> &Ops = CPS->getValues();
- vector<Constant*> Operands(Ops.size());
+ const std::vector<Use> &Ops = CPS->getValues();
+ std::vector<Constant*> Operands(Ops.size());
for (unsigned i = 0; i < Ops.size(); ++i)
Operands[i] =
cast<Constant>(RemapOperand(Ops[i], LocalMap, GlobalMap));
}
// Cache the mapping in our local map structure...
- LocalMap.insert(make_pair(In, CPV));
+ LocalMap.insert(std::make_pair(In, CPV));
return Result;
}
PrintMap(*GlobalMap);
}
- cerr << "Couldn't remap value: " << (void*)In << " " << In << endl;
+ cerr << "Couldn't remap value: " << (void*)In << " " << In << "\n";
assert(0 && "Couldn't remap value!");
return 0;
}
" - Global variables differ in const'ness");
// Okay, everything is cool, remember the mapping...
- ValueMap.insert(make_pair(SGV, DGV));
+ ValueMap.insert(std::make_pair(SGV, DGV));
} else {
// No linking to be performed, simply create an identical version of the
// symbol over in the dest module... the initializer will be filled in
Dest->getGlobalList().push_back(DGV);
// Make sure to remember this mapping...
- ValueMap.insert(make_pair(SGV, DGV));
+ ValueMap.insert(std::make_pair(SGV, DGV));
}
}
return false;
SM->getName() + "\" - Method is already defined!");
// Otherwise, just remember this mapping...
- ValueMap.insert(make_pair(SM, DM));
+ ValueMap.insert(std::make_pair(SM, DM));
} else {
// Method does not already exist, simply insert an external method
// signature identical to SM into the dest module...
Dest->getMethodList().push_back(DM);
// ... and remember this mapping...
- ValueMap.insert(make_pair(SM, DM));
+ ValueMap.insert(std::make_pair(SM, DM));
}
}
return false;
Dest->getArgumentList().push_back(DMA);
// Add a mapping to our local map
- LocalMap.insert(make_pair(SMA, DMA));
+ LocalMap.insert(std::make_pair(SMA, DMA));
}
// Loop over all of the basic blocks, copying the instructions over...
// Create new basic block and add to mapping and the Dest method...
BasicBlock *DBB = new BasicBlock(SBB->getName(), Dest);
- LocalMap.insert(make_pair(SBB, DBB));
+ LocalMap.insert(std::make_pair(SBB, DBB));
// Loop over all of the instructions in the src basic block, copying them
// over. Note that this is broken in a strict sense because the cloned
Instruction *DI = SI->clone();
DI->setName(SI->getName());
DBB->getInstList().push_back(DI);
- LocalMap.insert(make_pair(SI, DI));
+ LocalMap.insert(std::make_pair(SI, DI));
}
}
#include <map>
#include "llvm/Annotation.h"
+using std::string;
+using std::map;
+using std::pair;
+using std::make_pair;
typedef map<const string, unsigned> IDMapType;
static unsigned IDCounter = 0; // Unique ID counter
#include <algorithm>
#include <map>
#include <set>
+#include <iostream>
using namespace cl;
+using std::map;
+using std::pair;
+using std::vector;
+using std::string;
+using std::cerr;
// Return the global command line option vector. Making it a function scoped
// static ensures that it will be initialized correctly before its first use.
<< "' specified more than once!\n";
} else {
// Add argument to the argument map!
- getOpts().insert(make_pair(ArgName, Opt));
+ getOpts().insert(std::make_pair(ArgName, Opt));
}
}
break;
case ValueOptional: break;
default: cerr << "Bad ValueMask flag! CommandLine usage error:"
- << Handler->getValueExpectedFlag() << endl; abort();
+ << Handler->getValueExpectedFlag() << "\n"; abort();
}
// Run the handler now!
bool Option::error(string Message, const char *ArgName = 0) {
if (ArgName == 0) ArgName = ArgStr;
- cerr << "-" << ArgName << " option" << Message << endl;
+ cerr << "-" << ArgName << " option" << Message << "\n";
return true;
}
unsigned L = std::strlen(ArgStr);
if (L == 0) return; // Don't print the empty arg like this!
cerr << " -" << ArgStr << string(GlobalWidth-L-6, ' ') << " - "
- << HelpStr << endl;
+ << HelpStr << "\n";
}
while (const char *EnumName = va_arg(Vals, const char *)) {
int EnumVal = va_arg(Vals, int);
const char *EnumDesc = va_arg(Vals, const char *);
- ValueMap.push_back(make_pair(EnumName, // Add value to value map
- make_pair(EnumVal, EnumDesc)));
+ ValueMap.push_back(std::make_pair(EnumName, // Add value to value map
+ std::make_pair(EnumVal, EnumDesc)));
}
}
unsigned EnumValueBase::getOptionWidth() const {
unsigned BaseSize = Option::getOptionWidth();
for (unsigned i = 0; i < ValueMap.size(); ++i)
- BaseSize = max(BaseSize, std::strlen(ValueMap[i].first)+8);
+ BaseSize = std::max(BaseSize, std::strlen(ValueMap[i].first)+8);
return BaseSize;
}
<< ValueMap[i].second.second;
if (i == 0) cerr << " (default)";
- cerr << endl;
+ cerr << "\n";
}
}
unsigned EnumFlagsBase::getOptionWidth() const {
unsigned BaseSize = 0;
for (unsigned i = 0; i < ValueMap.size(); ++i)
- BaseSize = max(BaseSize, std::strlen(ValueMap[i].first)+6);
+ BaseSize = std::max(BaseSize, std::strlen(ValueMap[i].first)+6);
return BaseSize;
}
cerr << " -" << ValueMap[i].first << string(GlobalWidth-L-6, ' ') << " - "
<< ValueMap[i].second.second;
if (i == 0) cerr << " (default)";
- cerr << endl;
+ cerr << "\n";
}
}
unsigned EnumListBase::getOptionWidth() const {
unsigned BaseSize = 0;
for (unsigned i = 0; i < ValueMap.size(); ++i)
- BaseSize = max(BaseSize, std::strlen(ValueMap[i].first)+6);
+ BaseSize = std::max(BaseSize, std::strlen(ValueMap[i].first)+6);
return BaseSize;
}
for (unsigned i = 0; i < ValueMap.size(); ++i) {
unsigned L = std::strlen(ValueMap[i].first);
cerr << " -" << ValueMap[i].first << string(GlobalWidth-L-6, ' ') << " - "
- << ValueMap[i].second.second << endl;
+ << ValueMap[i].second.second << "\n";
}
}
virtual bool handleOccurance(const char *ArgName, const string &Arg) {
// Copy Options into a vector so we can sort them as we like...
vector<pair<string, Option*> > Options;
- copy(getOpts().begin(), getOpts().end(), back_inserter(Options));
+ copy(getOpts().begin(), getOpts().end(), std::back_inserter(Options));
// Eliminate Hidden or ReallyHidden arguments, depending on ShowHidden
Options.erase(remove_if(Options.begin(), Options.end(),
- ptr_fun(ShowHidden ? isReallyHidden : isHidden)),
+ std::ptr_fun(ShowHidden ? isReallyHidden : isHidden)),
Options.end());
// Eliminate duplicate entries in table (from enum flags options, f.e.)
- set<Option*> OptionSet;
+ std::set<Option*> OptionSet;
for (unsigned i = 0; i < Options.size(); )
if (OptionSet.count(Options[i].second) == 0)
OptionSet.insert(Options[i++].second); // Add to set
if (ProgramOverview)
- cerr << "OVERVIEW:" << ProgramOverview << endl;
+ cerr << "OVERVIEW:" << ProgramOverview << "\n";
// TODO: Sort options by some criteria
cerr << "USAGE: " << ProgramName << " [options]\n\n";
void getMaxArgLen(pair<string, Option *> OptPair) {
const Option *Opt = OptPair.second;
if (Opt->ArgStr[0] == 0) EmptyArg = Opt; // Capture the empty arg if exists
- MaxArgLen = max(MaxArgLen, Opt->getOptionWidth());
+ MaxArgLen = std::max(MaxArgLen, Opt->getOptionWidth());
}
void printOption(pair<string, Option *> OptPair) {
#include "llvm/Instruction.h"
#include "Support/CommandLine.h"
#include "SchedPriorities.h"
-#include <hash_set>
#include <algorithm>
#include <iterator>
-
+#include <ext/hash_set>
+#include <iostream>
+using std::cerr;
+using std::vector;
//************************* External Data Types *****************************/
unsigned int totalInstrCount;
cycles_t curTime;
cycles_t nextEarliestIssueTime; // next cycle we can issue
- vector<hash_set<const SchedGraphNode*> > choicesForSlot; // indexed by slot#
+ vector<std::hash_set<const SchedGraphNode*> > choicesForSlot; // indexed by slot#
vector<const SchedGraphNode*> choiceVec; // indexed by node ptr
vector<int> numInClass; // indexed by sched class
vector<cycles_t> nextEarliestStartTime; // indexed by opCode
- hash_map<const SchedGraphNode*, DelaySlotInfo*> delaySlotInfoForBranches;
+ std::hash_map<const SchedGraphNode*, DelaySlotInfo*> delaySlotInfoForBranches;
// indexed by branch node ptr
public:
return choiceVec[i];
}
- inline hash_set<const SchedGraphNode*>& getChoicesForSlot(unsigned slotNum) {
+ inline std::hash_set<const SchedGraphNode*>& getChoicesForSlot(unsigned slotNum) {
assert(slotNum < nslots);
return choicesForSlot[slotNum];
}
bool createIfMissing=false)
{
DelaySlotInfo* dinfo;
- hash_map<const SchedGraphNode*, DelaySlotInfo* >::const_iterator
+ std::hash_map<const SchedGraphNode*, DelaySlotInfo* >::const_iterator
I = delaySlotInfoForBranches.find(bn);
if (I == delaySlotInfoForBranches.end())
{
{
if (schedInfo.numBubblesAfter(node->getOpCode()) > 0)
{ // Update next earliest time before which *nothing* can issue.
- nextEarliestIssueTime = max(nextEarliestIssueTime,
+ nextEarliestIssueTime = std::max(nextEarliestIssueTime,
curTime + 1 + schedInfo.numBubblesAfter(node->getOpCode()));
}
unsigned numIssued;
for (numIssued = 0; numIssued < maxIssue; numIssued++)
{
- int chosenSlot = -1, chosenNodeIndex = -1;
+ int chosenSlot = -1;
for (unsigned s=startSlot; s < S.nslots; s++)
if ((*igroup)[s] == NULL && S.getChoicesForSlot(s).size() == 1)
{
assert(s < S.nslots && "No feasible slot for instruction?");
- highestSlotUsed = max(highestSlotUsed, (int) s);
+ highestSlotUsed = std::max(highestSlotUsed, (int) s);
}
assert(highestSlotUsed <= (int) S.nslots-1 && "Invalid slot used?");
// Otherwise, just ignore the instruction.
for (unsigned i=indexForBreakingNode+1; i < S.getNumChoices(); i++)
{
- bool foundLowerSlot = false;
MachineOpCode opCode = S.getChoice(i)->getOpCode();
for (unsigned int s=startSlot; s < nslotsToUse; s++)
if (S.schedInfo.instrCanUseSlot(opCode, s))
{
for (cycles_t c = firstCycle; c <= S.getTime(); c++)
{
- cout << " Cycle " << c << " : Scheduled instructions:\n";
+ cerr << " Cycle " << (long)c << " : Scheduled instructions:\n";
const InstrGroup* igroup = S.isched.getIGroup(c);
for (unsigned int s=0; s < S.nslots; s++)
{
- cout << " ";
+ cerr << " ";
if ((*igroup)[s] != NULL)
- cout << * ((*igroup)[s])->getMachineInstr() << endl;
+ cerr << * ((*igroup)[s])->getMachineInstr() << "\n";
else
- cout << "<none>" << endl;
+ cerr << "<none>\n";
}
}
}
// an instruction can be issued, or the next earliest in which
// one will be ready, or to the next cycle, whichever is latest.
//
- S.updateTime(max(S.getTime() + 1,
- max(S.getEarliestIssueTime(),
- S.schedPrio.getEarliestReadyTime())));
+ S.updateTime(std::max(S.getTime() + 1,
+ std::max(S.getEarliestIssueTime(),
+ S.schedPrio.getEarliestReadyTime())));
}
}
if (SchedDebugLevel >= Sched_PrintSchedGraphs)
{
- cout << endl << "*** SCHEDULING GRAPHS FOR INSTRUCTION SCHEDULING"
- << endl;
+ cerr << "\n*** SCHEDULING GRAPHS FOR INSTRUCTION SCHEDULING\n";
graphSet.dump();
}
const BasicBlock* bb = bbvec[0];
if (SchedDebugLevel >= Sched_PrintSchedTrace)
- cout << endl << "*** TRACE OF INSTRUCTION SCHEDULING OPERATIONS\n\n";
+ cerr << "\n*** TRACE OF INSTRUCTION SCHEDULING OPERATIONS\n\n";
SchedPriorities schedPrio(method, graph); // expensive!
SchedulingManager S(target, graph, schedPrio);
if (SchedDebugLevel >= Sched_PrintMachineCode)
{
- cout << endl
- << "*** Machine instructions after INSTRUCTION SCHEDULING" << endl;
+ cerr << "\n*** Machine instructions after INSTRUCTION SCHEDULING\n";
MachineCodeForMethod::get(method).dump();
}
#include "llvm/Target/MachineRegInfo.h"
#include "llvm/iOther.h"
#include "Support/StringExtras.h"
+#include "Support/STLExtras.h"
#include <algorithm>
-#include <hash_map>
#include <vector>
+#include <iostream>
+#include <ext/hash_map>
+using std::vector;
+using std::pair;
+using std::hash_map;
+using std::cerr;
//*********************** Internal Data Structures *************************/
}
void SchedGraphEdge::dump(int indent=0) const {
- cout << string(indent*2, ' ') << *this;
+ cerr << std::string(indent*2, ' ') << *this;
}
}
void SchedGraphNode::dump(int indent=0) const {
- cout << string(indent*2, ' ') << *this;
+ cerr << std::string(indent*2, ' ') << *this;
}
const TargetMachine& target)
{
bbVec.push_back(bb);
- this->buildGraph(target);
+ buildGraph(target);
}
/*dtor*/
SchedGraph::~SchedGraph()
{
- for (iterator I=begin(); I != end(); ++I)
+ for (const_iterator I = begin(); I != end(); ++I)
{
- SchedGraphNode* node = (*I).second;
+ SchedGraphNode *node = I->second;
// for each node, delete its out-edges
- for (SchedGraphNode::iterator I = node->beginOutEdges();
- I != node->endOutEdges(); ++I)
- delete *I;
+ std::for_each(node->beginOutEdges(), node->endOutEdges(),
+ deleter<SchedGraphEdge>);
// then delete the node itself.
delete node;
void
SchedGraph::dump() const
{
- cout << " Sched Graph for Basic Blocks: ";
+ cerr << " Sched Graph for Basic Blocks: ";
for (unsigned i=0, N=bbVec.size(); i < N; i++)
{
- cout << (bbVec[i]->hasName()? bbVec[i]->getName() : "block")
+ cerr << (bbVec[i]->hasName()? bbVec[i]->getName() : "block")
<< " (" << bbVec[i] << ")"
<< ((i == N-1)? "" : ", ");
}
- cout << endl << endl << " Actual Root nodes : ";
+ cerr << "\n\n Actual Root nodes : ";
for (unsigned i=0, N=graphRoot->outEdges.size(); i < N; i++)
- cout << graphRoot->outEdges[i]->getSink()->getNodeId()
+ cerr << graphRoot->outEdges[i]->getSink()->getNodeId()
<< ((i == N-1)? "" : ", ");
- cout << endl << " Graph Nodes:" << endl;
+ cerr << "\n Graph Nodes:\n";
for (const_iterator I=begin(); I != end(); ++I)
- cout << endl << * (*I).second;
+ cerr << "\n" << *I->second;
- cout << endl;
+ cerr << "\n";
}
// this operand is a definition or use of value `instr'
SchedGraphNode* node = this->getGraphNodeForInstr(mvec[i]);
assert(node && "No node for machine instruction in this BB?");
- refVec.push_back(make_pair(node, o));
+ refVec.push_back(std::make_pair(node, o));
}
}
{
int regNum = mop.getMachineRegNum();
if (regNum != target.getRegInfo().getZeroRegNum())
- regToRefVecMap[mop.getMachineRegNum()].push_back(make_pair(node,
- i));
+ regToRefVecMap[mop.getMachineRegNum()].push_back(
+ std::make_pair(node, i));
continue; // nothing more to do
}
&& "Do not expect any other kind of operand to be defined!");
const Instruction* defInstr = cast<Instruction>(mop.getVRegValue());
- valueToDefVecMap[defInstr].push_back(make_pair(node, i));
+ valueToDefVecMap[defInstr].push_back(std::make_pair(node, i));
}
//
if (const Instruction* defInstr =
dyn_cast_or_null<Instruction>(minstr.getImplicitRef(i)))
{
- valueToDefVecMap[defInstr].push_back(make_pair(node, -i));
+ valueToDefVecMap[defInstr].push_back(std::make_pair(node, -i));
}
}
void
SchedGraph::buildGraph(const TargetMachine& target)
{
- const MachineInstrInfo& mii = target.getInstrInfo();
const BasicBlock* bb = bbVec[0];
assert(bbVec.size() == 1 && "Only handling a single basic block here");
SchedGraphSet::~SchedGraphSet()
{
// delete all the graphs
- for (iterator I=begin(); I != end(); ++I)
- delete (*I).second;
+ for (const_iterator I = begin(); I != end(); ++I)
+ delete I->second;
}
void
SchedGraphSet::dump() const
{
- cout << "======== Sched graphs for method `"
- << (method->hasName()? method->getName() : "???")
- << "' ========" << endl << endl;
+ cerr << "======== Sched graphs for method `" << method->getName()
+ << "' ========\n\n";
for (const_iterator I=begin(); I != end(); ++I)
- (*I).second->dump();
+ I->second->dump();
- cout << endl << "====== End graphs for method `"
- << (method->hasName()? method->getName() : "")
- << "' ========" << endl << endl;
+ cerr << "\n====== End graphs for method `" << method->getName()
+ << "' ========\n\n";
}
-ostream&
-operator<<(ostream& os, const SchedGraphEdge& edge)
+std::ostream &operator<<(std::ostream &os, const SchedGraphEdge& edge)
{
os << "edge [" << edge.src->getNodeId() << "] -> ["
<< edge.sink->getNodeId() << "] : ";
default: assert(0); break;
}
- os << " : delay = " << edge.minDelay << endl;
+ os << " : delay = " << edge.minDelay << "\n";
return os;
}
-ostream&
-operator<<(ostream& os, const SchedGraphNode& node)
+std::ostream &operator<<(std::ostream &os, const SchedGraphNode& node)
{
- os << string(8, ' ')
+ os << std::string(8, ' ')
<< "Node " << node.nodeId << " : "
- << "latency = " << node.latency << endl << string(12, ' ');
+ << "latency = " << node.latency << "\n" << std::string(12, ' ');
if (node.getMachineInstr() == NULL)
- os << "(Dummy node)" << endl;
+ os << "(Dummy node)\n";
else
{
- os << *node.getMachineInstr() << endl << string(12, ' ');
- os << node.inEdges.size() << " Incoming Edges:" << endl;
+ os << *node.getMachineInstr() << "\n" << std::string(12, ' ');
+ os << node.inEdges.size() << " Incoming Edges:\n";
for (unsigned i=0, N=node.inEdges.size(); i < N; i++)
- os << string(16, ' ') << *node.inEdges[i];
+ os << std::string(16, ' ') << *node.inEdges[i];
- os << string(12, ' ') << node.outEdges.size()
- << " Outgoing Edges:" << endl;
+ os << std::string(12, ' ') << node.outEdges.size()
+ << " Outgoing Edges:\n";
for (unsigned i=0, N=node.outEdges.size(); i < N; i++)
- {
- os << string(16, ' ') << * node.outEdges[i];
- }
+ os << std::string(16, ' ') << *node.outEdges[i];
}
return os;
#include "Support/NonCopyable.h"
#include "Support/HashExtras.h"
#include "Support/GraphTraits.h"
-#include <hash_map>
+#include <ext/hash_map>
class Value;
class Instruction;
//
// Debugging support
//
- friend ostream& operator<<(ostream& os, const SchedGraphEdge& edge);
+ friend std::ostream& operator<<(std::ostream& os, const SchedGraphEdge& edge);
void dump (int indent=0) const;
unsigned int nodeId;
const BasicBlock* bb;
const MachineInstr* minstr;
- vector<SchedGraphEdge*> inEdges;
- vector<SchedGraphEdge*> outEdges;
+ std::vector<SchedGraphEdge*> inEdges;
+ std::vector<SchedGraphEdge*> outEdges;
int origIndexInBB; // original position of machine instr in BB
int latency;
public:
- typedef vector<SchedGraphEdge*>:: iterator iterator;
- typedef vector<SchedGraphEdge*>::const_iterator const_iterator;
- typedef vector<SchedGraphEdge*>:: reverse_iterator reverse_iterator;
- typedef vector<SchedGraphEdge*>::const_reverse_iterator const_reverse_iterator;
+ typedef std::vector<SchedGraphEdge*>:: iterator iterator;
+ typedef std::vector<SchedGraphEdge*>::const_iterator const_iterator;
+ typedef std::vector<SchedGraphEdge*>:: reverse_iterator reverse_iterator;
+ typedef std::vector<SchedGraphEdge*>::const_reverse_iterator const_reverse_iterator;
public:
//
//
// Debugging support
//
- friend ostream& operator<<(ostream& os, const SchedGraphNode& node);
+ friend std::ostream& operator<<(std::ostream& os, const SchedGraphNode& node);
void dump (int indent=0) const;
class SchedGraph :
public NonCopyable,
- private hash_map<const MachineInstr*, SchedGraphNode*>
+ private std::hash_map<const MachineInstr*, SchedGraphNode*>
{
private:
- vector<const BasicBlock*> bbVec; // basic blocks included in the graph
+ std::vector<const BasicBlock*> bbVec; // basic blocks included in the graph
SchedGraphNode* graphRoot; // the root and leaf are not inserted
SchedGraphNode* graphLeaf; // in the hash_map (see getNumNodes())
+ typedef std::hash_map<const MachineInstr*, SchedGraphNode*> map_base;
public:
- typedef hash_map<const MachineInstr*, SchedGraphNode*>::iterator iterator;
- typedef hash_map<const MachineInstr*, SchedGraphNode*>::const_iterator const_iterator;
+ using map_base::iterator;
+ using map_base::const_iterator;
public:
//
// Accessor methods
//
- const vector<const BasicBlock*>& getBasicBlocks() const { return bbVec; }
+ const std::vector<const BasicBlock*>& getBasicBlocks() const { return bbVec; }
const unsigned int getNumNodes() const { return size()+2; }
SchedGraphNode* getRoot() const { return graphRoot; }
SchedGraphNode* getLeaf() const { return graphLeaf; }
// Unordered iterators.
// Return values is pair<const MachineIntr*,SchedGraphNode*>.
//
- iterator begin() {
- return hash_map<const MachineInstr*, SchedGraphNode*>::begin();
- }
- iterator end() {
- return hash_map<const MachineInstr*, SchedGraphNode*>::end();
- }
- const_iterator begin() const {
- return hash_map<const MachineInstr*, SchedGraphNode*>::begin();
- }
- const_iterator end() const {
- return hash_map<const MachineInstr*, SchedGraphNode*>::end();
- }
-
+ using map_base::begin;
+ using map_base::end;
+
//
// Ordered iterators.
// Return values is pair<const MachineIntr*,SchedGraphNode*>.
void buildNodesforBB (const TargetMachine& target,
const BasicBlock* bb,
- vector<SchedGraphNode*>& memNodeVec,
+ std::vector<SchedGraphNode*>& memNod,
RegToRefVecMap& regToRefVecMap,
ValueToDefVecMap& valueToDefVecMap);
void findDefUseInfoAtInstr (const TargetMachine& target,
SchedGraphNode* node,
- vector<SchedGraphNode*>& memNodeVec,
+ std::vector<SchedGraphNode*>& memNode,
RegToRefVecMap& regToRefVecMap,
ValueToDefVecMap& valueToDefVecMap);
void addCDEdges (const TerminatorInst* term,
const TargetMachine& target);
- void addMemEdges (const vector<SchedGraphNode*>& memNodeVec,
+ void addMemEdges (const std::vector<SchedGraphNode*>& memNod,
const TargetMachine& target);
- void addCallCCEdges (const vector<SchedGraphNode*>& memNodeVec,
+ void addCallCCEdges (const std::vector<SchedGraphNode*>& memNod,
MachineCodeForBasicBlock& bbMvec,
const TargetMachine& target);
class SchedGraphSet :
public NonCopyable,
- private hash_map<const BasicBlock*, SchedGraph*>
+ private std::hash_map<const BasicBlock*, SchedGraph*>
{
private:
const Method* method;
public:
- typedef hash_map<const BasicBlock*, SchedGraph*>::iterator iterator;
- typedef hash_map<const BasicBlock*, SchedGraph*>::const_iterator const_iterator;
+ typedef std::hash_map<const BasicBlock*, SchedGraph*> map_base;
+ using map_base::iterator;
+ using map_base::const_iterator;
public:
/*ctor*/ SchedGraphSet (const Method* _method,
//
// Iterators
//
- iterator begin() {
- return hash_map<const BasicBlock*, SchedGraph*>::begin();
- }
- iterator end() {
- return hash_map<const BasicBlock*, SchedGraph*>::end();
- }
- const_iterator begin() const {
- return hash_map<const BasicBlock*, SchedGraph*>::begin();
- }
- const_iterator end() const {
- return hash_map<const BasicBlock*, SchedGraph*>::end();
- }
+ using map_base::begin;
+ using map_base::end;
//
// Debugging support
};
-//************************ External Functions *****************************/
-
-
-ostream& operator<<(ostream& os, const SchedGraphEdge& edge);
-
-ostream& operator<<(ostream& os, const SchedGraphNode& node);
-
-
-/***************************************************************************/
+std::ostream &operator<<(std::ostream& os, const SchedGraphEdge& edge);
+std::ostream &operator<<(std::ostream &os, const SchedGraphNode& node);
#endif
#include "SchedPriorities.h"
#include "Support/PostOrderIterator.h"
-
+#include <iostream>
+using std::cerr;
SchedPriorities::SchedPriorities(const Method* method,
const SchedGraph* _graph)
: curTime(0),
graph(_graph),
- methodLiveVarInfo(method), // expensive!
- lastUseMap(),
- nodeDelayVec(_graph->getNumNodes(),INVALID_LATENCY), //make errors obvious
+ methodLiveVarInfo(method), // expensive!
+ nodeDelayVec(_graph->getNumNodes(), INVALID_LATENCY), // make errors obvious
earliestForNode(_graph->getNumNodes(), 0),
earliestReadyTime(0),
- candsAsHeap(),
- candsAsSet(),
- mcands(),
nextToTry(candsAsHeap.begin())
{
methodLiveVarInfo.analyze();
E != node->endOutEdges(); ++E)
{
cycles_t sinkDelay = getNodeDelayRef((*E)->getSink());
- nodeDelay = max(nodeDelay, sinkDelay + (*E)->getMinDelay());
+ nodeDelay = std::max(nodeDelay, sinkDelay + (*E)->getMinDelay());
}
}
getNodeDelayRef(node) = nodeDelay;
#undef TEST_HEAP_CONVERSION
#ifdef TEST_HEAP_CONVERSION
- cout << "Before heap conversion:" << endl;
+ cerr << "Before heap conversion:\n";
copy(candsAsHeap.begin(), candsAsHeap.end(),
- ostream_iterator<NodeDelayPair*>(cout,"\n"));
+ ostream_iterator<NodeDelayPair*>(cerr,"\n"));
#endif
candsAsHeap.makeHeap();
#ifdef TEST_HEAP_CONVERSION
- cout << "After heap conversion:" << endl;
+ cerr << "After heap conversion:\n";
copy(candsAsHeap.begin(), candsAsHeap.end(),
- ostream_iterator<NodeDelayPair*>(cout,"\n"));
+ ostream_iterator<NodeDelayPair*>(cerr,"\n"));
#endif
}
+void
+SchedPriorities::insertReady(const SchedGraphNode* node)
+{
+ candsAsHeap.insert(node, nodeDelayVec[node->getNodeId()]);
+ candsAsSet.insert(node);
+ mcands.clear(); // ensure reset choices is called before any more choices
+ earliestReadyTime = std::min(earliestReadyTime,
+ earliestForNode[node->getNodeId()]);
+
+ if (SchedDebugLevel >= Sched_PrintSchedTrace)
+ {
+ cerr << " Cycle " << (long)getTime() << ": "
+ << " Node " << node->getNodeId() << " is ready; "
+ << " Delay = " << (long)getNodeDelayRef(node) << "; Instruction: \n";
+ cerr << " " << *node->getMachineInstr() << "\n";
+ }
+}
void
SchedPriorities::issuedReadyNodeAt(cycles_t curTime,
for (NodeHeap::const_iterator I=candsAsHeap.begin();
I != candsAsHeap.end(); ++I)
if (candsAsHeap.getNode(I))
- earliestReadyTime = min(earliestReadyTime,
+ earliestReadyTime = std::min(earliestReadyTime,
getEarliestForNodeRef(candsAsHeap.getNode(I)));
}
E != node->endOutEdges(); ++E)
{
cycles_t& etime = getEarliestForNodeRef((*E)->getSink());
- etime = max(etime, curTime + (*E)->getMinDelay());
+ etime = std::max(etime, curTime + (*E)->getMinDelay());
}
}
//----------------------------------------------------------------------
inline int
-SchedPriorities::chooseByRule1(vector<candIndex>& mcands)
+SchedPriorities::chooseByRule1(std::vector<candIndex>& mcands)
{
return (mcands.size() == 1)? 0 // only one choice exists so take it
: -1; // -1 indicates multiple choices
}
inline int
-SchedPriorities::chooseByRule2(vector<candIndex>& mcands)
+SchedPriorities::chooseByRule2(std::vector<candIndex>& mcands)
{
assert(mcands.size() >= 1 && "Should have at least one candidate here.");
for (unsigned i=0, N = mcands.size(); i < N; i++)
}
inline int
-SchedPriorities::chooseByRule3(vector<candIndex>& mcands)
+SchedPriorities::chooseByRule3(std::vector<candIndex>& mcands)
{
assert(mcands.size() >= 1 && "Should have at least one candidate here.");
int maxUses = candsAsHeap.getNode(mcands[0])->getNumOutEdges();
void
-SchedPriorities::findSetWithMaxDelay(vector<candIndex>& mcands,
+SchedPriorities::findSetWithMaxDelay(std::vector<candIndex>& mcands,
const SchedulingManager& S)
{
if (mcands.size() == 0 && nextToTry != candsAsHeap.end())
if (SchedDebugLevel >= Sched_PrintSchedTrace)
{
- cout << " Cycle " << this->getTime() << ": "
- << "Next highest delay = " << maxDelay << " : "
+ cerr << " Cycle " << (long)getTime() << ": "
+ << "Next highest delay = " << (long)maxDelay << " : "
<< mcands.size() << " Nodes with this delay: ";
for (unsigned i=0; i < mcands.size(); i++)
- cout << candsAsHeap.getNode(mcands[i])->getNodeId() << ", ";
- cout << endl;
+ cerr << candsAsHeap.getNode(mcands[i])->getNodeId() << ", ";
+ cerr << "\n";
}
}
}
{
const MachineInstr* minstr = graphNode->getMachineInstr();
- hash_map<const MachineInstr*, bool>::const_iterator
+ std::hash_map<const MachineInstr*, bool>::const_iterator
ui = lastUseMap.find(minstr);
if (ui != lastUseMap.end())
- return (*ui).second;
+ return ui->second;
// else check if instruction is a last use and save it in the hash_map
bool hasLastUse = false;
#include "llvm/Analysis/LiveVar/MethodLiveVarInfo.h"
#include "llvm/Target/MachineSchedInfo.h"
#include <list>
+#include <ostream>
class Method;
class MachineInstr;
const SchedGraphNode* node;
cycles_t delay;
NodeDelayPair(const SchedGraphNode* n, cycles_t d) : node(n), delay(d) {}
- inline bool operator< (const NodeDelayPair& np) { return delay < np.delay; }
+ inline bool operator<(const NodeDelayPair& np) { return delay < np.delay; }
};
inline bool
NDPLessThan(const NodeDelayPair* np1, const NodeDelayPair* np2)
{
- return (np1->delay < np2->delay);
+ return np1->delay < np2->delay;
}
-class NodeHeap: public list<NodeDelayPair*>, public NonCopyable {
+class NodeHeap: public std::list<NodeDelayPair*>, public NonCopyable {
public:
- typedef list<NodeDelayPair*>::iterator iterator;
- typedef list<NodeDelayPair*>::const_iterator const_iterator;
+ typedef std::list<NodeDelayPair*>::iterator iterator;
+ typedef std::list<NodeDelayPair*>::const_iterator const_iterator;
public:
- /*ctor*/ NodeHeap () : list<NodeDelayPair*>(), _size(0) {}
+ /*ctor*/ NodeHeap () : std::list<NodeDelayPair*>(), _size(0) {}
/*dtor*/ ~NodeHeap () {}
inline unsigned int size () const { return _size; }
iterator I=begin();
for ( ; I != end() && getDelay(I) >= delay; ++I)
;
- list<NodeDelayPair*>::insert(I, ndp);
+ std::list<NodeDelayPair*>::insert(I, ndp);
}
_size++;
}
cycles_t curTime;
const SchedGraph* graph;
MethodLiveVarInfo methodLiveVarInfo;
- hash_map<const MachineInstr*, bool> lastUseMap;
- vector<cycles_t> nodeDelayVec;
- vector<cycles_t> earliestForNode;
+ std::hash_map<const MachineInstr*, bool> lastUseMap;
+ std::vector<cycles_t> nodeDelayVec;
+ std::vector<cycles_t> earliestForNode;
cycles_t earliestReadyTime;
NodeHeap candsAsHeap; // candidate nodes, ready to go
- hash_set<const SchedGraphNode*> candsAsSet; // same entries as candsAsHeap,
+ std::hash_set<const SchedGraphNode*> candsAsSet;//same entries as candsAsHeap,
// but as set for fast lookup
- vector<candIndex> mcands; // holds pointers into cands
+ std::vector<candIndex> mcands; // holds pointers into cands
candIndex nextToTry; // next cand after the last
// one tried in this cycle
- int chooseByRule1 (vector<candIndex>& mcands);
- int chooseByRule2 (vector<candIndex>& mcands);
- int chooseByRule3 (vector<candIndex>& mcands);
+ int chooseByRule1 (std::vector<candIndex>& mcands);
+ int chooseByRule2 (std::vector<candIndex>& mcands);
+ int chooseByRule3 (std::vector<candIndex>& mcands);
- void findSetWithMaxDelay (vector<candIndex>& mcands,
+ void findSetWithMaxDelay (std::vector<candIndex>& mcands,
const SchedulingManager& S);
void computeDelays (const SchedGraph* graph);
};
-inline void
-SchedPriorities::insertReady(const SchedGraphNode* node)
-{
- candsAsHeap.insert(node, nodeDelayVec[node->getNodeId()]);
- candsAsSet.insert(node);
- mcands.clear(); // ensure reset choices is called before any more choices
- earliestReadyTime = min(earliestReadyTime,
- earliestForNode[node->getNodeId()]);
-
- if (SchedDebugLevel >= Sched_PrintSchedTrace)
- {
- cout << " Cycle " << this->getTime() << ": "
- << " Node " << node->getNodeId() << " is ready; "
- << " Delay = " << this->getNodeDelayRef(node) << "; Instruction: "
- << endl;
- cout << " " << *node->getMachineInstr() << endl;
- }
-}
-
inline void SchedPriorities::updateTime(cycles_t c) {
curTime = c;
nextToTry = candsAsHeap.begin();
mcands.clear();
}
-inline ostream& operator<< (ostream& os, const NodeDelayPair* nd) {
+inline std::ostream &operator<<(std::ostream &os, const NodeDelayPair* nd) {
return os << "Delay for node " << nd->node->getNodeId()
- << " = " << nd->delay << endl;
+ << " = " << (long)nd->delay << "\n";
}
-/***************************************************************************/
-
#endif
#include "llvm/BasicBlock.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "Support/STLExtras.h"
+#include <iostream>
+using std::cerr;
+using std::vector;
//------------------------------------------------------------------------
// class InstrTreeNode
InstructionNode::dumpNode(int indent) const
{
for (int i=0; i < indent; i++)
- cout << " ";
+ cerr << " ";
- cout << getInstruction()->getOpcodeName();
+ cerr << getInstruction()->getOpcodeName();
const vector<MachineInstr*> &mvec = getInstruction()->getMachineInstrVec();
if (mvec.size() > 0)
- cout << "\tMachine Instructions: ";
+ cerr << "\tMachine Instructions: ";
for (unsigned int i=0; i < mvec.size(); i++)
{
mvec[i]->dump(0);
if (i < mvec.size() - 1)
- cout << "; ";
+ cerr << "; ";
}
- cout << endl;
+ cerr << "\n";
}
VRegListNode::dumpNode(int indent) const
{
for (int i=0; i < indent; i++)
- cout << " ";
+ cerr << " ";
- cout << "List" << endl;
+ cerr << "List" << "\n";
}
VRegNode::dumpNode(int indent) const
{
for (int i=0; i < indent; i++)
- cout << " ";
+ cerr << " ";
- cout << "VReg " << getValue() << "\t(type "
- << (int) getValue()->getValueType() << ")" << endl;
+ cerr << "VReg " << getValue() << "\t(type "
+ << (int) getValue()->getValueType() << ")" << "\n";
}
void
ConstantNode::dumpNode(int indent) const
{
for (int i=0; i < indent; i++)
- cout << " ";
+ cerr << " ";
- cout << "Constant " << getValue() << "\t(type "
- << (int) getValue()->getValueType() << ")" << endl;
+ cerr << "Constant " << getValue() << "\t(type "
+ << (int) getValue()->getValueType() << ")" << "\n";
}
void
LabelNode::dumpNode(int indent) const
{
for (int i=0; i < indent; i++)
- cout << " ";
+ cerr << " ";
- cout << "Label " << getValue() << endl;
+ cerr << "Label " << getValue() << "\n";
}
//------------------------------------------------------------------------
InstrForest::~InstrForest()
{
- for (hash_map<const Instruction*, InstructionNode*>:: iterator I = begin();
+ for (std::hash_map<const Instruction*,InstructionNode*>::iterator I = begin();
I != end(); ++I)
delete (*I).second;
}
void
InstrForest::dump() const
{
- for (hash_set<InstructionNode*>::const_iterator I = treeRoots.begin();
+ for (std::hash_set<InstructionNode*>::const_iterator I = treeRoots.begin();
I != treeRoots.end(); ++I)
(*I)->dump(/*dumpChildren*/ 1, /*indent*/ 0);
}
#include "llvm/iPHINode.h"
#include "llvm/Target/MachineRegInfo.h"
#include "Support/CommandLine.h"
-#include <string.h>
-
+#include <iostream>
+using std::cerr;
//******************** Internal Data Declarations ************************/
if (SelectDebugLevel >= Select_DebugInstTrees)
{
- cout << "\n\n*** Instruction trees for method "
+ cerr << "\n\n*** Instruction trees for method "
<< (method->hasName()? method->getName() : "")
- << endl << endl;
+ << "\n\n";
instrForest.dump();
}
//
// Invoke BURG instruction selection for each tree
//
- const hash_set<InstructionNode*> &treeRoots = instrForest.getRootSet();
- for (hash_set<InstructionNode*>::const_iterator
+ const std::hash_set<InstructionNode*> &treeRoots = instrForest.getRootSet();
+ for (std::hash_set<InstructionNode*>::const_iterator
treeRootIter = treeRoots.begin(); treeRootIter != treeRoots.end();
++treeRootIter)
{
if (SelectDebugLevel >= Select_PrintMachineCode)
{
- cout << endl
- << "*** Machine instructions after INSTRUCTION SELECTION" << endl;
+ cerr << "\n*** Machine instructions after INSTRUCTION SELECTION\n";
MachineCodeForMethod::get(method).dump();
}
// insert the copy instruction to the predecessor BB
- vector<MachineInstr*> CopyInstVec;
+ std::vector<MachineInstr*> CopyInstVec;
MachineInstr *CpMI =
target.getRegInfo().cpValue2Value(PN->getIncomingValue(i), PN);
PHINode *PN = (PHINode *) (*IIt);
- Value *PhiCpRes = new Value(PN->getType(), PN->getValueType());
-
- string *Name = new string("PhiCp:");
- (*Name) += (int) PhiCpRes;
- PhiCpRes->setName( *Name );
-
+ Value *PhiCpRes = new Value(PN->getType(), PN->getValueType(),"PhiCp:");
// for each incoming value of the phi, insert phi elimination
//
for (unsigned i = 0; i < PN->getNumIncomingValues(); ++i) {
// insert the copy instruction to the predecessor BB
-
MachineInstr *CpMI =
target.getRegInfo().cpValue2Value(PN->getIncomingValue(i),
PhiCpRes);
InsertPhiElimInst(PN->getIncomingBlock(i), CpMI);
-
}
MachineCodeForBasicBlock& bbMvec = BB->getMachineInstrVec();
bbMvec.insert( bbMvec.begin(), CpMI2);
-
-
}
else break; // since PHI nodes can only be at the top
MachineCodeForVMInstr& mvec = vmInstr->getMachineInstrVec();
for (int i = (int) mvec.size()-1; i >= 0; i--)
{
- vector<MachineInstr*> loadConstVec =
+ std::vector<MachineInstr*> loadConstVec =
FixConstantOperandsForInstr(vmInstr, mvec[i], target);
if (loadConstVec.size() > 0)
if (ruleForNode == 0)
{
- cerr << "Could not match instruction tree for instr selection" << endl;
+ cerr << "Could not match instruction tree for instr selection\n";
assert(0);
return true;
}
#include "llvm/Instruction.h"
#include "llvm/Type.h"
#include "llvm/iMemory.h"
-
+using std::vector;
//*************************** Local Functions ******************************/
#include "llvm/Analysis/LiveVar/BBLiveVar.h"
#include "llvm/Analysis/LiveVar/MethodLiveVarInfo.h"
#include "llvm/CodeGen/MachineInstr.h"
+
+/// BROKEN: Should not include sparc stuff directly into here
#include "../../Target/Sparc/SparcInternals.h" // Only for PHI defn
+using std::cerr;
+using std::endl;
+using std::pair;
//-----------------------------------------------------------------------------
// Constructor
if( DEBUG_LV > 1) { // debug msg
cerr << " *Iterating over machine instr ";
MInst->dump();
- cerr << endl;
+ cerr << "\n";
}
// iterate over MI operands to find defs
if( DEBUG_LV > 1) { // debug msg of level 2
cerr << " - phi operand ";
printValue( ArgVal );
- cerr << " came from BB ";
+ cerr << " came from BB ";
printValue( PhiArgMap[ ArgVal ]);
- cerr<<endl;
+ cerr << "\n";
}
} // if( IsPhi )
InSetChanged = true;
if( DEBUG_LV > 1) {
- cerr << " +Def: "; printValue( Op ); cerr << endl;
+ cerr << " +Def: "; printValue( Op ); cerr << "\n";
}
}
// map that contains phi args->BB they came
// set by calcDefUseSets & used by setPropagate
- hash_map<const Value *, const BasicBlock *, hashFuncValue> PhiArgMap;
+ std::hash_map<const Value *, const BasicBlock *> PhiArgMap;
// method to propogate an InSet to OutSet of a predecessor
bool setPropagate( LiveVarSet *const OutSetOfPred,
#include "llvm/Analysis/LiveVar/MethodLiveVarInfo.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "Support/PostOrderIterator.h"
-
+#include <iostream>
+using std::cout;
+using std::endl;
//************************** Constructor/Destructor ***************************
-MethodLiveVarInfo::MethodLiveVarInfo(const Method *const M) : Meth(M),
- BB2BBLVMap()
-{
- assert(! M->isExternal() ); // cannot be a prototype decleration
+MethodLiveVarInfo::MethodLiveVarInfo(const Method *const M) : Meth(M) {
+ assert(!M->isExternal() && "Cannot be a prototype declaration");
HasAnalyzed = false; // still we haven't called analyze()
}
if( (*MI).first ) // delete all LiveVarSets in MInst2LVSetBI
delete (*MI).second;
}
-
-
}
#include "llvm/Analysis/LiveVar/ValueSet.h"
#include "llvm/ConstantVals.h"
-
+#include <iostream>
+using std::cerr;
+using std::endl;
+using std::pair;
+using std::hash_set;
void printValue( const Value *const v) // func to print a Value
{
-
if (v->hasName())
cerr << v << "(" << ((*v).getName()) << ") ";
else if (Constant *C = dyn_cast<Constant>(v))
//---------------- Method implementations --------------------------
-
-
-ValueSet:: ValueSet() : hash_set<const Value *, hashFuncValue> () { }
-
// for performing two set unions
bool ValueSet::setUnion( const ValueSet *const set1) {
const_iterator set1it;
pair<iterator, bool> result;
bool changed = false;
- for( set1it = set1->begin() ; set1it != set1->end(); set1it++) {
+ for( set1it = set1->begin() ; set1it != set1->end(); ++set1it) {
// for all all elements in set1
result = insert( *set1it ); // insert to this set
if( result.second == true) changed = true;
const ValueSet *const set2) {
const_iterator set1it, set2it;
- for( set1it = set1->begin() ; set1it != set1->end(); set1it++) {
+ for( set1it = set1->begin() ; set1it != set1->end(); ++set1it) {
// for all elements in set1
iterator set2it = set2->find( *set1it ); // find wether the elem is in set2
if( set2it == set2->end() ) // if the element is not in set2
// for performing set subtraction
void ValueSet::setSubtract( const ValueSet *const set1) {
const_iterator set1it;
- for( set1it = set1->begin() ; set1it != set1->end(); set1it++)
+ for( set1it = set1->begin() ; set1it != set1->end(); ++set1it)
// for all elements in set1
erase( *set1it ); // erase that element from this set
}
void ValueSet::printSet() const { // for printing a live variable set
- const_iterator it;
- for( it = begin() ; it != end(); it++)
- printValue( *it );
+ for_each(begin(), end(), printValue);
}
#include "llvm/CodeGen/IGNode.h"
-
+#include <algorithm>
+#include <iostream>
+using std::cerr;
//-----------------------------------------------------------------------------
// Constructor
//-----------------------------------------------------------------------------
-IGNode::IGNode(LiveRange *const PLR, unsigned int Ind): Index(Ind),
- AdjList(),
- ParentLR(PLR)
+IGNode::IGNode(LiveRange *const PLR, unsigned int Ind) : Index(Ind),
+ ParentLR(PLR)
{
OnStack = false;
CurDegree = -1 ;
int neighs = AdjList.size();
if( neighs < 0) {
- cout << "\nAdj List size = " << neighs;
+ cerr << "\nAdj List size = " << neighs;
assert(0 && "Invalid adj list size");
}
- for(int i=0; i < neighs; i++) (AdjList[i])->decCurDegree();
+ for(int i=0; i < neighs; i++)
+ AdjList[i]->decCurDegree();
}
//-----------------------------------------------------------------------------
// two IGNodes together.
//-----------------------------------------------------------------------------
void IGNode::delAdjIGNode(const IGNode *const Node) {
- vector <IGNode *>::iterator It = AdjList.begin();
-
- // find Node
- for( ; It != AdjList.end() && (*It != Node); It++ ) ;
+ std::vector<IGNode *>::iterator It =
+ find(AdjList.begin(), AdjList.end(), Node);
assert( It != AdjList.end() ); // the node must be there
-
- AdjList.erase( It );
+
+ AdjList.erase(It);
}
#include "llvm/CodeGen/RegAllocCommon.h"
#include "llvm/CodeGen/LiveRange.h"
-
-
//----------------------------------------------------------------------------
// Class IGNode
//
class IGNode
{
- private:
-
const int Index; // index within IGNodeList
bool OnStack; // this has been pushed on to stack for coloring
- vector<IGNode *> AdjList; // adjacency list for this live range
+ std::vector<IGNode *> AdjList; // adjacency list for this live range
int CurDegree;
//
// Decremented when a neighbor is pushed on to the stack.
// After that, never incremented/set again nor used.
-
LiveRange *const ParentLR; // parent LR (cannot be a const)
};
-
-
-
-
-
-
#endif
#include "llvm/CodeGen/InterferenceGraph.h"
+#include "Support/STLExtras.h"
+#include <iostream>
+using std::cerr;
//-----------------------------------------------------------------------------
// Constructor: Records the RegClass and initalizes IGNodeList.
IG = NULL;
Size = 0;
if( DEBUG_RA) {
- cout << "Interference graph created!" << endl;
+ cerr << "Interference graph created!\n";
}
}
InterferenceGraph:: ~InterferenceGraph() {
// delete the matrix
- //
- if( IG )
- delete []IG;
+ for(unsigned int r=0; r < IGNodeList.size(); ++r)
+ delete[] IG[r];
+ delete[] IG;
// delete all IGNodes in the IGNodeList
- //
- vector<IGNode *>::const_iterator IGIt = IGNodeList.begin();
- for(unsigned i=0; i < IGNodeList.size() ; ++i) {
-
- const IGNode *const Node = IGNodeList[i];
- if( Node ) delete Node;
- }
-
+ for_each(IGNodeList.begin(), IGNodeList.end(), deleter<IGNode>);
}
void InterferenceGraph::createGraph()
{
Size = IGNodeList.size();
- IG = (char **) new char *[Size];
+ IG = new char*[Size];
for( unsigned int r=0; r < Size; ++r)
IG[r] = new char[Size];
// init IG matrix
for(unsigned int i=0; i < Size; i++)
- for( unsigned int j=0; j < Size ; j++)
+ for(unsigned int j=0; j < Size; j++)
IG[i][j] = 0;
}
//-----------------------------------------------------------------------------
void InterferenceGraph::addLRToIG(LiveRange *const LR)
{
- IGNode *Node = new IGNode(LR, IGNodeList.size() );
- IGNodeList.push_back( Node );
-
+ IGNodeList.push_back(new IGNode(LR, IGNodeList.size()));
}
char *val;
if( DEBUG_RA > 1)
- cout << "setting intf for: [" << row << "][" << col << "]" << endl;
+ cerr << "setting intf for: [" << row << "][" << col << "]\n";
( row > col) ? val = &IG[row][col]: val = &IG[col][row];
if( ! (*val) ) { // if this interf is not previously set
-
*val = 1; // add edges between nodes
IGNode1->addAdjIGNode( IGNode2 );
IGNode2->addAdjIGNode( IGNode1 );
const unsigned int col = LR2->getUserIGNode()->getIndex();
char ret;
- ( row > col) ? (ret = IG[row][col]) : (ret = IG[col][row]) ;
+ if (row > col)
+ ret = IG[row][col];
+ else
+ ret = IG[col][row];
return ret;
}
assertIGNode( SrcNode );
if( DEBUG_RA > 1) {
- cout << "Merging LRs: \""; LR1->printSet();
- cout << "\" and \""; LR2->printSet();
- cout << "\"" << endl;
+ cerr << "Merging LRs: \""; LR1->printSet();
+ cerr << "\" and \""; LR2->printSet();
+ cerr << "\"\n";
}
unsigned SrcDegree = SrcNode->getNumOfNeighbors();
for(unsigned int i=0; i < Size; i++) {
const IGNode *const Node = IGNodeList[i];
- if( ! Node )
- continue; // skip empty rows
-
- cout << " [" << i << "] ";
+ if(Node) {
+ cerr << " [" << i << "] ";
- for( unsigned int j=0; j < Size; j++) {
- if( j >= i) break;
- if( IG[i][j] ) cout << "(" << i << "," << j << ") ";
+ for( unsigned int j=0; j < i; j++) {
+ if(IG[i][j])
+ cerr << "(" << i << "," << j << ") ";
}
- cout << endl;
+ cerr << "\n";
}
+ }
}
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
void InterferenceGraph::printIGNodeList() const
{
- vector<IGNode *>::const_iterator IGIt = IGNodeList.begin(); // hash map iter
-
for(unsigned i=0; i < IGNodeList.size() ; ++i) {
-
const IGNode *const Node = IGNodeList[i];
- if( ! Node )
- continue;
-
- cout << " [" << Node->getIndex() << "] ";
- (Node->getParentLR())->printSet();
- //int Deg = Node->getCurDegree();
- cout << "\t <# of Neighs: " << Node->getNumOfNeighbors() << ">" << endl;
-
+ if (Node) {
+ cerr << " [" << Node->getIndex() << "] ";
+ Node->getParentLR()->printSet();
+ //int Deg = Node->getCurDegree();
+ cerr << "\t <# of Neighs: " << Node->getNumOfNeighbors() << ">\n";
+ }
}
}
-
-
-/* Title: InterferenceGraph.h
+/* Title: InterferenceGraph.h -*- C++ -*-
Author: Ruchira Sasanka
Date: July 20, 01
Purpose: Interference Graph used for register coloring.
#include "llvm/CodeGen/IGNode.h"
-typedef vector <IGNode *> IGNodeListType;
+typedef std::vector <IGNode *> IGNodeListType;
class InterferenceGraph
// to create it after adding all IGNodes to the IGNodeList
InterferenceGraph(RegClass *const RC);
+ ~InterferenceGraph();
+
void createGraph();
void addLRToIG(LiveRange *const LR);
void printIG() const;
void printIGNodeList() const;
-
- ~InterferenceGraph();
-
-
};
-
#endif
-
-/* Title: LiveRange.h
+/* Title: LiveRange.h -*- C++ -*-
Author: Ruchira Sasanka
Date: July 25, 01
Purpose: To keep info about a live range.
#include "llvm/Analysis/LiveVar/ValueSet.h"
#include "llvm/Type.h"
+#include <iostream>
class RegClass;
class IGNode;
if(SuggestedColor == -1 )
SuggestedColor = Col;
else if (DEBUG_RA)
- cerr << "Already has a suggested color " << Col << endl;
+ std::cerr << "Already has a suggested color " << Col << "\n";
}
inline unsigned getSuggestedColor() const {
#include "llvm/CodeGen/LiveRangeInfo.h"
+#include <iostream>
+using std::cerr;
//---------------------------------------------------------------------------
// Constructor
//---------------------------------------------------------------------------
LiveRangeInfo::LiveRangeInfo(const Method *const M,
const TargetMachine& tm,
- vector<RegClass *> &RCL)
- : Meth(M), LiveRangeMap(),
- TM(tm), RegClassList(RCL),
- MRI( tm.getRegInfo()),
- CallRetInstrList()
+ std::vector<RegClass *> &RCL)
+ : Meth(M), LiveRangeMap(), TM(tm),
+ RegClassList(RCL), MRI(tm.getRegInfo())
{ }
// Destructor: Deletes all LiveRanges in the LiveRangeMap
//---------------------------------------------------------------------------
LiveRangeInfo::~LiveRangeInfo() {
-
LiveRangeMapType::iterator MI = LiveRangeMap.begin();
for( ; MI != LiveRangeMap.end() ; ++MI) {
- if( (*MI).first ) {
-
- LiveRange *LR = (*MI).second;
-
- if( LR ) {
-
- // we need to be careful in deleting LiveRanges in LiveRangeMap
- // since two/more Values in the live range map can point to the same
- // live range. We have to make the other entries NULL when we delete
- // a live range.
-
- LiveRange::iterator LI = LR->begin();
-
- for( ; LI != LR->end() ; ++LI) {
- LiveRangeMap[*LI] = NULL;
- }
+ if (MI->first && MI->second) {
+ LiveRange *LR = MI->second;
- delete LR;
+ // we need to be careful in deleting LiveRanges in LiveRangeMap
+ // since two/more Values in the live range map can point to the same
+ // live range. We have to make the other entries NULL when we delete
+ // a live range.
- }
+ LiveRange::iterator LI = LR->begin();
+
+ for( ; LI != LR->end() ; ++LI)
+ LiveRangeMap[*LI] = 0;
+
+ delete LR;
}
}
-
}
L1->addSpillCost( L2->getSpillCost() ); // add the spill costs
- delete ( L2 ); // delete L2 as it is no longer needed
+ delete L2; // delete L2 as it is no longer needed
}
{
if( DEBUG_RA)
- cout << "Consturcting Live Ranges ..." << endl;
+ cerr << "Consturcting Live Ranges ...\n";
// first find the live ranges for all incoming args of the method since
// those LRs start from the start of the method
for( ; ArgIt != ArgList.end() ; ++ArgIt) { // for each argument
-
LiveRange * ArgRange = new LiveRange(); // creates a new LR and
const Value *const Val = (const Value *) *ArgIt;
assert( Val);
- ArgRange->add( Val ); // add the arg (def) to it
- LiveRangeMap[ Val ] = ArgRange;
+ ArgRange->add(Val); // add the arg (def) to it
+ LiveRangeMap[Val] = ArgRange;
// create a temp machine op to find the register class of value
//const MachineOperand Op(MachineOperand::MO_VirtualRegister);
if( DEBUG_RA > 1) {
- cout << " adding LiveRange for argument ";
- printValue( (const Value *) *ArgIt); cout << endl;
+ cerr << " adding LiveRange for argument ";
+ printValue((const Value *) *ArgIt); cerr << "\n";
}
}
Method::const_iterator BBI = Meth->begin(); // random iterator for BBs
-
for( ; BBI != Meth->end(); ++BBI) { // go thru BBs in random order
// Now find all LRs for machine the instructions. A new LR will be created
// get the iterator for machine instructions
const MachineCodeForBasicBlock& MIVec = (*BBI)->getMachineInstrVec();
- MachineCodeForBasicBlock::const_iterator
- MInstIterator = MIVec.begin();
+ MachineCodeForBasicBlock::const_iterator MInstIterator = MIVec.begin();
// iterate over all the machine instructions in BB
for( ; MInstIterator != MIVec.end(); MInstIterator++) {
// Now if the machine instruction is a call/return instruction,
// add it to CallRetInstrList for processing its implicit operands
- if( (TM.getInstrInfo()).isReturn( MInst->getOpCode()) ||
- (TM.getInstrInfo()).isCall( MInst->getOpCode()) )
+ if(TM.getInstrInfo().isReturn(MInst->getOpCode()) ||
+ TM.getInstrInfo().isCall(MInst->getOpCode()))
CallRetInstrList.push_back( MInst );
// iterate over MI operands to find defs
- for( MachineInstr::val_const_op_iterator OpI(MInst);!OpI.done(); ++OpI) {
-
- if( DEBUG_RA) {
+ for (MachineInstr::val_const_op_iterator OpI(MInst); !OpI.done(); ++OpI) {
+ if(DEBUG_RA) {
MachineOperand::MachineOperandType OpTyp =
OpI.getMachineOperand().getOperandType();
- if ( OpTyp == MachineOperand::MO_CCRegister) {
- cout << "\n**CC reg found. Is Def=" << OpI.isDef() << " Val:";
+ if (OpTyp == MachineOperand::MO_CCRegister) {
+ cerr << "\n**CC reg found. Is Def=" << OpI.isDef() << " Val:";
printValue( OpI.getMachineOperand().getVRegValue() );
- cout << endl;
+ cerr << "\n";
}
}
// create a new LR iff this operand is a def
if( OpI.isDef() ) {
-
const Value *const Def = *OpI;
-
// Only instruction values are accepted for live ranges here
-
if( Def->getValueType() != Value::InstructionVal ) {
- cout << "\n**%%Error: Def is not an instruction val. Def=";
- printValue( Def ); cout << endl;
+ cerr << "\n**%%Error: Def is not an instruction val. Def=";
+ printValue( Def ); cerr << "\n";
continue;
}
-
LiveRange *DefRange = LiveRangeMap[Def];
// see LR already there (because of multiple defs)
-
if( !DefRange) { // if it is not in LiveRangeMap
-
DefRange = new LiveRange(); // creates a new live range and
DefRange->add( Def ); // add the instruction (def) to it
LiveRangeMap[ Def ] = DefRange; // update the map
if( DEBUG_RA > 1) {
- cout << " creating a LR for def: ";
- printValue(Def); cout << endl;
+ cerr << " creating a LR for def: ";
+ printValue(Def); cerr << "\n";
}
// set the register class of the new live range
if(isCC && DEBUG_RA) {
- cout << "\a**created a LR for a CC reg:";
+ cerr << "\a**created a LR for a CC reg:";
printValue( OpI.getMachineOperand().getVRegValue() );
}
LiveRangeMap[ Def ] = DefRange;
if( DEBUG_RA > 1) {
- cout << " added to an existing LR for def: ";
- printValue( Def ); cout << endl;
+ cerr << " added to an existing LR for def: ";
+ printValue( Def ); cerr << "\n";
}
}
suggestRegs4CallRets();
if( DEBUG_RA)
- cout << "Initial Live Ranges constructed!" << endl;
+ cerr << "Initial Live Ranges constructed!\n";
}
//---------------------------------------------------------------------------
void LiveRangeInfo::coalesceLRs()
{
-
-
-
if( DEBUG_RA)
- cout << endl << "Coalscing LRs ..." << endl;
+ cerr << "\nCoalscing LRs ...\n";
Method::const_iterator BBI = Meth->begin(); // random iterator for BBs
// get the iterator for machine instructions
const MachineCodeForBasicBlock& MIVec = (*BBI)->getMachineInstrVec();
- MachineCodeForBasicBlock::const_iterator
- MInstIterator = MIVec.begin();
+ MachineCodeForBasicBlock::const_iterator MInstIterator = MIVec.begin();
// iterate over all the machine instructions in BB
for( ; MInstIterator != MIVec.end(); ++MInstIterator) {
const MachineInstr * MInst = *MInstIterator;
if( DEBUG_RA > 1) {
- cout << " *Iterating over machine instr ";
+ cerr << " *Iterating over machine instr ";
MInst->dump();
- cout << endl;
+ cerr << "\n";
}
//don't warn about labels
if (!((*UseI)->getType())->isLabelType() && DEBUG_RA) {
- cout<<" !! Warning: No LR for use "; printValue(*UseI);
- cout << endl;
+ cerr<<" !! Warning: No LR for use "; printValue(*UseI);
+ cerr << "\n";
}
continue; // ignore and continue
}
} // for all BBs
if( DEBUG_RA)
- cout << endl << "Coalscing Done!" << endl;
+ cerr << "\nCoalscing Done!\n";
}
void LiveRangeInfo::printLiveRanges()
{
LiveRangeMapType::iterator HMI = LiveRangeMap.begin(); // hash map iterator
- cout << endl << "Printing Live Ranges from Hash Map:" << endl;
- for( ; HMI != LiveRangeMap.end() ; HMI ++ ) {
- if( (*HMI).first && (*HMI).second ) {
- cout <<" "; printValue((*HMI).first); cout << "\t: ";
- ((*HMI).second)->printSet(); cout << endl;
+ cerr << "\nPrinting Live Ranges from Hash Map:\n";
+ for( ; HMI != LiveRangeMap.end() ; ++HMI) {
+ if( HMI->first && HMI->second ) {
+ cerr <<" "; printValue((*HMI).first); cerr << "\t: ";
+ HMI->second->printSet(); cerr << "\n";
}
}
}
-/* Title: LiveRangeInfo.h
+/* Title: LiveRangeInfo.h -*- C++ -*-
Author: Ruchira Sasanka
Date: Jun 30, 01
Purpose:
#include "llvm/CodeGen/RegClass.h"
-typedef hash_map <const Value *, LiveRange *, hashFuncValue> LiveRangeMapType;
-typedef vector <const MachineInstr *> CallRetInstrListType;
+typedef std::hash_map<const Value*, LiveRange*> LiveRangeMapType;
+typedef std::vector<const MachineInstr*> CallRetInstrListType;
const TargetMachine& TM; // target machine description
- vector<RegClass *> & RegClassList;// a vector containing register classess
+ std::vector<RegClass *> & RegClassList;// vector containing register classess
const MachineRegInfo& MRI; // machine reg info
LiveRangeInfo(const Method *const M,
const TargetMachine& tm,
- vector<RegClass *> & RCList);
+ std::vector<RegClass *> & RCList);
// Destructor to destroy all LiveRanges in the LiveRange Map
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/MachineFrameInfo.h"
+#include <iostream>
#include <math.h>
+using std::cerr;
// ***TODO: There are several places we add instructions. Validate the order
PhyRegAlloc::PhyRegAlloc(Method *M,
const TargetMachine& tm,
MethodLiveVarInfo *const Lvi)
- : RegClassList(),
- TM(tm),
- Meth(M),
+ : TM(tm), Meth(M),
mcInfo(MachineCodeForMethod::get(M)),
LVI(Lvi), LRI(M, tm, RegClassList),
MRI( tm.getRegInfo() ),
NumOfRegClasses(MRI.getNumOfRegClasses()),
- AddedInstrMap(), LoopDepthCalc(M), ResColList() {
+ LoopDepthCalc(M) {
// create each RegisterClass and put in RegClassList
//
- for( unsigned int rc=0; rc < NumOfRegClasses; rc++)
+ for(unsigned int rc=0; rc < NumOfRegClasses; rc++)
RegClassList.push_back( new RegClass(M, MRI.getMachineRegClass(rc),
&ResColList) );
}
//----------------------------------------------------------------------------
void PhyRegAlloc::createIGNodeListsAndIGs()
{
- if(DEBUG_RA ) cout << "Creating LR lists ..." << endl;
+ if(DEBUG_RA ) cerr << "Creating LR lists ...\n";
// hash map iterator
LiveRangeMapType::const_iterator HMI = (LRI.getLiveRangeMap())->begin();
if( !L) {
if( DEBUG_RA) {
- cout << "\n*?!?Warning: Null liver range found for: ";
- printValue( (*HMI).first) ; cout << endl;
+ cerr << "\n*?!?Warning: Null liver range found for: ";
+ printValue(HMI->first); cerr << "\n";
}
continue;
}
RegClassList[ rc ]->createInterferenceGraph();
if( DEBUG_RA)
- cout << "LRLists Created!" << endl;
+ cerr << "LRLists Created!\n";
}
for( ; LIt != LVSet->end(); ++LIt) {
if( DEBUG_RA > 1) {
- cout << "< Def="; printValue(Def);
- cout << ", Lvar="; printValue( *LIt); cout << "> ";
+ cerr << "< Def="; printValue(Def);
+ cerr << ", Lvar="; printValue( *LIt); cerr << "> ";
}
// get the live range corresponding to live var
else if(DEBUG_RA > 1) {
// we will not have LRs for values not explicitly allocated in the
// instruction stream (e.g., constants)
- cout << " warning: no live range for " ;
- printValue( *LIt); cout << endl; }
+ cerr << " warning: no live range for " ;
+ printValue(*LIt); cerr << "\n"; }
}
}
if( DEBUG_RA)
- cout << "\n For call inst: " << *MInst;
+ cerr << "\n For call inst: " << *MInst;
LiveVarSet::const_iterator LIt = LVSetAft->begin();
LiveRange *const LR = LRI.getLiveRangeForValue(*LIt );
if( LR && DEBUG_RA) {
- cout << "\n\tLR Aft Call: ";
+ cerr << "\n\tLR Aft Call: ";
LR->printSet();
}
if( LR && (LR != RetValLR) ) {
LR->setCallInterference();
if( DEBUG_RA) {
- cout << "\n ++Added call interf for LR: " ;
+ cerr << "\n ++Added call interf for LR: " ;
LR->printSet();
}
}
void PhyRegAlloc::buildInterferenceGraphs()
{
- if(DEBUG_RA) cout << "Creating interference graphs ..." << endl;
+ if(DEBUG_RA) cerr << "Creating interference graphs ...\n";
unsigned BBLoopDepthCost;
Method::const_iterator BBI = Meth->begin(); // random iterator for BBs
addInterferencesForArgs();
if( DEBUG_RA)
- cout << "Interference graphs calculted!" << endl;
+ cerr << "Interference graphs calculted!\n";
}
addInterference( *ArgIt, InSet, false ); // add interferences between
// args and LVars at start
if( DEBUG_RA > 1) {
- cout << " - %% adding interference for argument ";
- printValue( (const Value *) *ArgIt); cout << endl;
+ cerr << " - %% adding interference for argument ";
+ printValue((const Value *)*ArgIt); cerr << "\n";
}
}
}
// delete this condition checking later (must assert if Val is null)
if( !Val) {
if (DEBUG_RA)
- cout << "Warning: NULL Value found for operand" << endl;
+ cerr << "Warning: NULL Value found for operand\n";
continue;
}
assert( Val && "Value is NULL");
// nothing to worry if it's a const or a label
if (DEBUG_RA) {
- cout << "*NO LR for operand : " << Op ;
- cout << " [reg:" << Op.getAllocatedRegNum() << "]";
- cout << " in inst:\t" << *MInst << endl;
+ cerr << "*NO LR for operand : " << Op ;
+ cerr << " [reg:" << Op.getAllocatedRegNum() << "]";
+ cerr << " in inst:\t" << *MInst << "\n";
}
// if register is not allocated, mark register as invalid
// instruction, add them now.
//
if( AddedInstrMap[ MInst ] ) {
-
- deque<MachineInstr *> &IBef = (AddedInstrMap[MInst])->InstrnsBefore;
+ std::deque<MachineInstr *> &IBef = AddedInstrMap[MInst]->InstrnsBefore;
if( ! IBef.empty() ) {
-
- deque<MachineInstr *>::iterator AdIt;
+ std::deque<MachineInstr *>::iterator AdIt;
for( AdIt = IBef.begin(); AdIt != IBef.end() ; ++AdIt ) {
if( DEBUG_RA) {
cerr << "For inst " << *MInst;
- cerr << " PREPENDed instr: " << **AdIt << endl;
+ cerr << " PREPENDed instr: " << **AdIt << "\n";
}
MInstIterator = MIVec.insert( MInstIterator, *AdIt );
if((delay=TM.getInstrInfo().getNumDelaySlots(MInst->getOpCode())) >0){
move2DelayedInstr(MInst, *(MInstIterator+delay) );
- if(DEBUG_RA) cout<< "\nMoved an added instr after the delay slot";
+ if(DEBUG_RA) cerr<< "\nMoved an added instr after the delay slot";
}
else {
// Here we can add the "instructions after" to the current
// instruction since there are no delay slots for this instruction
- deque<MachineInstr *> &IAft = (AddedInstrMap[MInst])->InstrnsAfter;
+ std::deque<MachineInstr *> &IAft = AddedInstrMap[MInst]->InstrnsAfter;
if( ! IAft.empty() ) {
- deque<MachineInstr *>::iterator AdIt;
+ std::deque<MachineInstr *>::iterator AdIt;
++MInstIterator; // advance to the next instruction
if(DEBUG_RA) {
cerr << "For inst " << *MInst;
- cerr << " APPENDed instr: " << **AdIt << endl;
+ cerr << " APPENDed instr: " << **AdIt << "\n";
}
MInstIterator = MIVec.insert( MInstIterator, *AdIt );
RegClass *RC = LR->getRegClass();
const LiveVarSet *LVSetBef = LVI->getLiveVarSetBeforeMInst(MInst, BB);
-
- int TmpOff =
- mcInfo.pushTempValue(TM, MRI.getSpilledRegSize(RegType) );
+ mcInfo.pushTempValue(TM, MRI.getSpilledRegSize(RegType) );
MachineInstr *MIBef=NULL, *AdIMid=NULL, *MIAft=NULL;
return MRI.getUnifiedRegNum(RC->getID(), c);
else
assert( 0 && "FATAL: No free register could be found in reg class!!");
-
+ return 0;
}
-
-
-
//----------------------------------------------------------------------------
// This method modifies the IsColorUsedArr of the register class passed to it.
// It sets the bits corresponding to the registers used by this machine
LiveRange *const LRofImpRef =
LRI.getLiveRangeForValue( MInst->getImplicitRef(z) );
-
- if( LRofImpRef )
- if( LRofImpRef->hasColor() )
- IsColorUsedArr[ LRofImpRef->getColor() ] = true;
+
+ if(LRofImpRef && LRofImpRef->hasColor())
+ IsColorUsedArr[LRofImpRef->getColor()] = true;
}
-
-
-
}
void PhyRegAlloc:: move2DelayedInstr(const MachineInstr *OrigMI,
const MachineInstr *DelayedMI) {
-
// "added after" instructions of the original instr
- deque<MachineInstr *> &OrigAft = (AddedInstrMap[OrigMI])->InstrnsAfter;
+ std::deque<MachineInstr *> &OrigAft = AddedInstrMap[OrigMI]->InstrnsAfter;
// "added instructions" of the delayed instr
AddedInstrns *DelayAdI = AddedInstrMap[DelayedMI];
}
// "added after" instructions of the delayed instr
- deque<MachineInstr *> &DelayedAft = DelayAdI->InstrnsAfter;
+ std::deque<MachineInstr *> &DelayedAft = DelayAdI->InstrnsAfter;
// go thru all the "added after instructions" of the original instruction
// and append them to the "addded after instructions" of the delayed
// instructions
-
- deque<MachineInstr *>::iterator OrigAdIt;
-
- for( OrigAdIt = OrigAft.begin(); OrigAdIt != OrigAft.end() ; ++OrigAdIt ) {
- DelayedAft.push_back( *OrigAdIt );
- }
+ DelayedAft.insert(DelayedAft.end(), OrigAft.begin(), OrigAft.end());
// empty the "added after instructions" of the original instruction
OrigAft.clear();
-
}
//----------------------------------------------------------------------------
void PhyRegAlloc::printMachineCode()
{
- cout << endl << ";************** Method ";
- cout << Meth->getName() << " *****************" << endl;
+ cerr << "\n;************** Method " << Meth->getName()
+ << " *****************\n";
Method::const_iterator BBI = Meth->begin(); // random iterator for BBs
for( ; BBI != Meth->end(); ++BBI) { // traverse BBs in random order
- cout << endl ; printLabel( *BBI); cout << ": ";
+ cerr << "\n"; printLabel( *BBI); cerr << ": ";
// get the iterator for machine instructions
MachineCodeForBasicBlock& MIVec = (*BBI)->getMachineInstrVec();
MachineInstr *const MInst = *MInstIterator;
- cout << endl << "\t";
- cout << TargetInstrDescriptors[MInst->getOpCode()].opCodeString;
+ cerr << "\n\t";
+ cerr << TargetInstrDescriptors[MInst->getOpCode()].opCodeString;
//for(MachineInstr::val_const_op_iterator OpI(MInst);!OpI.done();++OpI) {
const Value *const Val = Op.getVRegValue () ;
// ****this code is temporary till NULL Values are fixed
if( ! Val ) {
- cout << "\t<*NULL*>";
+ cerr << "\t<*NULL*>";
continue;
}
// if a label or a constant
- if( (Val->getValueType() == Value::BasicBlockVal) ) {
-
- cout << "\t"; printLabel( Op.getVRegValue () );
- }
- else {
+ if(isa<BasicBlock>(Val) {
+ cerr << "\t"; printLabel( Op.getVRegValue () );
+ } else {
// else it must be a register value
const int RegNum = Op.getAllocatedRegNum();
- cout << "\t" << "%" << MRI.getUnifiedRegName( RegNum );
+ cerr << "\t" << "%" << MRI.getUnifiedRegName( RegNum );
if (Val->hasName() )
- cout << "(" << Val->getName() << ")";
+ cerr << "(" << Val->getName() << ")";
else
- cout << "(" << Val << ")";
+ cerr << "(" << Val << ")";
if( Op.opIsDef() )
- cout << "*";
+ cerr << "*";
const LiveRange *LROfVal = LRI.getLiveRangeForValue(Val);
if( LROfVal )
if( LROfVal->hasSpillOffset() )
- cout << "$";
+ cerr << "$";
}
}
else if(Op.getOperandType() == MachineOperand::MO_MachineRegister) {
- cout << "\t" << "%" << MRI.getUnifiedRegName(Op.getMachineRegNum());
+ cerr << "\t" << "%" << MRI.getUnifiedRegName(Op.getMachineRegNum());
}
else
- cout << "\t" << Op; // use dump field
+ cerr << "\t" << Op; // use dump field
}
unsigned NumOfImpRefs = MInst->getNumImplicitRefs();
if( NumOfImpRefs > 0 ) {
- cout << "\tImplicit:";
+ cerr << "\tImplicit:";
for(unsigned z=0; z < NumOfImpRefs; z++) {
printValue( MInst->getImplicitRef(z) );
- cout << "\t";
+ cerr << "\t";
}
}
} // for all machine instructions
-
- cout << endl;
+ cerr << "\n";
} // for all BBs
- cout << endl;
+ cerr << "\n";
}
assert( FirstMI && "No machine instruction in entry BB");
AddedInstrns *AI = AddedInstrMap[ FirstMI ];
- if ( !AI ) {
+ if (!AI) {
AI = new AddedInstrns();
- AddedInstrMap[ FirstMI ] = AI;
+ AddedInstrMap[FirstMI] = AI;
}
MRI.colorMethodArgs(Meth, LRI, AI );
//----------------------------------------------------------------------------
// Used to generate a label for a basic block
//----------------------------------------------------------------------------
-void PhyRegAlloc::printLabel(const Value *const Val)
-{
- if( Val->hasName() )
- cout << Val->getName();
+void PhyRegAlloc::printLabel(const Value *const Val) {
+ if (Val->hasName())
+ cerr << Val->getName();
else
- cout << "Label" << Val;
+ cerr << "Label" << Val;
}
void PhyRegAlloc::markUnusableSugColors()
{
- if(DEBUG_RA ) cout << "\nmarking unusable suggested colors ..." << endl;
+ if(DEBUG_RA ) cerr << "\nmarking unusable suggested colors ...\n";
// hash map iterator
LiveRangeMapType::const_iterator HMI = (LRI.getLiveRangeMap())->begin();
void PhyRegAlloc::allocateStackSpace4SpilledLRs()
{
- if(DEBUG_RA ) cout << "\nsetting LR stack offsets ..." << endl;
+ if(DEBUG_RA ) cerr << "\nsetting LR stack offsets ...\n";
// hash map iterator
LiveRangeMapType::const_iterator HMI = (LRI.getLiveRangeMap())->begin();
LiveRangeMapType::const_iterator HMIEnd = (LRI.getLiveRangeMap())->end();
for( ; HMI != HMIEnd ; ++HMI ) {
- if( (*HMI).first ) {
- LiveRange *L = (*HMI).second; // get the LiveRange
- if(L)
- if( ! L->hasColor() )
-
- // NOTE: ** allocating the size of long Type **
- L->setSpillOffFromFP(mcInfo.allocateSpilledValue(TM,
- Type::LongTy));
-
+ if(HMI->first && HMI->second) {
+ LiveRange *L = HMI->second; // get the LiveRange
+ if( ! L->hasColor() )
+ // NOTE: ** allocating the size of long Type **
+ L->setSpillOffFromFP(mcInfo.allocateSpilledValue(TM, Type::LongTy));
}
} // for all LR's in hash map
}
-/* Title: PhyRegAlloc.h
+/* Title: PhyRegAlloc.h -*- C++ -*-
Author: Ruchira Sasanka
Date: Aug 20, 01
Purpose: This is the main entry point for register allocation.
class AddedInstrns
{
public:
- deque<MachineInstr *> InstrnsBefore; // Added insts BEFORE an existing inst
- deque<MachineInstr *> InstrnsAfter; // Added insts AFTER an existing inst
-
- AddedInstrns() : InstrnsBefore(), InstrnsAfter() { }
+ std::deque<MachineInstr*> InstrnsBefore;// Added insts BEFORE an existing inst
+ std::deque<MachineInstr*> InstrnsAfter; // Added insts AFTER an existing inst
};
-typedef hash_map<const MachineInstr *, AddedInstrns *> AddedInstrMapType;
+typedef std::hash_map<const MachineInstr *, AddedInstrns *> AddedInstrMapType;
class PhyRegAlloc: public NonCopyable
{
- vector<RegClass *> RegClassList ; // vector of register classes
+ std::vector<RegClass *> RegClassList; // vector of register classes
const TargetMachine &TM; // target machine
const Method* Meth; // name of the method we work on
MachineCodeForMethod& mcInfo; // descriptor for method's native code
const BasicBlock *BB,
const unsigned OpNum);
- inline void constructLiveRanges()
- { LRI.constructLiveRanges(); }
+ inline void constructLiveRanges() { LRI.constructLiveRanges(); }
void colorIncomingArgs();
void colorCallRetArgs();
void addInterf4PseudoInstr(const MachineInstr *MInst);
-
public:
-
PhyRegAlloc(Method *const M, const TargetMachine& TM,
MethodLiveVarInfo *const Lvi);
-
~PhyRegAlloc();
// main method called for allocating registers
#include "llvm/CodeGen/RegClass.h"
-
+#include <iostream>
+using std::cerr;
//----------------------------------------------------------------------------
// This constructor inits IG. The actual matrix is created by a call to
: Meth(M), MRC(Mrc), RegClassID( Mrc->getRegClassID() ),
IG(this), IGNodeStack(), ReservedColorList(RCL) {
if( DEBUG_RA)
- cout << "Created Reg Class: " << RegClassID << endl;
+ cerr << "Created Reg Class: " << RegClassID << "\n";
IsColorUsedArr = new bool[ Mrc->getNumOfAllRegs() ];
}
//----------------------------------------------------------------------------
void RegClass::colorAllRegs()
{
- if(DEBUG_RA) cout << "Coloring IG of reg class " << RegClassID << " ...\n";
+ if(DEBUG_RA) cerr << "Coloring IG of reg class " << RegClassID << " ...\n";
// pre-color IGNodes
pushAllIGNodes(); // push all IG Nodes
bool PushedAll = pushUnconstrainedIGNodes();
if( DEBUG_RA) {
- cout << " Puhsed all-unconstrained IGNodes. ";
- if( PushedAll ) cout << " No constrained nodes left.";
- cout << endl;
+ cerr << " Puhsed all-unconstrained IGNodes. ";
+ if( PushedAll ) cerr << " No constrained nodes left.";
+ cerr << "\n";
}
if( PushedAll ) // if NO constrained nodes left
IGNode->pushOnStack(); // set OnStack and dec deg of neighs
if (DEBUG_RA > 1) {
- cout << " pushed un-constrained IGNode " << IGNode->getIndex() ;
- cout << " on to stack" << endl;
+ cerr << " pushed un-constrained IGNode " << IGNode->getIndex() ;
+ cerr << " on to stack\n";
}
}
else pushedall = false; // we didn't push all live ranges
}
else {
if( DEBUG_RA ) {
- cout << " Node " << Node->getIndex();
- cout << " already colored with color " << Node->getColor() << endl;
+ cerr << " Node " << Node->getIndex();
+ cerr << " already colored with color " << Node->getColor() << "\n";
}
}
if( !Node->hasColor() ) {
if( DEBUG_RA ) {
- cout << " Node " << Node->getIndex();
- cout << " - could not find a color (needs spilling)" << endl;
+ cerr << " Node " << Node->getIndex();
+ cerr << " - could not find a color (needs spilling)\n";
}
}
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/MachineRegInfo.h"
#include <stack>
+#include <iostream>
-typedef vector<unsigned int> ReservedColorListType;
+typedef std::vector<unsigned int> ReservedColorListType;
//-----------------------------------------------------------------------------
InterferenceGraph IG; // Interference graph - constructed by
// buildInterferenceGraph
- stack <IGNode *> IGNodeStack; // the stack used for coloring
+ std::stack<IGNode *> IGNodeStack; // the stack used for coloring
const ReservedColorListType *const ReservedColorList;
//
inline void printIGNodeList() const {
- cerr << "IG Nodes for Register Class " << RegClassID << ":" << endl;
+ std::cerr << "IG Nodes for Register Class " << RegClassID << ":" << "\n";
IG.printIGNodeList();
}
inline void printIG() {
- cerr << "IG for Register Class " << RegClassID << ":" << endl;
+ std::cerr << "IG for Register Class " << RegClassID << ":" << "\n";
IG.printIG();
}
-
};
-
-
-
-
-
-
#endif
#include "Support/StringExtras.h"
#include "Support/HashExtras.h"
#include <locale.h>
+using std::string;
namespace {
class SparcAsmPrinter {
- typedef hash_map<const Value*, int> ValIdMap;
+ typedef std::hash_map<const Value*, int> ValIdMap;
typedef ValIdMap:: iterator ValIdMapIterator;
typedef ValIdMap::const_iterator ValIdMapConstIterator;
- ostream &toAsm;
+ std::ostream &toAsm;
SlotCalculator Table; // map anonymous values to unique integer IDs
ValIdMap valToIdMap; // used for values not handled by SlotCalculator
const UltraSparc &Target;
} CurSection;
public:
- inline SparcAsmPrinter(ostream &o, const Module *M, const UltraSparc &t)
+ inline SparcAsmPrinter(std::ostream &o, const Module *M, const UltraSparc &t)
: toAsm(o), Table(SlotCalculator(M, true)), Target(t), CurSection(Unknown) {
emitModule(M);
}
void printGlobalVariable( const GlobalVariable* GV);
void printSingleConstant( const Constant* CV);
void printConstantValueOnly(const Constant* CV);
- void printConstant( const Constant* CV, string valID=string(""));
+ void printConstant( const Constant* CV, std::string valID = "");
unsigned int printOperands(const MachineInstr *MI, unsigned int opNum);
void printOneOperand(const MachineOperand &Op);
toAsm << "\n";
}
- string getValidSymbolName(const string &S) {
+ std::string getValidSymbolName(const string &S) {
string Result;
// Symbol names in Sparc assembly language have these rules:
case MachineOperand::MO_SignExtendedImmed:
case MachineOperand::MO_UnextendedImmed:
- toAsm << op.getImmedValue();
+ toAsm << (long)op.getImmedValue();
break;
default:
else
N = 1;
- toAsm << endl;
+ toAsm << "\n";
}
void
// Output a .size directive so the debugger knows the extents of the function
toAsm << ".EndOf_" << methName << ":\n\t.size "
<< methName << ", .EndOf_"
- << methName << "-" << methName << endl;
+ << methName << "-" << methName << "\n";
// Put some spaces between the methods
toAsm << "\n\n";
inline unsigned int
ConstantToAlignment(const Constant* CV, const TargetMachine& target)
{
- unsigned int constantSize;
if (ConstantArray* CPA = dyn_cast<ConstantArray>(CV))
if (ArrayTypeIsString(cast<ArrayType>(CPA->getType())))
return SizeToAlignment(1 + CPA->getNumOperands(), target);
{
if (CV->getType() == Type::FloatTy || CV->getType() == Type::DoubleTy)
toAsm << "0r"; // FP constants must have this prefix
- toAsm << CV->getStrValue() << endl;
+ toAsm << CV->getStrValue() << "\n";
}
else if (ConstantPointer* CPP = dyn_cast<ConstantPointer>(CV))
{
- if (! CPP->isNullValue())
- assert(0 && "Cannot yet print non-null pointer constants to assembly");
- else
- toAsm << (void*) NULL << endl;
+ assert(CPP->isNullValue() &&
+ "Cannot yet print non-null pointer constants to assembly");
+ toAsm << "0\n";
}
- else if (ConstantPointerRef* CPRef = dyn_cast<ConstantPointerRef>(CV))
+ else if (isa<ConstantPointerRef>(CV))
{
assert(0 && "Cannot yet initialize pointer refs in assembly");
}
if (CPA && isStringCompatible(CPA))
{ // print the string alone and return
- toAsm << "\t" << ".ascii" << "\t" << getAsCString(CPA) << endl;
+ toAsm << "\t" << ".ascii" << "\t" << getAsCString(CPA) << "\n";
}
else if (CPA)
{ // Not a string. Print the values in successive locations
- const vector<Use>& constValues = CPA->getValues();
+ const std::vector<Use> &constValues = CPA->getValues();
for (unsigned i=1; i < constValues.size(); i++)
this->printConstantValueOnly(cast<Constant>(constValues[i].get()));
}
else if (ConstantStruct *CPS = dyn_cast<ConstantStruct>(CV))
{ // Print the fields in successive locations
- const vector<Use>& constValues = CPS->getValues();
+ const std::vector<Use>& constValues = CPS->getValues();
for (unsigned i=1; i < constValues.size(); i++)
this->printConstantValueOnly(cast<Constant>(constValues[i].get()));
}
valID = getID(CV);
toAsm << "\t.align\t" << ConstantToAlignment(CV, Target)
- << endl;
+ << "\n";
// Print .size and .type only if it is not a string.
ConstantArray *CPA = dyn_cast<ConstantArray>(CV);
if (CPA && isStringCompatible(CPA))
{ // print it as a string and return
- toAsm << valID << ":" << endl;
- toAsm << "\t" << ".ascii" << "\t" << getAsCString(CPA) << endl;
+ toAsm << valID << ":\n";
+ toAsm << "\t" << ".ascii" << "\t" << getAsCString(CPA) << "\n";
return;
}
- toAsm << "\t.type" << "\t" << valID << ",#object" << endl;
+ toAsm << "\t.type" << "\t" << valID << ",#object\n";
unsigned int constSize = ConstantToSize(CV, Target);
if (constSize)
toAsm << "\t.size" << "\t" << valID << ","
- << constSize << endl;
+ << constSize << "\n";
- toAsm << valID << ":" << endl;
+ toAsm << valID << ":\n";
this->printConstantValueOnly(CV);
}
void
SparcAsmPrinter::printGlobalVariable(const GlobalVariable* GV)
{
- toAsm << "\t.global\t" << getID(GV) << endl;
+ toAsm << "\t.global\t" << getID(GV) << "\n";
if (GV->hasInitializer())
printConstant(GV->getInitializer(), getID(GV));
else {
toAsm << "\t.align\t"
- << TypeToAlignment(GV->getType()->getElementType(), Target) << endl;
- toAsm << "\t.type\t" << getID(GV) << ",#object" << endl;
+ << TypeToAlignment(GV->getType()->getElementType(), Target) << "\n";
+ toAsm << "\t.type\t" << getID(GV) << ",#object\n";
toAsm << "\t.reserve\t" << getID(GV) << ","
<< TypeToSize(GV->getType()->getElementType(), Target)
- << endl;
+ << "\n";
}
}
static void
FoldConstants(const Module *M,
- hash_set<const Constant*>& moduleConstants)
+ std::hash_set<const Constant*>& moduleConstants)
{
for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
if (! (*I)->isExternal())
{
- const hash_set<const Constant*>& pool =
+ const std::hash_set<const Constant*>& pool =
MachineCodeForMethod::get(*I).getConstantPoolValues();
moduleConstants.insert(pool.begin(), pool.end());
}
// lets force these constants into the slot table so that we can get
// unique names for unnamed constants also.
//
- hash_set<const Constant*> moduleConstants;
+ std::hash_set<const Constant*> moduleConstants;
FoldConstants(M, moduleConstants);
// Now, emit the three data sections separately; the cost of I/O should
}
}
- for (hash_set<const Constant*>::const_iterator I = moduleConstants.begin(),
+ for (std::hash_set<const Constant*>::const_iterator
+ I = moduleConstants.begin(),
E = moduleConstants.end(); I != E; ++I)
printConstant(*I);
}
}
- toAsm << endl;
+ toAsm << "\n";
}
// used.
//
void
-UltraSparc::emitAssembly(const Module *M, ostream &toAsm) const
+UltraSparc::emitAssembly(const Module *M, std::ostream &toAsm) const
{
SparcAsmPrinter Print(toAsm, M, *this);
}
static inline MachineInstr*
CreateIntSetInstruction(int64_t C, Value* dest,
- vector<TmpInstruction*>& tempVec)
+ std::vector<TmpInstruction*>& tempVec)
{
MachineInstr* minstr;
uint64_t absC = (C >= 0)? C : -C;
static inline MachineInstr*
CreateUIntSetInstruction(uint64_t C, Value* dest,
- vector<TmpInstruction*>& tempVec)
+ std::vector<TmpInstruction*>& tempVec)
{
MachineInstr* minstr;
if (C > (unsigned int) ~0)
//
void
UltraSparcInstrInfo::CreateCodeToLoadConst(Value* val,
- Instruction* dest,
- vector<MachineInstr*>& minstrVec,
- vector<TmpInstruction*>& tempVec) const
+ Instruction* dest,
+ std::vector<MachineInstr*>& minstrVec,
+ std::vector<TmpInstruction*>& tempVec) const
{
MachineInstr* minstr;
//
void
UltraSparcInstrInfo::CreateCodeToCopyIntToFloat(Method* method,
- Value* val,
- Instruction* dest,
- vector<MachineInstr*>& minstrVec,
- vector<TmpInstruction*>& tempVec,
- TargetMachine& target) const
+ Value* val,
+ Instruction* dest,
+ std::vector<MachineInstr*>& minstrVec,
+ std::vector<TmpInstruction*>& tempVec,
+ TargetMachine& target) const
{
assert((val->getType()->isIntegral() || val->getType()->isPointerType())
&& "Source type must be integral");
assert((dest->getType() ==Type::FloatTy || dest->getType() ==Type::DoubleTy)
&& "Dest type must be float/double");
- const MachineFrameInfo& frameInfo = ((UltraSparc&) target).getFrameInfo();
-
MachineCodeForMethod& mcinfo = MachineCodeForMethod::get(method);
int offset = mcinfo.allocateLocalVar(target, val);
//
void
UltraSparcInstrInfo::CreateCodeToCopyFloatToInt(Method* method,
- Value* val,
- Instruction* dest,
- vector<MachineInstr*>& minstrVec,
- vector<TmpInstruction*>& tempVec,
- TargetMachine& target) const
+ Value* val,
+ Instruction* dest,
+ std::vector<MachineInstr*>& minstrVec,
+ std::vector<TmpInstruction*>& tempVec,
+ TargetMachine& target) const
{
assert((val->getType() ==Type::FloatTy || val->getType() ==Type::DoubleTy)
&& "Source type must be float/double");
assert((dest->getType()->isIntegral() || dest->getType()->isPointerType())
&& "Dest type must be integral");
- const MachineFrameInfo& frameInfo = ((UltraSparc&) target).getFrameInfo();
-
MachineCodeForMethod& mcinfo = MachineCodeForMethod::get(method);
int offset = mcinfo.allocateLocalVar(target, val);
#include "llvm/ConstantVals.h"
#include "Support/MathExtras.h"
#include <math.h>
-
+using std::vector;
//************************* Forward Declarations ***************************/
const InstructionNode* vmInstrNode,
Value* ptrVal,
Value* arrayOffsetVal,
- const vector<Value*>& idxVec,
+ const std::vector<Value*>& idxVec,
const TargetMachine& target);
static TmpInstruction*
GetTmpForCC(Value* boolVal, const Method* method, const Type* ccType)
{
- typedef hash_map<const Value*, TmpInstruction*> BoolTmpCache;
+ typedef std::hash_map<const Value*, TmpInstruction*> BoolTmpCache;
static BoolTmpCache boolToTmpCache; // Map boolVal -> TmpInstruction*
static const Method* lastMethod = NULL; // Use to flush cache between methods
{
MachineInstr* minstr = NULL; // return NULL if we cannot exploit constant
getMinstr2 = NULL; // to create a cheaper instruction
- bool needNeg = false;
Value* constOp = ((InstrTreeNode*) instrNode->rightChild())->getValue();
assert(isa<Constant>(constOp));
TargetMachine &target,
MachineInstr** mvec)
{
- int64_t s0=0; // used to avoid overloading ambiguity below
-
const MachineFrameInfo& frameInfo = target.getFrameInfo();
// The second operand is the stack size. If it does not fit in the
TargetMachine &target,
MachineInstr** mvec)
{
- int64_t s0=0; // used to avoid overloading ambiguity below
-
mvec[0] = new MachineInstr(RESTORE);
mvec[0]->SetMachineOperand(0, target.getRegInfo().getZeroRegNum());
- mvec[0]->SetMachineOperand(1, MachineOperand::MO_SignExtendedImmed, s0);
+ mvec[0]->SetMachineOperand(1, MachineOperand::MO_SignExtendedImmed,
+ (int64_t)0);
mvec[0]->SetMachineOperand(2, target.getRegInfo().getZeroRegNum());
return 1;
bool checkCast = false; // initialize here to use fall-through
int nextRule;
int forwardOperandNum = -1;
- int64_t s0=0, s8=8; // variables holding constants to avoid
- uint64_t u0=0; // overloading ambiguities below
for (unsigned i=0; i < MAX_INSTR_PER_VMINSTR; i++)
mvec[i] = NULL;
mvec[0] = new MachineInstr(JMPLRET);
mvec[0]->SetMachineOperand(0, MachineOperand::MO_VirtualRegister,
returnReg);
- mvec[0]->SetMachineOperand(1, MachineOperand::MO_SignExtendedImmed,s8);
+ mvec[0]->SetMachineOperand(1, MachineOperand::MO_SignExtendedImmed,
+ (int64_t)8);
mvec[0]->SetMachineOperand(2, target.getRegInfo().getZeroRegNum());
if (returnInstr->getReturnValue() != NULL)
int n = numInstr++;
mvec[n] = new MachineInstr(SETHI);
mvec[n]->SetMachineOperand(0,MachineOperand::MO_UnextendedImmed,
- s0);
+ (int64_t)0);
mvec[n]->SetMachineOperand(1,MachineOperand::MO_VirtualRegister,
setCCInstr);
}
phi->getOperand(i));
break;
}
-#endif NEED_PHI_MACHINE_INSTRS
+#endif // NEED_PHI_MACHINE_INSTRS
case 71: // reg: VReg
case 72: // reg: Constant
return 0;
}
-#endif SPARC_INSTR_SELECTION_SUPPORT_h
+#endif
//
virtual void CreateCodeToLoadConst(Value* val,
Instruction* dest,
- vector<MachineInstr*>& minstrVec,
- vector<TmpInstruction*>& tempVec) const;
+ std::vector<MachineInstr*>& minstrVec,
+ std::vector<TmpInstruction*>& tmp) const;
// Create an instruction sequence to copy an integer value `val'
virtual void CreateCodeToCopyIntToFloat(Method* method,
Value* val,
Instruction* dest,
- vector<MachineInstr*>& minstrVec,
- vector<TmpInstruction*>& tempVec,
+ std::vector<MachineInstr*>& minstr,
+ std::vector<TmpInstruction*>& temp,
TargetMachine& target) const;
// Similarly, create an instruction sequence to copy an FP value
virtual void CreateCodeToCopyFloatToInt(Method* method,
Value* val,
Instruction* dest,
- vector<MachineInstr*>& minstrVec,
- vector<TmpInstruction*>& tempVec,
+ std::vector<MachineInstr*>& minstr,
+ std::vector<TmpInstruction*>& temp,
TargetMachine& target) const;
// create copy instruction(s)
CreateCopyInstructionsByType(const TargetMachine& target,
Value* src,
Instruction* dest,
- vector<MachineInstr*>& minstrVec) const;
+ std::vector<MachineInstr*>& minstr) const;
};
LiveRangeInfo& LRI) const;
void suggestReg4CallAddr(const MachineInstr * CallMI, LiveRangeInfo& LRI,
- vector<RegClass *> RCList) const;
+ std::vector<RegClass *> RCList) const;
// the register allocator in association with method calling. See
// SparcRegInfo.cpp for more details
//
- void moveInst2OrdVec(vector<MachineInstr *> &OrdVec, MachineInstr *UnordInst,
- PhyRegAlloc &PRA ) const;
+ void moveInst2OrdVec(std::vector<MachineInstr *> &OrdVec,
+ MachineInstr *UnordInst,
+ PhyRegAlloc &PRA) const;
- void OrderAddedInstrns( vector<MachineInstr *> &UnordVec,
- vector<MachineInstr *> &OrdVec,
- PhyRegAlloc &PRA) const;
+ void OrderAddedInstrns(std::vector<MachineInstr *> &UnordVec,
+ std::vector<MachineInstr *> &OrdVec,
+ PhyRegAlloc &PRA) const;
// To find whether a particular call is to a var arg method
else if( ty <= Type::DoubleTyID)
res = FloatRegClassID; // sparc float reg class
else {
- cerr << "TypeID: " << ty << endl;
+ std::cerr << "TypeID: " << ty << "\n";
assert(0 && "Cannot resolve register class for type");
return 0;
}
LiveRangeInfo& LRI) const;
void suggestRegs4CallArgs(const MachineInstr *const CallMI,
- LiveRangeInfo& LRI, vector<RegClass *> RCL) const;
+ LiveRangeInfo& LRI,
+ std::vector<RegClass *> RCL) const;
void suggestReg4RetValue(const MachineInstr *const RetMI,
- LiveRangeInfo& LRI ) const;
+ LiveRangeInfo& LRI) const;
void colorMethodArgs(const Method *const Meth, LiveRangeInfo& LRI,
// given the unified register number, this gives the name
// for generating assembly code or debugging.
//
- inline const string getUnifiedRegName(int reg) const {
+ inline const std::string getUnifiedRegName(int reg) const {
if( reg < 32 )
return SparcIntRegOrder::getRegName(reg);
else if ( reg < (64 + 32) )
// The fllowing methods are used by instruction selection
//
- inline unsigned int getRegNumInCallersWindow(int reg) {
+ inline unsigned getRegNumInCallersWindow(int reg) {
if (reg == InvalidRegNum || reg >= 32)
return reg;
return SparcIntRegOrder::getRegNumInCallersWindow(reg);
// module. The specified module must have been compiled before this may be
// used.
//
- virtual void emitAssembly(const Module *M, ostream &OutStr) const;
+ virtual void emitAssembly(const Module *M, std::ostream &OutStr) const;
};
-#include "llvm/CodeGen/IGNode.h"
#include "SparcInternals.h"
-
+#include "llvm/CodeGen/IGNode.h"
#include "llvm/Target/Sparc.h"
+#include <iostream>
+using std::cerr;
//-----------------------------------------------------------------------------
// Int Register Class - method for coloring a node in the interference graph.
}
if( DEBUG_RA ) {
- cout << "\nColoring LR [CallInt=" << LR->isCallInterference() <<"]:";
+ cerr << "\nColoring LR [CallInt=" << LR->isCallInterference() <<"]:";
LR->printSet();
}
// there are no call interferences. Otherwise, it will get spilled.
if (DEBUG_RA)
- cout << "\n -Coloring with sug color: " << SugCol;
+ cerr << "\n -Coloring with sug color: " << SugCol;
LR->setColor( LR->getSuggestedColor() );
return;
}
else if(DEBUG_RA)
- cout << "\n Couldn't alloc Sug col - LR voloatile & calls interf";
+ cerr << "\n Couldn't alloc Sug col - LR voloatile & calls interf";
}
else if ( DEBUG_RA ) { // can't allocate the suggested col
cerr << " \n Could NOT allocate the suggested color (already used) ";
- LR->printSet(); cerr << endl;
+ LR->printSet(); cerr << "\n";
}
}
if( ColorFound) {
LR->setColor(c); // first color found in preffered order
- if (DEBUG_RA) cout << "\n Colored after first search with col " << c ;
+ if (DEBUG_RA) cerr << "\n Colored after first search with col " << c ;
}
// if color is not found because of call interference
// since LR span across calls, must save across calls
//
LR->markForSaveAcrossCalls();
- if(DEBUG_RA) cout << "\n Colored after SECOND search with col " << c ;
+ if(DEBUG_RA) cerr << "\n Colored after SECOND search with col " << c ;
}
}
}
else if (DEBUG_RA) { // can't allocate the suggested col
cerr << " Could NOT allocate the suggested color for LR ";
- LR->printSet(); cerr << endl;
+ LR->printSet(); cerr << "\n";
}
}
// Int register names in same order as enum in class SparcIntRegOrder
-static string const IntRegNames[] =
+static const std::string IntRegNames[] =
{
"o0", "o1", "o2", "o3", "o4", "o5", "o7",
"l0", "l1", "l2", "l3", "l4", "l5", "l6", "l7",
static unsigned int const NumOfAllRegs = o6 + 1;
- static const string getRegName(const unsigned reg) {
+ static const std::string getRegName(const unsigned reg) {
assert( reg < NumOfAllRegs );
return IntRegNames[reg];
}
// Float Register Class
//-----------------------------------------------------------------------------
-static string const FloatRegNames[] =
+static const std::string FloatRegNames[] =
{
"f0", "f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "f9",
"f10", "f11", "f12", "f13", "f14", "f15", "f16", "f17", "f18", "f19",
static unsigned int const StartOfAllRegs = f0;
- static const string getRegName(const unsigned reg) {
+ static const std::string getRegName(const unsigned reg) {
assert( reg < NumOfAllRegs );
return FloatRegNames[reg];
}
//-----------------------------------------------------------------------------
-static string const IntCCRegNames[] =
+static const std::string IntCCRegNames[] =
{
"xcc", "ccr"
};
xcc, ccr // only one is available - see the note above
};
- static const string getRegName(const unsigned reg) {
+ static const std::string getRegName(const unsigned reg) {
assert( reg < 2 );
return IntCCRegNames[reg];
}
//-----------------------------------------------------------------------------
-static string const FloatCCRegNames[] =
+static const std::string FloatCCRegNames[] =
{
"fcc0", "fcc1", "fcc2", "fcc3"
};
fcc0, fcc1, fcc2, fcc3
};
- static const string getRegName(const unsigned reg) {
+ static const std::string getRegName(const unsigned reg) {
assert( reg < 4 );
return FloatCCRegNames[reg];
}
#include "llvm/Analysis/LiveVar/MethodLiveVarInfo.h"
#include "llvm/CodeGen/PhyRegAlloc.h"
#include "llvm/DerivedTypes.h"
+#include <iostream>
+using std::cerr;
//---------------------------------------------------------------------------
// Purpose:
//---------------------------------------------------------------------------
const Value *
UltraSparcRegInfo::getCallInstRetVal(const MachineInstr *CallMI) const {
-
unsigned OpCode = CallMI->getOpCode();
- unsigned NumOfImpRefs = CallMI->getNumImplicitRefs();
+ unsigned NumOfImpRefs = CallMI->getNumImplicitRefs();
- if( OpCode == CALL ) {
+ if (OpCode == CALL) {
// The one before the last implicit operand is the return value of
// a CALL instr
if( CallMI->implicitRefIsDefined(NumOfImpRefs-2) )
return CallMI->getImplicitRef(NumOfImpRefs-2);
- }
- else if( OpCode == JMPLCALL) {
+ } else if (OpCode == JMPLCALL) {
// The last implicit operand is the return value of a JMPL
//
- if( NumOfImpRefs > 0 )
- if( CallMI->implicitRefIsDefined(NumOfImpRefs-1) )
- return CallMI->getImplicitRef(NumOfImpRefs-1);
+ if(NumOfImpRefs > 0)
+ if (CallMI->implicitRefIsDefined(NumOfImpRefs-1))
+ return CallMI->getImplicitRef(NumOfImpRefs-1);
}
else
assert(0 && "OpCode must be CALL/JMPL for a call instr");
//---------------------------------------------------------------------------
void UltraSparcRegInfo::suggestReg4CallAddr(const MachineInstr * CallMI,
LiveRangeInfo& LRI,
- vector<RegClass *> RCList) const {
+ std::vector<RegClass *> RCList) const {
const Value *RetAddrVal = getCallInstRetAddr( CallMI );
// that on to the stack pos of LR
if( isArgInReg ) {
-
- MachineInstr *AdIBef =
- cpReg2MemMI(UniArgReg, getFramePointer(),
- LR->getSpillOffFromFP(), RegType );
+ cpReg2MemMI(UniArgReg, getFramePointer(),
+ LR->getSpillOffFromFP(), RegType );
FirstAI->InstrnsBefore.push_back( AdMI );
}
//---------------------------------------------------------------------------
void UltraSparcRegInfo::suggestRegs4CallArgs(const MachineInstr *const CallMI,
LiveRangeInfo& LRI,
- vector<RegClass *> RCList) const {
+ std::vector<RegClass *> RCList) const {
assert ( (UltraSparcInfo->getInstrInfo()).isCall(CallMI->getOpCode()) );
if( !LR ) {
if( DEBUG_RA) {
cerr << " ERROR: In call instr, no LR for arg: " ;
- printValue(CallArg); cerr << endl;
+ printValue(CallArg); cerr << "\n";
}
assert(0 && "NO LR for call arg");
// continue;
else if (DEBUG_RA)
// Do NOTHING as this will be colored as a normal value.
- cerr << " Regr not suggested for int call arg" << endl;
+ cerr << " Regr not suggested for int call arg\n";
}
else if( RegType == FPSingleRegType && (argNo*2 +1)< NumOfFloatArgRegs)
if( !RetValLR ) {
cerr << "\nNo LR for:";
printValue( RetVal );
- cerr << endl;
+ cerr << "\n";
assert( RetValLR && "ERR:No LR for non-void return value");
//return;
}
// Now color all args of the call instruction
//-------------------------------------------
- vector <MachineInstr *> AddedInstrnsBefore;
+ std::vector<MachineInstr *> AddedInstrnsBefore;
unsigned NumOfCallArgs = getCallInstNumArgs( CallMI );
if( !LR ) {
if( DEBUG_RA) {
cerr << " ERROR: In call instr, no LR for arg: " ;
- printValue(CallArg); cerr << endl;
+ printValue(CallArg); cerr << "\n";
}
assert(0 && "NO LR for call arg");
// continue;
cerr << *(AddedInstrnsBefore[i]);
}
- vector <MachineInstr *> TmpVec;
+ std::vector<MachineInstr *> TmpVec;
OrderAddedInstrns(AddedInstrnsBefore, TmpVec, PRA);
if( DEBUG_RA ) {
// The first implicit operand is the return value of a return instr
const Value *RetVal = RetMI->getImplicitRef(0);
- MachineInstr *AdMI;
LiveRange *const LR = LRI.getLiveRangeForValue( RetVal );
if( !LR ) {
cerr << "\nNo LR for:";
printValue( RetVal );
- cerr << endl;
+ cerr << "\n";
assert( LR && "No LR for return value of non-void method");
//return;
}
// The first implicit operand is the return value of a return instr
const Value *RetVal = RetMI->getImplicitRef(0);
- MachineInstr *AdMI;
LiveRange *const LR = LRI.getLiveRangeForValue( RetVal );
if( ! LR ) {
cerr << "\nNo LR for:";
printValue( RetVal );
- cerr << endl;
+ cerr << "\n";
// assert( LR && "No LR for return value of non-void method");
return;
}
// the LR received UniLRReg but must be colored with UniRetReg
// to pass as the return value
-
- AdMI = cpReg2RegMI( UniLRReg, UniRetReg, RegType);
- RetAI->InstrnsBefore.push_back( AdMI );
+ RetAI->InstrnsBefore.push_back(cpReg2RegMI(UniLRReg, UniRetReg, RegType));
}
else { // if the LR is spilled
-
- AdMI = cpMem2RegMI(getFramePointer(), LR->getSpillOffFromFP(),
- UniRetReg, RegType);
- RetAI->InstrnsBefore.push_back( AdMI );
- cout << "\nCopied the return value from stack";
+ MachineInstr *AdMI = cpMem2RegMI(getFramePointer(),
+ LR->getSpillOffFromFP(),
+ UniRetReg, RegType);
+ RetAI->InstrnsBefore.push_back(AdMI);
+ cerr << "\nCopied the return value from stack\n";
}
} // if there is a return value
// has set to record which registers were saved/restored
//
- hash_set<unsigned> PushedRegSet;
-
-
+ std::hash_set<unsigned> PushedRegSet;
// Now find the LR of the return value of the call
// The last *implicit operand* is the return value of a call
cerr << " *Node " << (LR->getUserIGNode())->getIndex();
if( ! LR->hasColor() ) {
- cerr << " - could not find a color" << endl;
+ cerr << " - could not find a color\n";
return;
}
cerr << " colored with color "<< LR->getColor();
if( RegClassID == IntRegClassID ) {
+ cerr<< " [" << SparcIntRegOrder::getRegName(LR->getColor()) << "]\n";
- cerr<< " [" << SparcIntRegOrder::getRegName(LR->getColor()) ;
- cerr << "]" << endl;
- }
- else if ( RegClassID == FloatRegClassID) {
+ } else if ( RegClassID == FloatRegClassID) {
cerr << "[" << SparcFloatRegOrder::getRegName(LR->getColor());
if( LR->getTypeID() == Type::DoubleTyID )
cerr << "+" << SparcFloatRegOrder::getRegName(LR->getColor()+1);
- cerr << "]" << endl;
+ cerr << "]\n";
}
}
//---------------------------------------------------------------------------
-void UltraSparcRegInfo::OrderAddedInstrns( vector<MachineInstr *> &UnordVec,
- vector<MachineInstr *> &OrdVec,
- PhyRegAlloc &PRA) const{
+void UltraSparcRegInfo::OrderAddedInstrns(std::vector<MachineInstr *> &UnordVec,
+ std::vector<MachineInstr *> &OrdVec,
+ PhyRegAlloc &PRA) const{
/*
Problem: We can have instructions inserted by RegAlloc like
CouldMoveAll = true;
- vector<MachineInstr *>::iterator DefIt = UnordVec.begin();
+ std::vector<MachineInstr *>::iterator DefIt = UnordVec.begin();
for( ; DefIt != UnordVec.end(); ++DefIt ) {
bool DefEqUse = false;
- vector<MachineInstr *>::iterator UseIt = DefIt;
+ std::vector<MachineInstr *>::iterator UseIt = DefIt;
UseIt++;
for( ; UseIt != UnordVec.end(); ++UseIt ) {
-void UltraSparcRegInfo::moveInst2OrdVec(vector<MachineInstr *> &OrdVec,
+void UltraSparcRegInfo::moveInst2OrdVec(std::vector<MachineInstr *> &OrdVec,
MachineInstr *UnordInst,
PhyRegAlloc &PRA ) const {
// before in the OrdVec
bool DefEqUse = false;
- vector<MachineInstr *>::iterator OrdIt = OrdVec.begin();
+ std::vector<MachineInstr *>::iterator OrdIt = OrdVec.begin();
for( ; OrdIt != OrdVec.end(); ++OrdIt ) {
#include "llvm/CodeGen/PhyRegAlloc.h"
#include "llvm/Analysis/LiveVar/MethodLiveVarInfo.h"
#include "llvm/Method.h"
-
+#include <iostream>
+using std::cerr;
// Build the MachineInstruction Description Array...
const MachineInstrDescriptor SparcMachineInstrDesc[] = {
if ( (M)->isExternal() ) // don't process prototypes
return;
- if( DEBUG_RA ) {
- cerr << endl << "******************** Method "<< (M)->getName();
- cerr << " ********************" <<endl;
- }
+ if( DEBUG_RA )
+ cerr << "\n******************** Method "<< M->getName()
+ << " ********************\n";
MethodLiveVarInfo LVI(M ); // Analyze live varaibles
LVI.analyze();
PRA.allocateRegisters();
- if( DEBUG_RA ) cerr << endl << "Register allocation complete!" << endl;
+ if( DEBUG_RA ) cerr << "\nRegister allocation complete!\n";
}
StructSize = (StructSize/TyAlign + 1) * TyAlign; // Add padding...
// Keep track of maximum alignment constraint
- StructAlignment = max(TyAlign, StructAlignment);
+ StructAlignment = std::max(TyAlign, StructAlignment);
MemberOffsets.push_back(StructSize);
StructSize += TySize; // Consume space for this data item...
// TargetData Class Implementation
//===----------------------------------------------------------------------===//
-TargetData::TargetData(const string &TargetName, unsigned char PtrSize = 8,
+TargetData::TargetData(const std::string &TargetName, unsigned char PtrSize = 8,
unsigned char PtrAl = 8, unsigned char DoubleAl = 8,
unsigned char FloatAl = 4, unsigned char LongAl = 8,
unsigned char IntAl = 4, unsigned char ShortAl = 2,
}
unsigned TargetData::getIndexedOffset(const Type *ptrTy,
- const vector<Value*> &Idx) const {
+ const std::vector<Value*> &Idx) const {
const PointerType *PtrTy = cast<const PointerType>(ptrTy);
unsigned Result = 0;
// (stl_algo.h).
//
inline static bool
-RUConflict(const vector<resourceId_t>& fromRVec,
- const vector<resourceId_t>& toRVec)
+RUConflict(const std::vector<resourceId_t>& fromRVec,
+ const std::vector<resourceId_t>& toRVec)
{
unsigned fN = fromRVec.size(), tN = toRVec.size();
{
// check if instr. #2 can start executing `gap' cycles after #1
// by checking for resource conflicts in each overlapping cycle
- cycles_t numOverlap = min(fromRU.numCycles - gap, toRU.numCycles);
+ cycles_t numOverlap =std::min(fromRU.numCycles - gap, toRU.numCycles);
for (cycles_t c = 0; c <= numOverlap-1; c++)
if (RUConflict(fromRU.resourcesByCycle[gap + c],
toRU.resourcesByCycle[c]))
// most instructions will probably behave the same as their class.
// Cannot allocate a vector of InstrRUsage so new each one.
//
- vector<InstrRUsage> instrRUForClasses;
+ std::vector<InstrRUsage> instrRUForClasses;
instrRUForClasses.resize(numSchedClasses);
for (InstrSchedClass sc = 0; sc < numSchedClasses; sc++) {
// instrRUForClasses.push_back(new InstrRUsage);
void
-MachineSchedInfo::computeInstrResources(const vector<InstrRUsage>&
+MachineSchedInfo::computeInstrResources(const std::vector<InstrRUsage>&
instrRUForClasses)
{
int numOpCodes = mii->getNumRealOpCodes();
void
-MachineSchedInfo::computeIssueGaps(const vector<InstrRUsage>&
+MachineSchedInfo::computeIssueGaps(const std::vector<InstrRUsage>&
instrRUForClasses)
{
int numOpCodes = mii->getNumRealOpCodes();
{
issueGaps[OpCodePair(fromOp,toOp)] = instrPairGap;
conflictLists[fromOp].push_back(toOp);
- longestIssueConflict = max(longestIssueConflict, instrPairGap);
+ longestIssueConflict = std::max(longestIssueConflict, instrPairGap);
}
}
}
#include "Support/STLExtras.h"
#include <map>
#include <algorithm>
+#include <iostream>
+using std::cerr;
#include "llvm/Assembly/Writer.h"
}
static Instruction *ConvertMallocToType(MallocInst *MI, const Type *Ty,
- const string &Name, ValueMapCache &VMC){
+ const std::string &Name,
+ ValueMapCache &VMC){
BasicBlock *BB = MI->getParent();
BasicBlock::iterator It = BB->end();
// index array. If there are, check to see if removing them causes us to
// get to the right type...
//
- vector<Value*> Indices = GEP->copyIndices();
+ std::vector<Value*> Indices = GEP->copyIndices();
const Type *BaseType = GEP->getPointerOperand()->getType();
const Type *ElTy = 0;
// Check to see if 'N' is an expression that can be converted to
// the appropriate size... if so, allow it.
//
- vector<Value*> Indices;
+ std::vector<Value*> Indices;
const Type *ElTy = ConvertableToGEP(PTy, I->getOperand(1), Indices);
if (ElTy) {
assert(ElTy == PVTy && "Internal error, setup wrong!");
BasicBlock *BB = I->getParent();
BasicBlock::InstListType &BIL = BB->getInstList();
- string Name = I->getName(); if (!Name.empty()) I->setName("");
+ std::string Name = I->getName(); if (!Name.empty()) I->setName("");
Instruction *Res; // Result of conversion
ValueHandle IHandle(VMC, I); // Prevent I from being removed!
// index array. If there are, check to see if removing them causes us to
// get to the right type...
//
- vector<Value*> Indices = GEP->copyIndices();
+ std::vector<Value*> Indices = GEP->copyIndices();
const Type *BaseType = GEP->getPointerOperand()->getType();
const Type *PVTy = cast<PointerType>(Ty)->getElementType();
Res = 0;
// Check to see if 'N' is an expression that can be converted to
// the appropriate size... if so, allow it.
//
- vector<Value*> Indices;
+ std::vector<Value*> Indices;
const Type *ElTy = ConvertableToGEP(NewSrcTy, I->getOperand(1),
Indices, &It);
if (ElTy) {
case Instruction::Add:
if (isa<PointerType>(Ty)) {
Value *IndexVal = I->getOperand(V == I->getOperand(0) ? 1 : 0);
- vector<Value*> Indices;
+ std::vector<Value*> Indices;
if (const Type *ETy = ConvertableToGEP(Ty, IndexVal, Indices)) {
const Type *RetTy = PointerType::get(ETy);
// They could be loading the first element of a composite type...
if (const CompositeType *CT = dyn_cast<CompositeType>(LoadedTy)) {
unsigned Offset = 0; // No offset, get first leaf.
- vector<Value*> Indices; // Discarded...
+ std::vector<Value*> Indices; // Discarded...
LoadedTy = getStructOffsetType(CT, Offset, Indices, false);
assert(Offset == 0 && "Offset changed from zero???");
}
// Check to see if the second argument is an expression that can
// be converted to the appropriate size... if so, allow it.
//
- vector<Value*> Indices;
+ std::vector<Value*> Indices;
const Type *ElTy = ConvertableToGEP(Ty, Index, Indices);
delete TempScale; // Free our temporary multiply if we made it
BasicBlock *BB = I->getParent();
BasicBlock::InstListType &BIL = BB->getInstList();
- string Name = I->getName(); if (!Name.empty()) I->setName("");
+ std::string Name = I->getName(); if (!Name.empty()) I->setName("");
Instruction *Res; // Result of conversion
//cerr << endl << endl << "Type:\t" << Ty << "\nInst: " << I << "BB Before: " << BB << endl;
case Instruction::Add:
if (isa<PointerType>(NewTy)) {
Value *IndexVal = I->getOperand(OldVal == I->getOperand(0) ? 1 : 0);
- vector<Value*> Indices;
+ std::vector<Value*> Indices;
BasicBlock::iterator It = find(BIL.begin(), BIL.end(), I);
if (const Type *ETy = ConvertableToGEP(NewTy, IndexVal, Indices, &It)) {
// If successful, convert the add to a GEP
- const Type *RetTy = PointerType::get(ETy);
+ //const Type *RetTy = PointerType::get(ETy);
// First operand is actually the given pointer...
Res = new GetElementPtrInst(NewVal, Indices, Name);
assert(cast<PointerType>(Res->getType())->getElementType() == ETy &&
const Type *LoadedTy =
cast<PointerType>(NewVal->getType())->getElementType();
- vector<Value*> Indices;
+ std::vector<Value*> Indices;
Indices.push_back(ConstantUInt::get(Type::UIntTy, 0));
if (const CompositeType *CT = dyn_cast<CompositeType>(LoadedTy)) {
Res->setOperand(1, ConvertExpressionToType(I->getOperand(1), NewPT, VMC));
} else { // Replace the source pointer
const Type *ValTy = cast<PointerType>(NewTy)->getElementType();
- vector<Value*> Indices;
+ std::vector<Value*> Indices;
#if 0
Indices.push_back(ConstantUInt::get(Type::UIntTy, 0));
while (ArrayType *AT = dyn_cast<ArrayType>(ValTy)) {
// Perform the conversion now...
//
- vector<Value*> Indices;
+ std::vector<Value*> Indices;
const Type *ElTy = ConvertableToGEP(NewVal->getType(), Index, Indices, &It);
assert(ElTy != 0 && "GEP Conversion Failure!");
Res = new GetElementPtrInst(NewVal, Indices, Name);
// Check to see if the second argument is an expression that can
// be converted to the appropriate size... if so, allow it.
//
- vector<Value*> Indices;
+ std::vector<Value*> Indices;
const Type *ElTy = ConvertableToGEP(NewVal->getType(), I->getOperand(1),
Indices, &It);
assert(ElTy != 0 && "GEP Conversion Failure!");
case Instruction::Call: {
Value *Meth = I->getOperand(0);
- vector<Value*> Params(I->op_begin()+1, I->op_end());
+ std::vector<Value*> Params(I->op_begin()+1, I->op_end());
- vector<Value*>::iterator OI = find(Params.begin(), Params.end(), OldVal);
+ std::vector<Value*>::iterator OI =
+ find(Params.begin(), Params.end(), OldVal);
assert (OI != Params.end() && "Not using value!");
*OI = NewVal;
#include <map>
#include <vector>
-typedef pair<BasicBlock *, Value*> BBConstTy;
-typedef map<BBConstTy, CastInst *> CachedCopyMap;
+typedef std::pair<BasicBlock *, Value*> BBConstTy;
+typedef std::map<BBConstTy, CastInst *> CachedCopyMap;
static Value *NormalizePhiOperand(PHINode *PN, Value *CPV,
BasicBlock *Pred, CachedCopyMap &CopyCache) {
// Create a copy instruction and add it to the cache...
CastInst *Inst = new CastInst(CPV, CPV->getType());
- CopyCache.insert(make_pair(BBConstTy(Pred, CPV), Inst));
+ CopyCache.insert(std::make_pair(BBConstTy(Pred, CPV), Inst));
// Insert the copy just before the terminator inst of the predecessor BB
assert(Pred->getTerminator() && "Degenerate BB encountered!");
bool Changed = false;
for (Method::iterator BI = M->begin(), BE = M->end(); BI != BE; ++BI) {
- vector<PHINode*> phis; // normalizing invalidates BB iterator
+ std::vector<PHINode*> phis; // normalizing invalidates BB iterator
for (BasicBlock::iterator II = (*BI)->begin(); II != (*BI)->end(); ++II) {
if (PHINode *PN = dyn_cast<PHINode>(*II))
break; // All PHIs occur at top of BB!
}
- for (vector<PHINode*>::iterator PI=phis.begin(); PI != phis.end(); ++PI)
+ for (std::vector<PHINode*>::iterator PI=phis.begin(); PI != phis.end();++PI)
for (unsigned i = 0; i < (*PI)->getNumIncomingValues(); ++i) {
Value *Op = (*PI)->getIncomingValue(i);
//
static inline
bool mergeDuplicateConstants(Module *M, unsigned &ConstantNo,
- map<Constant*, GlobalVariable*> &CMap) {
+ std::map<Constant*, GlobalVariable*> &CMap) {
Module::GlobalListType &GList = M->getGlobalList();
if (GList.size() <= ConstantNo) return false; // No new constants
bool MadeChanges = false;
Constant *Init = GV->getInitializer();
// Check to see if the initializer is already known...
- map<Constant*, GlobalVariable*>::iterator I = CMap.find(Init);
+ std::map<Constant*, GlobalVariable*>::iterator I = CMap.find(Init);
if (I == CMap.end()) { // Nope, add it to the map
- CMap.insert(make_pair(Init, GV));
+ CMap.insert(std::make_pair(Init, GV));
} else { // Yup, this is a duplicate!
// Make all uses of the duplicate constant use the cannonical version...
GV->replaceAllUsesWith(I->second);
// deal with passes.
//
bool ConstantMerge::mergeDuplicateConstants(Module *M) {
- map<Constant*, GlobalVariable*> Constants;
+ std::map<Constant*, GlobalVariable*> Constants;
unsigned LastConstantSeen = 0;
return ::mergeDuplicateConstants(M, LastConstantSeen, Constants);
}
#include "llvm/iTerminators.h"
#include "llvm/iOther.h"
#include <algorithm>
+#include <iostream>
+using std::vector;
+using std::string;
+using std::cerr;
static const Type *PtrSByte = 0; // 'sbyte*' type
SymbolTable *ST = M->getSymbolTable();
if (!ST) return false;
- map<string, vector<Method*> > Methods;
+ std::map<string, vector<Method*> > Methods;
// Loop over the entries in the symbol table. If an entry is a method pointer,
// then add it to the Methods map. We do a two pass algorithm here to avoid
//
for (SymbolTable::iterator I = ST->begin(), E = ST->end(); I != E; ++I)
if (const PointerType *PT = dyn_cast<PointerType>(I->first))
- if (const MethodType *MT = dyn_cast<MethodType>(PT->getElementType())) {
+ if (isa<MethodType>(PT->getElementType())) {
SymbolTable::VarMap &Plane = I->second;
for (SymbolTable::type_iterator PI = Plane.begin(), PE = Plane.end();
PI != PE; ++PI) {
// Now we have a list of all methods with a particular name. If there is more
// than one entry in a list, merge the methods together.
//
- for (map<string, vector<Method*> >::iterator I = Methods.begin(),
+ for (std::map<string, vector<Method*> >::iterator I = Methods.begin(),
E = Methods.end(); I != E; ++I) {
vector<Method*> &Methods = I->second;
Method *Implementation = 0; // Find the implementation
cerr << "Warning: Found methods types that are not compatible:\n";
for (unsigned i = 0; i < Methods.size(); ++i) {
cerr << "\t" << Methods[i]->getType()->getDescription() << " %"
- << Methods[i]->getName() << endl;
+ << Methods[i]->getName() << "\n";
}
cerr << " No linkage of methods named '" << Methods[0]->getName()
<< "' performed!\n";
++i;
}
} else {
- cerr << "Cannot convert use of method: " << U << endl;
+ cerr << "Cannot convert use of method: " << U << "\n";
++i;
}
}
// ShouldNukSymtabEntry - Return true if this module level symbol table entry
// should be eliminated.
//
-static inline bool ShouldNukeSymtabEntry(const pair<string, Value*> &E) {
+static inline bool ShouldNukeSymtabEntry(const std::pair<string, Value*> &E) {
// Nuke all names for primitive types!
if (cast<Type>(E.second)->isPrimitiveType()) return true;
Value *Src = CI->getOperand(0);
// Move the cast instruction to the current insert position...
- --InsertPos; // New position for cast to go...
- swap(*InsertPos, *I); // Cast goes down, PHI goes up
+ --InsertPos; // New position for cast to go...
+ std::swap(*InsertPos, *I); // Cast goes down, PHI goes up
if (isa<PHINode>(Src) && // Handle case #1
cast<PHINode>(Src)->getParent() == BB) {
if (M->hasSymbolTable()) {
SymbolTable *ST = M->getSymbolTable();
- const set<const Type *> &UsedTypes = FUT.getTypes();
+ const std::set<const Type *> &UsedTypes = FUT.getTypes();
// Check the symbol table for superfluous type entries that aren't used in
// the program
// Calculate which methods are reachable from the external methods in the call
// graph.
//
- set<cfg::CallGraphNode*> ReachableNodes(df_begin(&CallGraph),
- df_end(&CallGraph));
+ std::set<cfg::CallGraphNode*> ReachableNodes(df_begin(&CallGraph),
+ df_end(&CallGraph));
// Loop over the methods in the module twice. The first time is used to drop
// references that methods have to each other before they are deleted. The
// second pass removes the methods that need to be removed.
//
- vector<cfg::CallGraphNode*> MethodsToDelete; // Track unused methods
+ std::vector<cfg::CallGraphNode*> MethodsToDelete; // Track unused methods
for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I) {
cfg::CallGraphNode *N = CallGraph[*I];
if (!ReachableNodes.count(N)) { // Not reachable??
// Unreachables methods have been found and should have no references to them,
// delete them now.
//
- for (vector<cfg::CallGraphNode*>::iterator I = MethodsToDelete.begin(),
+ for (std::vector<cfg::CallGraphNode*>::iterator I = MethodsToDelete.begin(),
E = MethodsToDelete.end(); I != E; ++I)
delete CallGraph.removeMethodFromModule(*I);
#include "llvm/iOther.h"
#include <algorithm>
#include <map>
+#include <iostream>
+using std::cerr;
#include "llvm/Assembly/Writer.h"
// current values into those specified by ValueMap.
//
static inline void RemapInstruction(Instruction *I,
- map<const Value *, Value*> &ValueMap) {
+ std::map<const Value *, Value*> &ValueMap) {
for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
const Value *Op = I->getOperand(op);
continue; // Globals and constants don't get relocated
if (!V) {
- cerr << "Val = " << endl << Op << "Addr = " << (void*)Op << endl;
- cerr << "Inst = " << I;
+ cerr << "Val = \n" << Op << "Addr = " << (void*)Op;
+ cerr << "\nInst = " << I;
}
assert(V && "Referenced value not in value map!");
I->setOperand(op, V);
const Method *CalledMeth = CI->getCalledMethod();
if (CalledMeth == 0 || // Can't inline external method or indirect call!
CalledMeth->isExternal()) return false;
- Method *CurrentMeth = CI->getParent()->getParent();
//cerr << "Inlining " << CalledMeth->getName() << " into "
- // << CurrentMeth->getName() << endl;
+ // << CurrentMeth->getName() << "\n";
BasicBlock *OrigBB = CI->getParent();
// code's values. This includes all of: Method arguments, instruction values,
// constant pool entries, and basic blocks.
//
- map<const Value *, Value*> ValueMap;
+ std::map<const Value *, Value*> ValueMap;
// Add the method arguments to the mapping: (start counting at 1 to skip the
// method reference itself)
#include "llvm/iTerminators.h"
#include "llvm/iOther.h"
#include <algorithm>
+using std::map;
+using std::make_pair;
+using std::vector;
// To enable debugging, uncomment this...
//#define DEBUG_MST(x) x
struct ValuePlaceHolder : public Instruction {
ValuePlaceHolder(const Type *Ty) : Instruction(Ty, UserOp1, "") {}
- virtual Instruction *clone() const { abort(); }
+ virtual Instruction *clone() const { abort(); return 0; }
virtual const char *getOpcodeName() const { return "placeholder"; }
};
// of the methods and global variables that we no longer need.
bool MutateStructTypes::doPassFinalization(Module *M) {
// The first half of the methods in the module have to go.
- unsigned NumMethods = M->size();
- unsigned NumGVars = M->gsize();
+ //unsigned NumMethods = M->size();
+ //unsigned NumGVars = M->gsize();
// Prepare for deletion of globals by dropping their interdependencies...
for(Module::iterator I = M->begin(); I != M->end(); ++I) {
AdjustIndices(cast<CompositeType>(PTy), Indices);
}
- if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
+ if (isa<LoadInst>(I)) {
NewI = new LoadInst(NewPtr, Indices);
- } else if (const StoreInst *SI = dyn_cast<StoreInst>(I)) {
+ } else if (isa<StoreInst>(I)) {
NewI = new StoreInst(ConvertValue(I->getOperand(0)), NewPtr, Indices);
- } else if (const GetElementPtrInst *GEP =
- dyn_cast<GetElementPtrInst>(I)) {
+ } else if (isa<GetElementPtrInst>(I)) {
NewI = new GetElementPtrInst(NewPtr, Indices);
} else {
assert(0 && "Unknown memory access inst!!!");
#include "llvm/Analysis/FindUnsafePointerTypes.h"
#include "TransformInternals.h"
#include <algorithm>
+#include <iostream>
+using std::vector;
+using std::set;
+using std::pair;
#include "llvm/Assembly/Writer.h"
+
// PruneTypes - Given a type Ty, make sure that neither it, or one of its
// subtypes, occur in TypesToModify.
//
// If the element is in TypesToModify, remove it now...
if (const StructType *ST = dyn_cast<StructType>(Ty)) {
TypesToModify.erase(ST); // This doesn't fail if the element isn't present
- cerr << "Unable to swap type: " << ST << endl;
+ std::cerr << "Unable to swap type: " << ST << "\n";
}
// Remove all types that this type contains as well... do not remove types
// Build mapping from index to size
for (unsigned i = 0; i < NumElements; ++i)
- ElList.push_back(make_pair(i, TD.getTypeSize(ST->getElementTypes()[i])));
+ ElList.push_back(
+ std::make_pair(i, TD.getTypeSize(ST->getElementTypes()[i])));
sort(ElList.begin(), ElList.end(), ptr_fun(FirstLess));
set<const Type*> ProcessedTypes;
for (set<PointerType*>::const_iterator I = UnsafePTys.begin(),
E = UnsafePTys.end(); I != E; ++I) {
- //cerr << "Pruning type: " << *I << endl;
+ //cerr << "Pruning type: " << *I << "\n";
PruneTypes(*I, TypesToModify, ProcessedTypes);
}
// Build up a set of structure types that we are going to modify, and
// information describing how to modify them.
- map<const StructType*, vector<int> > Transforms;
+ std::map<const StructType*, vector<int> > Transforms;
for (set<const StructType*>::iterator I = TypesToModify.begin(),
E = TypesToModify.end(); I != E; ++I) {
#include "llvm/Assembly/Writer.h"
#include "Support/StringExtras.h"
#include <sstream>
-
+using std::vector;
+using std::string;
// Add a prototype for printf if it is not already in the program.
//
// Escape Message by replacing all % characters with %% chars.
unsigned Offset = 0;
while ((Offset = Message.find('%', Offset)) != string::npos) {
- string::iterator Offs = Message.begin()+Offset;
- //Message.replace(Offs, Offs+1, "%%");
Message.replace(Offset, 2, "%%");
Offset += 2; // Skip over the new %'s
}
static void InsertVerbosePrintInst(Value *V, BasicBlock *BB,
BasicBlock::iterator &BBI,
const string &Message, Method *Printf) {
- ostringstream OutStr;
+ std::ostringstream OutStr;
if (V) WriteAsOperand(OutStr, V);
InsertPrintInst(V, BB, BBI, Message+OutStr.str()+" = ", Printf);
}
// Copy all of the instructions into a vector to avoid problems with Setcc
const vector<Instruction*> Insts(BB->begin(), InsertPos);
- ostringstream OutStr;
+ std::ostringstream OutStr;
WriteAsOperand(OutStr, BB, false);
InsertPrintInst(0, BB, InsertPos, "LEAVING BB:" + OutStr.str(), Printf);
BasicBlock *BB = M->getEntryNode();
BasicBlock::iterator BBI = BB->begin();
- ostringstream OutStr;
+ std::ostringstream OutStr;
WriteAsOperand(OutStr, M, true);
InsertPrintInst(0, BB, BBI, "ENTERING METHOD: " + OutStr.str(), Printf);
BasicBlock::iterator BBI = BB->end()-1;
ReturnInst *Ret = cast<ReturnInst>(*BBI);
- ostringstream OutStr;
+ std::ostringstream OutStr;
WriteAsOperand(OutStr, BB->getParent(), true);
InsertPrintInst(0, BB, BBI, "LEAVING METHOD: " + OutStr.str(), Printf);
vector<Instruction*> valuesStoredInMethod;
vector<BasicBlock*> exitBlocks;
- Module *module = M->getParent();
-
if (traceMethodEvents)
InsertCodeToShowMethodEntry(M, Printf);
}
}
- vector<Value*> Indices;
+ std::vector<Value*> Indices;
Value *Src = CI->getOperand(0);
const Type *Result = ConvertableToGEP(DestPTy, Src, Indices, &BI);
if (Result == 0) return false; // Not convertable...
if (!CompTy || !SrcPtr || !OffsetVal->getType()->isIntegral())
return false;
- vector<Value*> Indices;
+ std::vector<Value*> Indices;
if (!ConvertableToGEP(SrcPtr->getType(), OffsetVal, Indices, &BI))
return false; // Not convertable... perhaps next time
PRINT_PEEPHOLE1("cast-of-self-ty", CI);
CI->replaceAllUsesWith(Src);
if (!Src->hasName() && CI->hasName()) {
- string Name = CI->getName();
+ std::string Name = CI->getName();
CI->setName("");
Src->setName(Name, BB->getParent()->getSymbolTable());
}
const Type *ElTy = 0;
// Build the index vector, full of all zeros
- vector<Value*> Indices;
+ std::vector<Value*> Indices;
Indices.push_back(ConstantUInt::get(Type::UIntTy, 0));
while (CurCTy && !isa<PointerType>(CurCTy)) {
if (const StructType *CurSTy = dyn_cast<StructType>(CurCTy)) {
#include "Support/DepthFirstIterator.h"
#include <set>
#include <algorithm>
+#include <iostream>
+using std::cerr;
#define DEBUG_ADCE 1
//
class ADCE {
Method *M; // The method that we are working on...
- vector<Instruction*> WorkList; // Instructions that just became live
- set<Instruction*> LiveSet; // The set of live instructions
+ std::vector<Instruction*> WorkList; // Instructions that just became live
+ std::set<Instruction*> LiveSet; // The set of live instructions
bool MadeChanges;
//===--------------------------------------------------------------------===//
// fixupCFG - Walk the CFG in depth first order, eliminating references to
// dead blocks.
//
- BasicBlock *fixupCFG(BasicBlock *Head, set<BasicBlock*> &VisitedBlocks,
- const set<BasicBlock*> &AliveBlocks);
+ BasicBlock *fixupCFG(BasicBlock *Head, std::set<BasicBlock*> &VisitedBlocks,
+ const std::set<BasicBlock*> &AliveBlocks);
};
// AliveBlocks - Set of basic blocks that we know have instructions that are
// alive in them...
//
- set<BasicBlock*> AliveBlocks;
+ std::set<BasicBlock*> AliveBlocks;
// Process the work list of instructions that just became live... if they
// became live, then that means that all of their operands are neccesary as
// After the worklist is processed, recursively walk the CFG in depth first
// order, patching up references to dead blocks...
//
- set<BasicBlock*> VisitedBlocks;
+ std::set<BasicBlock*> VisitedBlocks;
BasicBlock *EntryBlock = fixupCFG(M->front(), VisitedBlocks, AliveBlocks);
if (EntryBlock && EntryBlock != M->front()) {
if (isa<PHINode>(EntryBlock->front())) {
} else {
// We need to move the new entry block to be the first bb of the method.
Method::iterator EBI = find(M->begin(), M->end(), EntryBlock);
- swap(*EBI, *M->begin()); // Exchange old location with start of method
+ std::swap(*EBI, *M->begin());// Exchange old location with start of method
MadeChanges = true;
}
}
// been in the alive set).
// 3. Return the nonnull child, or 0 if no non-null children.
//
-BasicBlock *ADCE::fixupCFG(BasicBlock *BB, set<BasicBlock*> &VisitedBlocks,
- const set<BasicBlock*> &AliveBlocks) {
+BasicBlock *ADCE::fixupCFG(BasicBlock *BB, std::set<BasicBlock*> &VisitedBlocks,
+ const std::set<BasicBlock*> &AliveBlocks) {
if (VisitedBlocks.count(BB)) return 0; // Revisiting a node? No update.
VisitedBlocks.insert(BB); // We have now visited this node!
bool opt::ConstantPropogation::doConstantPropogation(BasicBlock *BB,
BasicBlock::iterator &II) {
Instruction *Inst = *II;
- if (BinaryOperator *BInst = dyn_cast<BinaryOperator>(Inst)) {
+ if (isa<BinaryOperator>(Inst)) {
Constant *D1 = dyn_cast<Constant>(Inst->getOperand(0));
Constant *D2 = dyn_cast<Constant>(Inst->getOperand(1));
// If there is more than one predecessor, and there are PHI nodes in
// the successor, then we need to add incoming edges for the PHI nodes
//
- const vector<BasicBlock*> BBPreds(BB->pred_begin(), BB->pred_end());
+ const std::vector<BasicBlock*> BBPreds(BB->pred_begin(), BB->pred_end());
// Check to see if one of the predecessors of BB is already a predecessor of
// Succ. If so, we cannot do the transformation!
Value *OldVal = PN->removeIncomingValue(BB);
assert(OldVal && "No entry in PHI for Pred BB!");
- for (vector<BasicBlock*>::const_iterator PredI = BBPreds.begin(),
+ for (std::vector<BasicBlock*>::const_iterator PredI = BBPreds.begin(),
End = BBPreds.end(); PredI != End; ++PredI) {
// Add an incoming value for each of the new incoming values...
PN->addIncoming(OldVal, *PredI);
// Transform all subloops before this loop...
bool Changed = reduce_apply_bool(Loop->getSubLoops().begin(),
Loop->getSubLoops().end(),
- std::bind1st(ptr_fun(TransformLoop), Loops));
+ std::bind1st(std::ptr_fun(TransformLoop), Loops));
// Get the header node for this loop. All of the phi nodes that could be
// induction variables must live in this basic block.
BasicBlock *Header = (BasicBlock*)Loop->getBlocks().front();
// induction variables that they represent... stuffing the induction variable
// info into a vector...
//
- vector<InductionVariable> IndVars; // Induction variables for block
+ std::vector<InductionVariable> IndVars; // Induction variables for block
for (BasicBlock::iterator I = Header->begin();
PHINode *PN = dyn_cast<PHINode>(*I); ++I)
IndVars.push_back(InductionVariable(PN, Loops));
Instruction *Val = IterCount;
if (!isa<ConstantInt>(IV->Step) || // If the step != 1
!cast<ConstantInt>(IV->Step)->equalsInt(1)) {
- string Name; // Create a scale by the step value...
+ std::string Name; // Create a scale by the step value...
if (IV->Phi->hasName()) Name = IV->Phi->getName()+"-scale";
// If the types are not compatible, insert a cast now...
if (!isa<Constant>(IV->Start) || // If the start != 0
!cast<Constant>(IV->Start)->isNullValue()) {
- string Name; // Create a offset by the start value...
+ std::string Name; // Create a offset by the start value...
if (IV->Phi->hasName()) Name = IV->Phi->getName()+"-offset";
// If the types are not compatible, insert a cast now...
IV->Phi->replaceAllUsesWith(Val);
// Move the PHI name to it's new equivalent value...
- string OldName = IV->Phi->getName();
+ std::string OldName = IV->Phi->getName();
IV->Phi->setName("");
Val->setName(OldName);
#include "llvm/iPHINode.h"
#include "Support/STLExtras.h"
#include <algorithm>
+#include <iostream>
+using std::cerr;
#include "llvm/Analysis/LoopDepth.h"
// present induction variables (instead of always using uint)
//
static PHINode *InjectSimpleInductionVariable(cfg::Interval *Int) {
- string PHIName, AddName;
+ std::string PHIName, AddName;
BasicBlock *Header = Int->getHeaderNode();
Method *M = Header->getParent();
assert(++PI == Header->pred_end() && "Header node should have 2 preds!");
// Make Pred1 be the loop entrance predecessor, Pred2 be the Loop predecessor
- if (Int->contains(Pred1)) swap(Pred1, Pred2);
+ if (Int->contains(Pred1)) std::swap(Pred1, Pred2);
assert(!Int->contains(Pred1) && "Pred1 should be loop entrance!");
assert( Int->contains(Pred2) && "Pred2 should be looping edge!");
static bool ProcessInterval(cfg::Interval *Int) {
if (!Int->isLoop()) return false; // Not a loop? Ignore it!
- vector<PHINode *> InductionVars;
+ std::vector<PHINode *> InductionVars;
BasicBlock *Header = Int->getHeaderNode();
// Loop over all of the PHI nodes in the interval header...
if (isLoopInvariant(Int, V2)) {
// They *are* loop invariant. Exchange BB1/BB2 and V1/V2 so that
// V1 is always the loop invariant computation.
- swap(V1, V2); swap(BB1, BB2);
+ std::swap(V1, V2); std::swap(BB1, BB2);
} else {
// Neither value is loop invariant. Must not be an induction variable.
// This case can happen if there is an unreachable loop in the CFG that
// anything about BB2/V2. Check now to see if V2 is a linear induction
// variable.
//
- cerr << "Found loop invariant computation: " << V1 << endl;
+ cerr << "Found loop invariant computation: " << V1 << "\n";
if (!isLinearInductionVariable(Int, V2, PN))
continue; // No, it is not a linear ind var, ignore the PHI node.
if (InductionVars.empty()) return false;
// Search to see if there is already a "simple" induction variable.
- vector<PHINode*>::iterator It =
+ std::vector<PHINode*>::iterator It =
find_if(InductionVars.begin(), InductionVars.end(), isSimpleInductionVar);
PHINode *PrimaryIndVar;
"How could Primary IndVar not be in the header!?!!?");
if (i != Header->begin())
- iter_swap(i, Header->begin());
+ std::iter_swap(i, Header->begin());
}
// Now we know that there is a simple induction variable PrimaryIndVar.
// variables in intervals that represent loops.
//
return reduce_apply(IP.begin(), IP.end(), bitwise_or<bool>(), false,
- ptr_fun(ProcessInterval));
+ std::ptr_fun(ProcessInterval));
}
// DoInductionVariableCannonicalize - Simplify induction variables in loops.
dyn_cast<GetElementPtrInst>(MAI->getPointerOperand());
if (!Src) return 0;
- vector<Value *> Indices;
+ std::vector<Value *> Indices;
// Only special case we have to watch out for is pointer arithmetic on the
// 0th index of MAI.
bool InstructionCombining::doit(Method *M) {
// Start the worklist out with all of the instructions in the method in it.
- vector<Instruction*> WorkList(M->inst_begin(), M->inst_end());
+ std::vector<Instruction*> WorkList(M->inst_begin(), M->inst_end());
while (!WorkList.empty()) {
Instruction *I = WorkList.back(); // Get an instruction from the worklist
#include <algorithm>
#include <map>
#include <set>
+#include <iostream>
+using std::cerr;
// InstVal class - This class represents the different lattice values that an
// instruction may occupy. It is a simple class with value semantics. The
// It's public interface consists of a constructor and a doSCCP() method.
//
class SCCP {
- Method *M; // The method that we are working on...
+ Method *M; // The method that we are working on...
- set<BasicBlock*> BBExecutable; // The basic blocks that are executable
- map<Value*, InstVal> ValueState; // The state each value is in...
+ std::set<BasicBlock*> BBExecutable;// The basic blocks that are executable
+ std::map<Value*, InstVal> ValueState; // The state each value is in...
- vector<Instruction*> InstWorkList; // The instruction work list
- vector<BasicBlock*> BBWorkList; // The BasicBlock work list
+ std::vector<Instruction*> InstWorkList;// The instruction work list
+ std::vector<BasicBlock*> BBWorkList; // The BasicBlock work list
//===--------------------------------------------------------------------===//
// The public interface for this class
// Instruction object, then use this accessor to get its value from the map.
//
inline InstVal &getValueState(Value *V) {
- map<Value*, InstVal>::iterator I = ValueState.find(V);
+ std::map<Value*, InstVal>::iterator I = ValueState.find(V);
if (I != ValueState.end()) return I->second; // Common case, in the map
if (Constant *CPV = dyn_cast<Constant>(V)) { // Constants are constant
bool RemovedSymbol = false;
for (SymbolTable::iterator I = SymTab->begin(); I != SymTab->end(); ++I) {
- map<const string, Value *> &Plane = I->second;
+ std::map<const std::string, Value *> &Plane = I->second;
SymbolTable::type_iterator B;
while ((B = Plane.begin()) != Plane.end()) { // Found nonempty type plane!
// false if you want a leaf
//
const Type *getStructOffsetType(const Type *Ty, unsigned &Offset,
- vector<Value*> &Offsets,
+ std::vector<Value*> &Offsets,
bool StopEarly = true) {
if (Offset == 0 && StopEarly && !Offsets.empty())
return Ty; // Return the leaf type
// instruction. The type returned is the root type that the GEP would point to
//
const Type *ConvertableToGEP(const Type *Ty, Value *OffsetVal,
- vector<Value*> &Indices,
+ std::vector<Value*> &Indices,
BasicBlock::iterator *BI = 0) {
const CompositeType *CompTy = dyn_cast<CompositeType>(Ty);
if (CompTy == 0) return 0;
//
extern const TargetData TD;
-static int getConstantValue(const ConstantInt *CPI) {
+static inline int getConstantValue(const ConstantInt *CPI) {
if (const ConstantSInt *CSI = dyn_cast<ConstantSInt>(CPI))
return CSI->getValue();
return cast<ConstantUInt>(CPI)->getValue();
// If BI is nonnull, cast instructions are inserted as appropriate for the
// arguments of the getelementptr.
//
-const Type *ConvertableToGEP(const Type *Ty, Value *V, vector<Value*> &Indices,
+const Type *ConvertableToGEP(const Type *Ty, Value *V,
+ std::vector<Value*> &Indices,
BasicBlock::iterator *BI = 0);
// ------------- Expression Conversion ---------------------
-typedef map<const Value*, const Type*> ValueTypeCache;
+typedef std::map<const Value*, const Type*> ValueTypeCache;
struct ValueMapCache {
// Operands mapped - Contains an entry if the first value (the user) has had
// the second value (the operand) mapped already.
//
- set<const User*> OperandsMapped;
+ std::set<const User*> OperandsMapped;
// Expression Map - Contains an entry from the old value to the new value of
// an expression that has been converted over.
//
- map<const Value *, Value *> ExprMap;
- typedef map<const Value *, Value *> ExprMapTy;
+ std::map<const Value *, Value *> ExprMap;
+ typedef std::map<const Value *, Value *> ExprMapTy;
};
// false if you want a leaf
//
const Type *getStructOffsetType(const Type *Ty, unsigned &Offset,
- vector<Value*> &Offsets,
+ std::vector<Value*> &Offsets,
bool StopEarly = true);
#endif
#include "llvm/DerivedTypes.h"
#include "llvm/iOther.h"
#include "llvm/ConstantVals.h"
+#include <iostream>
+using std::cerr;
+using std::string;
+using std::map;
// Error - Simple wrapper function to conditionally assign to E and return true.
// This just makes error return conditions a little bit simpler...
for (map<const Value*, Value*>::const_iterator I = M.begin(), E = M.end();
I != E; ++I) {
cerr << " Fr: " << (void*)I->first << " " << I->first
- << " To: " << (void*)I->second << " " << I->second << endl;
+ << " To: " << (void*)I->second << " " << I->second << "\n";
}
}
Constant *Result = 0;
if (ConstantArray *CPA = dyn_cast<ConstantArray>(CPV)) {
- const vector<Use> &Ops = CPA->getValues();
- vector<Constant*> Operands(Ops.size());
+ const std::vector<Use> &Ops = CPA->getValues();
+ std::vector<Constant*> Operands(Ops.size());
for (unsigned i = 0; i < Ops.size(); ++i)
Operands[i] =
cast<Constant>(RemapOperand(Ops[i], LocalMap, GlobalMap));
Result = ConstantArray::get(cast<ArrayType>(CPA->getType()), Operands);
} else if (ConstantStruct *CPS = dyn_cast<ConstantStruct>(CPV)) {
- const vector<Use> &Ops = CPS->getValues();
- vector<Constant*> Operands(Ops.size());
+ const std::vector<Use> &Ops = CPS->getValues();
+ std::vector<Constant*> Operands(Ops.size());
for (unsigned i = 0; i < Ops.size(); ++i)
Operands[i] =
cast<Constant>(RemapOperand(Ops[i], LocalMap, GlobalMap));
}
// Cache the mapping in our local map structure...
- LocalMap.insert(make_pair(In, CPV));
+ LocalMap.insert(std::make_pair(In, CPV));
return Result;
}
PrintMap(*GlobalMap);
}
- cerr << "Couldn't remap value: " << (void*)In << " " << In << endl;
+ cerr << "Couldn't remap value: " << (void*)In << " " << In << "\n";
assert(0 && "Couldn't remap value!");
return 0;
}
" - Global variables differ in const'ness");
// Okay, everything is cool, remember the mapping...
- ValueMap.insert(make_pair(SGV, DGV));
+ ValueMap.insert(std::make_pair(SGV, DGV));
} else {
// No linking to be performed, simply create an identical version of the
// symbol over in the dest module... the initializer will be filled in
Dest->getGlobalList().push_back(DGV);
// Make sure to remember this mapping...
- ValueMap.insert(make_pair(SGV, DGV));
+ ValueMap.insert(std::make_pair(SGV, DGV));
}
}
return false;
SM->getName() + "\" - Method is already defined!");
// Otherwise, just remember this mapping...
- ValueMap.insert(make_pair(SM, DM));
+ ValueMap.insert(std::make_pair(SM, DM));
} else {
// Method does not already exist, simply insert an external method
// signature identical to SM into the dest module...
Dest->getMethodList().push_back(DM);
// ... and remember this mapping...
- ValueMap.insert(make_pair(SM, DM));
+ ValueMap.insert(std::make_pair(SM, DM));
}
}
return false;
Dest->getArgumentList().push_back(DMA);
// Add a mapping to our local map
- LocalMap.insert(make_pair(SMA, DMA));
+ LocalMap.insert(std::make_pair(SMA, DMA));
}
// Loop over all of the basic blocks, copying the instructions over...
// Create new basic block and add to mapping and the Dest method...
BasicBlock *DBB = new BasicBlock(SBB->getName(), Dest);
- LocalMap.insert(make_pair(SBB, DBB));
+ LocalMap.insert(std::make_pair(SBB, DBB));
// Loop over all of the instructions in the src basic block, copying them
// over. Note that this is broken in a strict sense because the cloned
Instruction *DI = SI->clone();
DI->setName(SI->getName());
DBB->getInstList().push_back(DI);
- LocalMap.insert(make_pair(SI, DI));
+ LocalMap.insert(std::make_pair(SI, DI));
}
}
#include "llvm/iOther.h"
#include "llvm/SymbolTable.h"
#include "llvm/ConstantVals.h"
+using std::vector;
+
// doPassInitialization - For the lower allocations pass, this ensures that a
// module contains a declaration for a malloc and a free function.
#include "llvm/iTerminators.h"
#include "llvm/iPHINode.h"
#include "llvm/Type.h"
+using std::vector;
// UnifyAllExitNodes - Unify all exit nodes of the CFG by creating a new
// BasicBlock, and converting all returns to unconditional branches to this
#include "Support/STLExtras.h"
#include <algorithm>
#include <map>
+using std::string;
+using std::map;
+using std::vector;
+using std::ostream;
static const Module *getModuleFromVal(const Value *V) {
if (const MethodArgument *MA =dyn_cast<const MethodArgument>(V))
const Type *Ty = cast<const Type>(I->second);
if (!isa<PointerType>(Ty) ||
!cast<PointerType>(Ty)->getElementType()->isPrimitiveType())
- TypeNames.insert(make_pair(Ty, "%"+I->first));
+ TypeNames.insert(std::make_pair(Ty, "%"+I->first));
}
}
}
//
vector<const Type *> TypeStack;
string TypeName = calcTypeName(Ty, TypeStack, TypeNames);
- TypeNames.insert(make_pair(Ty, TypeName)); // Cache type name for later use
+ TypeNames.insert(std::make_pair(Ty, TypeName));//Cache type name for later use
return Out << TypeName;
}
writeOperand(GV->getInitializer(), false, false);
printInfoComment(GV);
- Out << endl;
+ Out << "\n";
}
if (const Constant *CPV = dyn_cast<const Constant>(V)) {
printConstant(CPV);
} else if (const Type *Ty = dyn_cast<const Type>(V)) {
- Out << "\t%" << I->first << " = type " << Ty->getDescription() << endl;
+ Out << "\t%" << I->first << " = type " << Ty->getDescription() << "\n";
}
}
}
else Out << "<badref>";
}
- Out << endl;
+ Out << "\n";
}
// printMethod - Print all aspects of a method.
}
printInfoComment(I);
- Out << endl;
+ Out << "\n";
}
//
template class ValueHolder<Instruction, BasicBlock, Method>;
-BasicBlock::BasicBlock(const string &name, Method *Parent)
+BasicBlock::BasicBlock(const std::string &name, Method *Parent)
: Value(Type::LabelTy, Value::BasicBlockVal, name), InstList(this, 0),
machineInstrVec(new MachineCodeForBasicBlock) {
if (Parent)
}
// Specialize setName to take care of symbol table majik
-void BasicBlock::setName(const string &name, SymbolTable *ST) {
+void BasicBlock::setName(const std::string &name, SymbolTable *ST) {
Method *P;
assert((ST == 0 || (!getParent() || ST == getParent()->getSymbolTable())) &&
"Invalid symtab argument!");
#include <algorithm>
#include <assert.h>
+using std::map;
+using std::pair;
+using std::make_pair;
+
ConstantBool *ConstantBool::True = new ConstantBool(true);
ConstantBool *ConstantBool::False = new ConstantBool(false);
//===----------------------------------------------------------------------===//
// Specialize setName to take care of symbol table majik
-void Constant::setName(const string &Name, SymbolTable *ST) {
+void Constant::setName(const std::string &Name, SymbolTable *ST) {
assert(ST && "Type::setName - Must provide symbol table argument!");
if (Name.size()) ST->insert(Name, this);
#ifndef NDEBUG
#include "llvm/Assembly/Writer.h"
+using std::cerr;
#endif
void Constant::destroyConstantImpl() {
Value *V = use_back();
#ifndef NDEBUG // Only in -g mode...
if (!isa<Constant>(V)) {
- cerr << "While deleting: " << this << endl;
- cerr << "Use still stuck around after Def is destroyed: " << V << endl;
+ cerr << "While deleting: " << this << "\n";
+ cerr << "Use still stuck around after Def is destroyed: " << V << "\n";
}
#endif
assert(isa<Constant>(V) && "References remain to ConstantPointerRef!");
}
ConstantArray::ConstantArray(const ArrayType *T,
- const vector<Constant*> &V) : Constant(T) {
+ const std::vector<Constant*> &V) : Constant(T) {
for (unsigned i = 0; i < V.size(); i++) {
assert(V[i]->getType() == T->getElementType());
Operands.push_back(Use(V[i], this));
}
ConstantStruct::ConstantStruct(const StructType *T,
- const vector<Constant*> &V) : Constant(T) {
+ const std::vector<Constant*> &V) : Constant(T) {
const StructType::ElementTypes &ETypes = T->getElementTypes();
for (unsigned i = 0; i < V.size(); i++) {
//===----------------------------------------------------------------------===//
// getStrValue implementations
-string ConstantBool::getStrValue() const {
+std::string ConstantBool::getStrValue() const {
return Val ? "true" : "false";
}
-string ConstantSInt::getStrValue() const {
+std::string ConstantSInt::getStrValue() const {
return itostr(Val.Signed);
}
-string ConstantUInt::getStrValue() const {
+std::string ConstantUInt::getStrValue() const {
return utostr(Val.Unsigned);
}
-string ConstantFP::getStrValue() const {
+std::string ConstantFP::getStrValue() const {
return ftostr(Val);
}
-string ConstantArray::getStrValue() const {
- string Result;
+std::string ConstantArray::getStrValue() const {
+ std::string Result;
// As a special case, print the array as a string if it is an array of
// ubytes or an array of sbytes with positive values.
return Result;
}
-string ConstantStruct::getStrValue() const {
- string Result = "{";
+std::string ConstantStruct::getStrValue() const {
+ std::string Result = "{";
if (Operands.size()) {
Result += " " + Operands[0]->getType()->getDescription() +
" " + cast<Constant>(Operands[0])->getStrValue();
return Result + " }";
}
-string ConstantPointerNull::getStrValue() const {
+std::string ConstantPointerNull::getStrValue() const {
return "null";
}
-string ConstantPointerRef::getStrValue() const {
+std::string ConstantPointerRef::getStrValue() const {
const GlobalValue *V = getValue();
if (V->hasName()) return "%" + V->getName();
int Slot = Table->getValSlot(V);
delete Table;
- if (Slot >= 0) return string(" %") + itostr(Slot);
+ if (Slot >= 0) return std::string(" %") + itostr(Slot);
else return "<pointer reference badref>";
}
}
unsigned ConstantArray::hash(const ArrayType *Ty,
- const vector<Constant*> &V) {
+ const std::vector<Constant*> &V) {
unsigned Result = (Ty->getUniqueID() << 5) ^ (Ty->getUniqueID() * 7);
for (unsigned i = 0; i < V.size(); ++i)
Result ^= V[i]->getHash() << (i & 7);
}
unsigned ConstantStruct::hash(const StructType *Ty,
- const vector<Constant*> &V) {
+ const std::vector<Constant*> &V) {
unsigned Result = (Ty->getUniqueID() << 5) ^ (Ty->getUniqueID() * 7);
for (unsigned i = 0; i < V.size(); ++i)
Result ^= V[i]->getHash() << (i & 7);
//---- ConstantArray::get() implementation...
//
-static ValueMap<vector<Constant*>, ConstantArray> ArrayConstants;
+static ValueMap<std::vector<Constant*>, ConstantArray> ArrayConstants;
ConstantArray *ConstantArray::get(const ArrayType *Ty,
- const vector<Constant*> &V) {
+ const std::vector<Constant*> &V) {
ConstantArray *Result = ArrayConstants.get(Ty, V);
if (!Result) // If no preexisting value, create one now...
ArrayConstants.add(Ty, V, Result = new ConstantArray(Ty, V));
// contain the specified string. A null terminator is added to the specified
// string so that it may be used in a natural way...
//
-ConstantArray *ConstantArray::get(const string &Str) {
- vector<Constant*> ElementVals;
+ConstantArray *ConstantArray::get(const std::string &Str) {
+ std::vector<Constant*> ElementVals;
for (unsigned i = 0; i < Str.length(); ++i)
ElementVals.push_back(ConstantSInt::get(Type::SByteTy, Str[i]));
//---- ConstantStruct::get() implementation...
//
-static ValueMap<vector<Constant*>, ConstantStruct> StructConstants;
+static ValueMap<std::vector<Constant*>, ConstantStruct> StructConstants;
ConstantStruct *ConstantStruct::get(const StructType *Ty,
- const vector<Constant*> &V) {
+ const std::vector<Constant*> &V) {
ConstantStruct *Result = StructConstants.get(Ty, V);
if (!Result) // If no preexisting value, create one now...
StructConstants.add(Ty, V, Result = new ConstantStruct(Ty, V));
#include "Support/DepthFirstIterator.h"
#include "Support/STLExtras.h"
#include <algorithm>
+using std::set;
+
//===----------------------------------------------------------------------===//
// Helper Template
template class ValueHolder<MethodArgument, Method, Method>;
template class ValueHolder<BasicBlock , Method, Method>;
-Method::Method(const MethodType *Ty, bool isInternal, const string &name)
+Method::Method(const MethodType *Ty, bool isInternal, const std::string &name)
: GlobalValue(PointerType::get(Ty), Value::MethodVal, isInternal, name),
SymTabValue(this), BasicBlocks(this), ArgumentList(this, this) {
assert(::isa<MethodType>(Ty) && "Method signature must be of method type!");
}
// Specialize setName to take care of symbol table majik
-void Method::setName(const string &name, SymbolTable *ST) {
+void Method::setName(const std::string &name, SymbolTable *ST) {
Module *P;
assert((ST == 0 || (!getParent() || ST == getParent()->getSymbolTable())) &&
"Invalid symtab argument!");
GlobalVariable::GlobalVariable(const Type *Ty, bool constant, bool isIntern,
Constant *Initializer = 0,
- const string &Name = "")
+ const std::string &Name = "")
: GlobalValue(PointerType::get(Ty), Value::GlobalVariableVal, isIntern, Name),
isConstantGlobal(constant) {
if (Initializer) Operands.push_back(Use((Value*)Initializer, this));
}
// Specialize setName to take care of symbol table majik
-void GlobalVariable::setName(const string &name, SymbolTable *ST) {
+void GlobalVariable::setName(const std::string &name, SymbolTable *ST) {
Module *P;
assert((ST == 0 || (!getParent() || ST == getParent()->getSymbolTable())) &&
"Invalid symtab argument!");
}
TerminatorInst::TerminatorInst(const Type *Ty, Instruction::TermOps iType,
- const string &Name = "")
+ const std::string &Name = "")
: Instruction(Ty, iType, Name) {
}
//===----------------------------------------------------------------------===//
// Specialize setName to take care of symbol table majik
-void MethodArgument::setName(const string &name, SymbolTable *ST) {
+void MethodArgument::setName(const std::string &name, SymbolTable *ST) {
Method *P;
assert((ST == 0 || (!getParent() || ST == getParent()->getSymbolTable())) &&
"Invalid symtab argument!");
// PHINode Class
//===----------------------------------------------------------------------===//
-PHINode::PHINode(const Type *Ty, const string &name)
+PHINode::PHINode(const Type *Ty, const std::string &name)
: Instruction(Ty, Instruction::PHINode, name) {
}
#include "llvm/SymbolTable.h"
#include "llvm/CodeGen/MachineInstr.h"
-Instruction::Instruction(const Type *ty, unsigned it, const string &Name)
+Instruction::Instruction(const Type *ty, unsigned it, const std::string &Name)
: User(ty, Value::InstructionVal, Name),
machineInstrVec(new MachineCodeForVMInstr) {
Parent = 0;
}
// Specialize setName to take care of symbol table majik
-void Instruction::setName(const string &name, SymbolTable *ST) {
+void Instruction::setName(const std::string &name, SymbolTable *ST) {
BasicBlock *P = 0; Method *PP = 0;
assert((ST == 0 || !getParent() || !getParent()->getParent() ||
ST == getParent()->getParent()->getSymbolTable()) &&
// sequence of forward declarations. Trying to fix that will
// cause a serious circularity in link order.
//
-const vector<Value*> &Instruction::getTempValuesForMachineCode() const {
+const std::vector<Value*> &Instruction::getTempValuesForMachineCode() const {
return machineInstrVec->getTempValues();
}
#endif
#include "llvm/DerivedTypes.h"
#include "llvm/iOther.h"
#include "llvm/ConstantVals.h"
+#include <iostream>
+using std::cerr;
+using std::string;
+using std::map;
// Error - Simple wrapper function to conditionally assign to E and return true.
// This just makes error return conditions a little bit simpler...
for (map<const Value*, Value*>::const_iterator I = M.begin(), E = M.end();
I != E; ++I) {
cerr << " Fr: " << (void*)I->first << " " << I->first
- << " To: " << (void*)I->second << " " << I->second << endl;
+ << " To: " << (void*)I->second << " " << I->second << "\n";
}
}
Constant *Result = 0;
if (ConstantArray *CPA = dyn_cast<ConstantArray>(CPV)) {
- const vector<Use> &Ops = CPA->getValues();
- vector<Constant*> Operands(Ops.size());
+ const std::vector<Use> &Ops = CPA->getValues();
+ std::vector<Constant*> Operands(Ops.size());
for (unsigned i = 0; i < Ops.size(); ++i)
Operands[i] =
cast<Constant>(RemapOperand(Ops[i], LocalMap, GlobalMap));
Result = ConstantArray::get(cast<ArrayType>(CPA->getType()), Operands);
} else if (ConstantStruct *CPS = dyn_cast<ConstantStruct>(CPV)) {
- const vector<Use> &Ops = CPS->getValues();
- vector<Constant*> Operands(Ops.size());
+ const std::vector<Use> &Ops = CPS->getValues();
+ std::vector<Constant*> Operands(Ops.size());
for (unsigned i = 0; i < Ops.size(); ++i)
Operands[i] =
cast<Constant>(RemapOperand(Ops[i], LocalMap, GlobalMap));
}
// Cache the mapping in our local map structure...
- LocalMap.insert(make_pair(In, CPV));
+ LocalMap.insert(std::make_pair(In, CPV));
return Result;
}
PrintMap(*GlobalMap);
}
- cerr << "Couldn't remap value: " << (void*)In << " " << In << endl;
+ cerr << "Couldn't remap value: " << (void*)In << " " << In << "\n";
assert(0 && "Couldn't remap value!");
return 0;
}
" - Global variables differ in const'ness");
// Okay, everything is cool, remember the mapping...
- ValueMap.insert(make_pair(SGV, DGV));
+ ValueMap.insert(std::make_pair(SGV, DGV));
} else {
// No linking to be performed, simply create an identical version of the
// symbol over in the dest module... the initializer will be filled in
Dest->getGlobalList().push_back(DGV);
// Make sure to remember this mapping...
- ValueMap.insert(make_pair(SGV, DGV));
+ ValueMap.insert(std::make_pair(SGV, DGV));
}
}
return false;
SM->getName() + "\" - Method is already defined!");
// Otherwise, just remember this mapping...
- ValueMap.insert(make_pair(SM, DM));
+ ValueMap.insert(std::make_pair(SM, DM));
} else {
// Method does not already exist, simply insert an external method
// signature identical to SM into the dest module...
Dest->getMethodList().push_back(DM);
// ... and remember this mapping...
- ValueMap.insert(make_pair(SM, DM));
+ ValueMap.insert(std::make_pair(SM, DM));
}
}
return false;
Dest->getArgumentList().push_back(DMA);
// Add a mapping to our local map
- LocalMap.insert(make_pair(SMA, DMA));
+ LocalMap.insert(std::make_pair(SMA, DMA));
}
// Loop over all of the basic blocks, copying the instructions over...
// Create new basic block and add to mapping and the Dest method...
BasicBlock *DBB = new BasicBlock(SBB->getName(), Dest);
- LocalMap.insert(make_pair(SBB, DBB));
+ LocalMap.insert(std::make_pair(SBB, DBB));
// Loop over all of the instructions in the src basic block, copying them
// over. Note that this is broken in a strict sense because the cloned
Instruction *DI = SI->clone();
DI->setName(SI->getName());
DBB->getInstList().push_back(DI);
- LocalMap.insert(make_pair(SI, DI));
+ LocalMap.insert(std::make_pair(SI, DI));
}
}
// Define the GlobalValueRefMap as a struct that wraps a map so that we don't
// have Module.h depend on <map>
//
-struct GlobalValueRefMap : public map<GlobalValue*, ConstantPointerRef*>{
+struct GlobalValueRefMap : public std::map<GlobalValue*, ConstantPointerRef*>{
};
if (I != GVRefMap->end()) return I->second;
ConstantPointerRef *Ref = new ConstantPointerRef(V);
- GVRefMap->insert(make_pair(V, Ref));
+ GVRefMap->insert(std::make_pair(V, Ref));
return Ref;
}
GVRefMap->erase(I);
// Insert the new entry...
- GVRefMap->insert(make_pair(NewGV, Ref));
+ GVRefMap->insert(std::make_pair(NewGV, Ref));
}
while (CurPlane.size() != ModuleSize) {
//SC_DEBUG(" Removing [" << i << "] Value=" << CurPlane.back() << "\n");
- map<const Value *, unsigned>::iterator NI = NodeMap.find(CurPlane.back());
+ std::map<const Value *, unsigned>::iterator NI =
+ NodeMap.find(CurPlane.back());
assert(NI != NodeMap.end() && "Node not in nodemap?");
NodeMap.erase(NI); // Erase from nodemap
CurPlane.pop_back(); // Shrink plane
}
int SlotCalculator::getValSlot(const Value *D) const {
- map<const Value*, unsigned>::const_iterator I = NodeMap.find(D);
+ std::map<const Value*, unsigned>::const_iterator I = NodeMap.find(D);
if (I == NodeMap.end()) return -1;
return (int)I->second;
#include "llvm/Module.h"
#include "llvm/Method.h"
#include "Support/StringExtras.h"
+#include <iostream>
+
+using std::string;
+using std::pair;
+using std::make_pair;
+using std::map;
+using std::cerr;
+using std::cout;
#define DEBUG_SYMBOL_TABLE 0
#define DEBUG_ABSTYPE 0
for (type_iterator I = i->second.begin(); I != i->second.end(); ++I)
if (!isa<Constant>(I->second) && !isa<Type>(I->second)) {
cerr << "Value still in symbol table! Type = '"
- << i->first->getDescription() << "' Name = '" << I->first << "'\n";
+ << i->first->getDescription() << "' Name = '"
+ << I->first << "'\n";
LeftoverValues = false;
}
}
#include <algorithm>
static void DumpVal(const pair<const string, Value *> &V) {
- cout << " '" << V.first << "' = " << V.second << endl;
+ cout << " '" << V.first << "' = " << V.second << "\n";
}
static void DumpPlane(const pair<const Type *, map<const string, Value *> >&P) {
- cout << " Plane: " << P.first << endl;
+ cout << " Plane: " << P.first << "\n";
for_each(P.second.begin(), P.second.end(), DumpVal);
}
#include "llvm/SymbolTable.h"
#include "Support/StringExtras.h"
#include "Support/STLExtras.h"
+#include <iostream>
+
+using std::vector;
+using std::string;
+using std::map;
+using std::swap;
+using std::make_pair;
+using std::cerr;
// DEBUG_MERGE_TYPES - Enable this #define to see how and when derived types are
// created and later destroyed, all in an effort to make sure that there is only
#include "llvm/Type.h"
#ifndef NDEBUG // Only in -g mode...
#include "llvm/Assembly/Writer.h"
+#include <iostream>
+using std::cerr;
#endif
#include <algorithm>
return Ty;
}
-Value::Value(const Type *ty, ValueTy vty, const string &name = "")
+Value::Value(const Type *ty, ValueTy vty, const std::string &name = "")
: Name(name), Ty(checkType(ty), this) {
VTy = vty;
}
if (Uses.begin() != Uses.end()) {
cerr << "While deleting: " << this;
for (use_const_iterator I = Uses.begin(); I != Uses.end(); ++I)
- cerr << "Use still stuck around after Def is destroyed:" << *I << endl;
+ cerr << "Use still stuck around after Def is destroyed:" << *I << "\n";
}
#endif
assert(Uses.begin() == Uses.end());
// User Class
//===----------------------------------------------------------------------===//
-User::User(const Type *Ty, ValueTy vty, const string &name)
+User::User(const Type *Ty, ValueTy vty, const std::string &name)
: Value(Ty, vty, name) {
}
#include "llvm/Module.h"
#include "llvm/BasicBlock.h"
#include "llvm/Type.h"
+using std::string;
+using std::vector;
+
// Error - Define a macro to do the common task of pushing a message onto the
// end of the error list and setting Bad to true.
#ifndef NDEBUG
#include "llvm/Type.h" // Only used for assertions...
#include "llvm/Assembly/Writer.h"
+#include <iostream>
#endif
BranchInst::BranchInst(BasicBlock *True, BasicBlock *False, Value *Cond)
#ifndef NDEBUG
if (Cond != 0 && Cond->getType() != Type::BoolTy)
- cerr << "Bad Condition: " << Cond << endl;
+ std::cerr << "Bad Condition: " << Cond << "\n";
#endif
assert((Cond == 0 || Cond->getType() == Type::BoolTy) &&
"May only branch on boolean predicates!!!!");
// CallInst Implementation
//===----------------------------------------------------------------------===//
-CallInst::CallInst(Value *Meth, const vector<Value*> ¶ms,
- const string &Name)
+CallInst::CallInst(Value *Meth, const std::vector<Value*> ¶ms,
+ const std::string &Name)
: Instruction(cast<MethodType>(cast<PointerType>(Meth->getType())
->getElementType())->getReturnType(),
Instruction::Call, Name) {
//===----------------------------------------------------------------------===//
InvokeInst::InvokeInst(Value *Meth, BasicBlock *IfNormal, \
- BasicBlock *IfException, const vector<Value*>¶ms,
- const string &Name)
+ BasicBlock *IfException,
+ const std::vector<Value*> ¶ms,
+ const std::string &Name)
: TerminatorInst(cast<MethodType>(cast<PointerType>(Meth->getType())
->getElementType())->getReturnType(),
Instruction::Invoke, Name) {
// pointer type.
//
const Type* MemAccessInst::getIndexedType(const Type *Ptr,
- const vector<Value*> &Idx,
+ const std::vector<Value*> &Idx,
bool AllowCompositeLeaf = false) {
if (!Ptr->isPointerType()) return 0; // Type isn't a pointer type!
// LoadInst Implementation
//===----------------------------------------------------------------------===//
-LoadInst::LoadInst(Value *Ptr, const vector<Value*> &Idx,
- const string &Name = "")
+LoadInst::LoadInst(Value *Ptr, const std::vector<Value*> &Idx,
+ const std::string &Name = "")
: MemAccessInst(checkType(getIndexedType(Ptr->getType(), Idx)), Load, Name) {
assert(getIndexedType(Ptr->getType(), Idx) && "Load operands invalid!");
Operands.reserve(1+Idx.size());
}
-LoadInst::LoadInst(Value *Ptr, const string &Name = "")
+LoadInst::LoadInst(Value *Ptr, const std::string &Name = "")
: MemAccessInst(cast<PointerType>(Ptr->getType())->getElementType(),
Load, Name) {
Operands.reserve(1);
// StoreInst Implementation
//===----------------------------------------------------------------------===//
-StoreInst::StoreInst(Value *Val, Value *Ptr, const vector<Value*> &Idx,
- const string &Name = "")
+StoreInst::StoreInst(Value *Val, Value *Ptr, const std::vector<Value*> &Idx,
+ const std::string &Name = "")
: MemAccessInst(Type::VoidTy, Store, Name) {
assert(getIndexedType(Ptr->getType(), Idx) && "Store operands invalid!");
Operands.push_back(Use(Idx[i], this));
}
-StoreInst::StoreInst(Value *Val, Value *Ptr, const string &Name = "")
+StoreInst::StoreInst(Value *Val, Value *Ptr, const std::string &Name = "")
: MemAccessInst(Type::VoidTy, Store, Name) {
Operands.reserve(2);
// GetElementPtrInst Implementation
//===----------------------------------------------------------------------===//
-GetElementPtrInst::GetElementPtrInst(Value *Ptr, const vector<Value*> &Idx,
- const string &Name = "")
+GetElementPtrInst::GetElementPtrInst(Value *Ptr, const std::vector<Value*> &Idx,
+ const std::string &Name = "")
: MemAccessInst(PointerType::get(checkType(getIndexedType(Ptr->getType(),
Idx, true))),
GetElementPtr, Name) {
#include "llvm/iOperators.h"
#include "llvm/Type.h"
+#include <iostream>
+using std::cerr;
//===----------------------------------------------------------------------===//
// UnaryOperator Class
switch (Op) {
case Not: return new GenericUnaryInst(Op, Source);
default:
- cerr << "Don't know how to Create UnaryOperator " << Op << endl;
+ cerr << "Don't know how to Create UnaryOperator " << Op << "\n";
return 0;
}
}
case Not: return "not";
case Cast: return "cast";
default:
- cerr << "Invalid unary operator type!" << getOpcode() << endl;
+ cerr << "Invalid unary operator type!" << getOpcode() << "\n";
abort();
}
+ return 0;
}
//===----------------------------------------------------------------------===//
BinaryOperator *BinaryOperator::create(BinaryOps Op, Value *S1, Value *S2,
- const string &Name) {
+ const std::string &Name) {
switch (Op) {
// Binary comparison operators...
case SetLT: case SetGT: case SetLE:
default:
return true;
}
- swap(Operands[0], Operands[1]);
+ std::swap(Operands[0], Operands[1]);
return false;
}
case Or : return "or";
case Xor: return "xor";
default:
- cerr << "Invalid binary operator type!" << getOpcode() << endl;
+ cerr << "Invalid binary operator type!" << getOpcode() << "\n";
abort();
}
+ return 0;
}
//===----------------------------------------------------------------------===//
SetCondInst::SetCondInst(BinaryOps opType, Value *S1, Value *S2,
- const string &Name)
+ const std::string &Name)
: BinaryOperator(opType, S1, S2, Name) {
OpType = opType;
#include <map>
#include "llvm/Annotation.h"
+using std::string;
+using std::map;
+using std::pair;
+using std::make_pair;
typedef map<const string, unsigned> IDMapType;
static unsigned IDCounter = 0; // Unique ID counter
#include <algorithm>
#include <map>
#include <set>
+#include <iostream>
using namespace cl;
+using std::map;
+using std::pair;
+using std::vector;
+using std::string;
+using std::cerr;
// Return the global command line option vector. Making it a function scoped
// static ensures that it will be initialized correctly before its first use.
<< "' specified more than once!\n";
} else {
// Add argument to the argument map!
- getOpts().insert(make_pair(ArgName, Opt));
+ getOpts().insert(std::make_pair(ArgName, Opt));
}
}
break;
case ValueOptional: break;
default: cerr << "Bad ValueMask flag! CommandLine usage error:"
- << Handler->getValueExpectedFlag() << endl; abort();
+ << Handler->getValueExpectedFlag() << "\n"; abort();
}
// Run the handler now!
bool Option::error(string Message, const char *ArgName = 0) {
if (ArgName == 0) ArgName = ArgStr;
- cerr << "-" << ArgName << " option" << Message << endl;
+ cerr << "-" << ArgName << " option" << Message << "\n";
return true;
}
unsigned L = std::strlen(ArgStr);
if (L == 0) return; // Don't print the empty arg like this!
cerr << " -" << ArgStr << string(GlobalWidth-L-6, ' ') << " - "
- << HelpStr << endl;
+ << HelpStr << "\n";
}
while (const char *EnumName = va_arg(Vals, const char *)) {
int EnumVal = va_arg(Vals, int);
const char *EnumDesc = va_arg(Vals, const char *);
- ValueMap.push_back(make_pair(EnumName, // Add value to value map
- make_pair(EnumVal, EnumDesc)));
+ ValueMap.push_back(std::make_pair(EnumName, // Add value to value map
+ std::make_pair(EnumVal, EnumDesc)));
}
}
unsigned EnumValueBase::getOptionWidth() const {
unsigned BaseSize = Option::getOptionWidth();
for (unsigned i = 0; i < ValueMap.size(); ++i)
- BaseSize = max(BaseSize, std::strlen(ValueMap[i].first)+8);
+ BaseSize = std::max(BaseSize, std::strlen(ValueMap[i].first)+8);
return BaseSize;
}
<< ValueMap[i].second.second;
if (i == 0) cerr << " (default)";
- cerr << endl;
+ cerr << "\n";
}
}
unsigned EnumFlagsBase::getOptionWidth() const {
unsigned BaseSize = 0;
for (unsigned i = 0; i < ValueMap.size(); ++i)
- BaseSize = max(BaseSize, std::strlen(ValueMap[i].first)+6);
+ BaseSize = std::max(BaseSize, std::strlen(ValueMap[i].first)+6);
return BaseSize;
}
cerr << " -" << ValueMap[i].first << string(GlobalWidth-L-6, ' ') << " - "
<< ValueMap[i].second.second;
if (i == 0) cerr << " (default)";
- cerr << endl;
+ cerr << "\n";
}
}
unsigned EnumListBase::getOptionWidth() const {
unsigned BaseSize = 0;
for (unsigned i = 0; i < ValueMap.size(); ++i)
- BaseSize = max(BaseSize, std::strlen(ValueMap[i].first)+6);
+ BaseSize = std::max(BaseSize, std::strlen(ValueMap[i].first)+6);
return BaseSize;
}
for (unsigned i = 0; i < ValueMap.size(); ++i) {
unsigned L = std::strlen(ValueMap[i].first);
cerr << " -" << ValueMap[i].first << string(GlobalWidth-L-6, ' ') << " - "
- << ValueMap[i].second.second << endl;
+ << ValueMap[i].second.second << "\n";
}
}
virtual bool handleOccurance(const char *ArgName, const string &Arg) {
// Copy Options into a vector so we can sort them as we like...
vector<pair<string, Option*> > Options;
- copy(getOpts().begin(), getOpts().end(), back_inserter(Options));
+ copy(getOpts().begin(), getOpts().end(), std::back_inserter(Options));
// Eliminate Hidden or ReallyHidden arguments, depending on ShowHidden
Options.erase(remove_if(Options.begin(), Options.end(),
- ptr_fun(ShowHidden ? isReallyHidden : isHidden)),
+ std::ptr_fun(ShowHidden ? isReallyHidden : isHidden)),
Options.end());
// Eliminate duplicate entries in table (from enum flags options, f.e.)
- set<Option*> OptionSet;
+ std::set<Option*> OptionSet;
for (unsigned i = 0; i < Options.size(); )
if (OptionSet.count(Options[i].second) == 0)
OptionSet.insert(Options[i++].second); // Add to set
if (ProgramOverview)
- cerr << "OVERVIEW:" << ProgramOverview << endl;
+ cerr << "OVERVIEW:" << ProgramOverview << "\n";
// TODO: Sort options by some criteria
cerr << "USAGE: " << ProgramName << " [options]\n\n";
void getMaxArgLen(pair<string, Option *> OptPair) {
const Option *Opt = OptPair.second;
if (Opt->ArgStr[0] == 0) EmptyArg = Opt; // Capture the empty arg if exists
- MaxArgLen = max(MaxArgLen, Opt->getOptionWidth());
+ MaxArgLen = std::max(MaxArgLen, Opt->getOptionWidth());
}
void printOption(pair<string, Option *> OptPair) {
#include "llvm/Support/NameMangling.h"
#include "llvm/DerivedTypes.h"
#include "llvm/GlobalValue.h"
+using std::string;
// MangleTypeName - Implement a consistent name-mangling scheme for
// a given type.
#include "llvm/Analysis/FindUsedTypes.h"
#include "Support/CommandLine.h"
#include <algorithm>
+#include <iostream>
+using std::cout;
+using std::cerr;
+using std::pair;
static void PrintMethod(Method *M) {
cout << M;
}
static void PrintClassifiedExprs(Method *M) {
- cout << "Classified expressions for: " << M->getName() << endl;
+ cout << "Classified expressions for: " << M->getName() << "\n";
Method::inst_iterator I = M->inst_begin(), E = M->inst_end();
for (; I != E; ++I) {
cout << *I;
if (R.Offset) WriteAsOperand(cout, (Value*)R.Offset); else cout << " 0";
break;
}
- cout << endl << endl;
+ cout << "\n\n";
}
}
#include "Support/CommandLine.h"
#include <fstream>
#include <string>
+#include <memory>
cl::String InputFilename ("", "Parse <arg> file, compile to bytecode", 0, "-");
cl::String OutputFilename("o", "Override output filename", cl::NoFlags, "");
ostream *Out = 0;
try {
// Parse the file now...
- Module *C = ParseAssemblyFile(InputFilename);
- if (C == 0) {
+ std::auto_ptr<Module> C(ParseAssemblyFile(InputFilename));
+ if (C.get() == 0) {
cerr << "assembly didn't read correctly.\n";
return 1;
}
if (DumpAsm)
- cerr << "Here's the assembly:\n" << C;
+ cerr << "Here's the assembly:\n" << C.get();
if (OutputFilename != "") { // Specified an output filename?
- Out = new ofstream(OutputFilename.c_str(),
- (Force ? 0 : ios::noreplace)|ios::out);
+ if (!Force && !std::ifstream(OutputFilename.c_str())) {
+ // If force is not specified, make sure not to overwrite a file!
+ cerr << "Error opening '" << OutputFilename << "': File exists!\n"
+ << "Use -f command line argument to force output\n";
+ return 1;
+ }
+ Out = new std::ofstream(OutputFilename.c_str());
} else {
if (InputFilename == "-") {
OutputFilename = "-";
Out = &cout;
} else {
- string IFN = InputFilename;
+ std::string IFN = InputFilename;
int Len = IFN.length();
if (IFN[Len-3] == '.' && IFN[Len-2] == 'l' && IFN[Len-1] == 'l') {
// Source ends in .ll
- OutputFilename = string(IFN.begin(), IFN.end()-3);
+ OutputFilename = std::string(IFN.begin(), IFN.end()-3);
} else {
OutputFilename = IFN; // Append a .bc to it
}
OutputFilename += ".bc";
- Out = new ofstream(OutputFilename.c_str(),
- (Force ? 0 : ios::noreplace)|ios::out);
+
+ if (!Force && !std::ifstream(OutputFilename.c_str())) {
+ // If force is not specified, make sure not to overwrite a file!
+ cerr << "Error opening '" << OutputFilename << "': File exists!\n"
+ << "Use -f command line argument to force output\n";
+ return 1;
+ }
+
+ Out = new std::ofstream(OutputFilename.c_str());
}
+ }
- if (!Out->good()) {
- cerr << "Error opening " << OutputFilename << "!\n";
- delete C;
- return 1;
- }
+ if (!Out->good()) {
+ cerr << "Error opening " << OutputFilename << "!\n";
+ return 1;
}
- WriteBytecodeToFile(C, *Out);
-
- delete C;
+ WriteBytecodeToFile(C.get(), *Out);
} catch (const ParseException &E) {
cerr << E.getMessage() << endl;
return 1;
#include "Support/PostOrderIterator.h"
#include "Support/CommandLine.h"
#include <fstream>
+#include <iostream>
+using std::cerr;
// OutputMode - The different orderings to print basic blocks in...
enum OutputMode {
int main(int argc, char **argv) {
cl::ParseCommandLineOptions(argc, argv, " llvm .bc -> .ll disassembler\n");
- ostream *Out = &cout; // Default to printing to stdout...
+ std::ostream *Out = &std::cout; // Default to printing to stdout...
Module *C = ParseBytecodeFile(InputFilename);
if (C == 0) {
}
if (OutputFilename != "") { // Specified an output filename?
- Out = new ofstream(OutputFilename.c_str(),
- (Force ? 0 : ios::noreplace)|ios::out);
+ if (!Force && !std::ifstream(OutputFilename.c_str())) {
+ // If force is not specified, make sure not to overwrite a file!
+ cerr << "Error opening '" << OutputFilename
+ << "': File exists! Sending to standard output.\n";
+ } else {
+ Out = new std::ofstream(OutputFilename.c_str());
+ }
} else {
if (InputFilename == "-") {
OutputFilename = "-";
- Out = &cout;
} else {
- string IFN = InputFilename;
+ std::string IFN = InputFilename;
int Len = IFN.length();
if (IFN[Len-3] == '.' && IFN[Len-2] == 'b' && IFN[Len-1] == 'c') {
// Source ends in .bc
- OutputFilename = string(IFN.begin(), IFN.end()-3);
+ OutputFilename = std::string(IFN.begin(), IFN.end()-3);
} else {
OutputFilename = IFN; // Append a .ll to it
}
OutputFilename += ".ll";
- Out = new ofstream(OutputFilename.c_str(),
- (Force ? 0 : ios::noreplace)|ios::out);
+
+ if (!Force && !std::ifstream(OutputFilename.c_str())) {
+ // If force is not specified, make sure not to overwrite a file!
+ cerr << "Error opening '" << OutputFilename
+ << "': File exists! Sending to standard output.\n";
+ } else {
+ Out = new std::ofstream(OutputFilename.c_str());
+ }
}
}
if (!Out->good()) {
cerr << "Error opening " << OutputFilename
<< ": sending to stdout instead!\n";
- Out = &cout;
+ Out = &std::cout;
}
// All that dis does is write the assembly out to a file... which is exactly
switch (WriteMode) {
case dfo: // Depth First ordering
copy(df_begin(M), df_end(M),
- ostream_iterator<BasicBlock*>(*Out, "\n"));
+ std::ostream_iterator<BasicBlock*>(*Out, "\n"));
break;
case rdfo: // Reverse Depth First ordering
copy(df_begin(M, true), df_end(M),
- ostream_iterator<BasicBlock*>(*Out, "\n"));
+ std::ostream_iterator<BasicBlock*>(*Out, "\n"));
break;
case po: // Post Order
copy(po_begin(M), po_end(M),
- ostream_iterator<BasicBlock*>(*Out, "\n"));
+ std::ostream_iterator<BasicBlock*>(*Out, "\n"));
break;
case rpo: { // Reverse Post Order
ReversePostOrderTraversal RPOT(M);
copy(RPOT.begin(), RPOT.end(),
- ostream_iterator<BasicBlock*>(*Out, "\n"));
+ std::ostream_iterator<BasicBlock*>(*Out, "\n"));
break;
}
default:
}
delete C;
- if (Out != &cout) delete Out;
+ if (Out != &std::cout) delete Out;
return 0;
}
}
if (OutputFilename == "") { // Didn't specify an output filename?
- string IFN = InputFilename;
+ std::string IFN = InputFilename;
int Len = IFN.length();
if (IFN[Len-2] == '.' && IFN[Len-1] == 's') { // Source ends in .s?
- OutputFilename = string(IFN.begin(), IFN.end()-2);
+ OutputFilename = std::string(IFN.begin(), IFN.end()-2);
} else {
OutputFilename = IFN; // Append a .o to it
}
OutputFilename += ".o";
}
- Out = new ofstream(OutputFilename.c_str(), ios::out);
+ Out = new std::ofstream(OutputFilename.c_str(), ios::out);
if (!Out->good()) {
cerr << "Error opening " << OutputFilename << "!\n";
return 1;
// In addition to just parsing the input from GCC, we also want to spiff it up
// a little bit. Do this now.
//
- vector<Pass*> Passes;
+ std::vector<Pass*> Passes;
Passes.push_back(new opt::DeadCodeElimination()); // Remove Dead code/vars
Passes.push_back(new CleanupGCCOutput()); // Fix gccisms
Passes.push_back(new InductionVariableSimplify()); // Simplify indvars
#include <fstream>
#include <memory>
#include <sys/types.h> // For FileExists
+typedef int blksize_t; // SYS/TYPES is broken!!!
#include <sys/stat.h>
// FileExists - Return true if the specified string is an openable file...
-static inline bool FileExists(const string &FN) {
+static inline bool FileExists(const std::string &FN) {
struct stat StatBuf;
return stat(FN.c_str(), &StatBuf) != -1;
}
// LoadFile - Read the specified bytecode file in and return it. This routine
// searches the link path for the specified file to try to find it...
//
-static inline std::auto_ptr<Module> LoadFile(const string &FN) {
- string Filename = FN;
- string ErrorMessage;
+static inline std::auto_ptr<Module> LoadFile(const std::string &FN) {
+ std::string Filename = FN;
+ std::string ErrorMessage;
unsigned NextLibPathIdx = 0;
bool FoundAFile = false;
assert(InputFilenames.size() > 0 && "OneOrMore is not working");
unsigned BaseArg = 0;
- string ErrorMessage;
+ std::string ErrorMessage;
// TODO: TEST argv[0] for llvm-ar forms... for now, this is a huge hack.
if (InputFilenames.size() >= 3 && InputFilenames[0] == "rc" &&
if (Composite.get() == 0) return 1;
for (unsigned i = BaseArg+1; i < InputFilenames.size(); ++i) {
- auto_ptr<Module> M(LoadFile(InputFilenames[i]));
+ std::auto_ptr<Module> M(LoadFile(InputFilenames[i]));
if (M.get() == 0) return 1;
if (Verbose) cerr << "Linking in '" << InputFilenames[i] << "'\n";
ostream *Out = &cout; // Default to printing to stdout...
if (OutputFilename != "-") {
- Out = new ofstream(OutputFilename.c_str(),
- (Force ? 0 : ios::noreplace)|ios::out);
+ if (!Force && !std::ifstream(OutputFilename.c_str())) {
+ // If force is not specified, make sure not to overwrite a file!
+ cerr << "Error opening '" << OutputFilename << "': File exists!\n"
+ << "Use -f command line argument to force output\n";
+ return 1;
+ }
+ Out = new std::ofstream(OutputFilename.c_str());
if (!Out->good()) {
cerr << "Error opening '" << OutputFilename << "'!\n";
return 1;
if (Verbose) cerr << "Writing bytecode...\n";
WriteBytecodeToFile(Composite.get(), *Out);
- if (Out != &cout) delete Out;
+ if (Out != &std::cout) delete Out;
return 0;
}
#include <memory>
#include <string>
#include <fstream>
+using std::string;
cl::String InputFilename ("", "Input filename", cl::NoFlags, "-");
cl::String OutputFilename("o", "Output filename", cl::NoFlags, "");
class EmitAssembly : public Pass {
const TargetMachine &Target; // Target to compile for
- ostream *Out; // Stream to print on
+ std::ostream *Out; // Stream to print on
bool DeleteStream; // Delete stream in dtor?
public:
- inline EmitAssembly(const TargetMachine &T, ostream *O, bool D)
+ inline EmitAssembly(const TargetMachine &T, std::ostream *O, bool D)
: Target(T), Out(O), DeleteStream(D) {}
// Allocate a target... in the future this will be controllable on the
// command line.
- auto_ptr<TargetMachine> target(allocateSparcTargetMachine());
+ std::auto_ptr<TargetMachine> target(allocateSparcTargetMachine());
assert(target.get() && "Could not allocate target machine!");
TargetMachine &Target = *target.get();
// Load the module to be compiled...
- auto_ptr<Module> M(ParseBytecodeFile(InputFilename));
+ std::auto_ptr<Module> M(ParseBytecodeFile(InputFilename));
if (M.get() == 0) {
cerr << "bytecode didn't read correctly.\n";
return 1;
}
// Build up all of the passes that we want to do to the module...
- vector<Pass*> Passes;
+ std::vector<Pass*> Passes;
// Hoist constants out of PHI nodes into predecessor BB's
Passes.push_back(new HoistPHIConstants());
assert(InputFilename != "-" &&
"files on stdin not supported with tracing");
string traceFileName = GetFileNameRoot(InputFilename) + ".trace.bc";
- ostream *os = new ofstream(traceFileName.c_str(),
- (Force ? 0 : ios::noreplace)|ios::out);
+
+ if (!Force && !std::ifstream(OutputFilename.c_str())) {
+ // If force is not specified, make sure not to overwrite a file!
+ cerr << "Error opening '" << OutputFilename << "': File exists!\n"
+ << "Use -f command line argument to force output\n";
+ return 1;
+ }
+
+ std::ostream *os = new std::ofstream(traceFileName.c_str());
if (!os->good()) {
cerr << "Error opening " << traceFileName
<< "! SKIPPING OUTPUT OF TRACE CODE\n";
if (!DoNotEmitAssembly) { // If asm output is enabled...
// Figure out where we are going to send the output...
- ostream *Out = 0;
+ std::ostream *Out = 0;
if (OutputFilename != "") { // Specified an output filename?
- Out = new ofstream(OutputFilename.c_str(),
- (Force ? 0 : ios::noreplace)|ios::out);
+ if (!Force && !std::ifstream(OutputFilename.c_str())) {
+ // If force is not specified, make sure not to overwrite a file!
+ cerr << "Error opening '" << OutputFilename << "': File exists!\n"
+ << "Use -f command line argument to force output\n";
+ return 1;
+ }
+ Out = new std::ofstream(OutputFilename.c_str());
} else {
if (InputFilename == "-") {
OutputFilename = "-";
- Out = &cout;
+ Out = &std::cout;
} else {
string OutputFilename = GetFileNameRoot(InputFilename);
OutputFilename += ".s";
- Out = new ofstream(OutputFilename.c_str(),
- (Force ? 0 : ios::noreplace)|ios::out);
+
+ if (!Force && !std::ifstream(OutputFilename.c_str())) {
+ // If force is not specified, make sure not to overwrite a file!
+ cerr << "Error opening '" << OutputFilename << "': File exists!\n"
+ << "Use -f command line argument to force output\n";
+ return 1;
+ }
+
+ Out = new std::ofstream(OutputFilename.c_str());
if (!Out->good()) {
cerr << "Error opening " << OutputFilename << "!\n";
delete Out;
}
// Output assembly language to the .s file
- Passes.push_back(new EmitAssembly(Target, Out, Out != &cout));
+ Passes.push_back(new EmitAssembly(Target, Out, Out != &std::cout));
}
// Run our queue of passes all at once now, efficiently. This form of
#include "Support/CommandLine.h"
#include <fstream>
#include <string>
+#include <memory>
cl::String InputFilename ("", "Parse <arg> file, compile to bytecode", 0, "-");
cl::String OutputFilename("o", "Override output filename", cl::NoFlags, "");
ostream *Out = 0;
try {
// Parse the file now...
- Module *C = ParseAssemblyFile(InputFilename);
- if (C == 0) {
+ std::auto_ptr<Module> C(ParseAssemblyFile(InputFilename));
+ if (C.get() == 0) {
cerr << "assembly didn't read correctly.\n";
return 1;
}
if (DumpAsm)
- cerr << "Here's the assembly:\n" << C;
+ cerr << "Here's the assembly:\n" << C.get();
if (OutputFilename != "") { // Specified an output filename?
- Out = new ofstream(OutputFilename.c_str(),
- (Force ? 0 : ios::noreplace)|ios::out);
+ if (!Force && !std::ifstream(OutputFilename.c_str())) {
+ // If force is not specified, make sure not to overwrite a file!
+ cerr << "Error opening '" << OutputFilename << "': File exists!\n"
+ << "Use -f command line argument to force output\n";
+ return 1;
+ }
+ Out = new std::ofstream(OutputFilename.c_str());
} else {
if (InputFilename == "-") {
OutputFilename = "-";
Out = &cout;
} else {
- string IFN = InputFilename;
+ std::string IFN = InputFilename;
int Len = IFN.length();
if (IFN[Len-3] == '.' && IFN[Len-2] == 'l' && IFN[Len-1] == 'l') {
// Source ends in .ll
- OutputFilename = string(IFN.begin(), IFN.end()-3);
+ OutputFilename = std::string(IFN.begin(), IFN.end()-3);
} else {
OutputFilename = IFN; // Append a .bc to it
}
OutputFilename += ".bc";
- Out = new ofstream(OutputFilename.c_str(),
- (Force ? 0 : ios::noreplace)|ios::out);
+
+ if (!Force && !std::ifstream(OutputFilename.c_str())) {
+ // If force is not specified, make sure not to overwrite a file!
+ cerr << "Error opening '" << OutputFilename << "': File exists!\n"
+ << "Use -f command line argument to force output\n";
+ return 1;
+ }
+
+ Out = new std::ofstream(OutputFilename.c_str());
}
+ }
- if (!Out->good()) {
- cerr << "Error opening " << OutputFilename << "!\n";
- delete C;
- return 1;
- }
+ if (!Out->good()) {
+ cerr << "Error opening " << OutputFilename << "!\n";
+ return 1;
}
- WriteBytecodeToFile(C, *Out);
-
- delete C;
+ WriteBytecodeToFile(C.get(), *Out);
} catch (const ParseException &E) {
cerr << E.getMessage() << endl;
return 1;
#include "Support/CommandLine.h"
#include <fstream>
#include <string>
+#include <memory>
cl::String InputFilename ("", "Parse <arg> file, compile to bytecode", 0, "-");
cl::String OutputFilename("o", "Override output filename", cl::NoFlags, "");
ostream *Out = 0;
try {
// Parse the file now...
- Module *C = ParseAssemblyFile(InputFilename);
- if (C == 0) {
+ std::auto_ptr<Module> C(ParseAssemblyFile(InputFilename));
+ if (C.get() == 0) {
cerr << "assembly didn't read correctly.\n";
return 1;
}
if (DumpAsm)
- cerr << "Here's the assembly:\n" << C;
+ cerr << "Here's the assembly:\n" << C.get();
if (OutputFilename != "") { // Specified an output filename?
- Out = new ofstream(OutputFilename.c_str(),
- (Force ? 0 : ios::noreplace)|ios::out);
+ if (!Force && !std::ifstream(OutputFilename.c_str())) {
+ // If force is not specified, make sure not to overwrite a file!
+ cerr << "Error opening '" << OutputFilename << "': File exists!\n"
+ << "Use -f command line argument to force output\n";
+ return 1;
+ }
+ Out = new std::ofstream(OutputFilename.c_str());
} else {
if (InputFilename == "-") {
OutputFilename = "-";
Out = &cout;
} else {
- string IFN = InputFilename;
+ std::string IFN = InputFilename;
int Len = IFN.length();
if (IFN[Len-3] == '.' && IFN[Len-2] == 'l' && IFN[Len-1] == 'l') {
// Source ends in .ll
- OutputFilename = string(IFN.begin(), IFN.end()-3);
+ OutputFilename = std::string(IFN.begin(), IFN.end()-3);
} else {
OutputFilename = IFN; // Append a .bc to it
}
OutputFilename += ".bc";
- Out = new ofstream(OutputFilename.c_str(),
- (Force ? 0 : ios::noreplace)|ios::out);
+
+ if (!Force && !std::ifstream(OutputFilename.c_str())) {
+ // If force is not specified, make sure not to overwrite a file!
+ cerr << "Error opening '" << OutputFilename << "': File exists!\n"
+ << "Use -f command line argument to force output\n";
+ return 1;
+ }
+
+ Out = new std::ofstream(OutputFilename.c_str());
}
+ }
- if (!Out->good()) {
- cerr << "Error opening " << OutputFilename << "!\n";
- delete C;
- return 1;
- }
+ if (!Out->good()) {
+ cerr << "Error opening " << OutputFilename << "!\n";
+ return 1;
}
- WriteBytecodeToFile(C, *Out);
-
- delete C;
+ WriteBytecodeToFile(C.get(), *Out);
} catch (const ParseException &E) {
cerr << E.getMessage() << endl;
return 1;
#include "Support/PostOrderIterator.h"
#include "Support/CommandLine.h"
#include <fstream>
+#include <iostream>
+using std::cerr;
// OutputMode - The different orderings to print basic blocks in...
enum OutputMode {
int main(int argc, char **argv) {
cl::ParseCommandLineOptions(argc, argv, " llvm .bc -> .ll disassembler\n");
- ostream *Out = &cout; // Default to printing to stdout...
+ std::ostream *Out = &std::cout; // Default to printing to stdout...
Module *C = ParseBytecodeFile(InputFilename);
if (C == 0) {
}
if (OutputFilename != "") { // Specified an output filename?
- Out = new ofstream(OutputFilename.c_str(),
- (Force ? 0 : ios::noreplace)|ios::out);
+ if (!Force && !std::ifstream(OutputFilename.c_str())) {
+ // If force is not specified, make sure not to overwrite a file!
+ cerr << "Error opening '" << OutputFilename
+ << "': File exists! Sending to standard output.\n";
+ } else {
+ Out = new std::ofstream(OutputFilename.c_str());
+ }
} else {
if (InputFilename == "-") {
OutputFilename = "-";
- Out = &cout;
} else {
- string IFN = InputFilename;
+ std::string IFN = InputFilename;
int Len = IFN.length();
if (IFN[Len-3] == '.' && IFN[Len-2] == 'b' && IFN[Len-1] == 'c') {
// Source ends in .bc
- OutputFilename = string(IFN.begin(), IFN.end()-3);
+ OutputFilename = std::string(IFN.begin(), IFN.end()-3);
} else {
OutputFilename = IFN; // Append a .ll to it
}
OutputFilename += ".ll";
- Out = new ofstream(OutputFilename.c_str(),
- (Force ? 0 : ios::noreplace)|ios::out);
+
+ if (!Force && !std::ifstream(OutputFilename.c_str())) {
+ // If force is not specified, make sure not to overwrite a file!
+ cerr << "Error opening '" << OutputFilename
+ << "': File exists! Sending to standard output.\n";
+ } else {
+ Out = new std::ofstream(OutputFilename.c_str());
+ }
}
}
if (!Out->good()) {
cerr << "Error opening " << OutputFilename
<< ": sending to stdout instead!\n";
- Out = &cout;
+ Out = &std::cout;
}
// All that dis does is write the assembly out to a file... which is exactly
switch (WriteMode) {
case dfo: // Depth First ordering
copy(df_begin(M), df_end(M),
- ostream_iterator<BasicBlock*>(*Out, "\n"));
+ std::ostream_iterator<BasicBlock*>(*Out, "\n"));
break;
case rdfo: // Reverse Depth First ordering
copy(df_begin(M, true), df_end(M),
- ostream_iterator<BasicBlock*>(*Out, "\n"));
+ std::ostream_iterator<BasicBlock*>(*Out, "\n"));
break;
case po: // Post Order
copy(po_begin(M), po_end(M),
- ostream_iterator<BasicBlock*>(*Out, "\n"));
+ std::ostream_iterator<BasicBlock*>(*Out, "\n"));
break;
case rpo: { // Reverse Post Order
ReversePostOrderTraversal RPOT(M);
copy(RPOT.begin(), RPOT.end(),
- ostream_iterator<BasicBlock*>(*Out, "\n"));
+ std::ostream_iterator<BasicBlock*>(*Out, "\n"));
break;
}
default:
}
delete C;
- if (Out != &cout) delete Out;
+ if (Out != &std::cout) delete Out;
return 0;
}
#include "Support/PostOrderIterator.h"
#include "Support/CommandLine.h"
#include <fstream>
+#include <iostream>
+using std::cerr;
// OutputMode - The different orderings to print basic blocks in...
enum OutputMode {
int main(int argc, char **argv) {
cl::ParseCommandLineOptions(argc, argv, " llvm .bc -> .ll disassembler\n");
- ostream *Out = &cout; // Default to printing to stdout...
+ std::ostream *Out = &std::cout; // Default to printing to stdout...
Module *C = ParseBytecodeFile(InputFilename);
if (C == 0) {
}
if (OutputFilename != "") { // Specified an output filename?
- Out = new ofstream(OutputFilename.c_str(),
- (Force ? 0 : ios::noreplace)|ios::out);
+ if (!Force && !std::ifstream(OutputFilename.c_str())) {
+ // If force is not specified, make sure not to overwrite a file!
+ cerr << "Error opening '" << OutputFilename
+ << "': File exists! Sending to standard output.\n";
+ } else {
+ Out = new std::ofstream(OutputFilename.c_str());
+ }
} else {
if (InputFilename == "-") {
OutputFilename = "-";
- Out = &cout;
} else {
- string IFN = InputFilename;
+ std::string IFN = InputFilename;
int Len = IFN.length();
if (IFN[Len-3] == '.' && IFN[Len-2] == 'b' && IFN[Len-1] == 'c') {
// Source ends in .bc
- OutputFilename = string(IFN.begin(), IFN.end()-3);
+ OutputFilename = std::string(IFN.begin(), IFN.end()-3);
} else {
OutputFilename = IFN; // Append a .ll to it
}
OutputFilename += ".ll";
- Out = new ofstream(OutputFilename.c_str(),
- (Force ? 0 : ios::noreplace)|ios::out);
+
+ if (!Force && !std::ifstream(OutputFilename.c_str())) {
+ // If force is not specified, make sure not to overwrite a file!
+ cerr << "Error opening '" << OutputFilename
+ << "': File exists! Sending to standard output.\n";
+ } else {
+ Out = new std::ofstream(OutputFilename.c_str());
+ }
}
}
if (!Out->good()) {
cerr << "Error opening " << OutputFilename
<< ": sending to stdout instead!\n";
- Out = &cout;
+ Out = &std::cout;
}
// All that dis does is write the assembly out to a file... which is exactly
switch (WriteMode) {
case dfo: // Depth First ordering
copy(df_begin(M), df_end(M),
- ostream_iterator<BasicBlock*>(*Out, "\n"));
+ std::ostream_iterator<BasicBlock*>(*Out, "\n"));
break;
case rdfo: // Reverse Depth First ordering
copy(df_begin(M, true), df_end(M),
- ostream_iterator<BasicBlock*>(*Out, "\n"));
+ std::ostream_iterator<BasicBlock*>(*Out, "\n"));
break;
case po: // Post Order
copy(po_begin(M), po_end(M),
- ostream_iterator<BasicBlock*>(*Out, "\n"));
+ std::ostream_iterator<BasicBlock*>(*Out, "\n"));
break;
case rpo: { // Reverse Post Order
ReversePostOrderTraversal RPOT(M);
copy(RPOT.begin(), RPOT.end(),
- ostream_iterator<BasicBlock*>(*Out, "\n"));
+ std::ostream_iterator<BasicBlock*>(*Out, "\n"));
break;
}
default:
}
delete C;
- if (Out != &cout) delete Out;
+ if (Out != &std::cout) delete Out;
return 0;
}
#include <fstream>
#include <memory>
#include <sys/types.h> // For FileExists
+typedef int blksize_t; // SYS/TYPES is broken!!!
#include <sys/stat.h>
// FileExists - Return true if the specified string is an openable file...
-static inline bool FileExists(const string &FN) {
+static inline bool FileExists(const std::string &FN) {
struct stat StatBuf;
return stat(FN.c_str(), &StatBuf) != -1;
}
// LoadFile - Read the specified bytecode file in and return it. This routine
// searches the link path for the specified file to try to find it...
//
-static inline std::auto_ptr<Module> LoadFile(const string &FN) {
- string Filename = FN;
- string ErrorMessage;
+static inline std::auto_ptr<Module> LoadFile(const std::string &FN) {
+ std::string Filename = FN;
+ std::string ErrorMessage;
unsigned NextLibPathIdx = 0;
bool FoundAFile = false;
assert(InputFilenames.size() > 0 && "OneOrMore is not working");
unsigned BaseArg = 0;
- string ErrorMessage;
+ std::string ErrorMessage;
// TODO: TEST argv[0] for llvm-ar forms... for now, this is a huge hack.
if (InputFilenames.size() >= 3 && InputFilenames[0] == "rc" &&
if (Composite.get() == 0) return 1;
for (unsigned i = BaseArg+1; i < InputFilenames.size(); ++i) {
- auto_ptr<Module> M(LoadFile(InputFilenames[i]));
+ std::auto_ptr<Module> M(LoadFile(InputFilenames[i]));
if (M.get() == 0) return 1;
if (Verbose) cerr << "Linking in '" << InputFilenames[i] << "'\n";
ostream *Out = &cout; // Default to printing to stdout...
if (OutputFilename != "-") {
- Out = new ofstream(OutputFilename.c_str(),
- (Force ? 0 : ios::noreplace)|ios::out);
+ if (!Force && !std::ifstream(OutputFilename.c_str())) {
+ // If force is not specified, make sure not to overwrite a file!
+ cerr << "Error opening '" << OutputFilename << "': File exists!\n"
+ << "Use -f command line argument to force output\n";
+ return 1;
+ }
+ Out = new std::ofstream(OutputFilename.c_str());
if (!Out->good()) {
cerr << "Error opening '" << OutputFilename << "'!\n";
return 1;
if (Verbose) cerr << "Writing bytecode...\n";
WriteBytecodeToFile(Composite.get(), *Out);
- if (Out != &cout) delete Out;
+ if (Out != &std::cout) delete Out;
return 0;
}
for (unsigned i = 0; i < OptimizationList.size(); ++i)
RunOptimization(M.get(), OptimizationList[i]);
- ostream *Out = &cout; // Default to printing to stdout...
+ std::ostream *Out = &std::cout; // Default to printing to stdout...
if (OutputFilename != "") {
- Out = new ofstream(OutputFilename.c_str(),
- (Force ? 0 : ios::noreplace)|ios::out);
+ if (!Force && !std::ifstream(OutputFilename.c_str())) {
+ // If force is not specified, make sure not to overwrite a file!
+ cerr << "Error opening '" << OutputFilename << "': File exists!\n"
+ << "Use -f command line argument to force output\n";
+ return 1;
+ }
+ Out = new std::ofstream(OutputFilename.c_str());
+
if (!Out->good()) {
cerr << "Error opening " << OutputFilename << "!\n";
return 1;