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