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