summaryrefslogtreecommitdiff
path: root/clang/lib/Analysis/Interval.cpp
blob: 726c6deeb37f193087e4938ef2ddb3f36e5c238f (about) (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
#include "clang/Analysis/Analyses/Interval.h"
#include "clang/AST/Stmt.h"
#include "clang/Analysis/CFG.h"
#include "clang/Analysis/AnalysisContext.h"
#include "clang/AST/StmtVisitor.h"

#include "clang/Analysis/Analyses/IntervalSolver/Log.hpp"
#include "clang/Analysis/Analyses/IntervalSolver/Complete.hpp"
#include "clang/Analysis/Analyses/IntervalSolver/VariableAssignment.hpp"
#include "clang/Analysis/Analyses/IntervalSolver/EquationSystem.hpp"
  
#include "llvm/ADT/PostOrderIterator.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/Support/Process.h"
  
#include <deque>
#include <algorithm>
#include <vector>
#include <map>

using namespace clang;

typedef EquationSystem<Complete<int> > EqnSys;
typedef Expression<Complete<int> > EqnExpr;

#include <sstream>
template<typename T>
std::string toString(const T& obj) {
  std::stringstream stream;
  stream << obj;
  return stream.str();
}

IntervalAnalysis :: IntervalAnalysis(AnalysisDeclContext &context)
  : context(&context) {
}

IntervalAnalysis :: ~IntervalAnalysis() {
}

// Two pieces of state:
//  -> condition protecting a node
//  -> node's expression itself
// We can then combine these in a straightforward way to
// get out equation system, whereupon we can solve for what
// we want to know. Then we can have program invariants!
//
// Hooray!

typedef Complete<int64_t> ZBar;
typedef std::map<std::string, ZBar> Vector;
typedef std::pair<Vector, ZBar> Result; // a "slice" of an equation

template<class F, class M>
void transform_values(const F& f, M& map) {
  for (typename M::iterator it = map.begin(),
         ei = map.end();
       it != ei;
       ++it) {
    it->second = f(it->second);
  }
}

template<class M, class F> 
M merge_maps_with(const F& f, const M& left, const M& right) {
  M result;
  typename M::const_iterator first1 = left.begin(), last1 = left.end(),
    first2 = right.begin(), last2 = right.end();
  for (; first1 != last1 && first2 != last2;) {
    if (first2->first < first1->first) {
      result[first2->first] = first2->second;
      ++first2;
    } else if (first1->first == first2->first) {
      result[first1->first] = f(first1->second, first2->second);
      ++first1;
      ++first2;
    } else {
      result[first1->first] = first1->second;
      ++first1;
    }
  }
  while (first1 != last1) {
    result[first1->first] = first1->second;
    ++first1;
  }
  while (first2 != last2) {
    result[first2->first] = first2->second;
    ++first2;
  }
  return result;
}

template<class T>
T negate(const T& v) {
  return -v;
}
template<class T>
T addValues(const T& l, const T& r) {
  return l + r;
}
template<class T>
T subValues(const T& l, const T& r) {
  return l - r;
}


Result fromStmt(const Stmt*, EqnSys&);

Result fromInteger(const IntegerLiteral* expr, EqnSys& system) {
  return Result(Vector(), *expr->getValue().getRawData());
}

Result fromDeclExpr(const DeclRefExpr* expr, EqnSys& system) {
  Vector val;
  val[expr->getNameInfo().getAsString()] = 1;
  return Result(val, 0);
}

Result fromUnary(const UnaryOperator* op, EqnSys& system) {
  switch (op->getOpcode()) {
  case UO_PreInc:
    break;
  case UO_PostInc:
    break;
  }
  return Result(Vector(), 0);
}


Addition<Complete<int> >* add = new Addition<Complete<int> >();
Subtraction<Complete<int> >* sub = new Subtraction<Complete<int> >();
Multiplication<Complete<int> >* mul = new Multiplication<Complete<int> >();

Result fromBinary(const BinaryOperator* op, EqnSys& system) {
  Result left = fromStmt(op->getLHS()->IgnoreParenCasts(), system);
  Result right = fromStmt(op->getRHS()->IgnoreParenCasts(), system);
  
  switch (op->getOpcode()) {
  case BO_Sub:
    transform_values(negate<ZBar>, right.first);
  case BO_Add:
    {
      Result result;
      result.first = merge_maps_with(addValues<ZBar>,
                                     left.first, right.first);
      result.second = left.second + right.second;
      return result;
    }
  case BO_Mul:
    {
      if (!left.first.empty() && !right.first.empty()) {
        return Result(Vector(), 0);
      }
      ZBar scalar = 0;
      Result value;
      if (left.first.empty()) {
        scalar = left.second;
        value = right;
      } else {
        scalar = right.second;
        value = left;
      }
      for (Vector::iterator it = value.first.begin(),
             ei = value.first.end();
           it != ei;
           ++it) {
        it->second *= scalar;
      }
      right.second *= scalar;
      return value;
    }
  case BO_LT:
  case BO_LE:
  case BO_GT:
  case BO_GE:
    break;
  } 
  return Result();
}

Result fromDeclStmt(const DeclStmt* stmt, EqnSys& system) {
  /*for (DeclStmt::const_decl_iterator it = stmt->decl_begin(),
                                     ei = stmt->decl_end();
       it != ei;
       ++it) {
    if ((*it)->getKind() == Decl::Var) {
      const VarDecl* decl = static_cast<const VarDecl*>(*it);
      Variable<Complete<int> > var = system.variable(decl->getNameAsString());
      std::vector<EqnExpr*> args;
      args.push_back(&system.constant(-infinity<Complete<int> >()));
      args.push_back(fromStmt(decl->getInit(), system));
      system[var] = &system.maxExpression(args);
    }
  }*/

  for (DeclStmt::const_decl_iterator it = stmt->decl_begin(),
                                     ei = stmt->decl_end();
       it != ei;
       ++it) {
    if ((*it)->getKind() == Decl::Var) {
      const VarDecl* decl = static_cast<const VarDecl*>(*it);
      llvm::errs() << decl->getNameAsString() << " = ";

      Result expr = fromStmt(decl->getInit(), system);
      llvm::errs() << "<{ ";
      for (Vector::iterator it = expr.first.begin(),
             ei = expr.first.end();
           it != ei;
           ++it) {
        if (it != expr.first.begin())
          llvm::errs() << ", ";
        llvm::errs() << toString(it->first) << " = " << toString(it->second);
      }
      llvm::errs() << " }, " << toString(expr.second) << ">\n";
    }
  }

  return Result();
}

Result fromAssignment(const BinaryOperator* op, EqnSys& system) {
  /*EqnExpr* left = fromStmt(op->getLHS()->IgnoreParenCasts(), system);
  EqnExpr* right = fromStmt(op->getRHS()->IgnoreParenCasts(), system);
  Variable<Complete<int> >* var = static_cast<Variable<Complete<int> >*>(left);

  std::vector<EqnExpr*> args;
  args.push_back(&system.constant(-infinity<Complete<int> >()));
  args.push_back(right);
  if (system[*var] != NULL)
    args.push_back(system[*var]);
    system[*var] = &system.maxExpression(args);*/
  
  const Expr* left = op->getLHS()->IgnoreParenCasts();
  if (left->getStmtClass() == Stmt::DeclRefExprClass) {
    std::string name = static_cast<const DeclRefExpr*>(left)->getNameInfo().getAsString();

    Result expr = fromStmt(op->getRHS()->IgnoreParenCasts(), system);
    llvm::errs() << name << " = <{ ";
    for (Vector::iterator it = expr.first.begin(),
           ei = expr.first.end();
         it != ei;
         ++it) {
      if (it != expr.first.begin())
        llvm::errs() << ", ";
      llvm::errs() << toString(it->first) << " = " << toString(it->second);
    }
    llvm::errs() << " }, " << toString(expr.second) << ">\n";
    return expr;
  }
  return Result();
}

Result fromStmt(const Stmt* stmt, EqnSys& system) {
  if (!stmt)
    return Result();
  switch (stmt->getStmtClass()) {
  case Stmt::IntegerLiteralClass:
    return fromInteger(static_cast<const IntegerLiteral*>(stmt), system);
  case Stmt::DeclRefExprClass:
    return fromDeclExpr(static_cast<const DeclRefExpr*>(stmt), system);
  case Stmt::UnaryOperatorClass:
    return fromUnary(static_cast<const UnaryOperator*>(stmt), system);
  case Stmt::DeclStmtClass:
    return fromDeclStmt(static_cast<const DeclStmt*>(stmt), system);
  case Stmt::BinaryOperatorClass:
    {
      const BinaryOperator* binop = static_cast<const BinaryOperator*>(stmt);
      if (binop->isAssignmentOp())
        return fromAssignment(binop, system);
      else
        return fromBinary(binop, system);
    }
  }
  return Result();
}

void runOnBlock(std::string id, const CFGBlock* block, EqnSys& system) {
  for (CFGBlock::const_iterator it = block->begin(),
                                ei = block->end();
       it != ei;
       ++it) {
    const CFGStmt* cfg_stmt = it->getAs<CFGStmt>();
    Result expr = fromStmt(cfg_stmt->getStmt(), system);
    /*llvm::errs() << "<{ ";
    for (Vector::iterator it = expr.first.begin(),
           ei = expr.first.end();
         it != ei;
         ++it) {
      if (it != expr.first.begin())
        llvm::errs() << ", ";
      llvm::errs() << toString(it->first) << " = " << toString(it->second);
    }
    llvm::errs() << "}, " << toString(expr.second) << ">\n";*/
  }
  fromStmt(block->getTerminatorCondition(), system);

  /*if (terminator.getStmt() != NULL) {
    if (terminator.getStmt()->getStmtClass() == Stmt::IfStmtClass) {
      const IfStmt* if_stmt = static_cast<const IfStmt*>(terminator.getStmt());
      llvm::errs() << "If: \n";
      if_stmt->dump();
    } else {
      llvm::errs() << "\n";
      terminator.getStmt()->dump();
    }
    }*/
  return; // TODO: return a generated expression
}

void IntervalAnalysis::runOnAllBlocks() {
  llvm::errs() << "Enter run on all blocks\n";

  const CFG *cfg = this->context->getCFG();

  EqnSys system;

  std::set<const CFGBlock*> seen;
  std::deque<const CFGBlock*> todo;
  todo.push_back(&cfg->getEntry());

  while (!todo.empty()) {
    const CFGBlock* block = todo.front();
    if (seen.find(todo.front()) != seen.end()) {
      todo.pop_front();
      continue;
    }
    llvm::errs() << (void*)block << "\n";
    seen.insert(block);
    todo.pop_front();
    runOnBlock(toString(block), block, system);
    llvm::errs() << "-> ";
    for (CFGBlock::const_succ_iterator it = block->succ_begin(),
                                       ei = block->succ_end();
         it != ei;
         it++ ) {
      llvm::errs() << (void*) *it << ", ";
      todo.push_back(*it);
    }
    llvm::errs() << "\n\n";
  }

  llvm::errs() << "Exit run on all blocks\n";

  llvm::errs() << toString(system) << "\n";

  system.indexMaxExpressions();
  DynamicMaxStrategy<Complete<int> > strategy(system);
  DynamicVariableAssignment<Complete<int> > rho(system, strategy);
  strategy.setRho(rho);

  for (unsigned int i = 0, size = system.variableCount(); i < size; ++i) {
    Variable<Complete<int> >& var = system.variable(i);
    llvm::errs() << toString(var.name()) << " = " << toString(rho[var]) << "\n";
  }

  //  cfg->dump(context->getASTContext().getLangOpts(),
  //            llvm::sys::Process::StandardErrHasColors());
}


const void *IntervalAnalysis::getTag() { static int x; return &x; }