1 //=-- ExprEngine.cpp - Path-Sensitive Expression-Level Dataflow ---*- 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 meta-engine for path-sensitive dataflow analysis that
11 //  is built on GREngine, but provides the boilerplate to execute transfer
12 //  functions and build the ExplodedGraph at the expression level.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
17 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
18 #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
19 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
20 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngineBuilders.h"
21 #include "clang/AST/CharUnits.h"
22 #include "clang/AST/ParentMap.h"
23 #include "clang/AST/StmtObjC.h"
24 #include "clang/AST/DeclCXX.h"
25 #include "clang/Basic/Builtins.h"
26 #include "clang/Basic/SourceManager.h"
27 #include "clang/Basic/SourceManager.h"
28 #include "clang/Basic/PrettyStackTrace.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include "llvm/ADT/ImmutableList.h"
31 
32 #ifndef NDEBUG
33 #include "llvm/Support/GraphWriter.h"
34 #endif
35 
36 using namespace clang;
37 using namespace ento;
38 using llvm::dyn_cast;
39 using llvm::dyn_cast_or_null;
40 using llvm::cast;
41 using llvm::APSInt;
42 
43 namespace {
44   // Trait class for recording returned expression in the state.
45   struct ReturnExpr {
46     static int TagInt;
47     typedef const Stmt *data_type;
48   };
49   int ReturnExpr::TagInt;
50 }
51 
52 //===----------------------------------------------------------------------===//
53 // Utility functions.
54 //===----------------------------------------------------------------------===//
55 
56 static inline Selector GetNullarySelector(const char* name, ASTContext& Ctx) {
57   IdentifierInfo* II = &Ctx.Idents.get(name);
58   return Ctx.Selectors.getSelector(0, &II);
59 }
60 
61 //===----------------------------------------------------------------------===//
62 // Engine construction and deletion.
63 //===----------------------------------------------------------------------===//
64 
65 ExprEngine::ExprEngine(AnalysisManager &mgr, TransferFuncs *tf)
66   : AMgr(mgr),
67     Engine(*this),
68     G(Engine.getGraph()),
69     Builder(NULL),
70     StateMgr(getContext(), mgr.getStoreManagerCreator(),
71              mgr.getConstraintManagerCreator(), G.getAllocator(),
72              *this),
73     SymMgr(StateMgr.getSymbolManager()),
74     svalBuilder(StateMgr.getSValBuilder()),
75     EntryNode(NULL), currentStmt(NULL),
76     NSExceptionII(NULL), NSExceptionInstanceRaiseSelectors(NULL),
77     RaiseSel(GetNullarySelector("raise", getContext())),
78     BR(mgr, *this), TF(tf) {
79 
80   // FIXME: Eventually remove the TF object entirely.
81   TF->RegisterChecks(*this);
82   TF->RegisterPrinters(getStateManager().Printers);
83 
84   if (mgr.shouldEagerlyTrimExplodedGraph()) {
85     // Enable eager node reclaimation when constructing the ExplodedGraph.
86     G.enableNodeReclamation();
87   }
88 }
89 
90 ExprEngine::~ExprEngine() {
91   BR.FlushReports();
92   delete [] NSExceptionInstanceRaiseSelectors;
93 }
94 
95 //===----------------------------------------------------------------------===//
96 // Utility methods.
97 //===----------------------------------------------------------------------===//
98 
99 const GRState* ExprEngine::getInitialState(const LocationContext *InitLoc) {
100   const GRState *state = StateMgr.getInitialState(InitLoc);
101 
102   // Preconditions.
103 
104   // FIXME: It would be nice if we had a more general mechanism to add
105   // such preconditions.  Some day.
106   do {
107     const Decl *D = InitLoc->getDecl();
108     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
109       // Precondition: the first argument of 'main' is an integer guaranteed
110       //  to be > 0.
111       const IdentifierInfo *II = FD->getIdentifier();
112       if (!II || !(II->getName() == "main" && FD->getNumParams() > 0))
113         break;
114 
115       const ParmVarDecl *PD = FD->getParamDecl(0);
116       QualType T = PD->getType();
117       if (!T->isIntegerType())
118         break;
119 
120       const MemRegion *R = state->getRegion(PD, InitLoc);
121       if (!R)
122         break;
123 
124       SVal V = state->getSVal(loc::MemRegionVal(R));
125       SVal Constraint_untested = evalBinOp(state, BO_GT, V,
126                                            svalBuilder.makeZeroVal(T),
127                                            getContext().IntTy);
128 
129       DefinedOrUnknownSVal *Constraint =
130         dyn_cast<DefinedOrUnknownSVal>(&Constraint_untested);
131 
132       if (!Constraint)
133         break;
134 
135       if (const GRState *newState = state->assume(*Constraint, true))
136         state = newState;
137 
138       break;
139     }
140 
141     if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
142       // Precondition: 'self' is always non-null upon entry to an Objective-C
143       // method.
144       const ImplicitParamDecl *SelfD = MD->getSelfDecl();
145       const MemRegion *R = state->getRegion(SelfD, InitLoc);
146       SVal V = state->getSVal(loc::MemRegionVal(R));
147 
148       if (const Loc *LV = dyn_cast<Loc>(&V)) {
149         // Assume that the pointer value in 'self' is non-null.
150         state = state->assume(*LV, true);
151         assert(state && "'self' cannot be null");
152       }
153     }
154   } while (0);
155 
156   return state;
157 }
158 
159 //===----------------------------------------------------------------------===//
160 // Top-level transfer function logic (Dispatcher).
161 //===----------------------------------------------------------------------===//
162 
163 /// evalAssume - Called by ConstraintManager. Used to call checker-specific
164 ///  logic for handling assumptions on symbolic values.
165 const GRState *ExprEngine::processAssume(const GRState *state, SVal cond,
166                                            bool assumption) {
167   state = getCheckerManager().runCheckersForEvalAssume(state, cond, assumption);
168 
169   // If the state is infeasible at this point, bail out.
170   if (!state)
171     return NULL;
172 
173   return TF->evalAssume(state, cond, assumption);
174 }
175 
176 bool ExprEngine::wantsRegionChangeUpdate(const GRState* state) {
177   return getCheckerManager().wantsRegionChangeUpdate(state);
178 }
179 
180 const GRState *
181 ExprEngine::processRegionChanges(const GRState *state,
182                                    const MemRegion * const *Begin,
183                                    const MemRegion * const *End) {
184   return getCheckerManager().runCheckersForRegionChanges(state, Begin, End);
185 }
186 
187 void ExprEngine::processEndWorklist(bool hasWorkRemaining) {
188   getCheckerManager().runCheckersForEndAnalysis(G, BR, *this);
189 }
190 
191 void ExprEngine::processCFGElement(const CFGElement E,
192                                   StmtNodeBuilder& builder) {
193   switch (E.getKind()) {
194     case CFGElement::Invalid:
195       llvm_unreachable("Unexpected CFGElement kind.");
196     case CFGElement::Statement:
197       ProcessStmt(E.getAs<CFGStmt>()->getStmt(), builder);
198       return;
199     case CFGElement::Initializer:
200       ProcessInitializer(E.getAs<CFGInitializer>()->getInitializer(), builder);
201       return;
202     case CFGElement::AutomaticObjectDtor:
203     case CFGElement::BaseDtor:
204     case CFGElement::MemberDtor:
205     case CFGElement::TemporaryDtor:
206       ProcessImplicitDtor(*E.getAs<CFGImplicitDtor>(), builder);
207       return;
208   }
209 }
210 
211 void ExprEngine::ProcessStmt(const CFGStmt S, StmtNodeBuilder& builder) {
212   // Reclaim any unnecessary nodes in the ExplodedGraph.
213   G.reclaimRecentlyAllocatedNodes();
214   // Recycle any unused states in the GRStateManager.
215   StateMgr.recycleUnusedStates();
216 
217   currentStmt = S.getStmt();
218   PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
219                                 currentStmt->getLocStart(),
220                                 "Error evaluating statement");
221 
222   Builder = &builder;
223   EntryNode = builder.getPredecessor();
224 
225   // Create the cleaned state.
226   const LocationContext *LC = EntryNode->getLocationContext();
227   SymbolReaper SymReaper(LC, currentStmt, SymMgr);
228 
229   if (AMgr.shouldPurgeDead()) {
230     const GRState *St = EntryNode->getState();
231     getCheckerManager().runCheckersForLiveSymbols(St, SymReaper);
232 
233     const StackFrameContext *SFC = LC->getCurrentStackFrame();
234     CleanedState = StateMgr.removeDeadBindings(St, SFC, SymReaper);
235   } else {
236     CleanedState = EntryNode->getState();
237   }
238 
239   // Process any special transfer function for dead symbols.
240   ExplodedNodeSet Tmp;
241 
242   if (!SymReaper.hasDeadSymbols())
243     Tmp.Add(EntryNode);
244   else {
245     SaveAndRestore<bool> OldSink(Builder->BuildSinks);
246     SaveOr OldHasGen(Builder->hasGeneratedNode);
247 
248     SaveAndRestore<bool> OldPurgeDeadSymbols(Builder->PurgingDeadSymbols);
249     Builder->PurgingDeadSymbols = true;
250 
251     // FIXME: This should soon be removed.
252     ExplodedNodeSet Tmp2;
253     getTF().evalDeadSymbols(Tmp2, *this, *Builder, EntryNode,
254                             CleanedState, SymReaper);
255 
256     getCheckerManager().runCheckersForDeadSymbols(Tmp, Tmp2,
257                                                  SymReaper, currentStmt, *this);
258 
259     if (!Builder->BuildSinks && !Builder->hasGeneratedNode)
260       Tmp.Add(EntryNode);
261   }
262 
263   bool HasAutoGenerated = false;
264 
265   for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end(); I!=E; ++I) {
266     ExplodedNodeSet Dst;
267 
268     // Set the cleaned state.
269     Builder->SetCleanedState(*I == EntryNode ? CleanedState : GetState(*I));
270 
271     // Visit the statement.
272     Visit(currentStmt, *I, Dst);
273 
274     // Do we need to auto-generate a node?  We only need to do this to generate
275     // a node with a "cleaned" state; CoreEngine will actually handle
276     // auto-transitions for other cases.
277     if (Dst.size() == 1 && *Dst.begin() == EntryNode
278         && !Builder->hasGeneratedNode && !HasAutoGenerated) {
279       HasAutoGenerated = true;
280       builder.generateNode(currentStmt, GetState(EntryNode), *I);
281     }
282   }
283 
284   // NULL out these variables to cleanup.
285   CleanedState = NULL;
286   EntryNode = NULL;
287 
288   currentStmt = 0;
289 
290   Builder = NULL;
291 }
292 
293 void ExprEngine::ProcessInitializer(const CFGInitializer Init,
294                                     StmtNodeBuilder &builder) {
295   // We don't set EntryNode and currentStmt. And we don't clean up state.
296   const CXXCtorInitializer *BMI = Init.getInitializer();
297 
298   ExplodedNode *pred = builder.getPredecessor();
299 
300   const StackFrameContext *stackFrame = cast<StackFrameContext>(pred->getLocationContext());
301   const CXXConstructorDecl *decl = cast<CXXConstructorDecl>(stackFrame->getDecl());
302   const CXXThisRegion *thisReg = getCXXThisRegion(decl, stackFrame);
303 
304   SVal thisVal = pred->getState()->getSVal(thisReg);
305 
306   if (BMI->isAnyMemberInitializer()) {
307     ExplodedNodeSet Dst;
308 
309     // Evaluate the initializer.
310     Visit(BMI->getInit(), pred, Dst);
311 
312     for (ExplodedNodeSet::iterator I = Dst.begin(), E = Dst.end(); I != E; ++I){
313       ExplodedNode *Pred = *I;
314       const GRState *state = Pred->getState();
315 
316       const FieldDecl *FD = BMI->getAnyMember();
317 
318       SVal FieldLoc = state->getLValue(FD, thisVal);
319       SVal InitVal = state->getSVal(BMI->getInit());
320       state = state->bindLoc(FieldLoc, InitVal);
321 
322       // Use a custom node building process.
323       PostInitializer PP(BMI, stackFrame);
324       // Builder automatically add the generated node to the deferred set,
325       // which are processed in the builder's dtor.
326       builder.generateNode(PP, state, Pred);
327     }
328     return;
329   }
330 
331   assert(BMI->isBaseInitializer());
332 
333   // Get the base class declaration.
334   const CXXConstructExpr *ctorExpr = cast<CXXConstructExpr>(BMI->getInit());
335 
336   // Create the base object region.
337   SVal baseVal =
338     getStoreManager().evalDerivedToBase(thisVal, ctorExpr->getType());
339   const MemRegion *baseReg = baseVal.getAsRegion();
340   assert(baseReg);
341   Builder = &builder;
342   ExplodedNodeSet dst;
343   VisitCXXConstructExpr(ctorExpr, baseReg, pred, dst);
344 }
345 
346 void ExprEngine::ProcessImplicitDtor(const CFGImplicitDtor D,
347                                        StmtNodeBuilder &builder) {
348   Builder = &builder;
349 
350   switch (D.getKind()) {
351   case CFGElement::AutomaticObjectDtor:
352     ProcessAutomaticObjDtor(cast<CFGAutomaticObjDtor>(D), builder);
353     break;
354   case CFGElement::BaseDtor:
355     ProcessBaseDtor(cast<CFGBaseDtor>(D), builder);
356     break;
357   case CFGElement::MemberDtor:
358     ProcessMemberDtor(cast<CFGMemberDtor>(D), builder);
359     break;
360   case CFGElement::TemporaryDtor:
361     ProcessTemporaryDtor(cast<CFGTemporaryDtor>(D), builder);
362     break;
363   default:
364     llvm_unreachable("Unexpected dtor kind.");
365   }
366 }
367 
368 void ExprEngine::ProcessAutomaticObjDtor(const CFGAutomaticObjDtor dtor,
369                                            StmtNodeBuilder &builder) {
370   ExplodedNode *pred = builder.getPredecessor();
371   const GRState *state = pred->getState();
372   const VarDecl *varDecl = dtor.getVarDecl();
373 
374   QualType varType = varDecl->getType();
375 
376   if (const ReferenceType *refType = varType->getAs<ReferenceType>())
377     varType = refType->getPointeeType();
378 
379   const CXXRecordDecl *recordDecl = varType->getAsCXXRecordDecl();
380   assert(recordDecl && "get CXXRecordDecl fail");
381   const CXXDestructorDecl *dtorDecl = recordDecl->getDestructor();
382 
383   Loc dest = state->getLValue(varDecl, pred->getLocationContext());
384 
385   ExplodedNodeSet dstSet;
386   VisitCXXDestructor(dtorDecl, cast<loc::MemRegionVal>(dest).getRegion(),
387                      dtor.getTriggerStmt(), pred, dstSet);
388 }
389 
390 void ExprEngine::ProcessBaseDtor(const CFGBaseDtor D,
391                                    StmtNodeBuilder &builder) {
392 }
393 
394 void ExprEngine::ProcessMemberDtor(const CFGMemberDtor D,
395                                      StmtNodeBuilder &builder) {
396 }
397 
398 void ExprEngine::ProcessTemporaryDtor(const CFGTemporaryDtor D,
399                                         StmtNodeBuilder &builder) {
400 }
401 
402 void ExprEngine::Visit(const Stmt* S, ExplodedNode* Pred,
403                          ExplodedNodeSet& Dst) {
404   PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
405                                 S->getLocStart(),
406                                 "Error evaluating statement");
407 
408   // Expressions to ignore.
409   if (const Expr *Ex = dyn_cast<Expr>(S))
410     S = Ex->IgnoreParens();
411 
412   // FIXME: add metadata to the CFG so that we can disable
413   //  this check when we KNOW that there is no block-level subexpression.
414   //  The motivation is that this check requires a hashtable lookup.
415 
416   if (S != currentStmt && Pred->getLocationContext()->getCFG()->isBlkExpr(S)) {
417     Dst.Add(Pred);
418     return;
419   }
420 
421   switch (S->getStmtClass()) {
422     // C++ stuff we don't support yet.
423     case Stmt::CXXBindTemporaryExprClass:
424     case Stmt::CXXCatchStmtClass:
425     case Stmt::CXXDependentScopeMemberExprClass:
426     case Stmt::CXXForRangeStmtClass:
427     case Stmt::CXXNullPtrLiteralExprClass:
428     case Stmt::CXXPseudoDestructorExprClass:
429     case Stmt::CXXTemporaryObjectExprClass:
430     case Stmt::CXXThrowExprClass:
431     case Stmt::CXXTryStmtClass:
432     case Stmt::CXXTypeidExprClass:
433     case Stmt::CXXUuidofExprClass:
434     case Stmt::CXXUnresolvedConstructExprClass:
435     case Stmt::CXXScalarValueInitExprClass:
436     case Stmt::DependentScopeDeclRefExprClass:
437     case Stmt::UnaryTypeTraitExprClass:
438     case Stmt::BinaryTypeTraitExprClass:
439     case Stmt::UnresolvedLookupExprClass:
440     case Stmt::UnresolvedMemberExprClass:
441     case Stmt::CXXNoexceptExprClass:
442     case Stmt::PackExpansionExprClass:
443     case Stmt::SubstNonTypeTemplateParmPackExprClass:
444     {
445       SaveAndRestore<bool> OldSink(Builder->BuildSinks);
446       Builder->BuildSinks = true;
447       const ExplodedNode *node = MakeNode(Dst, S, Pred, GetState(Pred));
448       Engine.addAbortedBlock(node, Builder->getBlock());
449       break;
450     }
451 
452     // We don't handle default arguments either yet, but we can fake it
453     // for now by just skipping them.
454     case Stmt::CXXDefaultArgExprClass: {
455       Dst.Add(Pred);
456       break;
457     }
458 
459     case Stmt::ParenExprClass:
460       llvm_unreachable("ParenExprs already handled.");
461     case Stmt::GenericSelectionExprClass:
462       llvm_unreachable("GenericSelectionExprs already handled.");
463     // Cases that should never be evaluated simply because they shouldn't
464     // appear in the CFG.
465     case Stmt::BreakStmtClass:
466     case Stmt::CaseStmtClass:
467     case Stmt::CompoundStmtClass:
468     case Stmt::ContinueStmtClass:
469     case Stmt::DefaultStmtClass:
470     case Stmt::DoStmtClass:
471     case Stmt::ForStmtClass:
472     case Stmt::GotoStmtClass:
473     case Stmt::IfStmtClass:
474     case Stmt::IndirectGotoStmtClass:
475     case Stmt::LabelStmtClass:
476     case Stmt::NoStmtClass:
477     case Stmt::NullStmtClass:
478     case Stmt::SwitchStmtClass:
479     case Stmt::WhileStmtClass:
480       llvm_unreachable("Stmt should not be in analyzer evaluation loop");
481       break;
482 
483     case Stmt::GNUNullExprClass: {
484       MakeNode(Dst, S, Pred, GetState(Pred)->BindExpr(S, svalBuilder.makeNull()));
485       break;
486     }
487 
488     case Stmt::ObjCAtSynchronizedStmtClass:
489       VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S), Pred, Dst);
490       break;
491 
492     case Stmt::ObjCPropertyRefExprClass:
493       VisitObjCPropertyRefExpr(cast<ObjCPropertyRefExpr>(S), Pred, Dst);
494       break;
495 
496     // Cases not handled yet; but will handle some day.
497     case Stmt::DesignatedInitExprClass:
498     case Stmt::ExtVectorElementExprClass:
499     case Stmt::ImaginaryLiteralClass:
500     case Stmt::ImplicitValueInitExprClass:
501     case Stmt::ObjCAtCatchStmtClass:
502     case Stmt::ObjCAtFinallyStmtClass:
503     case Stmt::ObjCAtTryStmtClass:
504     case Stmt::ObjCEncodeExprClass:
505     case Stmt::ObjCIsaExprClass:
506     case Stmt::ObjCProtocolExprClass:
507     case Stmt::ObjCSelectorExprClass:
508     case Stmt::ObjCStringLiteralClass:
509     case Stmt::ParenListExprClass:
510     case Stmt::PredefinedExprClass:
511     case Stmt::ShuffleVectorExprClass:
512     case Stmt::VAArgExprClass:
513     case Stmt::CUDAKernelCallExprClass:
514     case Stmt::OpaqueValueExprClass:
515         // Fall through.
516 
517     // Cases we intentionally don't evaluate, since they don't need
518     // to be explicitly evaluated.
519     case Stmt::AddrLabelExprClass:
520     case Stmt::IntegerLiteralClass:
521     case Stmt::CharacterLiteralClass:
522     case Stmt::CXXBoolLiteralExprClass:
523     case Stmt::ExprWithCleanupsClass:
524     case Stmt::FloatingLiteralClass:
525     case Stmt::SizeOfPackExprClass:
526       Dst.Add(Pred); // No-op. Simply propagate the current state unchanged.
527       break;
528 
529     case Stmt::ArraySubscriptExprClass:
530       VisitLvalArraySubscriptExpr(cast<ArraySubscriptExpr>(S), Pred, Dst);
531       break;
532 
533     case Stmt::AsmStmtClass:
534       VisitAsmStmt(cast<AsmStmt>(S), Pred, Dst);
535       break;
536 
537     case Stmt::BlockDeclRefExprClass: {
538       const BlockDeclRefExpr *BE = cast<BlockDeclRefExpr>(S);
539       VisitCommonDeclRefExpr(BE, BE->getDecl(), Pred, Dst);
540       break;
541     }
542 
543     case Stmt::BlockExprClass:
544       VisitBlockExpr(cast<BlockExpr>(S), Pred, Dst);
545       break;
546 
547     case Stmt::BinaryOperatorClass: {
548       const BinaryOperator* B = cast<BinaryOperator>(S);
549       if (B->isLogicalOp()) {
550         VisitLogicalExpr(B, Pred, Dst);
551         break;
552       }
553       else if (B->getOpcode() == BO_Comma) {
554         const GRState* state = GetState(Pred);
555         MakeNode(Dst, B, Pred, state->BindExpr(B, state->getSVal(B->getRHS())));
556         break;
557       }
558 
559       if (AMgr.shouldEagerlyAssume() &&
560           (B->isRelationalOp() || B->isEqualityOp())) {
561         ExplodedNodeSet Tmp;
562         VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Tmp);
563         evalEagerlyAssume(Dst, Tmp, cast<Expr>(S));
564       }
565       else
566         VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst);
567 
568       break;
569     }
570 
571     case Stmt::CallExprClass:
572     case Stmt::CXXOperatorCallExprClass:
573     case Stmt::CXXMemberCallExprClass: {
574       VisitCallExpr(cast<CallExpr>(S), Pred, Dst);
575       break;
576     }
577 
578     case Stmt::CXXConstructExprClass: {
579       const CXXConstructExpr *C = cast<CXXConstructExpr>(S);
580       // For block-level CXXConstructExpr, we don't have a destination region.
581       // Let VisitCXXConstructExpr() create one.
582       VisitCXXConstructExpr(C, 0, Pred, Dst);
583       break;
584     }
585 
586     case Stmt::CXXNewExprClass: {
587       const CXXNewExpr *NE = cast<CXXNewExpr>(S);
588       VisitCXXNewExpr(NE, Pred, Dst);
589       break;
590     }
591 
592     case Stmt::CXXDeleteExprClass: {
593       const CXXDeleteExpr *CDE = cast<CXXDeleteExpr>(S);
594       VisitCXXDeleteExpr(CDE, Pred, Dst);
595       break;
596     }
597       // FIXME: ChooseExpr is really a constant.  We need to fix
598       //        the CFG do not model them as explicit control-flow.
599 
600     case Stmt::ChooseExprClass: { // __builtin_choose_expr
601       const ChooseExpr* C = cast<ChooseExpr>(S);
602       VisitGuardedExpr(C, C->getLHS(), C->getRHS(), Pred, Dst);
603       break;
604     }
605 
606     case Stmt::CompoundAssignOperatorClass:
607       VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst);
608       break;
609 
610     case Stmt::CompoundLiteralExprClass:
611       VisitCompoundLiteralExpr(cast<CompoundLiteralExpr>(S), Pred, Dst);
612       break;
613 
614     case Stmt::BinaryConditionalOperatorClass:
615     case Stmt::ConditionalOperatorClass: { // '?' operator
616       const AbstractConditionalOperator *C
617         = cast<AbstractConditionalOperator>(S);
618       VisitGuardedExpr(C, C->getTrueExpr(), C->getFalseExpr(), Pred, Dst);
619       break;
620     }
621 
622     case Stmt::CXXThisExprClass:
623       VisitCXXThisExpr(cast<CXXThisExpr>(S), Pred, Dst);
624       break;
625 
626     case Stmt::DeclRefExprClass: {
627       const DeclRefExpr *DE = cast<DeclRefExpr>(S);
628       VisitCommonDeclRefExpr(DE, DE->getDecl(), Pred, Dst);
629       break;
630     }
631 
632     case Stmt::DeclStmtClass:
633       VisitDeclStmt(cast<DeclStmt>(S), Pred, Dst);
634       break;
635 
636     case Stmt::ImplicitCastExprClass:
637     case Stmt::CStyleCastExprClass:
638     case Stmt::CXXStaticCastExprClass:
639     case Stmt::CXXDynamicCastExprClass:
640     case Stmt::CXXReinterpretCastExprClass:
641     case Stmt::CXXConstCastExprClass:
642     case Stmt::CXXFunctionalCastExprClass: {
643       const CastExpr* C = cast<CastExpr>(S);
644       VisitCast(C, C->getSubExpr(), Pred, Dst);
645       break;
646     }
647 
648     case Stmt::InitListExprClass:
649       VisitInitListExpr(cast<InitListExpr>(S), Pred, Dst);
650       break;
651 
652     case Stmt::MemberExprClass:
653       VisitMemberExpr(cast<MemberExpr>(S), Pred, Dst);
654       break;
655     case Stmt::ObjCIvarRefExprClass:
656       VisitLvalObjCIvarRefExpr(cast<ObjCIvarRefExpr>(S), Pred, Dst);
657       break;
658 
659     case Stmt::ObjCForCollectionStmtClass:
660       VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S), Pred, Dst);
661       break;
662 
663     case Stmt::ObjCMessageExprClass:
664       VisitObjCMessageExpr(cast<ObjCMessageExpr>(S), Pred, Dst);
665       break;
666 
667     case Stmt::ObjCAtThrowStmtClass: {
668       // FIXME: This is not complete.  We basically treat @throw as
669       // an abort.
670       SaveAndRestore<bool> OldSink(Builder->BuildSinks);
671       Builder->BuildSinks = true;
672       MakeNode(Dst, S, Pred, GetState(Pred));
673       break;
674     }
675 
676     case Stmt::ReturnStmtClass:
677       VisitReturnStmt(cast<ReturnStmt>(S), Pred, Dst);
678       break;
679 
680     case Stmt::OffsetOfExprClass:
681       VisitOffsetOfExpr(cast<OffsetOfExpr>(S), Pred, Dst);
682       break;
683 
684     case Stmt::UnaryExprOrTypeTraitExprClass:
685       VisitUnaryExprOrTypeTraitExpr(cast<UnaryExprOrTypeTraitExpr>(S),
686                                     Pred, Dst);
687       break;
688 
689     case Stmt::StmtExprClass: {
690       const StmtExpr* SE = cast<StmtExpr>(S);
691 
692       if (SE->getSubStmt()->body_empty()) {
693         // Empty statement expression.
694         assert(SE->getType() == getContext().VoidTy
695                && "Empty statement expression must have void type.");
696         Dst.Add(Pred);
697         break;
698       }
699 
700       if (Expr* LastExpr = dyn_cast<Expr>(*SE->getSubStmt()->body_rbegin())) {
701         const GRState* state = GetState(Pred);
702         MakeNode(Dst, SE, Pred, state->BindExpr(SE, state->getSVal(LastExpr)));
703       }
704       else
705         Dst.Add(Pred);
706 
707       break;
708     }
709 
710     case Stmt::StringLiteralClass: {
711       const GRState* state = GetState(Pred);
712       SVal V = state->getLValue(cast<StringLiteral>(S));
713       MakeNode(Dst, S, Pred, state->BindExpr(S, V));
714       return;
715     }
716 
717     case Stmt::UnaryOperatorClass: {
718       const UnaryOperator *U = cast<UnaryOperator>(S);
719       if (AMgr.shouldEagerlyAssume()&&(U->getOpcode() == UO_LNot)) {
720         ExplodedNodeSet Tmp;
721         VisitUnaryOperator(U, Pred, Tmp);
722         evalEagerlyAssume(Dst, Tmp, U);
723       }
724       else
725         VisitUnaryOperator(U, Pred, Dst);
726       break;
727     }
728   }
729 }
730 
731 //===----------------------------------------------------------------------===//
732 // Block entrance.  (Update counters).
733 //===----------------------------------------------------------------------===//
734 
735 void ExprEngine::processCFGBlockEntrance(ExplodedNodeSet &dstNodes,
736                                GenericNodeBuilder<BlockEntrance> &nodeBuilder){
737 
738   // FIXME: Refactor this into a checker.
739   const CFGBlock *block = nodeBuilder.getProgramPoint().getBlock();
740   ExplodedNode *pred = nodeBuilder.getPredecessor();
741 
742   if (nodeBuilder.getBlockCounter().getNumVisited(
743                        pred->getLocationContext()->getCurrentStackFrame(),
744                        block->getBlockID()) >= AMgr.getMaxVisit()) {
745 
746     static int tag = 0;
747     nodeBuilder.generateNode(pred->getState(), pred, &tag, true);
748   }
749 }
750 
751 //===----------------------------------------------------------------------===//
752 // Generic node creation.
753 //===----------------------------------------------------------------------===//
754 
755 ExplodedNode* ExprEngine::MakeNode(ExplodedNodeSet& Dst, const Stmt* S,
756                                      ExplodedNode* Pred, const GRState* St,
757                                      ProgramPoint::Kind K, const void *tag) {
758   assert (Builder && "StmtNodeBuilder not present.");
759   SaveAndRestore<const void*> OldTag(Builder->Tag);
760   Builder->Tag = tag;
761   return Builder->MakeNode(Dst, S, Pred, St, K);
762 }
763 
764 //===----------------------------------------------------------------------===//
765 // Branch processing.
766 //===----------------------------------------------------------------------===//
767 
768 const GRState* ExprEngine::MarkBranch(const GRState* state,
769                                         const Stmt* Terminator,
770                                         bool branchTaken) {
771 
772   switch (Terminator->getStmtClass()) {
773     default:
774       return state;
775 
776     case Stmt::BinaryOperatorClass: { // '&&' and '||'
777 
778       const BinaryOperator* B = cast<BinaryOperator>(Terminator);
779       BinaryOperator::Opcode Op = B->getOpcode();
780 
781       assert (Op == BO_LAnd || Op == BO_LOr);
782 
783       // For &&, if we take the true branch, then the value of the whole
784       // expression is that of the RHS expression.
785       //
786       // For ||, if we take the false branch, then the value of the whole
787       // expression is that of the RHS expression.
788 
789       const Expr* Ex = (Op == BO_LAnd && branchTaken) ||
790                        (Op == BO_LOr && !branchTaken)
791                        ? B->getRHS() : B->getLHS();
792 
793       return state->BindExpr(B, UndefinedVal(Ex));
794     }
795 
796     case Stmt::BinaryConditionalOperatorClass:
797     case Stmt::ConditionalOperatorClass: { // ?:
798       const AbstractConditionalOperator* C
799         = cast<AbstractConditionalOperator>(Terminator);
800 
801       // For ?, if branchTaken == true then the value is either the LHS or
802       // the condition itself. (GNU extension).
803 
804       const Expr* Ex;
805 
806       if (branchTaken)
807         Ex = C->getTrueExpr();
808       else
809         Ex = C->getFalseExpr();
810 
811       return state->BindExpr(C, UndefinedVal(Ex));
812     }
813 
814     case Stmt::ChooseExprClass: { // ?:
815 
816       const ChooseExpr* C = cast<ChooseExpr>(Terminator);
817 
818       const Expr* Ex = branchTaken ? C->getLHS() : C->getRHS();
819       return state->BindExpr(C, UndefinedVal(Ex));
820     }
821   }
822 }
823 
824 /// RecoverCastedSymbol - A helper function for ProcessBranch that is used
825 /// to try to recover some path-sensitivity for casts of symbolic
826 /// integers that promote their values (which are currently not tracked well).
827 /// This function returns the SVal bound to Condition->IgnoreCasts if all the
828 //  cast(s) did was sign-extend the original value.
829 static SVal RecoverCastedSymbol(GRStateManager& StateMgr, const GRState* state,
830                                 const Stmt* Condition, ASTContext& Ctx) {
831 
832   const Expr *Ex = dyn_cast<Expr>(Condition);
833   if (!Ex)
834     return UnknownVal();
835 
836   uint64_t bits = 0;
837   bool bitsInit = false;
838 
839   while (const CastExpr *CE = dyn_cast<CastExpr>(Ex)) {
840     QualType T = CE->getType();
841 
842     if (!T->isIntegerType())
843       return UnknownVal();
844 
845     uint64_t newBits = Ctx.getTypeSize(T);
846     if (!bitsInit || newBits < bits) {
847       bitsInit = true;
848       bits = newBits;
849     }
850 
851     Ex = CE->getSubExpr();
852   }
853 
854   // We reached a non-cast.  Is it a symbolic value?
855   QualType T = Ex->getType();
856 
857   if (!bitsInit || !T->isIntegerType() || Ctx.getTypeSize(T) > bits)
858     return UnknownVal();
859 
860   return state->getSVal(Ex);
861 }
862 
863 void ExprEngine::processBranch(const Stmt* Condition, const Stmt* Term,
864                                  BranchNodeBuilder& builder) {
865 
866   // Check for NULL conditions; e.g. "for(;;)"
867   if (!Condition) {
868     builder.markInfeasible(false);
869     return;
870   }
871 
872   PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
873                                 Condition->getLocStart(),
874                                 "Error evaluating branch");
875 
876   getCheckerManager().runCheckersForBranchCondition(Condition, builder, *this);
877 
878   // If the branch condition is undefined, return;
879   if (!builder.isFeasible(true) && !builder.isFeasible(false))
880     return;
881 
882   const GRState* PrevState = builder.getState();
883   SVal X = PrevState->getSVal(Condition);
884 
885   if (X.isUnknownOrUndef()) {
886     // Give it a chance to recover from unknown.
887     if (const Expr *Ex = dyn_cast<Expr>(Condition)) {
888       if (Ex->getType()->isIntegerType()) {
889         // Try to recover some path-sensitivity.  Right now casts of symbolic
890         // integers that promote their values are currently not tracked well.
891         // If 'Condition' is such an expression, try and recover the
892         // underlying value and use that instead.
893         SVal recovered = RecoverCastedSymbol(getStateManager(),
894                                              builder.getState(), Condition,
895                                              getContext());
896 
897         if (!recovered.isUnknown()) {
898           X = recovered;
899         }
900       }
901     }
902     // If the condition is still unknown, give up.
903     if (X.isUnknownOrUndef()) {
904       builder.generateNode(MarkBranch(PrevState, Term, true), true);
905       builder.generateNode(MarkBranch(PrevState, Term, false), false);
906       return;
907     }
908   }
909 
910   DefinedSVal V = cast<DefinedSVal>(X);
911 
912   // Process the true branch.
913   if (builder.isFeasible(true)) {
914     if (const GRState *state = PrevState->assume(V, true))
915       builder.generateNode(MarkBranch(state, Term, true), true);
916     else
917       builder.markInfeasible(true);
918   }
919 
920   // Process the false branch.
921   if (builder.isFeasible(false)) {
922     if (const GRState *state = PrevState->assume(V, false))
923       builder.generateNode(MarkBranch(state, Term, false), false);
924     else
925       builder.markInfeasible(false);
926   }
927 }
928 
929 /// processIndirectGoto - Called by CoreEngine.  Used to generate successor
930 ///  nodes by processing the 'effects' of a computed goto jump.
931 void ExprEngine::processIndirectGoto(IndirectGotoNodeBuilder &builder) {
932 
933   const GRState *state = builder.getState();
934   SVal V = state->getSVal(builder.getTarget());
935 
936   // Three possibilities:
937   //
938   //   (1) We know the computed label.
939   //   (2) The label is NULL (or some other constant), or Undefined.
940   //   (3) We have no clue about the label.  Dispatch to all targets.
941   //
942 
943   typedef IndirectGotoNodeBuilder::iterator iterator;
944 
945   if (isa<loc::GotoLabel>(V)) {
946     const LabelDecl *L = cast<loc::GotoLabel>(V).getLabel();
947 
948     for (iterator I = builder.begin(), E = builder.end(); I != E; ++I) {
949       if (I.getLabel() == L) {
950         builder.generateNode(I, state);
951         return;
952       }
953     }
954 
955     assert(false && "No block with label.");
956     return;
957   }
958 
959   if (isa<loc::ConcreteInt>(V) || isa<UndefinedVal>(V)) {
960     // Dispatch to the first target and mark it as a sink.
961     //ExplodedNode* N = builder.generateNode(builder.begin(), state, true);
962     // FIXME: add checker visit.
963     //    UndefBranches.insert(N);
964     return;
965   }
966 
967   // This is really a catch-all.  We don't support symbolics yet.
968   // FIXME: Implement dispatch for symbolic pointers.
969 
970   for (iterator I=builder.begin(), E=builder.end(); I != E; ++I)
971     builder.generateNode(I, state);
972 }
973 
974 
975 void ExprEngine::VisitGuardedExpr(const Expr* Ex, const Expr* L,
976                                     const Expr* R,
977                                     ExplodedNode* Pred, ExplodedNodeSet& Dst) {
978 
979   assert(Ex == currentStmt &&
980          Pred->getLocationContext()->getCFG()->isBlkExpr(Ex));
981 
982   const GRState* state = GetState(Pred);
983   SVal X = state->getSVal(Ex);
984 
985   assert (X.isUndef());
986 
987   const Expr *SE = (Expr*) cast<UndefinedVal>(X).getData();
988   assert(SE);
989   X = state->getSVal(SE);
990 
991   // Make sure that we invalidate the previous binding.
992   MakeNode(Dst, Ex, Pred, state->BindExpr(Ex, X, true));
993 }
994 
995 /// ProcessEndPath - Called by CoreEngine.  Used to generate end-of-path
996 ///  nodes when the control reaches the end of a function.
997 void ExprEngine::processEndOfFunction(EndOfFunctionNodeBuilder& builder) {
998   getTF().evalEndPath(*this, builder);
999   StateMgr.EndPath(builder.getState());
1000   getCheckerManager().runCheckersForEndPath(builder, *this);
1001 }
1002 
1003 /// ProcessSwitch - Called by CoreEngine.  Used to generate successor
1004 ///  nodes by processing the 'effects' of a switch statement.
1005 void ExprEngine::processSwitch(SwitchNodeBuilder& builder) {
1006   typedef SwitchNodeBuilder::iterator iterator;
1007   const GRState* state = builder.getState();
1008   const Expr* CondE = builder.getCondition();
1009   SVal  CondV_untested = state->getSVal(CondE);
1010 
1011   if (CondV_untested.isUndef()) {
1012     //ExplodedNode* N = builder.generateDefaultCaseNode(state, true);
1013     // FIXME: add checker
1014     //UndefBranches.insert(N);
1015 
1016     return;
1017   }
1018   DefinedOrUnknownSVal CondV = cast<DefinedOrUnknownSVal>(CondV_untested);
1019 
1020   const GRState *DefaultSt = state;
1021 
1022   iterator I = builder.begin(), EI = builder.end();
1023   bool defaultIsFeasible = I == EI;
1024 
1025   for ( ; I != EI; ++I) {
1026     // Successor may be pruned out during CFG construction.
1027     if (!I.getBlock())
1028       continue;
1029 
1030     const CaseStmt* Case = I.getCase();
1031 
1032     // Evaluate the LHS of the case value.
1033     Expr::EvalResult V1;
1034     bool b = Case->getLHS()->Evaluate(V1, getContext());
1035 
1036     // Sanity checks.  These go away in Release builds.
1037     assert(b && V1.Val.isInt() && !V1.HasSideEffects
1038              && "Case condition must evaluate to an integer constant.");
1039     (void)b; // silence unused variable warning
1040     assert(V1.Val.getInt().getBitWidth() ==
1041            getContext().getTypeSize(CondE->getType()));
1042 
1043     // Get the RHS of the case, if it exists.
1044     Expr::EvalResult V2;
1045 
1046     if (const Expr* E = Case->getRHS()) {
1047       b = E->Evaluate(V2, getContext());
1048       assert(b && V2.Val.isInt() && !V2.HasSideEffects
1049              && "Case condition must evaluate to an integer constant.");
1050       (void)b; // silence unused variable warning
1051     }
1052     else
1053       V2 = V1;
1054 
1055     // FIXME: Eventually we should replace the logic below with a range
1056     //  comparison, rather than concretize the values within the range.
1057     //  This should be easy once we have "ranges" for NonLVals.
1058 
1059     do {
1060       nonloc::ConcreteInt CaseVal(getBasicVals().getValue(V1.Val.getInt()));
1061       DefinedOrUnknownSVal Res = svalBuilder.evalEQ(DefaultSt ? DefaultSt : state,
1062                                                CondV, CaseVal);
1063 
1064       // Now "assume" that the case matches.
1065       if (const GRState* stateNew = state->assume(Res, true)) {
1066         builder.generateCaseStmtNode(I, stateNew);
1067 
1068         // If CondV evaluates to a constant, then we know that this
1069         // is the *only* case that we can take, so stop evaluating the
1070         // others.
1071         if (isa<nonloc::ConcreteInt>(CondV))
1072           return;
1073       }
1074 
1075       // Now "assume" that the case doesn't match.  Add this state
1076       // to the default state (if it is feasible).
1077       if (DefaultSt) {
1078         if (const GRState *stateNew = DefaultSt->assume(Res, false)) {
1079           defaultIsFeasible = true;
1080           DefaultSt = stateNew;
1081         }
1082         else {
1083           defaultIsFeasible = false;
1084           DefaultSt = NULL;
1085         }
1086       }
1087 
1088       // Concretize the next value in the range.
1089       if (V1.Val.getInt() == V2.Val.getInt())
1090         break;
1091 
1092       ++V1.Val.getInt();
1093       assert (V1.Val.getInt() <= V2.Val.getInt());
1094 
1095     } while (true);
1096   }
1097 
1098   if (!defaultIsFeasible)
1099     return;
1100 
1101   // If we have switch(enum value), the default branch is not
1102   // feasible if all of the enum constants not covered by 'case:' statements
1103   // are not feasible values for the switch condition.
1104   //
1105   // Note that this isn't as accurate as it could be.  Even if there isn't
1106   // a case for a particular enum value as long as that enum value isn't
1107   // feasible then it shouldn't be considered for making 'default:' reachable.
1108   const SwitchStmt *SS = builder.getSwitch();
1109   const Expr *CondExpr = SS->getCond()->IgnoreParenImpCasts();
1110   if (CondExpr->getType()->getAs<EnumType>()) {
1111     if (SS->isAllEnumCasesCovered())
1112       return;
1113   }
1114 
1115   builder.generateDefaultCaseNode(DefaultSt);
1116 }
1117 
1118 void ExprEngine::processCallEnter(CallEnterNodeBuilder &B) {
1119   const GRState *state = B.getState()->enterStackFrame(B.getCalleeContext());
1120   B.generateNode(state);
1121 }
1122 
1123 void ExprEngine::processCallExit(CallExitNodeBuilder &B) {
1124   const GRState *state = B.getState();
1125   const ExplodedNode *Pred = B.getPredecessor();
1126   const StackFrameContext *calleeCtx =
1127                             cast<StackFrameContext>(Pred->getLocationContext());
1128   const Stmt *CE = calleeCtx->getCallSite();
1129 
1130   // If the callee returns an expression, bind its value to CallExpr.
1131   const Stmt *ReturnedExpr = state->get<ReturnExpr>();
1132   if (ReturnedExpr) {
1133     SVal RetVal = state->getSVal(ReturnedExpr);
1134     state = state->BindExpr(CE, RetVal);
1135     // Clear the return expr GDM.
1136     state = state->remove<ReturnExpr>();
1137   }
1138 
1139   // Bind the constructed object value to CXXConstructExpr.
1140   if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(CE)) {
1141     const CXXThisRegion *ThisR =
1142       getCXXThisRegion(CCE->getConstructor()->getParent(), calleeCtx);
1143 
1144     SVal ThisV = state->getSVal(ThisR);
1145     // Always bind the region to the CXXConstructExpr.
1146     state = state->BindExpr(CCE, ThisV);
1147   }
1148 
1149   B.generateNode(state);
1150 }
1151 
1152 //===----------------------------------------------------------------------===//
1153 // Transfer functions: logical operations ('&&', '||').
1154 //===----------------------------------------------------------------------===//
1155 
1156 void ExprEngine::VisitLogicalExpr(const BinaryOperator* B, ExplodedNode* Pred,
1157                                     ExplodedNodeSet& Dst) {
1158 
1159   assert(B->getOpcode() == BO_LAnd ||
1160          B->getOpcode() == BO_LOr);
1161 
1162   assert(B==currentStmt && Pred->getLocationContext()->getCFG()->isBlkExpr(B));
1163 
1164   const GRState* state = GetState(Pred);
1165   SVal X = state->getSVal(B);
1166   assert(X.isUndef());
1167 
1168   const Expr *Ex = (const Expr*) cast<UndefinedVal>(X).getData();
1169   assert(Ex);
1170 
1171   if (Ex == B->getRHS()) {
1172     X = state->getSVal(Ex);
1173 
1174     // Handle undefined values.
1175     if (X.isUndef()) {
1176       MakeNode(Dst, B, Pred, state->BindExpr(B, X));
1177       return;
1178     }
1179 
1180     DefinedOrUnknownSVal XD = cast<DefinedOrUnknownSVal>(X);
1181 
1182     // We took the RHS.  Because the value of the '&&' or '||' expression must
1183     // evaluate to 0 or 1, we must assume the value of the RHS evaluates to 0
1184     // or 1.  Alternatively, we could take a lazy approach, and calculate this
1185     // value later when necessary.  We don't have the machinery in place for
1186     // this right now, and since most logical expressions are used for branches,
1187     // the payoff is not likely to be large.  Instead, we do eager evaluation.
1188     if (const GRState *newState = state->assume(XD, true))
1189       MakeNode(Dst, B, Pred,
1190                newState->BindExpr(B, svalBuilder.makeIntVal(1U, B->getType())));
1191 
1192     if (const GRState *newState = state->assume(XD, false))
1193       MakeNode(Dst, B, Pred,
1194                newState->BindExpr(B, svalBuilder.makeIntVal(0U, B->getType())));
1195   }
1196   else {
1197     // We took the LHS expression.  Depending on whether we are '&&' or
1198     // '||' we know what the value of the expression is via properties of
1199     // the short-circuiting.
1200     X = svalBuilder.makeIntVal(B->getOpcode() == BO_LAnd ? 0U : 1U,
1201                           B->getType());
1202     MakeNode(Dst, B, Pred, state->BindExpr(B, X));
1203   }
1204 }
1205 
1206 //===----------------------------------------------------------------------===//
1207 // Transfer functions: Loads and stores.
1208 //===----------------------------------------------------------------------===//
1209 
1210 void ExprEngine::VisitBlockExpr(const BlockExpr *BE, ExplodedNode *Pred,
1211                                   ExplodedNodeSet &Dst) {
1212 
1213   ExplodedNodeSet Tmp;
1214 
1215   CanQualType T = getContext().getCanonicalType(BE->getType());
1216   SVal V = svalBuilder.getBlockPointer(BE->getBlockDecl(), T,
1217                                   Pred->getLocationContext());
1218 
1219   MakeNode(Tmp, BE, Pred, GetState(Pred)->BindExpr(BE, V),
1220            ProgramPoint::PostLValueKind);
1221 
1222   // Post-visit the BlockExpr.
1223   getCheckerManager().runCheckersForPostStmt(Dst, Tmp, BE, *this);
1224 }
1225 
1226 void ExprEngine::VisitCommonDeclRefExpr(const Expr *Ex, const NamedDecl *D,
1227                                         ExplodedNode *Pred,
1228                                         ExplodedNodeSet &Dst) {
1229   const GRState *state = GetState(Pred);
1230 
1231   if (const VarDecl* VD = dyn_cast<VarDecl>(D)) {
1232     assert(Ex->isLValue());
1233     SVal V = state->getLValue(VD, Pred->getLocationContext());
1234 
1235     // For references, the 'lvalue' is the pointer address stored in the
1236     // reference region.
1237     if (VD->getType()->isReferenceType()) {
1238       if (const MemRegion *R = V.getAsRegion())
1239         V = state->getSVal(R);
1240       else
1241         V = UnknownVal();
1242     }
1243 
1244     MakeNode(Dst, Ex, Pred, state->BindExpr(Ex, V),
1245              ProgramPoint::PostLValueKind);
1246     return;
1247   }
1248   if (const EnumConstantDecl* ED = dyn_cast<EnumConstantDecl>(D)) {
1249     assert(!Ex->isLValue());
1250     SVal V = svalBuilder.makeIntVal(ED->getInitVal());
1251     MakeNode(Dst, Ex, Pred, state->BindExpr(Ex, V));
1252     return;
1253   }
1254   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(D)) {
1255     SVal V = svalBuilder.getFunctionPointer(FD);
1256     MakeNode(Dst, Ex, Pred, state->BindExpr(Ex, V),
1257              ProgramPoint::PostLValueKind);
1258     return;
1259   }
1260   assert (false &&
1261           "ValueDecl support for this ValueDecl not implemented.");
1262 }
1263 
1264 /// VisitArraySubscriptExpr - Transfer function for array accesses
1265 void ExprEngine::VisitLvalArraySubscriptExpr(const ArraySubscriptExpr* A,
1266                                              ExplodedNode* Pred,
1267                                              ExplodedNodeSet& Dst){
1268 
1269   const Expr* Base = A->getBase()->IgnoreParens();
1270   const Expr* Idx  = A->getIdx()->IgnoreParens();
1271 
1272   // Evaluate the base.
1273   ExplodedNodeSet Tmp;
1274   Visit(Base, Pred, Tmp);
1275 
1276   for (ExplodedNodeSet::iterator I1=Tmp.begin(), E1=Tmp.end(); I1!=E1; ++I1) {
1277     ExplodedNodeSet Tmp2;
1278     Visit(Idx, *I1, Tmp2);     // Evaluate the index.
1279     ExplodedNodeSet Tmp3;
1280     getCheckerManager().runCheckersForPreStmt(Tmp3, Tmp2, A, *this);
1281 
1282     for (ExplodedNodeSet::iterator I2=Tmp3.begin(),E2=Tmp3.end();I2!=E2; ++I2) {
1283       const GRState* state = GetState(*I2);
1284       SVal V = state->getLValue(A->getType(), state->getSVal(Idx),
1285                                 state->getSVal(Base));
1286       assert(A->isLValue());
1287       MakeNode(Dst, A, *I2, state->BindExpr(A, V), ProgramPoint::PostLValueKind);
1288     }
1289   }
1290 }
1291 
1292 /// VisitMemberExpr - Transfer function for member expressions.
1293 void ExprEngine::VisitMemberExpr(const MemberExpr* M, ExplodedNode* Pred,
1294                                  ExplodedNodeSet& Dst) {
1295 
1296   Expr *baseExpr = M->getBase()->IgnoreParens();
1297   ExplodedNodeSet dstBase;
1298   Visit(baseExpr, Pred, dstBase);
1299 
1300   FieldDecl *field = dyn_cast<FieldDecl>(M->getMemberDecl());
1301   if (!field) // FIXME: skipping member expressions for non-fields
1302     return;
1303 
1304   for (ExplodedNodeSet::iterator I = dstBase.begin(), E = dstBase.end();
1305     I != E; ++I) {
1306     const GRState* state = GetState(*I);
1307     SVal baseExprVal = state->getSVal(baseExpr);
1308     if (isa<nonloc::LazyCompoundVal>(baseExprVal) ||
1309         isa<nonloc::CompoundVal>(baseExprVal) ||
1310         // FIXME: This can originate by conjuring a symbol for an unknown
1311         // temporary struct object, see test/Analysis/fields.c:
1312         // (p = getit()).x
1313         isa<nonloc::SymbolVal>(baseExprVal)) {
1314       MakeNode(Dst, M, *I, state->BindExpr(M, UnknownVal()));
1315       continue;
1316     }
1317 
1318     // FIXME: Should we insert some assumption logic in here to determine
1319     // if "Base" is a valid piece of memory?  Before we put this assumption
1320     // later when using FieldOffset lvals (which we no longer have).
1321 
1322     // For all other cases, compute an lvalue.
1323     SVal L = state->getLValue(field, baseExprVal);
1324     if (M->isLValue())
1325       MakeNode(Dst, M, *I, state->BindExpr(M, L), ProgramPoint::PostLValueKind);
1326     else
1327       evalLoad(Dst, M, *I, state, L);
1328   }
1329 }
1330 
1331 /// evalBind - Handle the semantics of binding a value to a specific location.
1332 ///  This method is used by evalStore and (soon) VisitDeclStmt, and others.
1333 void ExprEngine::evalBind(ExplodedNodeSet& Dst, const Stmt* StoreE,
1334                             ExplodedNode* Pred, const GRState* state,
1335                             SVal location, SVal Val, bool atDeclInit) {
1336 
1337 
1338   // Do a previsit of the bind.
1339   ExplodedNodeSet CheckedSet, Src;
1340   Src.Add(Pred);
1341   getCheckerManager().runCheckersForBind(CheckedSet, Src, location, Val, StoreE,
1342                                          *this);
1343 
1344   for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end();
1345        I!=E; ++I) {
1346 
1347     if (Pred != *I)
1348       state = GetState(*I);
1349 
1350     const GRState* newState = 0;
1351 
1352     if (atDeclInit) {
1353       const VarRegion *VR =
1354         cast<VarRegion>(cast<loc::MemRegionVal>(location).getRegion());
1355 
1356       newState = state->bindDecl(VR, Val);
1357     }
1358     else {
1359       if (location.isUnknown()) {
1360         // We know that the new state will be the same as the old state since
1361         // the location of the binding is "unknown".  Consequently, there
1362         // is no reason to just create a new node.
1363         newState = state;
1364       }
1365       else {
1366         // We are binding to a value other than 'unknown'.  Perform the binding
1367         // using the StoreManager.
1368         newState = state->bindLoc(cast<Loc>(location), Val);
1369       }
1370     }
1371 
1372     // The next thing to do is check if the TransferFuncs object wants to
1373     // update the state based on the new binding.  If the GRTransferFunc object
1374     // doesn't do anything, just auto-propagate the current state.
1375 
1376     // NOTE: We use 'AssignE' for the location of the PostStore if 'AssignE'
1377     // is non-NULL.  Checkers typically care about
1378 
1379     StmtNodeBuilderRef BuilderRef(Dst, *Builder, *this, *I, newState, StoreE,
1380                                     true);
1381 
1382     getTF().evalBind(BuilderRef, location, Val);
1383   }
1384 }
1385 
1386 /// evalStore - Handle the semantics of a store via an assignment.
1387 ///  @param Dst The node set to store generated state nodes
1388 ///  @param AssignE The assignment expression if the store happens in an
1389 ///         assignment.
1390 ///  @param LocatioinE The location expression that is stored to.
1391 ///  @param state The current simulation state
1392 ///  @param location The location to store the value
1393 ///  @param Val The value to be stored
1394 void ExprEngine::evalStore(ExplodedNodeSet& Dst, const Expr *AssignE,
1395                              const Expr* LocationE,
1396                              ExplodedNode* Pred,
1397                              const GRState* state, SVal location, SVal Val,
1398                              const void *tag) {
1399 
1400   assert(Builder && "StmtNodeBuilder must be defined.");
1401 
1402   // Proceed with the store.  We use AssignE as the anchor for the PostStore
1403   // ProgramPoint if it is non-NULL, and LocationE otherwise.
1404   const Expr *StoreE = AssignE ? AssignE : LocationE;
1405 
1406   if (isa<loc::ObjCPropRef>(location)) {
1407     loc::ObjCPropRef prop = cast<loc::ObjCPropRef>(location);
1408     ExplodedNodeSet src = Pred;
1409     return VisitObjCMessage(ObjCPropertySetter(prop.getPropRefExpr(),
1410                                                StoreE, Val), src, Dst);
1411   }
1412 
1413   // Evaluate the location (checks for bad dereferences).
1414   ExplodedNodeSet Tmp;
1415   evalLocation(Tmp, LocationE, Pred, state, location, tag, false);
1416 
1417   if (Tmp.empty())
1418     return;
1419 
1420   if (location.isUndef())
1421     return;
1422 
1423   SaveAndRestore<ProgramPoint::Kind> OldSPointKind(Builder->PointKind,
1424                                                    ProgramPoint::PostStoreKind);
1425 
1426   for (ExplodedNodeSet::iterator NI=Tmp.begin(), NE=Tmp.end(); NI!=NE; ++NI)
1427     evalBind(Dst, StoreE, *NI, GetState(*NI), location, Val);
1428 }
1429 
1430 void ExprEngine::evalLoad(ExplodedNodeSet& Dst, const Expr *Ex,
1431                             ExplodedNode* Pred,
1432                             const GRState* state, SVal location,
1433                             const void *tag, QualType LoadTy) {
1434   assert(!isa<NonLoc>(location) && "location cannot be a NonLoc.");
1435 
1436   if (isa<loc::ObjCPropRef>(location)) {
1437     loc::ObjCPropRef prop = cast<loc::ObjCPropRef>(location);
1438     ExplodedNodeSet src = Pred;
1439     return VisitObjCMessage(ObjCPropertyGetter(prop.getPropRefExpr(), Ex),
1440                             src, Dst);
1441   }
1442 
1443   // Are we loading from a region?  This actually results in two loads; one
1444   // to fetch the address of the referenced value and one to fetch the
1445   // referenced value.
1446   if (const TypedRegion *TR =
1447         dyn_cast_or_null<TypedRegion>(location.getAsRegion())) {
1448 
1449     QualType ValTy = TR->getValueType();
1450     if (const ReferenceType *RT = ValTy->getAs<ReferenceType>()) {
1451       static int loadReferenceTag = 0;
1452       ExplodedNodeSet Tmp;
1453       evalLoadCommon(Tmp, Ex, Pred, state, location, &loadReferenceTag,
1454                      getContext().getPointerType(RT->getPointeeType()));
1455 
1456       // Perform the load from the referenced value.
1457       for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end() ; I!=E; ++I) {
1458         state = GetState(*I);
1459         location = state->getSVal(Ex);
1460         evalLoadCommon(Dst, Ex, *I, state, location, tag, LoadTy);
1461       }
1462       return;
1463     }
1464   }
1465 
1466   evalLoadCommon(Dst, Ex, Pred, state, location, tag, LoadTy);
1467 }
1468 
1469 void ExprEngine::evalLoadCommon(ExplodedNodeSet& Dst, const Expr *Ex,
1470                                   ExplodedNode* Pred,
1471                                   const GRState* state, SVal location,
1472                                   const void *tag, QualType LoadTy) {
1473 
1474   // Evaluate the location (checks for bad dereferences).
1475   ExplodedNodeSet Tmp;
1476   evalLocation(Tmp, Ex, Pred, state, location, tag, true);
1477 
1478   if (Tmp.empty())
1479     return;
1480 
1481   if (location.isUndef())
1482     return;
1483 
1484   SaveAndRestore<ProgramPoint::Kind> OldSPointKind(Builder->PointKind);
1485 
1486   // Proceed with the load.
1487   for (ExplodedNodeSet::iterator NI=Tmp.begin(), NE=Tmp.end(); NI!=NE; ++NI) {
1488     state = GetState(*NI);
1489 
1490     if (location.isUnknown()) {
1491       // This is important.  We must nuke the old binding.
1492       MakeNode(Dst, Ex, *NI, state->BindExpr(Ex, UnknownVal()),
1493                ProgramPoint::PostLoadKind, tag);
1494     }
1495     else {
1496       if (LoadTy.isNull())
1497         LoadTy = Ex->getType();
1498       SVal V = state->getSVal(cast<Loc>(location), LoadTy);
1499       MakeNode(Dst, Ex, *NI, state->bindExprAndLocation(Ex, location, V),
1500                ProgramPoint::PostLoadKind, tag);
1501     }
1502   }
1503 }
1504 
1505 void ExprEngine::evalLocation(ExplodedNodeSet &Dst, const Stmt *S,
1506                                 ExplodedNode* Pred,
1507                                 const GRState* state, SVal location,
1508                                 const void *tag, bool isLoad) {
1509   // Early checks for performance reason.
1510   if (location.isUnknown()) {
1511     Dst.Add(Pred);
1512     return;
1513   }
1514 
1515   ExplodedNodeSet Src;
1516   if (Builder->GetState(Pred) == state) {
1517     Src.Add(Pred);
1518   } else {
1519     // Associate this new state with an ExplodedNode.
1520     // FIXME: If I pass null tag, the graph is incorrect, e.g for
1521     //   int *p;
1522     //   p = 0;
1523     //   *p = 0xDEADBEEF;
1524     // "p = 0" is not noted as "Null pointer value stored to 'p'" but
1525     // instead "int *p" is noted as
1526     // "Variable 'p' initialized to a null pointer value"
1527     ExplodedNode *N = Builder->generateNode(S, state, Pred, this);
1528     Src.Add(N ? N : Pred);
1529   }
1530   getCheckerManager().runCheckersForLocation(Dst, Src, location, isLoad, S,
1531                                              *this);
1532 }
1533 
1534 bool ExprEngine::InlineCall(ExplodedNodeSet &Dst, const CallExpr *CE,
1535                               ExplodedNode *Pred) {
1536   return false;
1537 
1538   // Inlining isn't correct right now because we:
1539   // (a) don't generate CallExit nodes.
1540   // (b) we need a way to postpone doing post-visits of CallExprs until
1541   // the CallExit.  This means we need CallExits for the non-inline
1542   // cases as well.
1543 
1544 #if 0
1545   const GRState *state = GetState(Pred);
1546   const Expr *Callee = CE->getCallee();
1547   SVal L = state->getSVal(Callee);
1548 
1549   const FunctionDecl *FD = L.getAsFunctionDecl();
1550   if (!FD)
1551     return false;
1552 
1553   // Specially handle CXXMethods.
1554   const CXXMethodDecl *methodDecl = 0;
1555 
1556   switch (CE->getStmtClass()) {
1557     default: break;
1558     case Stmt::CXXOperatorCallExprClass: {
1559       const CXXOperatorCallExpr *opCall = cast<CXXOperatorCallExpr>(CE);
1560       methodDecl =
1561         llvm::dyn_cast_or_null<CXXMethodDecl>(opCall->getCalleeDecl());
1562       break;
1563     }
1564     case Stmt::CXXMemberCallExprClass: {
1565       const CXXMemberCallExpr *memberCall = cast<CXXMemberCallExpr>(CE);
1566       const MemberExpr *memberExpr =
1567         cast<MemberExpr>(memberCall->getCallee()->IgnoreParens());
1568       methodDecl = cast<CXXMethodDecl>(memberExpr->getMemberDecl());
1569       break;
1570     }
1571   }
1572 
1573 
1574 
1575 
1576   // Check if the function definition is in the same translation unit.
1577   if (FD->hasBody(FD)) {
1578     const StackFrameContext *stackFrame =
1579       AMgr.getStackFrame(AMgr.getAnalysisContext(FD),
1580                          Pred->getLocationContext(),
1581                          CE, Builder->getBlock(), Builder->getIndex());
1582     // Now we have the definition of the callee, create a CallEnter node.
1583     CallEnter Loc(CE, stackFrame, Pred->getLocationContext());
1584 
1585     ExplodedNode *N = Builder->generateNode(Loc, state, Pred);
1586     Dst.Add(N);
1587     return true;
1588   }
1589 
1590   // Check if we can find the function definition in other translation units.
1591   if (AMgr.hasIndexer()) {
1592     AnalysisContext *C = AMgr.getAnalysisContextInAnotherTU(FD);
1593     if (C == 0)
1594       return false;
1595     const StackFrameContext *stackFrame =
1596       AMgr.getStackFrame(C, Pred->getLocationContext(),
1597                          CE, Builder->getBlock(), Builder->getIndex());
1598     CallEnter Loc(CE, stackFrame, Pred->getLocationContext());
1599     ExplodedNode *N = Builder->generateNode(Loc, state, Pred);
1600     Dst.Add(N);
1601     return true;
1602   }
1603 
1604   // Generate the CallExit node.
1605 
1606   return false;
1607 #endif
1608 }
1609 
1610 void ExprEngine::VisitCallExpr(const CallExpr* CE, ExplodedNode* Pred,
1611                                ExplodedNodeSet& dst) {
1612 
1613   // Determine the type of function we're calling (if available).
1614   const FunctionProtoType *Proto = NULL;
1615   QualType FnType = CE->getCallee()->IgnoreParens()->getType();
1616   if (const PointerType *FnTypePtr = FnType->getAs<PointerType>())
1617     Proto = FnTypePtr->getPointeeType()->getAs<FunctionProtoType>();
1618 
1619   // Should the first argument be evaluated as an lvalue?
1620   bool firstArgumentAsLvalue = false;
1621   switch (CE->getStmtClass()) {
1622     case Stmt::CXXOperatorCallExprClass:
1623       firstArgumentAsLvalue = true;
1624       break;
1625     default:
1626       break;
1627   }
1628 
1629   // Evaluate the arguments.
1630   ExplodedNodeSet dstArgsEvaluated;
1631   evalArguments(CE->arg_begin(), CE->arg_end(), Proto, Pred, dstArgsEvaluated,
1632                 firstArgumentAsLvalue);
1633 
1634   // Evaluate the callee.
1635   ExplodedNodeSet dstCalleeEvaluated;
1636   evalCallee(CE, dstArgsEvaluated, dstCalleeEvaluated);
1637 
1638   // Perform the previsit of the CallExpr.
1639   ExplodedNodeSet dstPreVisit;
1640   getCheckerManager().runCheckersForPreStmt(dstPreVisit, dstCalleeEvaluated,
1641                                             CE, *this);
1642 
1643   // Now evaluate the call itself.
1644   class DefaultEval : public GraphExpander {
1645     ExprEngine &Eng;
1646     const CallExpr *CE;
1647   public:
1648 
1649     DefaultEval(ExprEngine &eng, const CallExpr *ce)
1650       : Eng(eng), CE(ce) {}
1651     virtual void expandGraph(ExplodedNodeSet &Dst, ExplodedNode *Pred) {
1652       // Should we inline the call?
1653       if (Eng.getAnalysisManager().shouldInlineCall() &&
1654           Eng.InlineCall(Dst, CE, Pred)) {
1655         return;
1656       }
1657 
1658       StmtNodeBuilder &Builder = Eng.getBuilder();
1659       assert(&Builder && "StmtNodeBuilder must be defined.");
1660 
1661       // Dispatch to the plug-in transfer function.
1662       unsigned oldSize = Dst.size();
1663       SaveOr OldHasGen(Builder.hasGeneratedNode);
1664 
1665       // Dispatch to transfer function logic to handle the call itself.
1666       const Expr* Callee = CE->getCallee()->IgnoreParens();
1667       const GRState* state = Eng.GetState(Pred);
1668       SVal L = state->getSVal(Callee);
1669       Eng.getTF().evalCall(Dst, Eng, Builder, CE, L, Pred);
1670 
1671       // Handle the case where no nodes where generated.  Auto-generate that
1672       // contains the updated state if we aren't generating sinks.
1673       if (!Builder.BuildSinks && Dst.size() == oldSize &&
1674           !Builder.hasGeneratedNode)
1675         Eng.MakeNode(Dst, CE, Pred, state);
1676     }
1677   };
1678 
1679   // Finally, evaluate the function call.  We try each of the checkers
1680   // to see if the can evaluate the function call.
1681   ExplodedNodeSet dstCallEvaluated;
1682   DefaultEval defEval(*this, CE);
1683   getCheckerManager().runCheckersForEvalCall(dstCallEvaluated,
1684                                              dstPreVisit,
1685                                              CE, *this, &defEval);
1686 
1687   // Finally, perform the post-condition check of the CallExpr and store
1688   // the created nodes in 'Dst'.
1689   getCheckerManager().runCheckersForPostStmt(dst, dstCallEvaluated, CE,
1690                                              *this);
1691 }
1692 
1693 //===----------------------------------------------------------------------===//
1694 // Transfer function: Objective-C dot-syntax to access a property.
1695 //===----------------------------------------------------------------------===//
1696 
1697 void ExprEngine::VisitObjCPropertyRefExpr(const ObjCPropertyRefExpr *Ex,
1698                                           ExplodedNode *Pred,
1699                                           ExplodedNodeSet &Dst) {
1700   ExplodedNodeSet dstBase;
1701 
1702   // Visit the receiver (if any).
1703   if (Ex->isObjectReceiver())
1704     Visit(Ex->getBase(), Pred, dstBase);
1705   else
1706     dstBase = Pred;
1707 
1708   ExplodedNodeSet dstPropRef;
1709 
1710   // Using the base, compute the lvalue of the instance variable.
1711   for (ExplodedNodeSet::iterator I = dstBase.begin(), E = dstBase.end();
1712        I!=E; ++I) {
1713     ExplodedNode *nodeBase = *I;
1714     const GRState *state = GetState(nodeBase);
1715     MakeNode(dstPropRef, Ex, *I, state->BindExpr(Ex, loc::ObjCPropRef(Ex)));
1716   }
1717 
1718   Dst.insert(dstPropRef);
1719 }
1720 
1721 //===----------------------------------------------------------------------===//
1722 // Transfer function: Objective-C ivar references.
1723 //===----------------------------------------------------------------------===//
1724 
1725 static std::pair<const void*,const void*> EagerlyAssumeTag
1726   = std::pair<const void*,const void*>(&EagerlyAssumeTag,static_cast<void*>(0));
1727 
1728 void ExprEngine::evalEagerlyAssume(ExplodedNodeSet &Dst, ExplodedNodeSet &Src,
1729                                      const Expr *Ex) {
1730   for (ExplodedNodeSet::iterator I=Src.begin(), E=Src.end(); I!=E; ++I) {
1731     ExplodedNode *Pred = *I;
1732 
1733     // Test if the previous node was as the same expression.  This can happen
1734     // when the expression fails to evaluate to anything meaningful and
1735     // (as an optimization) we don't generate a node.
1736     ProgramPoint P = Pred->getLocation();
1737     if (!isa<PostStmt>(P) || cast<PostStmt>(P).getStmt() != Ex) {
1738       Dst.Add(Pred);
1739       continue;
1740     }
1741 
1742     const GRState* state = GetState(Pred);
1743     SVal V = state->getSVal(Ex);
1744     if (nonloc::SymExprVal *SEV = dyn_cast<nonloc::SymExprVal>(&V)) {
1745       // First assume that the condition is true.
1746       if (const GRState *stateTrue = state->assume(*SEV, true)) {
1747         stateTrue = stateTrue->BindExpr(Ex,
1748                                         svalBuilder.makeIntVal(1U, Ex->getType()));
1749         Dst.Add(Builder->generateNode(PostStmtCustom(Ex,
1750                                 &EagerlyAssumeTag, Pred->getLocationContext()),
1751                                       stateTrue, Pred));
1752       }
1753 
1754       // Next, assume that the condition is false.
1755       if (const GRState *stateFalse = state->assume(*SEV, false)) {
1756         stateFalse = stateFalse->BindExpr(Ex,
1757                                           svalBuilder.makeIntVal(0U, Ex->getType()));
1758         Dst.Add(Builder->generateNode(PostStmtCustom(Ex, &EagerlyAssumeTag,
1759                                                    Pred->getLocationContext()),
1760                                       stateFalse, Pred));
1761       }
1762     }
1763     else
1764       Dst.Add(Pred);
1765   }
1766 }
1767 
1768 //===----------------------------------------------------------------------===//
1769 // Transfer function: Objective-C @synchronized.
1770 //===----------------------------------------------------------------------===//
1771 
1772 void ExprEngine::VisitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt *S,
1773                                                ExplodedNode *Pred,
1774                                                ExplodedNodeSet &Dst) {
1775 
1776   // The mutex expression is a CFGElement, so we don't need to explicitly
1777   // visit it since it will already be processed.
1778 
1779   // Pre-visit the ObjCAtSynchronizedStmt.
1780   ExplodedNodeSet Tmp;
1781   Tmp.Add(Pred);
1782   getCheckerManager().runCheckersForPreStmt(Dst, Tmp, S, *this);
1783 }
1784 
1785 //===----------------------------------------------------------------------===//
1786 // Transfer function: Objective-C ivar references.
1787 //===----------------------------------------------------------------------===//
1788 
1789 void ExprEngine::VisitLvalObjCIvarRefExpr(const ObjCIvarRefExpr* Ex,
1790                                           ExplodedNode* Pred,
1791                                           ExplodedNodeSet& Dst) {
1792 
1793   // Visit the base expression, which is needed for computing the lvalue
1794   // of the ivar.
1795   ExplodedNodeSet dstBase;
1796   const Expr *baseExpr = Ex->getBase();
1797   Visit(baseExpr, Pred, dstBase);
1798 
1799   ExplodedNodeSet dstIvar;
1800 
1801   // Using the base, compute the lvalue of the instance variable.
1802   for (ExplodedNodeSet::iterator I = dstBase.begin(), E = dstBase.end();
1803        I!=E; ++I) {
1804     ExplodedNode *nodeBase = *I;
1805     const GRState *state = GetState(nodeBase);
1806     SVal baseVal = state->getSVal(baseExpr);
1807     SVal location = state->getLValue(Ex->getDecl(), baseVal);
1808     MakeNode(dstIvar, Ex, *I, state->BindExpr(Ex, location));
1809   }
1810 
1811   // Perform the post-condition check of the ObjCIvarRefExpr and store
1812   // the created nodes in 'Dst'.
1813   getCheckerManager().runCheckersForPostStmt(Dst, dstIvar, Ex, *this);
1814 }
1815 
1816 //===----------------------------------------------------------------------===//
1817 // Transfer function: Objective-C fast enumeration 'for' statements.
1818 //===----------------------------------------------------------------------===//
1819 
1820 void ExprEngine::VisitObjCForCollectionStmt(const ObjCForCollectionStmt* S,
1821                                      ExplodedNode* Pred, ExplodedNodeSet& Dst) {
1822 
1823   // ObjCForCollectionStmts are processed in two places.  This method
1824   // handles the case where an ObjCForCollectionStmt* occurs as one of the
1825   // statements within a basic block.  This transfer function does two things:
1826   //
1827   //  (1) binds the next container value to 'element'.  This creates a new
1828   //      node in the ExplodedGraph.
1829   //
1830   //  (2) binds the value 0/1 to the ObjCForCollectionStmt* itself, indicating
1831   //      whether or not the container has any more elements.  This value
1832   //      will be tested in ProcessBranch.  We need to explicitly bind
1833   //      this value because a container can contain nil elements.
1834   //
1835   // FIXME: Eventually this logic should actually do dispatches to
1836   //   'countByEnumeratingWithState:objects:count:' (NSFastEnumeration).
1837   //   This will require simulating a temporary NSFastEnumerationState, either
1838   //   through an SVal or through the use of MemRegions.  This value can
1839   //   be affixed to the ObjCForCollectionStmt* instead of 0/1; when the loop
1840   //   terminates we reclaim the temporary (it goes out of scope) and we
1841   //   we can test if the SVal is 0 or if the MemRegion is null (depending
1842   //   on what approach we take).
1843   //
1844   //  For now: simulate (1) by assigning either a symbol or nil if the
1845   //    container is empty.  Thus this transfer function will by default
1846   //    result in state splitting.
1847 
1848   const Stmt* elem = S->getElement();
1849   SVal ElementV;
1850 
1851   if (const DeclStmt* DS = dyn_cast<DeclStmt>(elem)) {
1852     const VarDecl* ElemD = cast<VarDecl>(DS->getSingleDecl());
1853     assert (ElemD->getInit() == 0);
1854     ElementV = GetState(Pred)->getLValue(ElemD, Pred->getLocationContext());
1855     VisitObjCForCollectionStmtAux(S, Pred, Dst, ElementV);
1856     return;
1857   }
1858 
1859   ExplodedNodeSet Tmp;
1860   Visit(cast<Expr>(elem), Pred, Tmp);
1861   for (ExplodedNodeSet::iterator I = Tmp.begin(), E = Tmp.end(); I!=E; ++I) {
1862     const GRState* state = GetState(*I);
1863     VisitObjCForCollectionStmtAux(S, *I, Dst, state->getSVal(elem));
1864   }
1865 }
1866 
1867 void ExprEngine::VisitObjCForCollectionStmtAux(const ObjCForCollectionStmt* S,
1868                                        ExplodedNode* Pred, ExplodedNodeSet& Dst,
1869                                                  SVal ElementV) {
1870 
1871   // Check if the location we are writing back to is a null pointer.
1872   const Stmt* elem = S->getElement();
1873   ExplodedNodeSet Tmp;
1874   evalLocation(Tmp, elem, Pred, GetState(Pred), ElementV, NULL, false);
1875 
1876   if (Tmp.empty())
1877     return;
1878 
1879   for (ExplodedNodeSet::iterator NI=Tmp.begin(), NE=Tmp.end(); NI!=NE; ++NI) {
1880     Pred = *NI;
1881     const GRState *state = GetState(Pred);
1882 
1883     // Handle the case where the container still has elements.
1884     SVal TrueV = svalBuilder.makeTruthVal(1);
1885     const GRState *hasElems = state->BindExpr(S, TrueV);
1886 
1887     // Handle the case where the container has no elements.
1888     SVal FalseV = svalBuilder.makeTruthVal(0);
1889     const GRState *noElems = state->BindExpr(S, FalseV);
1890 
1891     if (loc::MemRegionVal* MV = dyn_cast<loc::MemRegionVal>(&ElementV))
1892       if (const TypedRegion* R = dyn_cast<TypedRegion>(MV->getRegion())) {
1893         // FIXME: The proper thing to do is to really iterate over the
1894         //  container.  We will do this with dispatch logic to the store.
1895         //  For now, just 'conjure' up a symbolic value.
1896         QualType T = R->getValueType();
1897         assert(Loc::isLocType(T));
1898         unsigned Count = Builder->getCurrentBlockCount();
1899         SymbolRef Sym = SymMgr.getConjuredSymbol(elem, T, Count);
1900         SVal V = svalBuilder.makeLoc(Sym);
1901         hasElems = hasElems->bindLoc(ElementV, V);
1902 
1903         // Bind the location to 'nil' on the false branch.
1904         SVal nilV = svalBuilder.makeIntVal(0, T);
1905         noElems = noElems->bindLoc(ElementV, nilV);
1906       }
1907 
1908     // Create the new nodes.
1909     MakeNode(Dst, S, Pred, hasElems);
1910     MakeNode(Dst, S, Pred, noElems);
1911   }
1912 }
1913 
1914 //===----------------------------------------------------------------------===//
1915 // Transfer function: Objective-C message expressions.
1916 //===----------------------------------------------------------------------===//
1917 
1918 namespace {
1919 class ObjCMsgWLItem {
1920 public:
1921   ObjCMessageExpr::const_arg_iterator I;
1922   ExplodedNode *N;
1923 
1924   ObjCMsgWLItem(const ObjCMessageExpr::const_arg_iterator &i, ExplodedNode *n)
1925     : I(i), N(n) {}
1926 };
1927 } // end anonymous namespace
1928 
1929 void ExprEngine::VisitObjCMessageExpr(const ObjCMessageExpr* ME,
1930                                         ExplodedNode* Pred,
1931                                         ExplodedNodeSet& Dst){
1932 
1933   // Create a worklist to process both the arguments.
1934   llvm::SmallVector<ObjCMsgWLItem, 20> WL;
1935 
1936   // But first evaluate the receiver (if any).
1937   ObjCMessageExpr::const_arg_iterator AI = ME->arg_begin(), AE = ME->arg_end();
1938   if (const Expr *Receiver = ME->getInstanceReceiver()) {
1939     ExplodedNodeSet Tmp;
1940     Visit(Receiver, Pred, Tmp);
1941 
1942     if (Tmp.empty())
1943       return;
1944 
1945     for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end(); I!=E; ++I)
1946       WL.push_back(ObjCMsgWLItem(AI, *I));
1947   }
1948   else
1949     WL.push_back(ObjCMsgWLItem(AI, Pred));
1950 
1951   // Evaluate the arguments.
1952   ExplodedNodeSet ArgsEvaluated;
1953   while (!WL.empty()) {
1954     ObjCMsgWLItem Item = WL.back();
1955     WL.pop_back();
1956 
1957     if (Item.I == AE) {
1958       ArgsEvaluated.insert(Item.N);
1959       continue;
1960     }
1961 
1962     // Evaluate the subexpression.
1963     ExplodedNodeSet Tmp;
1964 
1965     // FIXME: [Objective-C++] handle arguments that are references
1966     Visit(*Item.I, Item.N, Tmp);
1967 
1968     // Enqueue evaluating the next argument on the worklist.
1969     ++(Item.I);
1970     for (ExplodedNodeSet::iterator NI=Tmp.begin(), NE=Tmp.end(); NI!=NE; ++NI)
1971       WL.push_back(ObjCMsgWLItem(Item.I, *NI));
1972   }
1973 
1974   // Now that the arguments are processed, handle the ObjC message.
1975   VisitObjCMessage(ME, ArgsEvaluated, Dst);
1976 }
1977 
1978 void ExprEngine::VisitObjCMessage(const ObjCMessage &msg,
1979                                   ExplodedNodeSet &Src, ExplodedNodeSet& Dst) {
1980 
1981   // Handle the previsits checks.
1982   ExplodedNodeSet DstPrevisit;
1983   getCheckerManager().runCheckersForPreObjCMessage(DstPrevisit, Src, msg,*this);
1984 
1985   // Proceed with evaluate the message expression.
1986   ExplodedNodeSet dstEval;
1987 
1988   for (ExplodedNodeSet::iterator DI = DstPrevisit.begin(),
1989                                  DE = DstPrevisit.end(); DI != DE; ++DI) {
1990 
1991     ExplodedNode *Pred = *DI;
1992     bool RaisesException = false;
1993     unsigned oldSize = dstEval.size();
1994     SaveAndRestore<bool> OldSink(Builder->BuildSinks);
1995     SaveOr OldHasGen(Builder->hasGeneratedNode);
1996 
1997     if (const Expr *Receiver = msg.getInstanceReceiver()) {
1998       const GRState *state = GetState(Pred);
1999       SVal recVal = state->getSVal(Receiver);
2000       if (!recVal.isUndef()) {
2001         // Bifurcate the state into nil and non-nil ones.
2002         DefinedOrUnknownSVal receiverVal = cast<DefinedOrUnknownSVal>(recVal);
2003 
2004         const GRState *notNilState, *nilState;
2005         llvm::tie(notNilState, nilState) = state->assume(receiverVal);
2006 
2007         // There are three cases: can be nil or non-nil, must be nil, must be
2008         // non-nil. We ignore must be nil, and merge the rest two into non-nil.
2009         if (nilState && !notNilState) {
2010           dstEval.insert(Pred);
2011           continue;
2012         }
2013 
2014         // Check if the "raise" message was sent.
2015         assert(notNilState);
2016         if (msg.getSelector() == RaiseSel)
2017           RaisesException = true;
2018 
2019         // Check if we raise an exception.  For now treat these as sinks.
2020         // Eventually we will want to handle exceptions properly.
2021         if (RaisesException)
2022           Builder->BuildSinks = true;
2023 
2024         // Dispatch to plug-in transfer function.
2025         evalObjCMessage(dstEval, msg, Pred, notNilState);
2026       }
2027     }
2028     else if (const ObjCInterfaceDecl *Iface = msg.getReceiverInterface()) {
2029       IdentifierInfo* ClsName = Iface->getIdentifier();
2030       Selector S = msg.getSelector();
2031 
2032       // Check for special instance methods.
2033       if (!NSExceptionII) {
2034         ASTContext& Ctx = getContext();
2035         NSExceptionII = &Ctx.Idents.get("NSException");
2036       }
2037 
2038       if (ClsName == NSExceptionII) {
2039         enum { NUM_RAISE_SELECTORS = 2 };
2040 
2041         // Lazily create a cache of the selectors.
2042         if (!NSExceptionInstanceRaiseSelectors) {
2043           ASTContext& Ctx = getContext();
2044           NSExceptionInstanceRaiseSelectors =
2045             new Selector[NUM_RAISE_SELECTORS];
2046           llvm::SmallVector<IdentifierInfo*, NUM_RAISE_SELECTORS> II;
2047           unsigned idx = 0;
2048 
2049           // raise:format:
2050           II.push_back(&Ctx.Idents.get("raise"));
2051           II.push_back(&Ctx.Idents.get("format"));
2052           NSExceptionInstanceRaiseSelectors[idx++] =
2053             Ctx.Selectors.getSelector(II.size(), &II[0]);
2054 
2055           // raise:format::arguments:
2056           II.push_back(&Ctx.Idents.get("arguments"));
2057           NSExceptionInstanceRaiseSelectors[idx++] =
2058             Ctx.Selectors.getSelector(II.size(), &II[0]);
2059         }
2060 
2061         for (unsigned i = 0; i < NUM_RAISE_SELECTORS; ++i)
2062           if (S == NSExceptionInstanceRaiseSelectors[i]) {
2063             RaisesException = true;
2064             break;
2065           }
2066       }
2067 
2068       // Check if we raise an exception.  For now treat these as sinks.
2069       // Eventually we will want to handle exceptions properly.
2070       if (RaisesException)
2071         Builder->BuildSinks = true;
2072 
2073       // Dispatch to plug-in transfer function.
2074       evalObjCMessage(dstEval, msg, Pred, Builder->GetState(Pred));
2075     }
2076 
2077     // Handle the case where no nodes where generated.  Auto-generate that
2078     // contains the updated state if we aren't generating sinks.
2079     if (!Builder->BuildSinks && dstEval.size() == oldSize &&
2080         !Builder->hasGeneratedNode)
2081       MakeNode(dstEval, msg.getOriginExpr(), Pred, GetState(Pred));
2082   }
2083 
2084   // Finally, perform the post-condition check of the ObjCMessageExpr and store
2085   // the created nodes in 'Dst'.
2086   getCheckerManager().runCheckersForPostObjCMessage(Dst, dstEval, msg, *this);
2087 }
2088 
2089 //===----------------------------------------------------------------------===//
2090 // Transfer functions: Miscellaneous statements.
2091 //===----------------------------------------------------------------------===//
2092 
2093 void ExprEngine::VisitCast(const CastExpr *CastE, const Expr *Ex,
2094                            ExplodedNode *Pred, ExplodedNodeSet &Dst) {
2095 
2096   ExplodedNodeSet S1;
2097   Visit(Ex, Pred, S1);
2098   ExplodedNodeSet S2;
2099   getCheckerManager().runCheckersForPreStmt(S2, S1, CastE, *this);
2100 
2101   if (CastE->getCastKind() == CK_LValueToRValue ||
2102       CastE->getCastKind() == CK_GetObjCProperty) {
2103     for (ExplodedNodeSet::iterator I = S2.begin(), E = S2.end(); I!=E; ++I) {
2104       ExplodedNode *subExprNode = *I;
2105       const GRState *state = GetState(subExprNode);
2106       evalLoad(Dst, CastE, subExprNode, state, state->getSVal(Ex));
2107     }
2108     return;
2109   }
2110 
2111   // All other casts.
2112   QualType T = CastE->getType();
2113   QualType ExTy = Ex->getType();
2114 
2115   if (const ExplicitCastExpr *ExCast=dyn_cast_or_null<ExplicitCastExpr>(CastE))
2116     T = ExCast->getTypeAsWritten();
2117 
2118   for (ExplodedNodeSet::iterator I = S2.begin(), E = S2.end(); I != E; ++I) {
2119     Pred = *I;
2120 
2121     switch (CastE->getCastKind()) {
2122       case CK_ToVoid:
2123         Dst.Add(Pred);
2124         continue;
2125       case CK_LValueToRValue:
2126       case CK_NoOp:
2127       case CK_FunctionToPointerDecay: {
2128         // Copy the SVal of Ex to CastE.
2129         const GRState *state = GetState(Pred);
2130         SVal V = state->getSVal(Ex);
2131         state = state->BindExpr(CastE, V);
2132         MakeNode(Dst, CastE, Pred, state);
2133         continue;
2134       }
2135       case CK_GetObjCProperty:
2136       case CK_Dependent:
2137       case CK_ArrayToPointerDecay:
2138       case CK_BitCast:
2139       case CK_LValueBitCast:
2140       case CK_IntegralCast:
2141       case CK_NullToPointer:
2142       case CK_IntegralToPointer:
2143       case CK_PointerToIntegral:
2144       case CK_PointerToBoolean:
2145       case CK_IntegralToBoolean:
2146       case CK_IntegralToFloating:
2147       case CK_FloatingToIntegral:
2148       case CK_FloatingToBoolean:
2149       case CK_FloatingCast:
2150       case CK_FloatingRealToComplex:
2151       case CK_FloatingComplexToReal:
2152       case CK_FloatingComplexToBoolean:
2153       case CK_FloatingComplexCast:
2154       case CK_FloatingComplexToIntegralComplex:
2155       case CK_IntegralRealToComplex:
2156       case CK_IntegralComplexToReal:
2157       case CK_IntegralComplexToBoolean:
2158       case CK_IntegralComplexCast:
2159       case CK_IntegralComplexToFloatingComplex:
2160       case CK_AnyPointerToObjCPointerCast:
2161       case CK_AnyPointerToBlockPointerCast:
2162       case CK_ObjCObjectLValueCast: {
2163         // Delegate to SValBuilder to process.
2164         const GRState* state = GetState(Pred);
2165         SVal V = state->getSVal(Ex);
2166         V = svalBuilder.evalCast(V, T, ExTy);
2167         state = state->BindExpr(CastE, V);
2168         MakeNode(Dst, CastE, Pred, state);
2169         continue;
2170       }
2171       case CK_DerivedToBase:
2172       case CK_UncheckedDerivedToBase: {
2173         // For DerivedToBase cast, delegate to the store manager.
2174         const GRState *state = GetState(Pred);
2175         SVal val = state->getSVal(Ex);
2176         val = getStoreManager().evalDerivedToBase(val, T);
2177         state = state->BindExpr(CastE, val);
2178         MakeNode(Dst, CastE, Pred, state);
2179         continue;
2180       }
2181       // Various C++ casts that are not handled yet.
2182       case CK_Dynamic:
2183       case CK_ToUnion:
2184       case CK_BaseToDerived:
2185       case CK_NullToMemberPointer:
2186       case CK_BaseToDerivedMemberPointer:
2187       case CK_DerivedToBaseMemberPointer:
2188       case CK_UserDefinedConversion:
2189       case CK_ConstructorConversion:
2190       case CK_VectorSplat:
2191       case CK_MemberPointerToBoolean: {
2192         // Recover some path-sensitivty by conjuring a new value.
2193         QualType resultType = CastE->getType();
2194         if (CastE->isLValue())
2195           resultType = getContext().getPointerType(resultType);
2196 
2197         SVal result =
2198           svalBuilder.getConjuredSymbolVal(NULL, CastE, resultType,
2199                                            Builder->getCurrentBlockCount());
2200 
2201         const GRState *state = GetState(Pred)->BindExpr(CastE, result);
2202         MakeNode(Dst, CastE, Pred, state);
2203         continue;
2204       }
2205     }
2206   }
2207 }
2208 
2209 void ExprEngine::VisitCompoundLiteralExpr(const CompoundLiteralExpr* CL,
2210                                             ExplodedNode* Pred,
2211                                             ExplodedNodeSet& Dst) {
2212   const InitListExpr* ILE
2213     = cast<InitListExpr>(CL->getInitializer()->IgnoreParens());
2214   ExplodedNodeSet Tmp;
2215   Visit(ILE, Pred, Tmp);
2216 
2217   for (ExplodedNodeSet::iterator I = Tmp.begin(), EI = Tmp.end(); I!=EI; ++I) {
2218     const GRState* state = GetState(*I);
2219     SVal ILV = state->getSVal(ILE);
2220     const LocationContext *LC = (*I)->getLocationContext();
2221     state = state->bindCompoundLiteral(CL, LC, ILV);
2222 
2223     if (CL->isLValue()) {
2224       MakeNode(Dst, CL, *I, state->BindExpr(CL, state->getLValue(CL, LC)));
2225     }
2226     else
2227       MakeNode(Dst, CL, *I, state->BindExpr(CL, ILV));
2228   }
2229 }
2230 
2231 void ExprEngine::VisitDeclStmt(const DeclStmt *DS, ExplodedNode *Pred,
2232                                  ExplodedNodeSet& Dst) {
2233 
2234   // The CFG has one DeclStmt per Decl.
2235   const Decl* D = *DS->decl_begin();
2236 
2237   if (!D || !isa<VarDecl>(D))
2238     return;
2239 
2240   const VarDecl* VD = dyn_cast<VarDecl>(D);
2241   const Expr* InitEx = VD->getInit();
2242 
2243   // FIXME: static variables may have an initializer, but the second
2244   //  time a function is called those values may not be current.
2245   ExplodedNodeSet Tmp;
2246 
2247   if (InitEx) {
2248     if (VD->getType()->isReferenceType() && !InitEx->isLValue()) {
2249       // If the initializer is C++ record type, it should already has a
2250       // temp object.
2251       if (!InitEx->getType()->isRecordType())
2252         CreateCXXTemporaryObject(InitEx, Pred, Tmp);
2253       else
2254         Tmp.Add(Pred);
2255     } else
2256       Visit(InitEx, Pred, Tmp);
2257   } else
2258     Tmp.Add(Pred);
2259 
2260   ExplodedNodeSet Tmp2;
2261   getCheckerManager().runCheckersForPreStmt(Tmp2, Tmp, DS, *this);
2262 
2263   for (ExplodedNodeSet::iterator I=Tmp2.begin(), E=Tmp2.end(); I!=E; ++I) {
2264     ExplodedNode *N = *I;
2265     const GRState *state = GetState(N);
2266 
2267     // Decls without InitExpr are not initialized explicitly.
2268     const LocationContext *LC = N->getLocationContext();
2269 
2270     if (InitEx) {
2271       SVal InitVal = state->getSVal(InitEx);
2272 
2273       // We bound the temp obj region to the CXXConstructExpr. Now recover
2274       // the lazy compound value when the variable is not a reference.
2275       if (AMgr.getLangOptions().CPlusPlus && VD->getType()->isRecordType() &&
2276           !VD->getType()->isReferenceType() && isa<loc::MemRegionVal>(InitVal)){
2277         InitVal = state->getSVal(cast<loc::MemRegionVal>(InitVal).getRegion());
2278         assert(isa<nonloc::LazyCompoundVal>(InitVal));
2279       }
2280 
2281       // Recover some path-sensitivity if a scalar value evaluated to
2282       // UnknownVal.
2283       if ((InitVal.isUnknown() ||
2284           !getConstraintManager().canReasonAbout(InitVal)) &&
2285           !VD->getType()->isReferenceType()) {
2286         InitVal = svalBuilder.getConjuredSymbolVal(NULL, InitEx,
2287                                                Builder->getCurrentBlockCount());
2288       }
2289 
2290       evalBind(Dst, DS, *I, state,
2291                loc::MemRegionVal(state->getRegion(VD, LC)), InitVal, true);
2292     }
2293     else {
2294       state = state->bindDeclWithNoInit(state->getRegion(VD, LC));
2295       MakeNode(Dst, DS, *I, state);
2296     }
2297   }
2298 }
2299 
2300 namespace {
2301   // This class is used by VisitInitListExpr as an item in a worklist
2302   // for processing the values contained in an InitListExpr.
2303 class InitListWLItem {
2304 public:
2305   llvm::ImmutableList<SVal> Vals;
2306   ExplodedNode* N;
2307   InitListExpr::const_reverse_iterator Itr;
2308 
2309   InitListWLItem(ExplodedNode* n, llvm::ImmutableList<SVal> vals,
2310                  InitListExpr::const_reverse_iterator itr)
2311   : Vals(vals), N(n), Itr(itr) {}
2312 };
2313 }
2314 
2315 
2316 void ExprEngine::VisitInitListExpr(const InitListExpr* E, ExplodedNode* Pred,
2317                                      ExplodedNodeSet& Dst) {
2318 
2319   const GRState* state = GetState(Pred);
2320   QualType T = getContext().getCanonicalType(E->getType());
2321   unsigned NumInitElements = E->getNumInits();
2322 
2323   if (T->isArrayType() || T->isRecordType() || T->isVectorType()) {
2324     llvm::ImmutableList<SVal> StartVals = getBasicVals().getEmptySValList();
2325 
2326     // Handle base case where the initializer has no elements.
2327     // e.g: static int* myArray[] = {};
2328     if (NumInitElements == 0) {
2329       SVal V = svalBuilder.makeCompoundVal(T, StartVals);
2330       MakeNode(Dst, E, Pred, state->BindExpr(E, V));
2331       return;
2332     }
2333 
2334     // Create a worklist to process the initializers.
2335     llvm::SmallVector<InitListWLItem, 10> WorkList;
2336     WorkList.reserve(NumInitElements);
2337     WorkList.push_back(InitListWLItem(Pred, StartVals, E->rbegin()));
2338     InitListExpr::const_reverse_iterator ItrEnd = E->rend();
2339     assert(!(E->rbegin() == E->rend()));
2340 
2341     // Process the worklist until it is empty.
2342     while (!WorkList.empty()) {
2343       InitListWLItem X = WorkList.back();
2344       WorkList.pop_back();
2345 
2346       ExplodedNodeSet Tmp;
2347       Visit(*X.Itr, X.N, Tmp);
2348 
2349       InitListExpr::const_reverse_iterator NewItr = X.Itr + 1;
2350 
2351       for (ExplodedNodeSet::iterator NI=Tmp.begin(),NE=Tmp.end();NI!=NE;++NI) {
2352         // Get the last initializer value.
2353         state = GetState(*NI);
2354         SVal InitV = state->getSVal(cast<Expr>(*X.Itr));
2355 
2356         // Construct the new list of values by prepending the new value to
2357         // the already constructed list.
2358         llvm::ImmutableList<SVal> NewVals =
2359           getBasicVals().consVals(InitV, X.Vals);
2360 
2361         if (NewItr == ItrEnd) {
2362           // Now we have a list holding all init values. Make CompoundValData.
2363           SVal V = svalBuilder.makeCompoundVal(T, NewVals);
2364 
2365           // Make final state and node.
2366           MakeNode(Dst, E, *NI, state->BindExpr(E, V));
2367         }
2368         else {
2369           // Still some initializer values to go.  Push them onto the worklist.
2370           WorkList.push_back(InitListWLItem(*NI, NewVals, NewItr));
2371         }
2372       }
2373     }
2374 
2375     return;
2376   }
2377 
2378   if (Loc::isLocType(T) || T->isIntegerType()) {
2379     assert (E->getNumInits() == 1);
2380     ExplodedNodeSet Tmp;
2381     const Expr* Init = E->getInit(0);
2382     Visit(Init, Pred, Tmp);
2383     for (ExplodedNodeSet::iterator I=Tmp.begin(), EI=Tmp.end(); I != EI; ++I) {
2384       state = GetState(*I);
2385       MakeNode(Dst, E, *I, state->BindExpr(E, state->getSVal(Init)));
2386     }
2387     return;
2388   }
2389 
2390   assert(0 && "unprocessed InitListExpr type");
2391 }
2392 
2393 /// VisitUnaryExprOrTypeTraitExpr - Transfer function for sizeof(type).
2394 void ExprEngine::VisitUnaryExprOrTypeTraitExpr(
2395                                           const UnaryExprOrTypeTraitExpr* Ex,
2396                                           ExplodedNode* Pred,
2397                                           ExplodedNodeSet& Dst) {
2398   QualType T = Ex->getTypeOfArgument();
2399 
2400   if (Ex->getKind() == UETT_SizeOf) {
2401     if (!T->isIncompleteType() && !T->isConstantSizeType()) {
2402       assert(T->isVariableArrayType() && "Unknown non-constant-sized type.");
2403 
2404       // FIXME: Add support for VLA type arguments, not just VLA expressions.
2405       // When that happens, we should probably refactor VLASizeChecker's code.
2406       if (Ex->isArgumentType()) {
2407         Dst.Add(Pred);
2408         return;
2409       }
2410 
2411       // Get the size by getting the extent of the sub-expression.
2412       // First, visit the sub-expression to find its region.
2413       const Expr *Arg = Ex->getArgumentExpr();
2414       ExplodedNodeSet Tmp;
2415       Visit(Arg, Pred, Tmp);
2416 
2417       for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end(); I!=E; ++I) {
2418         const GRState* state = GetState(*I);
2419         const MemRegion *MR = state->getSVal(Arg).getAsRegion();
2420 
2421         // If the subexpression can't be resolved to a region, we don't know
2422         // anything about its size. Just leave the state as is and continue.
2423         if (!MR) {
2424           Dst.Add(*I);
2425           continue;
2426         }
2427 
2428         // The result is the extent of the VLA.
2429         SVal Extent = cast<SubRegion>(MR)->getExtent(svalBuilder);
2430         MakeNode(Dst, Ex, *I, state->BindExpr(Ex, Extent));
2431       }
2432 
2433       return;
2434     }
2435     else if (T->getAs<ObjCObjectType>()) {
2436       // Some code tries to take the sizeof an ObjCObjectType, relying that
2437       // the compiler has laid out its representation.  Just report Unknown
2438       // for these.
2439       Dst.Add(Pred);
2440       return;
2441     }
2442   }
2443 
2444   Expr::EvalResult Result;
2445   Ex->Evaluate(Result, getContext());
2446   CharUnits amt = CharUnits::fromQuantity(Result.Val.getInt().getZExtValue());
2447 
2448   MakeNode(Dst, Ex, Pred,
2449            GetState(Pred)->BindExpr(Ex,
2450               svalBuilder.makeIntVal(amt.getQuantity(), Ex->getType())));
2451 }
2452 
2453 void ExprEngine::VisitOffsetOfExpr(const OffsetOfExpr* OOE,
2454                                      ExplodedNode* Pred, ExplodedNodeSet& Dst) {
2455   Expr::EvalResult Res;
2456   if (OOE->Evaluate(Res, getContext()) && Res.Val.isInt()) {
2457     const APSInt &IV = Res.Val.getInt();
2458     assert(IV.getBitWidth() == getContext().getTypeSize(OOE->getType()));
2459     assert(OOE->getType()->isIntegerType());
2460     assert(IV.isSigned() == OOE->getType()->isSignedIntegerType());
2461     SVal X = svalBuilder.makeIntVal(IV);
2462     MakeNode(Dst, OOE, Pred, GetState(Pred)->BindExpr(OOE, X));
2463     return;
2464   }
2465   // FIXME: Handle the case where __builtin_offsetof is not a constant.
2466   Dst.Add(Pred);
2467 }
2468 
2469 void ExprEngine::VisitUnaryOperator(const UnaryOperator* U,
2470                                       ExplodedNode* Pred,
2471                                       ExplodedNodeSet& Dst) {
2472 
2473   switch (U->getOpcode()) {
2474 
2475     default:
2476       break;
2477 
2478     case UO_Real: {
2479       const Expr* Ex = U->getSubExpr()->IgnoreParens();
2480       ExplodedNodeSet Tmp;
2481       Visit(Ex, Pred, Tmp);
2482 
2483       for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end(); I!=E; ++I) {
2484 
2485         // FIXME: We don't have complex SValues yet.
2486         if (Ex->getType()->isAnyComplexType()) {
2487           // Just report "Unknown."
2488           Dst.Add(*I);
2489           continue;
2490         }
2491 
2492         // For all other types, UO_Real is an identity operation.
2493         assert (U->getType() == Ex->getType());
2494         const GRState* state = GetState(*I);
2495         MakeNode(Dst, U, *I, state->BindExpr(U, state->getSVal(Ex)));
2496       }
2497 
2498       return;
2499     }
2500 
2501     case UO_Imag: {
2502 
2503       const Expr* Ex = U->getSubExpr()->IgnoreParens();
2504       ExplodedNodeSet Tmp;
2505       Visit(Ex, Pred, Tmp);
2506 
2507       for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end(); I!=E; ++I) {
2508         // FIXME: We don't have complex SValues yet.
2509         if (Ex->getType()->isAnyComplexType()) {
2510           // Just report "Unknown."
2511           Dst.Add(*I);
2512           continue;
2513         }
2514 
2515         // For all other types, UO_Imag returns 0.
2516         const GRState* state = GetState(*I);
2517         SVal X = svalBuilder.makeZeroVal(Ex->getType());
2518         MakeNode(Dst, U, *I, state->BindExpr(U, X));
2519       }
2520 
2521       return;
2522     }
2523 
2524     case UO_Plus:
2525       assert(!U->isLValue());
2526       // FALL-THROUGH.
2527     case UO_Deref:
2528     case UO_AddrOf:
2529     case UO_Extension: {
2530 
2531       // Unary "+" is a no-op, similar to a parentheses.  We still have places
2532       // where it may be a block-level expression, so we need to
2533       // generate an extra node that just propagates the value of the
2534       // subexpression.
2535 
2536       const Expr* Ex = U->getSubExpr()->IgnoreParens();
2537       ExplodedNodeSet Tmp;
2538       Visit(Ex, Pred, Tmp);
2539 
2540       for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end(); I!=E; ++I) {
2541         const GRState* state = GetState(*I);
2542         MakeNode(Dst, U, *I, state->BindExpr(U, state->getSVal(Ex)));
2543       }
2544 
2545       return;
2546     }
2547 
2548     case UO_LNot:
2549     case UO_Minus:
2550     case UO_Not: {
2551       assert (!U->isLValue());
2552       const Expr* Ex = U->getSubExpr()->IgnoreParens();
2553       ExplodedNodeSet Tmp;
2554       Visit(Ex, Pred, Tmp);
2555 
2556       for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end(); I!=E; ++I) {
2557         const GRState* state = GetState(*I);
2558 
2559         // Get the value of the subexpression.
2560         SVal V = state->getSVal(Ex);
2561 
2562         if (V.isUnknownOrUndef()) {
2563           MakeNode(Dst, U, *I, state->BindExpr(U, V));
2564           continue;
2565         }
2566 
2567 //        QualType DstT = getContext().getCanonicalType(U->getType());
2568 //        QualType SrcT = getContext().getCanonicalType(Ex->getType());
2569 //
2570 //        if (DstT != SrcT) // Perform promotions.
2571 //          V = evalCast(V, DstT);
2572 //
2573 //        if (V.isUnknownOrUndef()) {
2574 //          MakeNode(Dst, U, *I, BindExpr(St, U, V));
2575 //          continue;
2576 //        }
2577 
2578         switch (U->getOpcode()) {
2579           default:
2580             assert(false && "Invalid Opcode.");
2581             break;
2582 
2583           case UO_Not:
2584             // FIXME: Do we need to handle promotions?
2585             state = state->BindExpr(U, evalComplement(cast<NonLoc>(V)));
2586             break;
2587 
2588           case UO_Minus:
2589             // FIXME: Do we need to handle promotions?
2590             state = state->BindExpr(U, evalMinus(cast<NonLoc>(V)));
2591             break;
2592 
2593           case UO_LNot:
2594 
2595             // C99 6.5.3.3: "The expression !E is equivalent to (0==E)."
2596             //
2597             //  Note: technically we do "E == 0", but this is the same in the
2598             //    transfer functions as "0 == E".
2599             SVal Result;
2600 
2601             if (isa<Loc>(V)) {
2602               Loc X = svalBuilder.makeNull();
2603               Result = evalBinOp(state, BO_EQ, cast<Loc>(V), X,
2604                                  U->getType());
2605             }
2606             else {
2607               nonloc::ConcreteInt X(getBasicVals().getValue(0, Ex->getType()));
2608               Result = evalBinOp(state, BO_EQ, cast<NonLoc>(V), X,
2609                                  U->getType());
2610             }
2611 
2612             state = state->BindExpr(U, Result);
2613 
2614             break;
2615         }
2616 
2617         MakeNode(Dst, U, *I, state);
2618       }
2619 
2620       return;
2621     }
2622   }
2623 
2624   // Handle ++ and -- (both pre- and post-increment).
2625   assert (U->isIncrementDecrementOp());
2626   ExplodedNodeSet Tmp;
2627   const Expr* Ex = U->getSubExpr()->IgnoreParens();
2628   Visit(Ex, Pred, Tmp);
2629 
2630   for (ExplodedNodeSet::iterator I = Tmp.begin(), E = Tmp.end(); I!=E; ++I) {
2631 
2632     const GRState* state = GetState(*I);
2633     SVal loc = state->getSVal(Ex);
2634 
2635     // Perform a load.
2636     ExplodedNodeSet Tmp2;
2637     evalLoad(Tmp2, Ex, *I, state, loc);
2638 
2639     for (ExplodedNodeSet::iterator I2=Tmp2.begin(), E2=Tmp2.end();I2!=E2;++I2) {
2640 
2641       state = GetState(*I2);
2642       SVal V2_untested = state->getSVal(Ex);
2643 
2644       // Propagate unknown and undefined values.
2645       if (V2_untested.isUnknownOrUndef()) {
2646         MakeNode(Dst, U, *I2, state->BindExpr(U, V2_untested));
2647         continue;
2648       }
2649       DefinedSVal V2 = cast<DefinedSVal>(V2_untested);
2650 
2651       // Handle all other values.
2652       BinaryOperator::Opcode Op = U->isIncrementOp() ? BO_Add
2653                                                      : BO_Sub;
2654 
2655       // If the UnaryOperator has non-location type, use its type to create the
2656       // constant value. If the UnaryOperator has location type, create the
2657       // constant with int type and pointer width.
2658       SVal RHS;
2659 
2660       if (U->getType()->isAnyPointerType())
2661         RHS = svalBuilder.makeArrayIndex(1);
2662       else
2663         RHS = svalBuilder.makeIntVal(1, U->getType());
2664 
2665       SVal Result = evalBinOp(state, Op, V2, RHS, U->getType());
2666 
2667       // Conjure a new symbol if necessary to recover precision.
2668       if (Result.isUnknown() || !getConstraintManager().canReasonAbout(Result)){
2669         DefinedOrUnknownSVal SymVal =
2670           svalBuilder.getConjuredSymbolVal(NULL, Ex,
2671                                       Builder->getCurrentBlockCount());
2672         Result = SymVal;
2673 
2674         // If the value is a location, ++/-- should always preserve
2675         // non-nullness.  Check if the original value was non-null, and if so
2676         // propagate that constraint.
2677         if (Loc::isLocType(U->getType())) {
2678           DefinedOrUnknownSVal Constraint =
2679             svalBuilder.evalEQ(state, V2,svalBuilder.makeZeroVal(U->getType()));
2680 
2681           if (!state->assume(Constraint, true)) {
2682             // It isn't feasible for the original value to be null.
2683             // Propagate this constraint.
2684             Constraint = svalBuilder.evalEQ(state, SymVal,
2685                                        svalBuilder.makeZeroVal(U->getType()));
2686 
2687 
2688             state = state->assume(Constraint, false);
2689             assert(state);
2690           }
2691         }
2692       }
2693 
2694       // Since the lvalue-to-rvalue conversion is explicit in the AST,
2695       // we bind an l-value if the operator is prefix and an lvalue (in C++).
2696       if (U->isLValue())
2697         state = state->BindExpr(U, loc);
2698       else
2699         state = state->BindExpr(U, V2);
2700 
2701       // Perform the store.
2702       evalStore(Dst, NULL, U, *I2, state, loc, Result);
2703     }
2704   }
2705 }
2706 
2707 void ExprEngine::VisitAsmStmt(const AsmStmt* A, ExplodedNode* Pred,
2708                                 ExplodedNodeSet& Dst) {
2709   VisitAsmStmtHelperOutputs(A, A->begin_outputs(), A->end_outputs(), Pred, Dst);
2710 }
2711 
2712 void ExprEngine::VisitAsmStmtHelperOutputs(const AsmStmt* A,
2713                                              AsmStmt::const_outputs_iterator I,
2714                                              AsmStmt::const_outputs_iterator E,
2715                                      ExplodedNode* Pred, ExplodedNodeSet& Dst) {
2716   if (I == E) {
2717     VisitAsmStmtHelperInputs(A, A->begin_inputs(), A->end_inputs(), Pred, Dst);
2718     return;
2719   }
2720 
2721   ExplodedNodeSet Tmp;
2722   Visit(*I, Pred, Tmp);
2723   ++I;
2724 
2725   for (ExplodedNodeSet::iterator NI = Tmp.begin(), NE = Tmp.end();NI != NE;++NI)
2726     VisitAsmStmtHelperOutputs(A, I, E, *NI, Dst);
2727 }
2728 
2729 void ExprEngine::VisitAsmStmtHelperInputs(const AsmStmt* A,
2730                                             AsmStmt::const_inputs_iterator I,
2731                                             AsmStmt::const_inputs_iterator E,
2732                                             ExplodedNode* Pred,
2733                                             ExplodedNodeSet& Dst) {
2734   if (I == E) {
2735 
2736     // We have processed both the inputs and the outputs.  All of the outputs
2737     // should evaluate to Locs.  Nuke all of their values.
2738 
2739     // FIXME: Some day in the future it would be nice to allow a "plug-in"
2740     // which interprets the inline asm and stores proper results in the
2741     // outputs.
2742 
2743     const GRState* state = GetState(Pred);
2744 
2745     for (AsmStmt::const_outputs_iterator OI = A->begin_outputs(),
2746                                    OE = A->end_outputs(); OI != OE; ++OI) {
2747 
2748       SVal X = state->getSVal(*OI);
2749       assert (!isa<NonLoc>(X));  // Should be an Lval, or unknown, undef.
2750 
2751       if (isa<Loc>(X))
2752         state = state->bindLoc(cast<Loc>(X), UnknownVal());
2753     }
2754 
2755     MakeNode(Dst, A, Pred, state);
2756     return;
2757   }
2758 
2759   ExplodedNodeSet Tmp;
2760   Visit(*I, Pred, Tmp);
2761 
2762   ++I;
2763 
2764   for (ExplodedNodeSet::iterator NI = Tmp.begin(), NE = Tmp.end(); NI!=NE; ++NI)
2765     VisitAsmStmtHelperInputs(A, I, E, *NI, Dst);
2766 }
2767 
2768 void ExprEngine::VisitReturnStmt(const ReturnStmt *RS, ExplodedNode *Pred,
2769                                    ExplodedNodeSet &Dst) {
2770   ExplodedNodeSet Src;
2771   if (const Expr *RetE = RS->getRetValue()) {
2772     // Record the returned expression in the state. It will be used in
2773     // processCallExit to bind the return value to the call expr.
2774     {
2775       static int tag = 0;
2776       const GRState *state = GetState(Pred);
2777       state = state->set<ReturnExpr>(RetE);
2778       Pred = Builder->generateNode(RetE, state, Pred, &tag);
2779     }
2780     // We may get a NULL Pred because we generated a cached node.
2781     if (Pred)
2782       Visit(RetE, Pred, Src);
2783   }
2784   else {
2785     Src.Add(Pred);
2786   }
2787 
2788   ExplodedNodeSet CheckedSet;
2789   getCheckerManager().runCheckersForPreStmt(CheckedSet, Src, RS, *this);
2790 
2791   for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end();
2792        I != E; ++I) {
2793 
2794     assert(Builder && "StmtNodeBuilder must be defined.");
2795 
2796     Pred = *I;
2797     unsigned size = Dst.size();
2798 
2799     SaveAndRestore<bool> OldSink(Builder->BuildSinks);
2800     SaveOr OldHasGen(Builder->hasGeneratedNode);
2801 
2802     getTF().evalReturn(Dst, *this, *Builder, RS, Pred);
2803 
2804     // Handle the case where no nodes where generated.
2805     if (!Builder->BuildSinks && Dst.size() == size &&
2806         !Builder->hasGeneratedNode)
2807       MakeNode(Dst, RS, Pred, GetState(Pred));
2808   }
2809 }
2810 
2811 //===----------------------------------------------------------------------===//
2812 // Transfer functions: Binary operators.
2813 //===----------------------------------------------------------------------===//
2814 
2815 void ExprEngine::VisitBinaryOperator(const BinaryOperator* B,
2816                                        ExplodedNode* Pred,
2817                                        ExplodedNodeSet& Dst) {
2818   ExplodedNodeSet Tmp1;
2819   Expr* LHS = B->getLHS()->IgnoreParens();
2820   Expr* RHS = B->getRHS()->IgnoreParens();
2821 
2822   Visit(LHS, Pred, Tmp1);
2823   ExplodedNodeSet Tmp3;
2824 
2825   for (ExplodedNodeSet::iterator I1=Tmp1.begin(), E1=Tmp1.end(); I1!=E1; ++I1) {
2826     SVal LeftV = GetState(*I1)->getSVal(LHS);
2827     ExplodedNodeSet Tmp2;
2828     Visit(RHS, *I1, Tmp2);
2829 
2830     ExplodedNodeSet CheckedSet;
2831     getCheckerManager().runCheckersForPreStmt(CheckedSet, Tmp2, B, *this);
2832 
2833     // With both the LHS and RHS evaluated, process the operation itself.
2834 
2835     for (ExplodedNodeSet::iterator I2=CheckedSet.begin(), E2=CheckedSet.end();
2836          I2 != E2; ++I2) {
2837 
2838       const GRState *state = GetState(*I2);
2839       SVal RightV = state->getSVal(RHS);
2840 
2841       BinaryOperator::Opcode Op = B->getOpcode();
2842 
2843       if (Op == BO_Assign) {
2844         // EXPERIMENTAL: "Conjured" symbols.
2845         // FIXME: Handle structs.
2846         if (RightV.isUnknown() ||!getConstraintManager().canReasonAbout(RightV))
2847         {
2848           unsigned Count = Builder->getCurrentBlockCount();
2849           RightV = svalBuilder.getConjuredSymbolVal(NULL, B->getRHS(), Count);
2850         }
2851 
2852         SVal ExprVal = B->isLValue() ? LeftV : RightV;
2853 
2854         // Simulate the effects of a "store":  bind the value of the RHS
2855         // to the L-Value represented by the LHS.
2856         evalStore(Tmp3, B, LHS, *I2, state->BindExpr(B, ExprVal), LeftV,RightV);
2857         continue;
2858       }
2859 
2860       if (!B->isAssignmentOp()) {
2861         // Process non-assignments except commas or short-circuited
2862         // logical expressions (LAnd and LOr).
2863         SVal Result = evalBinOp(state, Op, LeftV, RightV, B->getType());
2864 
2865         if (Result.isUnknown()) {
2866           MakeNode(Tmp3, B, *I2, state);
2867           continue;
2868         }
2869 
2870         state = state->BindExpr(B, Result);
2871 
2872         MakeNode(Tmp3, B, *I2, state);
2873         continue;
2874       }
2875 
2876       assert (B->isCompoundAssignmentOp());
2877 
2878       switch (Op) {
2879         default:
2880           assert(0 && "Invalid opcode for compound assignment.");
2881         case BO_MulAssign: Op = BO_Mul; break;
2882         case BO_DivAssign: Op = BO_Div; break;
2883         case BO_RemAssign: Op = BO_Rem; break;
2884         case BO_AddAssign: Op = BO_Add; break;
2885         case BO_SubAssign: Op = BO_Sub; break;
2886         case BO_ShlAssign: Op = BO_Shl; break;
2887         case BO_ShrAssign: Op = BO_Shr; break;
2888         case BO_AndAssign: Op = BO_And; break;
2889         case BO_XorAssign: Op = BO_Xor; break;
2890         case BO_OrAssign:  Op = BO_Or;  break;
2891       }
2892 
2893       // Perform a load (the LHS).  This performs the checks for
2894       // null dereferences, and so on.
2895       ExplodedNodeSet Tmp4;
2896       SVal location = state->getSVal(LHS);
2897       evalLoad(Tmp4, LHS, *I2, state, location);
2898 
2899       for (ExplodedNodeSet::iterator I4=Tmp4.begin(), E4=Tmp4.end(); I4!=E4;
2900            ++I4) {
2901         state = GetState(*I4);
2902         SVal V = state->getSVal(LHS);
2903 
2904         // Get the computation type.
2905         QualType CTy =
2906           cast<CompoundAssignOperator>(B)->getComputationResultType();
2907         CTy = getContext().getCanonicalType(CTy);
2908 
2909         QualType CLHSTy =
2910           cast<CompoundAssignOperator>(B)->getComputationLHSType();
2911         CLHSTy = getContext().getCanonicalType(CLHSTy);
2912 
2913         QualType LTy = getContext().getCanonicalType(LHS->getType());
2914 
2915         // Promote LHS.
2916         V = svalBuilder.evalCast(V, CLHSTy, LTy);
2917 
2918         // Compute the result of the operation.
2919         SVal Result = svalBuilder.evalCast(evalBinOp(state, Op, V, RightV, CTy),
2920                                       B->getType(), CTy);
2921 
2922         // EXPERIMENTAL: "Conjured" symbols.
2923         // FIXME: Handle structs.
2924 
2925         SVal LHSVal;
2926 
2927         if (Result.isUnknown() ||
2928             !getConstraintManager().canReasonAbout(Result)) {
2929 
2930           unsigned Count = Builder->getCurrentBlockCount();
2931 
2932           // The symbolic value is actually for the type of the left-hand side
2933           // expression, not the computation type, as this is the value the
2934           // LValue on the LHS will bind to.
2935           LHSVal = svalBuilder.getConjuredSymbolVal(NULL, B->getRHS(), LTy, Count);
2936 
2937           // However, we need to convert the symbol to the computation type.
2938           Result = svalBuilder.evalCast(LHSVal, CTy, LTy);
2939         }
2940         else {
2941           // The left-hand side may bind to a different value then the
2942           // computation type.
2943           LHSVal = svalBuilder.evalCast(Result, LTy, CTy);
2944         }
2945 
2946         // In C++, assignment and compound assignment operators return an
2947         // lvalue.
2948         if (B->isLValue())
2949           state = state->BindExpr(B, location);
2950         else
2951           state = state->BindExpr(B, Result);
2952 
2953         evalStore(Tmp3, B, LHS, *I4, state, location, LHSVal);
2954       }
2955     }
2956   }
2957 
2958   getCheckerManager().runCheckersForPostStmt(Dst, Tmp3, B, *this);
2959 }
2960 
2961 //===----------------------------------------------------------------------===//
2962 // Visualization.
2963 //===----------------------------------------------------------------------===//
2964 
2965 #ifndef NDEBUG
2966 static ExprEngine* GraphPrintCheckerState;
2967 static SourceManager* GraphPrintSourceManager;
2968 
2969 namespace llvm {
2970 template<>
2971 struct DOTGraphTraits<ExplodedNode*> :
2972   public DefaultDOTGraphTraits {
2973 
2974   DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
2975 
2976   // FIXME: Since we do not cache error nodes in ExprEngine now, this does not
2977   // work.
2978   static std::string getNodeAttributes(const ExplodedNode* N, void*) {
2979 
2980 #if 0
2981       // FIXME: Replace with a general scheme to tell if the node is
2982       // an error node.
2983     if (GraphPrintCheckerState->isImplicitNullDeref(N) ||
2984         GraphPrintCheckerState->isExplicitNullDeref(N) ||
2985         GraphPrintCheckerState->isUndefDeref(N) ||
2986         GraphPrintCheckerState->isUndefStore(N) ||
2987         GraphPrintCheckerState->isUndefControlFlow(N) ||
2988         GraphPrintCheckerState->isUndefResult(N) ||
2989         GraphPrintCheckerState->isBadCall(N) ||
2990         GraphPrintCheckerState->isUndefArg(N))
2991       return "color=\"red\",style=\"filled\"";
2992 
2993     if (GraphPrintCheckerState->isNoReturnCall(N))
2994       return "color=\"blue\",style=\"filled\"";
2995 #endif
2996     return "";
2997   }
2998 
2999   static std::string getNodeLabel(const ExplodedNode* N, void*){
3000 
3001     std::string sbuf;
3002     llvm::raw_string_ostream Out(sbuf);
3003 
3004     // Program Location.
3005     ProgramPoint Loc = N->getLocation();
3006 
3007     switch (Loc.getKind()) {
3008       case ProgramPoint::BlockEntranceKind:
3009         Out << "Block Entrance: B"
3010             << cast<BlockEntrance>(Loc).getBlock()->getBlockID();
3011         break;
3012 
3013       case ProgramPoint::BlockExitKind:
3014         assert (false);
3015         break;
3016 
3017       case ProgramPoint::CallEnterKind:
3018         Out << "CallEnter";
3019         break;
3020 
3021       case ProgramPoint::CallExitKind:
3022         Out << "CallExit";
3023         break;
3024 
3025       default: {
3026         if (StmtPoint *L = dyn_cast<StmtPoint>(&Loc)) {
3027           const Stmt* S = L->getStmt();
3028           SourceLocation SLoc = S->getLocStart();
3029 
3030           Out << S->getStmtClassName() << ' ' << (void*) S << ' ';
3031           LangOptions LO; // FIXME.
3032           S->printPretty(Out, 0, PrintingPolicy(LO));
3033 
3034           if (SLoc.isFileID()) {
3035             Out << "\\lline="
3036               << GraphPrintSourceManager->getInstantiationLineNumber(SLoc)
3037               << " col="
3038               << GraphPrintSourceManager->getInstantiationColumnNumber(SLoc)
3039               << "\\l";
3040           }
3041 
3042           if (isa<PreStmt>(Loc))
3043             Out << "\\lPreStmt\\l;";
3044           else if (isa<PostLoad>(Loc))
3045             Out << "\\lPostLoad\\l;";
3046           else if (isa<PostStore>(Loc))
3047             Out << "\\lPostStore\\l";
3048           else if (isa<PostLValue>(Loc))
3049             Out << "\\lPostLValue\\l";
3050 
3051 #if 0
3052             // FIXME: Replace with a general scheme to determine
3053             // the name of the check.
3054           if (GraphPrintCheckerState->isImplicitNullDeref(N))
3055             Out << "\\|Implicit-Null Dereference.\\l";
3056           else if (GraphPrintCheckerState->isExplicitNullDeref(N))
3057             Out << "\\|Explicit-Null Dereference.\\l";
3058           else if (GraphPrintCheckerState->isUndefDeref(N))
3059             Out << "\\|Dereference of undefialied value.\\l";
3060           else if (GraphPrintCheckerState->isUndefStore(N))
3061             Out << "\\|Store to Undefined Loc.";
3062           else if (GraphPrintCheckerState->isUndefResult(N))
3063             Out << "\\|Result of operation is undefined.";
3064           else if (GraphPrintCheckerState->isNoReturnCall(N))
3065             Out << "\\|Call to function marked \"noreturn\".";
3066           else if (GraphPrintCheckerState->isBadCall(N))
3067             Out << "\\|Call to NULL/Undefined.";
3068           else if (GraphPrintCheckerState->isUndefArg(N))
3069             Out << "\\|Argument in call is undefined";
3070 #endif
3071 
3072           break;
3073         }
3074 
3075         const BlockEdge& E = cast<BlockEdge>(Loc);
3076         Out << "Edge: (B" << E.getSrc()->getBlockID() << ", B"
3077             << E.getDst()->getBlockID()  << ')';
3078 
3079         if (const Stmt* T = E.getSrc()->getTerminator()) {
3080 
3081           SourceLocation SLoc = T->getLocStart();
3082 
3083           Out << "\\|Terminator: ";
3084           LangOptions LO; // FIXME.
3085           E.getSrc()->printTerminator(Out, LO);
3086 
3087           if (SLoc.isFileID()) {
3088             Out << "\\lline="
3089               << GraphPrintSourceManager->getInstantiationLineNumber(SLoc)
3090               << " col="
3091               << GraphPrintSourceManager->getInstantiationColumnNumber(SLoc);
3092           }
3093 
3094           if (isa<SwitchStmt>(T)) {
3095             const Stmt* Label = E.getDst()->getLabel();
3096 
3097             if (Label) {
3098               if (const CaseStmt* C = dyn_cast<CaseStmt>(Label)) {
3099                 Out << "\\lcase ";
3100                 LangOptions LO; // FIXME.
3101                 C->getLHS()->printPretty(Out, 0, PrintingPolicy(LO));
3102 
3103                 if (const Stmt* RHS = C->getRHS()) {
3104                   Out << " .. ";
3105                   RHS->printPretty(Out, 0, PrintingPolicy(LO));
3106                 }
3107 
3108                 Out << ":";
3109               }
3110               else {
3111                 assert (isa<DefaultStmt>(Label));
3112                 Out << "\\ldefault:";
3113               }
3114             }
3115             else
3116               Out << "\\l(implicit) default:";
3117           }
3118           else if (isa<IndirectGotoStmt>(T)) {
3119             // FIXME
3120           }
3121           else {
3122             Out << "\\lCondition: ";
3123             if (*E.getSrc()->succ_begin() == E.getDst())
3124               Out << "true";
3125             else
3126               Out << "false";
3127           }
3128 
3129           Out << "\\l";
3130         }
3131 
3132 #if 0
3133           // FIXME: Replace with a general scheme to determine
3134           // the name of the check.
3135         if (GraphPrintCheckerState->isUndefControlFlow(N)) {
3136           Out << "\\|Control-flow based on\\lUndefined value.\\l";
3137         }
3138 #endif
3139       }
3140     }
3141 
3142     const GRState *state = N->getState();
3143     Out << "\\|StateID: " << (void*) state
3144         << " NodeID: " << (void*) N << "\\|";
3145     state->printDOT(Out, *N->getLocationContext()->getCFG());
3146     Out << "\\l";
3147     return Out.str();
3148   }
3149 };
3150 } // end llvm namespace
3151 #endif
3152 
3153 #ifndef NDEBUG
3154 template <typename ITERATOR>
3155 ExplodedNode* GetGraphNode(ITERATOR I) { return *I; }
3156 
3157 template <> ExplodedNode*
3158 GetGraphNode<llvm::DenseMap<ExplodedNode*, Expr*>::iterator>
3159   (llvm::DenseMap<ExplodedNode*, Expr*>::iterator I) {
3160   return I->first;
3161 }
3162 #endif
3163 
3164 void ExprEngine::ViewGraph(bool trim) {
3165 #ifndef NDEBUG
3166   if (trim) {
3167     std::vector<ExplodedNode*> Src;
3168 
3169     // Flush any outstanding reports to make sure we cover all the nodes.
3170     // This does not cause them to get displayed.
3171     for (BugReporter::iterator I=BR.begin(), E=BR.end(); I!=E; ++I)
3172       const_cast<BugType*>(*I)->FlushReports(BR);
3173 
3174     // Iterate through the reports and get their nodes.
3175     for (BugReporter::EQClasses_iterator
3176            EI = BR.EQClasses_begin(), EE = BR.EQClasses_end(); EI != EE; ++EI) {
3177       BugReportEquivClass& EQ = *EI;
3178       const BugReport &R = **EQ.begin();
3179       ExplodedNode *N = const_cast<ExplodedNode*>(R.getErrorNode());
3180       if (N) Src.push_back(N);
3181     }
3182 
3183     ViewGraph(&Src[0], &Src[0]+Src.size());
3184   }
3185   else {
3186     GraphPrintCheckerState = this;
3187     GraphPrintSourceManager = &getContext().getSourceManager();
3188 
3189     llvm::ViewGraph(*G.roots_begin(), "ExprEngine");
3190 
3191     GraphPrintCheckerState = NULL;
3192     GraphPrintSourceManager = NULL;
3193   }
3194 #endif
3195 }
3196 
3197 void ExprEngine::ViewGraph(ExplodedNode** Beg, ExplodedNode** End) {
3198 #ifndef NDEBUG
3199   GraphPrintCheckerState = this;
3200   GraphPrintSourceManager = &getContext().getSourceManager();
3201 
3202   std::auto_ptr<ExplodedGraph> TrimmedG(G.Trim(Beg, End).first);
3203 
3204   if (!TrimmedG.get())
3205     llvm::errs() << "warning: Trimmed ExplodedGraph is empty.\n";
3206   else
3207     llvm::ViewGraph(*TrimmedG->roots_begin(), "TrimmedExprEngine");
3208 
3209   GraphPrintCheckerState = NULL;
3210   GraphPrintSourceManager = NULL;
3211 #endif
3212 }
3213