MCFunction.h revision 685a2501b20baf688f6cc087f4b92bbafcd8028e
1//===-- MCFunction.h ------------------------------------------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the data structures to hold a CFG reconstructed from
11// machine code.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/ADT/ArrayRef.h"
16#include "llvm/ADT/SmallPtrSet.h"
17#include "llvm/MC/MCInst.h"
18#include <map>
19
20namespace llvm {
21
22class MCDisassembler;
23class MCInstrInfo;
24class MemoryObject;
25class raw_ostream;
26
27/// MCDecodedInst - Small container to hold an MCInst and associated info like
28/// address and size.
29struct MCDecodedInst {
30  uint64_t Address;
31  uint64_t Size;
32  MCInst Inst;
33
34  MCDecodedInst(uint64_t Address, uint64_t Size, MCInst Inst)
35    : Address(Address), Size(Size), Inst(Inst) {}
36};
37
38/// MCBasicBlock - Consists of multiple MCDecodedInsts and a list of successing
39/// MCBasicBlocks.
40class MCBasicBlock {
41  SmallVector<MCDecodedInst, 8> Insts;
42  typedef SmallPtrSet<MCBasicBlock*, 8> SetTy;
43  SetTy Succs;
44public:
45  ArrayRef<MCDecodedInst> getInsts() const { return Insts; }
46
47  typedef SetTy::const_iterator succ_iterator;
48  succ_iterator succ_begin() const { return Succs.begin(); }
49  succ_iterator succ_end() const { return Succs.end(); }
50
51  void addInst(const MCDecodedInst &Inst) { Insts.push_back(Inst); }
52  void addSucc(MCBasicBlock *BB) { Succs.insert(BB); }
53};
54
55/// MCFunction - Represents a named function in machine code, containing
56/// multiple MCBasicBlocks.
57class MCFunction {
58  const StringRef Name;
59  // Keep BBs sorted by address.
60  typedef std::map<uint64_t, MCBasicBlock> MapTy;
61  MapTy Blocks;
62public:
63  MCFunction(StringRef Name) : Name(Name) {}
64
65  // Create an MCFunction from a region of binary machine code.
66  static MCFunction
67  createFunctionFromMC(StringRef Name, const MCDisassembler *DisAsm,
68                       const MemoryObject &Region, uint64_t Start, uint64_t End,
69                       const MCInstrInfo *InstrInfo, raw_ostream &DebugOut);
70
71  typedef MapTy::iterator iterator;
72  iterator begin() { return Blocks.begin(); }
73  iterator end() { return Blocks.end(); }
74
75  StringRef getName() const { return Name; }
76
77  MCBasicBlock &addBlock(uint64_t Address, const MCBasicBlock &BB) {
78    assert(!Blocks.count(Address) && "Already a BB at address.");
79    return Blocks[Address] = BB;
80  }
81
82  MCBasicBlock &getBlockAtAddress(uint64_t Address) {
83    assert(Blocks.count(Address) && "No BB at address.");
84    return Blocks[Address];
85  }
86};
87
88}
89