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