]> granicus.if.org Git - clang/blob - include/clang/Analysis/Analyses/ThreadSafetyTIL.h
Fix the build with LLVM_DELETED_FUNCTION instead of '= delete'
[clang] / include / clang / Analysis / Analyses / ThreadSafetyTIL.h
1 //===- ThreadSafetyTIL.h ---------------------------------------*- C++ --*-===//
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 a simple intermediate language that is used by the
11 // thread safety analysis (See ThreadSafety.cpp).  The thread safety analysis
12 // works by comparing mutex expressions, e.g.
13 //
14 // class A { Mutex mu; int dat GUARDED_BY(this->mu); }
15 // class B { A a; }
16 //
17 // void foo(B* b) {
18 //   (*b).a.mu.lock();     // locks (*b).a.mu
19 //   b->a.dat = 0;         // substitute &b->a for 'this';
20 //                         // requires lock on (&b->a)->mu
21 //   (b->a.mu).unlock();   // unlocks (b->a.mu)
22 // }
23 //
24 // As illustrated by the above example, clang Exprs are not well-suited to
25 // represent mutex expressions directly, since there is no easy way to compare
26 // Exprs for equivalence.  The thread safety analysis thus lowers clang Exprs
27 // into a simple intermediate language (IL).  The IL supports:
28 //
29 // (1) comparisons for semantic equality of expressions
30 // (2) SSA renaming of variables
31 // (3) wildcards and pattern matching over expressions
32 // (4) hash-based expression lookup
33 //
34 // The IL is currently very experimental, is intended only for use within
35 // the thread safety analysis, and is subject to change without notice.
36 // After the API stabilizes and matures, it may be appropriate to make this
37 // more generally available to other analyses.
38 //
39 // UNDER CONSTRUCTION.  USE AT YOUR OWN RISK.
40 //
41 //===----------------------------------------------------------------------===//
42
43 #ifndef LLVM_CLANG_THREAD_SAFETY_TIL_H
44 #define LLVM_CLANG_THREAD_SAFETY_TIL_H
45
46 #include "clang/Analysis/Analyses/ThreadSafetyUtil.h"
47 #include "clang/AST/ExprCXX.h"
48 #include "llvm/ADT/StringRef.h"
49 #include "llvm/Support/Compiler.h"
50
51 #include <cassert>
52 #include <cstddef>
53 #include <utility>
54
55
56 namespace clang {
57 namespace threadSafety {
58 namespace til {
59
60 using llvm::StringRef;
61 using clang::SourceLocation;
62
63
64 enum TIL_Opcode {
65 #define TIL_OPCODE_DEF(X) COP_##X,
66 #include "clang/Analysis/Analyses/ThreadSafetyOps.def"
67 #undef TIL_OPCODE_DEF
68   COP_MAX
69 };
70
71
72 typedef clang::BinaryOperatorKind TIL_BinaryOpcode;
73 typedef clang::UnaryOperatorKind TIL_UnaryOpcode;
74 typedef clang::CastKind TIL_CastOpcode;
75
76
77 enum TraversalKind {
78   TRV_Normal,
79   TRV_Lazy, // subexpression may need to be traversed lazily
80   TRV_Tail  // subexpression occurs in a tail position
81 };
82
83
84 // Base class for AST nodes in the typed intermediate language.
85 class SExpr {
86 public:
87   TIL_Opcode opcode() const { return static_cast<TIL_Opcode>(Opcode); }
88
89   // Subclasses of SExpr must define the following:
90   //
91   // This(const This& E, ...) {
92   //   copy constructor: construct copy of E, with some additional arguments.
93   // }
94   //
95   // template <class V> typename V::R_SExpr traverse(V &Visitor) {
96   //   traverse all subexpressions, following the traversal/rewriter interface
97   // }
98   //
99   // template <class C> typename C::CType compare(CType* E, C& Cmp) {
100   //   compare all subexpressions, following the comparator interface
101   // }
102
103   void *operator new(size_t S, clang::threadSafety::til::MemRegionRef &R) {
104     return ::operator new(S, R);
105   }
106
107 protected:
108   SExpr(TIL_Opcode Op) : Opcode(Op), Reserved(0), Flags(0) {}
109   SExpr(const SExpr &E) : Opcode(E.Opcode), Reserved(0), Flags(E.Flags) {}
110
111   const unsigned char Opcode;
112   unsigned char Reserved;
113   unsigned short Flags;
114
115 private:
116   SExpr() LLVM_DELETED_FUNCTION;
117
118   // SExpr objects must be created in an arena and cannot be deleted.
119   void *operator new(size_t) LLVM_DELETED_FUNCTION;
120   void operator delete(void *) LLVM_DELETED_FUNCTION;
121 };
122
123
124 // Class for owning references to SExprs.
125 // Includes attach/detach logic for counting variable references and lazy
126 // rewriting strategies.
127 class SExprRef {
128 public:
129   SExprRef() : Ptr(nullptr) { }
130   SExprRef(std::nullptr_t P) : Ptr(nullptr) { }
131   SExprRef(SExprRef &&R) : Ptr(R.Ptr) { R.Ptr = nullptr; }
132
133   // Defined after Variable and Future, below.
134   inline SExprRef(SExpr *P);
135   inline ~SExprRef();
136
137   SExpr       *get()       { return Ptr; }
138   const SExpr *get() const { return Ptr; }
139
140   SExpr       *operator->()       { return get(); }
141   const SExpr *operator->() const { return get(); }
142
143   SExpr       &operator*()        { return *Ptr; }
144   const SExpr &operator*() const  { return *Ptr; }
145
146   bool operator==(const SExprRef &R) const { return Ptr == R.Ptr; }
147   bool operator!=(const SExprRef &R) const { return !operator==(R); }
148   bool operator==(const SExpr *P) const { return Ptr == P; }
149   bool operator!=(const SExpr *P) const { return !operator==(P); }
150   bool operator==(std::nullptr_t) const { return Ptr == nullptr; }
151   bool operator!=(std::nullptr_t) const { return Ptr != nullptr; }
152
153   inline void reset(SExpr *E);
154
155 private:
156   inline void attach();
157   inline void detach();
158
159   SExpr *Ptr;
160 };
161
162
163 // Contains various helper functions for SExprs.
164 namespace ThreadSafetyTIL {
165   inline bool isTrivial(SExpr *E) {
166     unsigned Op = E->opcode();
167     return Op == COP_Variable || Op == COP_Literal || Op == COP_LiteralPtr;
168   }
169 }
170
171 class Function;
172 class SFunction;
173 class BasicBlock;
174
175
176 // A named variable, e.g. "x".
177 //
178 // There are two distinct places in which a Variable can appear in the AST.
179 // A variable declaration introduces a new variable, and can occur in 3 places:
180 //   Let-expressions:           (Let (x = t) u)
181 //   Functions:                 (Function (x : t) u)
182 //   Self-applicable functions  (SFunction (x) t)
183 //
184 // If a variable occurs in any other location, it is a reference to an existing
185 // variable declaration -- e.g. 'x' in (x * y + z). To save space, we don't
186 // allocate a separate AST node for variable references; a reference is just a
187 // pointer to the original declaration.
188 class Variable : public SExpr {
189 public:
190   static bool classof(const SExpr *E) { return E->opcode() == COP_Variable; }
191
192   // Let-variable, function parameter, or self-variable
193   enum VariableKind {
194     VK_Let,
195     VK_Fun,
196     VK_SFun
197   };
198
199   // These are defined after SExprRef contructor, below
200   inline Variable(VariableKind K, SExpr *D = nullptr,
201                   const clang::ValueDecl *Cvd = nullptr);
202   inline Variable(const clang::ValueDecl *Cvd, SExpr *D = nullptr);
203   inline Variable(const Variable &Vd, SExpr *D);
204
205   VariableKind kind() const { return static_cast<VariableKind>(Flags); }
206
207   const StringRef name() const { return Cvdecl ? Cvdecl->getName() : "_x"; }
208   const clang::ValueDecl *clangDecl() const { return Cvdecl; }
209
210   // Returns the definition (for let vars) or type (for parameter & self vars)
211   SExpr *definition() { return Definition.get(); }
212
213   void attachVar() const { ++NumUses; }
214   void detachVar() const { assert(NumUses > 0); --NumUses; }
215
216   unsigned getID() const { return Id; }
217   unsigned getBlockID() const { return BlockID; }
218
219   void setID(unsigned Bid, unsigned I) {
220     BlockID = static_cast<unsigned short>(Bid);
221     Id = static_cast<unsigned short>(I);
222   }
223
224   template <class V> typename V::R_SExpr traverse(V &Visitor) {
225     // This routine is only called for variable references.
226     return Visitor.reduceVariableRef(this);
227   }
228
229   template <class C> typename C::CType compare(Variable* E, C& Cmp) {
230     return Cmp.compareVariableRefs(this, E);
231   }
232
233 private:
234   friend class Function;
235   friend class SFunction;
236   friend class BasicBlock;
237
238   // Function, SFunction, and BasicBlock will reset the kind.
239   void setKind(VariableKind K) { Flags = K; }
240
241   SExprRef Definition;             // The TIL type or definition
242   const clang::ValueDecl *Cvdecl;  // The clang declaration for this variable.
243
244   unsigned short BlockID;
245   unsigned short Id;
246   mutable unsigned NumUses;
247 };
248
249
250 // Placeholder for an expression that has not yet been created.
251 // Used to implement lazy copy and rewriting strategies.
252 class Future : public SExpr {
253 public:
254   static bool classof(const SExpr *E) { return E->opcode() == COP_Future; }
255
256   enum FutureStatus {
257     FS_pending,
258     FS_evaluating,
259     FS_done
260   };
261
262   Future() :
263     SExpr(COP_Future), Status(FS_pending), Result(nullptr), Location(nullptr)
264   {}
265 private:
266   virtual ~Future() LLVM_DELETED_FUNCTION;
267 public:
268
269   // Registers the location in the AST where this future is stored.
270   // Forcing the future will automatically update the AST.
271   static inline void registerLocation(SExprRef *Member) {
272     if (Future *F = dyn_cast_or_null<Future>(Member->get()))
273       F->Location = Member;
274   }
275
276   // A lazy rewriting strategy should subclass Future and override this method.
277   virtual SExpr *create() { return nullptr; }
278
279   // Return the result of this future if it exists, otherwise return null.
280   SExpr *maybeGetResult() {
281     return Result;
282   }
283
284   // Return the result of this future; forcing it if necessary.
285   SExpr *result() {
286     switch (Status) {
287     case FS_pending:
288       force();
289       return Result;
290     case FS_evaluating:
291       return nullptr; // infinite loop; illegal recursion.
292     case FS_done:
293       return Result;
294     }
295   }
296
297   template <class V> typename V::R_SExpr traverse(V &Visitor) {
298     assert(Result && "Cannot traverse Future that has not been forced.");
299     return Visitor.traverse(Result);
300   }
301
302   template <class C> typename C::CType compare(Future* E, C& Cmp) {
303     if (!Result || !E->Result)
304       return Cmp.comparePointers(this, E);
305     return Cmp.compare(Result, E->Result);
306   }
307
308 private:
309   // Force the future.
310   inline void force();
311
312   FutureStatus Status;
313   SExpr *Result;
314   SExprRef *Location;
315 };
316
317
318
319 void SExprRef::attach() {
320   if (!Ptr)
321     return;
322
323   TIL_Opcode Op = Ptr->opcode();
324   if (Op == COP_Variable) {
325     cast<Variable>(Ptr)->attachVar();
326   }
327   else if (Op == COP_Future) {
328     cast<Future>(Ptr)->registerLocation(this);
329   }
330 }
331
332 void SExprRef::detach() {
333   if (Ptr && Ptr->opcode() == COP_Variable) {
334     cast<Variable>(Ptr)->detachVar();
335   }
336 }
337
338 SExprRef::SExprRef(SExpr *P) : Ptr(P) {
339   if (P)
340     attach();
341 }
342
343 SExprRef::~SExprRef() {
344   detach();
345 }
346
347 void SExprRef::reset(SExpr *P) {
348   if (Ptr)
349     detach();
350   Ptr = P;
351   if (P)
352     attach();
353 }
354
355
356 Variable::Variable(VariableKind K, SExpr *D, const clang::ValueDecl *Cvd)
357     : SExpr(COP_Variable), Definition(D), Cvdecl(Cvd),
358       BlockID(0), Id(0),  NumUses(0) {
359   Flags = K;
360 }
361
362 Variable::Variable(const clang::ValueDecl *Cvd, SExpr *D)
363     : SExpr(COP_Variable), Definition(D), Cvdecl(Cvd),
364       BlockID(0), Id(0),  NumUses(0) {
365   Flags = VK_Let;
366 }
367
368 Variable::Variable(const Variable &Vd, SExpr *D) // rewrite constructor
369     : SExpr(Vd), Definition(D), Cvdecl(Vd.Cvdecl),
370       BlockID(0), Id(0), NumUses(0) {
371   Flags = Vd.kind();
372 }
373
374
375 void Future::force() {
376   Status = FS_evaluating;
377   SExpr *R = create();
378   Result = R;
379   if (Location) {
380     Location->reset(R);
381   }
382   Status = FS_done;
383 }
384
385
386
387 // Placeholder for C++ expressions that cannot be represented in the TIL.
388 class Undefined : public SExpr {
389 public:
390   static bool classof(const SExpr *E) { return E->opcode() == COP_Undefined; }
391
392   Undefined(const clang::Stmt *S = nullptr) : SExpr(COP_Undefined), Cstmt(S) {}
393   Undefined(const Undefined &U) : SExpr(U), Cstmt(U.Cstmt) {}
394
395   template <class V> typename V::R_SExpr traverse(V &Visitor) {
396     return Visitor.reduceUndefined(*this);
397   }
398
399   template <class C> typename C::CType compare(Undefined* E, C& Cmp) {
400     return Cmp.comparePointers(Cstmt, E->Cstmt);
401   }
402
403 private:
404   const clang::Stmt *Cstmt;
405 };
406
407
408 // Placeholder for a wildcard that matches any other expression.
409 class Wildcard : public SExpr {
410 public:
411   static bool classof(const SExpr *E) { return E->opcode() == COP_Wildcard; }
412
413   Wildcard() : SExpr(COP_Wildcard) {}
414   Wildcard(const Wildcard &W) : SExpr(W) {}
415
416   template <class V> typename V::R_SExpr traverse(V &Visitor) {
417     return Visitor.reduceWildcard(*this);
418   }
419
420   template <class C> typename C::CType compare(Wildcard* E, C& Cmp) {
421     return Cmp.trueResult();
422   }
423 };
424
425
426 // Base class for literal values.
427 class Literal : public SExpr {
428 public:
429   static bool classof(const SExpr *E) { return E->opcode() == COP_Literal; }
430
431   Literal(const clang::Expr *C) : SExpr(COP_Literal), Cexpr(C) {}
432   Literal(const Literal &L) : SExpr(L), Cexpr(L.Cexpr) {}
433
434   // The clang expression for this literal.
435   const clang::Expr *clangExpr() { return Cexpr; }
436
437   template <class V> typename V::R_SExpr traverse(V &Visitor) {
438     return Visitor.reduceLiteral(*this);
439   }
440
441   template <class C> typename C::CType compare(Literal* E, C& Cmp) {
442     // TODO -- use value, not pointer equality
443     return Cmp.comparePointers(Cexpr, E->Cexpr);
444   }
445
446 private:
447   const clang::Expr *Cexpr;
448 };
449
450
451 // Literal pointer to an object allocated in memory.
452 // At compile time, pointer literals are represented by symbolic names.
453 class LiteralPtr : public SExpr {
454 public:
455   static bool classof(const SExpr *E) { return E->opcode() == COP_LiteralPtr; }
456
457   LiteralPtr(const clang::ValueDecl *D) : SExpr(COP_LiteralPtr), Cvdecl(D) {}
458   LiteralPtr(const LiteralPtr &R) : SExpr(R), Cvdecl(R.Cvdecl) {}
459
460   // The clang declaration for the value that this pointer points to.
461   const clang::ValueDecl *clangDecl() { return Cvdecl; }
462
463   template <class V> typename V::R_SExpr traverse(V &Visitor) {
464     return Visitor.reduceLiteralPtr(*this);
465   }
466
467   template <class C> typename C::CType compare(LiteralPtr* E, C& Cmp) {
468     return Cmp.comparePointers(Cvdecl, E->Cvdecl);
469   }
470
471 private:
472   const clang::ValueDecl *Cvdecl;
473 };
474
475
476
477
478
479 // A function -- a.k.a. lambda abstraction.
480 // Functions with multiple arguments are created by currying,
481 // e.g. (function (x: Int) (function (y: Int) (add x y)))
482 class Function : public SExpr {
483 public:
484   static bool classof(const SExpr *E) { return E->opcode() == COP_Function; }
485
486   Function(Variable *Vd, SExpr *Bd)
487       : SExpr(COP_Function), VarDecl(Vd), Body(Bd) {
488     Vd->setKind(Variable::VK_Fun);
489   }
490   Function(const Function &F, Variable *Vd, SExpr *Bd) // rewrite constructor
491       : SExpr(F), VarDecl(Vd), Body(Bd) {
492     Vd->setKind(Variable::VK_Fun);
493   }
494
495   Variable *variableDecl()  { return VarDecl; }
496   const Variable *variableDecl() const { return VarDecl; }
497
498   SExpr *body() { return Body.get(); }
499   const SExpr *body() const { return Body.get(); }
500
501   template <class V> typename V::R_SExpr traverse(V &Visitor) {
502     // This is a variable declaration, so traverse the definition.
503     typename V::R_SExpr E0 = Visitor.traverse(VarDecl->Definition, TRV_Lazy);
504     // Tell the rewriter to enter the scope of the function.
505     Variable *Nvd = Visitor.enterScope(*VarDecl, E0);
506     typename V::R_SExpr E1 = Visitor.traverse(Body);
507     Visitor.exitScope(*VarDecl);
508     return Visitor.reduceFunction(*this, Nvd, E1);
509   }
510
511   template <class C> typename C::CType compare(Function* E, C& Cmp) {
512     typename C::CType Ct =
513       Cmp.compare(VarDecl->definition(), E->VarDecl->definition());
514     if (Cmp.notTrue(Ct))
515       return Ct;
516     Cmp.enterScope(variableDecl(), E->variableDecl());
517     Ct = Cmp.compare(body(), E->body());
518     Cmp.leaveScope();
519     return Ct;
520   }
521
522 private:
523   Variable *VarDecl;
524   SExprRef Body;
525 };
526
527
528 // A self-applicable function.
529 // A self-applicable function can be applied to itself.  It's useful for
530 // implementing objects and late binding
531 class SFunction : public SExpr {
532 public:
533   static bool classof(const SExpr *E) { return E->opcode() == COP_SFunction; }
534
535   SFunction(Variable *Vd, SExpr *B)
536       : SExpr(COP_SFunction), VarDecl(Vd), Body(B) {
537     assert(Vd->Definition == nullptr);
538     Vd->setKind(Variable::VK_SFun);
539     Vd->Definition.reset(this);
540   }
541   SFunction(const SFunction &F, Variable *Vd, SExpr *B) // rewrite constructor
542       : SExpr(F),
543         VarDecl(Vd),
544         Body(B) {
545     assert(Vd->Definition == nullptr);
546     Vd->setKind(Variable::VK_SFun);
547     Vd->Definition.reset(this);
548   }
549
550   Variable *variableDecl() { return VarDecl; }
551   const Variable *variableDecl() const { return VarDecl; }
552
553   SExpr *body() { return Body.get(); }
554   const SExpr *body() const { return Body.get(); }
555
556   template <class V> typename V::R_SExpr traverse(V &Visitor) {
557     // A self-variable points to the SFunction itself.
558     // A rewrite must introduce the variable with a null definition, and update
559     // it after 'this' has been rewritten.
560     Variable *Nvd = Visitor.enterScope(*VarDecl, nullptr /* def */);
561     typename V::R_SExpr E1 = Visitor.traverse(Body);
562     Visitor.exitScope(*VarDecl);
563     // A rewrite operation will call SFun constructor to set Vvd->Definition.
564     return Visitor.reduceSFunction(*this, Nvd, E1);
565   }
566
567   template <class C> typename C::CType compare(SFunction* E, C& Cmp) {
568     Cmp.enterScope(variableDecl(), E->variableDecl());
569     typename C::CType Ct = Cmp.compare(body(), E->body());
570     Cmp.leaveScope();
571     return Ct;
572   }
573
574 private:
575   Variable *VarDecl;
576   SExprRef Body;
577 };
578
579
580 // A block of code -- e.g. the body of a function.
581 class Code : public SExpr {
582 public:
583   static bool classof(const SExpr *E) { return E->opcode() == COP_Code; }
584
585   Code(SExpr *T, SExpr *B) : SExpr(COP_Code), ReturnType(T), Body(B) {}
586   Code(const Code &C, SExpr *T, SExpr *B) // rewrite constructor
587       : SExpr(C), ReturnType(T), Body(B) {}
588
589   SExpr *returnType() { return ReturnType.get(); }
590   const SExpr *returnType() const { return ReturnType.get(); }
591
592   SExpr *body() { return Body.get(); }
593   const SExpr *body() const { return Body.get(); }
594
595   template <class V> typename V::R_SExpr traverse(V &Visitor) {
596     typename V::R_SExpr Nt = Visitor.traverse(ReturnType, TRV_Lazy);
597     typename V::R_SExpr Nb = Visitor.traverse(Body, TRV_Lazy);
598     return Visitor.reduceCode(*this, Nt, Nb);
599   }
600
601   template <class C> typename C::CType compare(Code* E, C& Cmp) {
602     typename C::CType Ct = Cmp.compare(returnType(), E->returnType());
603     if (Cmp.notTrue(Ct))
604       return Ct;
605     return Cmp.compare(body(), E->body());
606   }
607
608 private:
609   SExprRef ReturnType;
610   SExprRef Body;
611 };
612
613
614 // Apply an argument to a function
615 class Apply : public SExpr {
616 public:
617   static bool classof(const SExpr *E) { return E->opcode() == COP_Apply; }
618
619   Apply(SExpr *F, SExpr *A) : SExpr(COP_Apply), Fun(F), Arg(A) {}
620   Apply(const Apply &A, SExpr *F, SExpr *Ar)  // rewrite constructor
621       : SExpr(A), Fun(F), Arg(Ar)
622   {}
623
624   SExpr *fun() { return Fun.get(); }
625   const SExpr *fun() const { return Fun.get(); }
626
627   SExpr *arg() { return Arg.get(); }
628   const SExpr *arg() const { return Arg.get(); }
629
630   template <class V> typename V::R_SExpr traverse(V &Visitor) {
631     typename V::R_SExpr Nf = Visitor.traverse(Fun);
632     typename V::R_SExpr Na = Visitor.traverse(Arg);
633     return Visitor.reduceApply(*this, Nf, Na);
634   }
635
636   template <class C> typename C::CType compare(Apply* E, C& Cmp) {
637     typename C::CType Ct = Cmp.compare(fun(), E->fun());
638     if (Cmp.notTrue(Ct))
639       return Ct;
640     return Cmp.compare(arg(), E->arg());
641   }
642
643 private:
644   SExprRef Fun;
645   SExprRef Arg;
646 };
647
648
649 // Apply a self-argument to a self-applicable function
650 class SApply : public SExpr {
651 public:
652   static bool classof(const SExpr *E) { return E->opcode() == COP_SApply; }
653
654   SApply(SExpr *Sf, SExpr *A = nullptr)
655       : SExpr(COP_SApply), Sfun(Sf), Arg(A)
656   {}
657   SApply(SApply &A, SExpr *Sf, SExpr *Ar = nullptr)  // rewrite constructor
658       : SExpr(A),  Sfun(Sf), Arg(Ar)
659   {}
660
661   SExpr *sfun() { return Sfun.get(); }
662   const SExpr *sfun() const { return Sfun.get(); }
663
664   SExpr *arg() { return Arg.get() ? Arg.get() : Sfun.get(); }
665   const SExpr *arg() const { return Arg.get() ? Arg.get() : Sfun.get(); }
666
667   bool isDelegation() const { return Arg == nullptr; }
668
669   template <class V> typename V::R_SExpr traverse(V &Visitor) {
670     typename V::R_SExpr Nf = Visitor.traverse(Sfun);
671     typename V::R_SExpr Na = Arg.get() ? Visitor.traverse(Arg) : nullptr;
672     return Visitor.reduceSApply(*this, Nf, Na);
673   }
674
675   template <class C> typename C::CType compare(SApply* E, C& Cmp) {
676     typename C::CType Ct = Cmp.compare(sfun(), E->sfun());
677     if (Cmp.notTrue(Ct) || (!arg() && !E->arg()))
678       return Ct;
679     return Cmp.compare(arg(), E->arg());
680   }
681
682 private:
683   SExprRef Sfun;
684   SExprRef Arg;
685 };
686
687
688 // Project a named slot from a C++ struct or class.
689 class Project : public SExpr {
690 public:
691   static bool classof(const SExpr *E) { return E->opcode() == COP_Project; }
692
693   Project(SExpr *R, clang::ValueDecl *Cvd)
694       : SExpr(COP_Project), Rec(R), Cvdecl(Cvd) {}
695   Project(const Project &P, SExpr *R) : SExpr(P), Rec(R), Cvdecl(P.Cvdecl) {}
696
697   SExpr *record() { return Rec.get(); }
698   const SExpr *record() const { return Rec.get(); }
699
700   const clang::ValueDecl *clangValueDecl() const { return Cvdecl; }
701
702   StringRef slotName() const { return Cvdecl->getName(); }
703
704   template <class V> typename V::R_SExpr traverse(V &Visitor) {
705     typename V::R_SExpr Nr = Visitor.traverse(Rec);
706     return Visitor.reduceProject(*this, Nr);
707   }
708
709   template <class C> typename C::CType compare(Project* E, C& Cmp) {
710     typename C::CType Ct = Cmp.compare(record(), E->record());
711     if (Cmp.notTrue(Ct))
712       return Ct;
713     return Cmp.comparePointers(Cvdecl, E->Cvdecl);
714   }
715
716 private:
717   SExprRef Rec;
718   clang::ValueDecl *Cvdecl;
719 };
720
721
722 // Call a function (after all arguments have been applied).
723 class Call : public SExpr {
724 public:
725   static bool classof(const SExpr *E) { return E->opcode() == COP_Call; }
726
727   Call(SExpr *T, const clang::CallExpr *Ce = nullptr)
728       : SExpr(COP_Call), Target(T), Cexpr(Ce) {}
729   Call(const Call &C, SExpr *T) : SExpr(C), Target(T), Cexpr(C.Cexpr) {}
730
731   SExpr *target() { return Target.get(); }
732   const SExpr *target() const { return Target.get(); }
733
734   const clang::CallExpr *clangCallExpr() { return Cexpr; }
735
736   template <class V> typename V::R_SExpr traverse(V &Visitor) {
737     typename V::R_SExpr Nt = Visitor.traverse(Target);
738     return Visitor.reduceCall(*this, Nt);
739   }
740
741   template <class C> typename C::CType compare(Call* E, C& Cmp) {
742     return Cmp.compare(target(), E->target());
743   }
744
745 private:
746   SExprRef Target;
747   const clang::CallExpr *Cexpr;
748 };
749
750
751 // Allocate memory for a new value on the heap or stack.
752 class Alloc : public SExpr {
753 public:
754   static bool classof(const SExpr *E) { return E->opcode() == COP_Call; }
755
756   enum AllocKind {
757     AK_Stack,
758     AK_Heap
759   };
760
761   Alloc(SExpr* D, AllocKind K) : SExpr(COP_Alloc), Dtype(D) {
762     Flags = K;
763   }
764   Alloc(const Alloc &A, SExpr* Dt) : SExpr(A), Dtype(Dt) {
765     Flags = A.kind();
766   }
767
768   AllocKind kind() const { return static_cast<AllocKind>(Flags); }
769
770   SExpr* dataType() { return Dtype.get(); }
771   const SExpr* dataType() const { return Dtype.get(); }
772
773   template <class V> typename V::R_SExpr traverse(V &Visitor) {
774     typename V::R_SExpr Nd = Visitor.traverse(Dtype);
775     return Visitor.reduceAlloc(*this, Nd);
776   }
777
778   template <class C> typename C::CType compare(Alloc* E, C& Cmp) {
779     typename C::CType Ct = Cmp.compareIntegers(kind(), E->kind());
780     if (Cmp.notTrue(Ct))
781       return Ct;
782     return Cmp.compare(dataType(), E->dataType());
783   }
784
785 private:
786   SExprRef Dtype;
787 };
788
789
790 // Load a value from memory.
791 class Load : public SExpr {
792 public:
793   static bool classof(const SExpr *E) { return E->opcode() == COP_Load; }
794
795   Load(SExpr *P) : SExpr(COP_Load), Ptr(P) {}
796   Load(const Load &L, SExpr *P) : SExpr(L), Ptr(P) {}
797
798   SExpr *pointer() { return Ptr.get(); }
799   const SExpr *pointer() const { return Ptr.get(); }
800
801   template <class V> typename V::R_SExpr traverse(V &Visitor) {
802     typename V::R_SExpr Np = Visitor.traverse(Ptr);
803     return Visitor.reduceLoad(*this, Np);
804   }
805
806   template <class C> typename C::CType compare(Load* E, C& Cmp) {
807     return Cmp.compare(pointer(), E->pointer());
808   }
809
810 private:
811   SExprRef Ptr;
812 };
813
814
815 // Store a value to memory.
816 class Store : public SExpr {
817 public:
818   static bool classof(const SExpr *E) { return E->opcode() == COP_Store; }
819
820   Store(SExpr *P, SExpr *V) : SExpr(COP_Store), Dest(P), Source(V) {}
821   Store(const Store &S, SExpr *P, SExpr *V) : SExpr(S), Dest(P), Source(V) {}
822
823   SExpr *destination() { return Dest.get(); }  // Address to store to
824   const SExpr *destination() const { return Dest.get(); }
825
826   SExpr *source() { return Source.get(); }     // Value to store
827   const SExpr *source() const { return Source.get(); }
828
829   template <class V> typename V::R_SExpr traverse(V &Visitor) {
830     typename V::R_SExpr Np = Visitor.traverse(Dest);
831     typename V::R_SExpr Nv = Visitor.traverse(Source);
832     return Visitor.reduceStore(*this, Np, Nv);
833   }
834
835   template <class C> typename C::CType compare(Store* E, C& Cmp) {
836     typename C::CType Ct = Cmp.compare(destination(), E->destination());
837     if (Cmp.notTrue(Ct))
838       return Ct;
839     return Cmp.compare(source(), E->source());
840   }
841
842   SExprRef Dest;
843   SExprRef Source;
844 };
845
846
847 // Simple unary operation -- e.g. !, ~, etc.
848 class UnaryOp : public SExpr {
849 public:
850   static bool classof(const SExpr *E) { return E->opcode() == COP_UnaryOp; }
851
852   UnaryOp(TIL_UnaryOpcode Op, SExpr *E) : SExpr(COP_UnaryOp), Expr0(E) {
853     Flags = Op;
854   }
855   UnaryOp(const UnaryOp &U, SExpr *E) : SExpr(U) { Flags = U.Flags; }
856
857   TIL_UnaryOpcode unaryOpcode() { return static_cast<TIL_UnaryOpcode>(Flags); }
858
859   SExpr *expr() { return Expr0.get(); }
860   const SExpr *expr() const { return Expr0.get(); }
861
862   template <class V> typename V::R_SExpr traverse(V &Visitor) {
863     typename V::R_SExpr Ne = Visitor.traverse(Expr0);
864     return Visitor.reduceUnaryOp(*this, Ne);
865   }
866
867   template <class C> typename C::CType compare(UnaryOp* E, C& Cmp) {
868     typename C::CType Ct =
869       Cmp.compareIntegers(unaryOpcode(), E->unaryOpcode());
870     if (Cmp.notTrue(Ct))
871       return Ct;
872     return Cmp.compare(expr(), E->expr());
873   }
874
875 private:
876   SExprRef Expr0;
877 };
878
879
880 // Simple binary operation -- e.g. +, -, etc.
881 class BinaryOp : public SExpr {
882 public:
883   static bool classof(const SExpr *E) { return E->opcode() == COP_BinaryOp; }
884
885   BinaryOp(TIL_BinaryOpcode Op, SExpr *E0, SExpr *E1)
886       : SExpr(COP_BinaryOp), Expr0(E0), Expr1(E1) {
887     Flags = Op;
888   }
889   BinaryOp(const BinaryOp &B, SExpr *E0, SExpr *E1)
890       : SExpr(B), Expr0(E0), Expr1(E1) {
891     Flags = B.Flags;
892   }
893
894   TIL_BinaryOpcode binaryOpcode() {
895     return static_cast<TIL_BinaryOpcode>(Flags);
896   }
897
898   SExpr *expr0() { return Expr0.get(); }
899   const SExpr *expr0() const { return Expr0.get(); }
900
901   SExpr *expr1() { return Expr1.get(); }
902   const SExpr *expr1() const { return Expr1.get(); }
903
904   template <class V> typename V::R_SExpr traverse(V &Visitor) {
905     typename V::R_SExpr Ne0 = Visitor.traverse(Expr0);
906     typename V::R_SExpr Ne1 = Visitor.traverse(Expr1);
907     return Visitor.reduceBinaryOp(*this, Ne0, Ne1);
908   }
909
910   template <class C> typename C::CType compare(BinaryOp* E, C& Cmp) {
911     typename C::CType Ct =
912       Cmp.compareIntegers(binaryOpcode(), E->binaryOpcode());
913     if (Cmp.notTrue(Ct))
914       return Ct;
915     Ct = Cmp.compare(expr0(), E->expr0());
916     if (Cmp.notTrue(Ct))
917       return Ct;
918     return Cmp.compare(expr1(), E->expr1());
919   }
920
921 private:
922   SExprRef Expr0;
923   SExprRef Expr1;
924 };
925
926
927 // Cast expression
928 class Cast : public SExpr {
929 public:
930   static bool classof(const SExpr *E) { return E->opcode() == COP_Cast; }
931
932   Cast(TIL_CastOpcode Op, SExpr *E) : SExpr(COP_Cast), Expr0(E) { Flags = Op; }
933   Cast(const Cast &C, SExpr *E) : SExpr(C), Expr0(E) { Flags = C.Flags; }
934
935   TIL_BinaryOpcode castOpcode() {
936     return static_cast<TIL_BinaryOpcode>(Flags);
937   }
938
939   SExpr *expr() { return Expr0.get(); }
940   const SExpr *expr() const { return Expr0.get(); }
941
942   template <class V> typename V::R_SExpr traverse(V &Visitor) {
943     typename V::R_SExpr Ne = Visitor.traverse(Expr0);
944     return Visitor.reduceCast(*this, Ne);
945   }
946
947   template <class C> typename C::CType compare(Cast* E, C& Cmp) {
948     typename C::CType Ct =
949       Cmp.compareIntegers(castOpcode(), E->castOpcode());
950     if (Cmp.notTrue(Ct))
951       return Ct;
952     return Cmp.compare(expr(), E->expr());
953   }
954
955 private:
956   SExprRef Expr0;
957 };
958
959
960
961
962 class BasicBlock;
963
964
965 // An SCFG is a control-flow graph.  It consists of a set of basic blocks, each
966 // of which terminates in a branch to another basic block.  There is one
967 // entry point, and one exit point.
968 class SCFG : public SExpr {
969 public:
970   typedef SimpleArray<BasicBlock*> BlockArray;
971
972   static bool classof(const SExpr *E) { return E->opcode() == COP_SCFG; }
973
974   SCFG(MemRegionRef A, unsigned Nblocks)
975       : SExpr(COP_SCFG), Blocks(A, Nblocks), Entry(nullptr), Exit(nullptr) {}
976   SCFG(const SCFG &Cfg, BlockArray &&Ba) // steals memory from Ba
977       : SExpr(COP_SCFG),
978         Blocks(std::move(Ba)),
979         Entry(nullptr),
980         Exit(nullptr) {
981     // TODO: set entry and exit!
982   }
983
984   typedef BlockArray::iterator iterator;
985   typedef BlockArray::const_iterator const_iterator;
986
987   iterator begin() { return Blocks.begin(); }
988   iterator end() { return Blocks.end(); }
989
990   const_iterator cbegin() const { return Blocks.cbegin(); }
991   const_iterator cend() const { return Blocks.cend(); }
992
993   BasicBlock *entry() const { return Entry; }
994   BasicBlock *exit() const { return Exit; }
995
996   void add(BasicBlock *BB) { Blocks.push_back(BB); }
997   void setEntry(BasicBlock *BB) { Entry = BB; }
998   void setExit(BasicBlock *BB) { Exit = BB; }
999
1000   template <class V> typename V::R_SExpr traverse(V &Visitor);
1001
1002   template <class C> typename C::CType compare(SCFG* E, C& Cmp) {
1003     // TODO -- implement CFG comparisons
1004     return Cmp.comparePointers(this, E);
1005   }
1006
1007 private:
1008   BlockArray Blocks;
1009   BasicBlock *Entry;
1010   BasicBlock *Exit;
1011 };
1012
1013
1014 // A basic block is part of an SCFG, and can be treated as a function in
1015 // continuation passing style.  It consists of a sequence of phi nodes, which
1016 // are "arguments" to the function, followed by a sequence of instructions.
1017 // Both arguments and instructions define new variables.  It ends with a
1018 // branch or goto to another basic block in the same SCFG.
1019 class BasicBlock {
1020 public:
1021   typedef SimpleArray<Variable*> VarArray;
1022
1023   BasicBlock(MemRegionRef A, unsigned Nargs, unsigned Nins,
1024              SExpr *Term = nullptr)
1025       : BlockID(0), Parent(nullptr), Args(A, Nargs), Instrs(A, Nins),
1026         Terminator(Term) {}
1027   BasicBlock(const BasicBlock &B, VarArray &&As, VarArray &&Is, SExpr *T)
1028       : BlockID(0), Parent(nullptr),
1029         Args(std::move(As)), Instrs(std::move(Is)), Terminator(T)
1030   {}
1031
1032   unsigned blockID() const { return BlockID; }
1033   BasicBlock *parent() const { return Parent; }
1034
1035   const VarArray &arguments() const { return Args; }
1036   VarArray &arguments() { return Args; }
1037
1038   const VarArray &instructions() const { return Instrs; }
1039   VarArray &instructions() { return Instrs; }
1040
1041   const SExpr *terminator() const { return Terminator.get(); }
1042   SExpr *terminator() { return Terminator.get(); }
1043
1044   void setParent(BasicBlock *P) { Parent = P; }
1045   void setBlockID(unsigned i) { BlockID = i; }
1046   void setTerminator(SExpr *E) { Terminator.reset(E); }
1047   void addArgument(Variable *V) { Args.push_back(V); }
1048   void addInstr(Variable *V) { Args.push_back(V); }
1049
1050   template <class V> BasicBlock *traverse(V &Visitor) {
1051     typename V::template Container<Variable*> Nas(Visitor, Args.size());
1052     typename V::template Container<Variable*> Nis(Visitor, Instrs.size());
1053
1054     for (auto A : Args) {
1055       typename V::R_SExpr Ne = Visitor.traverse(A->Definition);
1056       Variable *Nvd = Visitor.enterScope(*A, Ne);
1057       Nas.push_back(Nvd);
1058     }
1059     for (auto I : Instrs) {
1060       typename V::R_SExpr Ne = Visitor.traverse(I->Definition);
1061       Variable *Nvd = Visitor.enterScope(*I, Ne);
1062       Nis.push_back(Nvd);
1063     }
1064     typename V::R_SExpr Nt = Visitor.traverse(Terminator);
1065
1066     // TODO: use reverse iterator
1067     for (unsigned J = 0, JN = Instrs.size(); J < JN; ++J)
1068       Visitor.exitScope(*Instrs[JN-J]);
1069     for (unsigned I = 0, IN = Instrs.size(); I < IN; ++I)
1070       Visitor.exitScope(*Args[IN-I]);
1071
1072     return Visitor.reduceBasicBlock(*this, Nas, Nis, Nt);
1073   }
1074
1075   template <class C> typename C::CType compare(BasicBlock* E, C& Cmp) {
1076     // TODO: implement CFG comparisons
1077     return Cmp.comparePointers(this, E);
1078   }
1079
1080 private:
1081   friend class SCFG;
1082
1083   unsigned BlockID;
1084   BasicBlock *Parent;   // The parent block is the enclosing lexical scope.
1085                         // The parent dominates this block.
1086   VarArray Args;        // Phi nodes
1087   VarArray Instrs;
1088   SExprRef Terminator;
1089 };
1090
1091
1092 template <class V>
1093 typename V::R_SExpr SCFG::traverse(V &Visitor) {
1094   Visitor.enterCFG(*this);
1095   typename V::template Container<BasicBlock *> Bbs(Visitor, Blocks.size());
1096   for (auto B : Blocks) {
1097     BasicBlock *Nbb = B->traverse(Visitor);
1098     Bbs.push_back(Nbb);
1099   }
1100   Visitor.exitCFG(*this);
1101   return Visitor.reduceSCFG(*this, Bbs);
1102 }
1103
1104
1105
1106 class Phi : public SExpr {
1107 public:
1108   // TODO: change to SExprRef
1109   typedef SimpleArray<SExpr*> ValArray;
1110
1111   static bool classof(const SExpr *E) { return E->opcode() == COP_Phi; }
1112
1113   Phi(MemRegionRef A, unsigned Nvals)
1114       : SExpr(COP_Phi), Values(A, Nvals)
1115   {}
1116   Phi(const Phi &P, ValArray &&Vs)  // steals memory of Vs
1117       : SExpr(COP_Phi), Values(std::move(Vs))
1118   {}
1119
1120   const ValArray &values() const { return Values; }
1121   ValArray &values() { return Values; }
1122
1123   template <class V> typename V::R_SExpr traverse(V &Visitor) {
1124     typename V::template Container<typename V::R_SExpr> Nvs(Visitor,
1125                                                             Values.size());
1126     for (auto Val : Values) {
1127       typename V::R_SExpr Nv = Visitor.traverse(Val);
1128       Nvs.push_back(Nv);
1129     }
1130     return Visitor.reducePhi(*this, Nvs);
1131   }
1132
1133   template <class C> typename C::CType compare(Phi* E, C& Cmp) {
1134     // TODO -- implement CFG comparisons
1135     return Cmp.comparePointers(this, E);
1136   }
1137
1138 private:
1139   ValArray Values;
1140 };
1141
1142
1143 class Goto : public SExpr {
1144 public:
1145   static bool classof(const SExpr *E) { return E->opcode() == COP_Goto; }
1146
1147   Goto(BasicBlock *B, unsigned Index)
1148       : SExpr(COP_Goto), TargetBlock(B), Index(0) {}
1149   Goto(const Goto &G, BasicBlock *B, unsigned I)
1150       : SExpr(COP_Goto), TargetBlock(B), Index(I) {}
1151
1152   BasicBlock *targetBlock() const { return TargetBlock; }
1153   unsigned index() const { return Index; }
1154
1155   template <class V> typename V::R_SExpr traverse(V &Visitor) {
1156     // TODO -- rewrite indices properly
1157     BasicBlock *Ntb = Visitor.reduceBasicBlockRef(TargetBlock);
1158     return Visitor.reduceGoto(*this, Ntb, Index);
1159   }
1160
1161   template <class C> typename C::CType compare(Goto* E, C& Cmp) {
1162     // TODO -- implement CFG comparisons
1163     return Cmp.comparePointers(this, E);
1164   }
1165
1166 private:
1167   BasicBlock *TargetBlock;
1168   unsigned Index;   // Index into Phi nodes of target block.
1169 };
1170
1171
1172 class Branch : public SExpr {
1173 public:
1174   static bool classof(const SExpr *E) { return E->opcode() == COP_Branch; }
1175
1176   Branch(SExpr *C, BasicBlock *T, BasicBlock *E)
1177       : SExpr(COP_Branch), Condition(C), ThenBlock(T), ElseBlock(E) {}
1178   Branch(const Branch &Br, SExpr *C, BasicBlock *T, BasicBlock *E)
1179       : SExpr(COP_Branch), Condition(C), ThenBlock(T), ElseBlock(E) {}
1180
1181   SExpr *condition() { return Condition; }
1182   BasicBlock *thenBlock() { return ThenBlock; }
1183   BasicBlock *elseBlock() { return ElseBlock; }
1184
1185   template <class V> typename V::R_SExpr traverse(V &Visitor) {
1186     typename V::R_SExpr Nc = Visitor.traverse(Condition);
1187     BasicBlock *Ntb = Visitor.reduceBasicBlockRef(ThenBlock);
1188     BasicBlock *Nte = Visitor.reduceBasicBlockRef(ElseBlock);
1189     return Visitor.reduceBranch(*this, Nc, Ntb, Nte);
1190   }
1191
1192   template <class C> typename C::CType compare(Branch* E, C& Cmp) {
1193     // TODO -- implement CFG comparisons
1194     return Cmp.comparePointers(this, E);
1195   }
1196
1197 private:
1198   SExpr *Condition;
1199   BasicBlock *ThenBlock;
1200   BasicBlock *ElseBlock;
1201 };
1202
1203
1204 } // end namespace til
1205 } // end namespace threadSafety
1206 } // end namespace clang
1207
1208 #endif // LLVM_CLANG_THREAD_SAFETY_TIL_H