[InstCombine] Re-commit of r218721 (Optimize icmp-select-icmp sequence)
[oota-llvm.git] / lib / IR / Value.cpp
1 //===-- Value.cpp - Implement the Value class -----------------------------===//
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 implements the Value, ValueHandle, and User classes.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/IR/Value.h"
15 #include "LLVMContextImpl.h"
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/ADT/SmallString.h"
18 #include "llvm/IR/CallSite.h"
19 #include "llvm/IR/Constant.h"
20 #include "llvm/IR/Constants.h"
21 #include "llvm/IR/DataLayout.h"
22 #include "llvm/IR/DerivedTypes.h"
23 #include "llvm/IR/GetElementPtrTypeIterator.h"
24 #include "llvm/IR/InstrTypes.h"
25 #include "llvm/IR/Instructions.h"
26 #include "llvm/IR/LeakDetector.h"
27 #include "llvm/IR/Module.h"
28 #include "llvm/IR/Operator.h"
29 #include "llvm/IR/ValueHandle.h"
30 #include "llvm/IR/ValueSymbolTable.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/ManagedStatic.h"
34 #include <algorithm>
35 using namespace llvm;
36
37 //===----------------------------------------------------------------------===//
38 //                                Value Class
39 //===----------------------------------------------------------------------===//
40
41 static inline Type *checkType(Type *Ty) {
42   assert(Ty && "Value defined with a null type: Error!");
43   return Ty;
44 }
45
46 Value::Value(Type *ty, unsigned scid)
47     : VTy(checkType(ty)), UseList(nullptr), Name(nullptr), SubclassID(scid),
48       HasValueHandle(0), SubclassOptionalData(0), SubclassData(0),
49       NumOperands(0) {
50   // FIXME: Why isn't this in the subclass gunk??
51   // Note, we cannot call isa<CallInst> before the CallInst has been
52   // constructed.
53   if (SubclassID == Instruction::Call || SubclassID == Instruction::Invoke)
54     assert((VTy->isFirstClassType() || VTy->isVoidTy() || VTy->isStructTy()) &&
55            "invalid CallInst type!");
56   else if (SubclassID != BasicBlockVal &&
57            (SubclassID < ConstantFirstVal || SubclassID > ConstantLastVal))
58     assert((VTy->isFirstClassType() || VTy->isVoidTy()) &&
59            "Cannot create non-first-class values except for constants!");
60 }
61
62 Value::~Value() {
63   // Notify all ValueHandles (if present) that this value is going away.
64   if (HasValueHandle)
65     ValueHandleBase::ValueIsDeleted(this);
66
67 #ifndef NDEBUG      // Only in -g mode...
68   // Check to make sure that there are no uses of this value that are still
69   // around when the value is destroyed.  If there are, then we have a dangling
70   // reference and something is wrong.  This code is here to print out what is
71   // still being referenced.  The value in question should be printed as
72   // a <badref>
73   //
74   if (!use_empty()) {
75     dbgs() << "While deleting: " << *VTy << " %" << getName() << "\n";
76     for (use_iterator I = use_begin(), E = use_end(); I != E; ++I)
77       dbgs() << "Use still stuck around after Def is destroyed:"
78            << **I << "\n";
79   }
80 #endif
81   assert(use_empty() && "Uses remain when a value is destroyed!");
82
83   // If this value is named, destroy the name.  This should not be in a symtab
84   // at this point.
85   if (Name && SubclassID != MDStringVal)
86     Name->Destroy();
87
88   // There should be no uses of this object anymore, remove it.
89   LeakDetector::removeGarbageObject(this);
90 }
91
92 bool Value::hasNUses(unsigned N) const {
93   const_use_iterator UI = use_begin(), E = use_end();
94
95   for (; N; --N, ++UI)
96     if (UI == E) return false;  // Too few.
97   return UI == E;
98 }
99
100 bool Value::hasNUsesOrMore(unsigned N) const {
101   const_use_iterator UI = use_begin(), E = use_end();
102
103   for (; N; --N, ++UI)
104     if (UI == E) return false;  // Too few.
105
106   return true;
107 }
108
109 bool Value::isUsedInBasicBlock(const BasicBlock *BB) const {
110   // This can be computed either by scanning the instructions in BB, or by
111   // scanning the use list of this Value. Both lists can be very long, but
112   // usually one is quite short.
113   //
114   // Scan both lists simultaneously until one is exhausted. This limits the
115   // search to the shorter list.
116   BasicBlock::const_iterator BI = BB->begin(), BE = BB->end();
117   const_user_iterator UI = user_begin(), UE = user_end();
118   for (; BI != BE && UI != UE; ++BI, ++UI) {
119     // Scan basic block: Check if this Value is used by the instruction at BI.
120     if (std::find(BI->op_begin(), BI->op_end(), this) != BI->op_end())
121       return true;
122     // Scan use list: Check if the use at UI is in BB.
123     const Instruction *User = dyn_cast<Instruction>(*UI);
124     if (User && User->getParent() == BB)
125       return true;
126   }
127   return false;
128 }
129
130 unsigned Value::getNumUses() const {
131   return (unsigned)std::distance(use_begin(), use_end());
132 }
133
134 static bool getSymTab(Value *V, ValueSymbolTable *&ST) {
135   ST = nullptr;
136   if (Instruction *I = dyn_cast<Instruction>(V)) {
137     if (BasicBlock *P = I->getParent())
138       if (Function *PP = P->getParent())
139         ST = &PP->getValueSymbolTable();
140   } else if (BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
141     if (Function *P = BB->getParent())
142       ST = &P->getValueSymbolTable();
143   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
144     if (Module *P = GV->getParent())
145       ST = &P->getValueSymbolTable();
146   } else if (Argument *A = dyn_cast<Argument>(V)) {
147     if (Function *P = A->getParent())
148       ST = &P->getValueSymbolTable();
149   } else if (isa<MDString>(V))
150     return true;
151   else {
152     assert(isa<Constant>(V) && "Unknown value type!");
153     return true;  // no name is setable for this.
154   }
155   return false;
156 }
157
158 StringRef Value::getName() const {
159   // Make sure the empty string is still a C string. For historical reasons,
160   // some clients want to call .data() on the result and expect it to be null
161   // terminated.
162   if (!Name) return StringRef("", 0);
163   return Name->getKey();
164 }
165
166 void Value::setName(const Twine &NewName) {
167   assert(SubclassID != MDStringVal &&
168          "Cannot set the name of MDString with this method!");
169
170   // Fast path for common IRBuilder case of setName("") when there is no name.
171   if (NewName.isTriviallyEmpty() && !hasName())
172     return;
173
174   SmallString<256> NameData;
175   StringRef NameRef = NewName.toStringRef(NameData);
176   assert(NameRef.find_first_of(0) == StringRef::npos &&
177          "Null bytes are not allowed in names");
178
179   // Name isn't changing?
180   if (getName() == NameRef)
181     return;
182
183   assert(!getType()->isVoidTy() && "Cannot assign a name to void values!");
184
185   // Get the symbol table to update for this object.
186   ValueSymbolTable *ST;
187   if (getSymTab(this, ST))
188     return;  // Cannot set a name on this value (e.g. constant).
189
190   if (Function *F = dyn_cast<Function>(this))
191     getContext().pImpl->IntrinsicIDCache.erase(F);
192
193   if (!ST) { // No symbol table to update?  Just do the change.
194     if (NameRef.empty()) {
195       // Free the name for this value.
196       Name->Destroy();
197       Name = nullptr;
198       return;
199     }
200
201     if (Name)
202       Name->Destroy();
203
204     // NOTE: Could optimize for the case the name is shrinking to not deallocate
205     // then reallocated.
206
207     // Create the new name.
208     Name = ValueName::Create(NameRef);
209     Name->setValue(this);
210     return;
211   }
212
213   // NOTE: Could optimize for the case the name is shrinking to not deallocate
214   // then reallocated.
215   if (hasName()) {
216     // Remove old name.
217     ST->removeValueName(Name);
218     Name->Destroy();
219     Name = nullptr;
220
221     if (NameRef.empty())
222       return;
223   }
224
225   // Name is changing to something new.
226   Name = ST->createValueName(NameRef, this);
227 }
228
229 void Value::takeName(Value *V) {
230   assert(SubclassID != MDStringVal && "Cannot take the name of an MDString!");
231
232   ValueSymbolTable *ST = nullptr;
233   // If this value has a name, drop it.
234   if (hasName()) {
235     // Get the symtab this is in.
236     if (getSymTab(this, ST)) {
237       // We can't set a name on this value, but we need to clear V's name if
238       // it has one.
239       if (V->hasName()) V->setName("");
240       return;  // Cannot set a name on this value (e.g. constant).
241     }
242
243     // Remove old name.
244     if (ST)
245       ST->removeValueName(Name);
246     Name->Destroy();
247     Name = nullptr;
248   }
249
250   // Now we know that this has no name.
251
252   // If V has no name either, we're done.
253   if (!V->hasName()) return;
254
255   // Get this's symtab if we didn't before.
256   if (!ST) {
257     if (getSymTab(this, ST)) {
258       // Clear V's name.
259       V->setName("");
260       return;  // Cannot set a name on this value (e.g. constant).
261     }
262   }
263
264   // Get V's ST, this should always succed, because V has a name.
265   ValueSymbolTable *VST;
266   bool Failure = getSymTab(V, VST);
267   assert(!Failure && "V has a name, so it should have a ST!"); (void)Failure;
268
269   // If these values are both in the same symtab, we can do this very fast.
270   // This works even if both values have no symtab yet.
271   if (ST == VST) {
272     // Take the name!
273     Name = V->Name;
274     V->Name = nullptr;
275     Name->setValue(this);
276     return;
277   }
278
279   // Otherwise, things are slightly more complex.  Remove V's name from VST and
280   // then reinsert it into ST.
281
282   if (VST)
283     VST->removeValueName(V->Name);
284   Name = V->Name;
285   V->Name = nullptr;
286   Name->setValue(this);
287
288   if (ST)
289     ST->reinsertValue(this);
290 }
291
292 #ifndef NDEBUG
293 static bool contains(SmallPtrSetImpl<ConstantExpr *> &Cache, ConstantExpr *Expr,
294                      Constant *C) {
295   if (!Cache.insert(Expr).second)
296     return false;
297
298   for (auto &O : Expr->operands()) {
299     if (O == C)
300       return true;
301     auto *CE = dyn_cast<ConstantExpr>(O);
302     if (!CE)
303       continue;
304     if (contains(Cache, CE, C))
305       return true;
306   }
307   return false;
308 }
309
310 static bool contains(Value *Expr, Value *V) {
311   if (Expr == V)
312     return true;
313
314   auto *C = dyn_cast<Constant>(V);
315   if (!C)
316     return false;
317
318   auto *CE = dyn_cast<ConstantExpr>(Expr);
319   if (!CE)
320     return false;
321
322   SmallPtrSet<ConstantExpr *, 4> Cache;
323   return contains(Cache, CE, C);
324 }
325 #endif
326
327 void Value::replaceAllUsesWith(Value *New) {
328   assert(New && "Value::replaceAllUsesWith(<null>) is invalid!");
329   assert(!contains(New, this) &&
330          "this->replaceAllUsesWith(expr(this)) is NOT valid!");
331   assert(New->getType() == getType() &&
332          "replaceAllUses of value with new value of different type!");
333
334   // Notify all ValueHandles (if present) that this value is going away.
335   if (HasValueHandle)
336     ValueHandleBase::ValueIsRAUWd(this, New);
337
338   while (!use_empty()) {
339     Use &U = *UseList;
340     // Must handle Constants specially, we cannot call replaceUsesOfWith on a
341     // constant because they are uniqued.
342     if (auto *C = dyn_cast<Constant>(U.getUser())) {
343       if (!isa<GlobalValue>(C)) {
344         C->replaceUsesOfWithOnConstant(this, New, &U);
345         continue;
346       }
347     }
348
349     U.set(New);
350   }
351
352   if (BasicBlock *BB = dyn_cast<BasicBlock>(this))
353     BB->replaceSuccessorsPhiUsesWith(cast<BasicBlock>(New));
354 }
355
356 // Like replaceAllUsesWith except it does not handle constants or basic blocks.
357 // This routine leaves uses within BB.
358 void Value::replaceUsesOutsideBlock(Value *New, BasicBlock *BB) {
359   assert(New && "Value::replaceUsesOutsideBlock(<null>, BB) is invalid!");
360   assert(!contains(New, this) &&
361          "this->replaceUsesOutsideBlock(expr(this), BB) is NOT valid!");
362   assert(New->getType() == getType() &&
363          "replaceUses of value with new value of different type!");
364   assert(BB && "Basic block that may contain a use of 'New' must be defined\n");
365
366   use_iterator UI = use_begin(), E = use_end();
367   for (; UI != E;) {
368     Use &U = *UI;
369     ++UI;
370     auto *Usr = dyn_cast<Instruction>(U.getUser());
371     if (Usr && Usr->getParent() == BB)
372       continue;
373     U.set(New);
374   }
375   return;
376 }
377
378 namespace {
379 // Various metrics for how much to strip off of pointers.
380 enum PointerStripKind {
381   PSK_ZeroIndices,
382   PSK_ZeroIndicesAndAliases,
383   PSK_InBoundsConstantIndices,
384   PSK_InBounds
385 };
386
387 template <PointerStripKind StripKind>
388 static Value *stripPointerCastsAndOffsets(Value *V) {
389   if (!V->getType()->isPointerTy())
390     return V;
391
392   // Even though we don't look through PHI nodes, we could be called on an
393   // instruction in an unreachable block, which may be on a cycle.
394   SmallPtrSet<Value *, 4> Visited;
395
396   Visited.insert(V);
397   do {
398     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
399       switch (StripKind) {
400       case PSK_ZeroIndicesAndAliases:
401       case PSK_ZeroIndices:
402         if (!GEP->hasAllZeroIndices())
403           return V;
404         break;
405       case PSK_InBoundsConstantIndices:
406         if (!GEP->hasAllConstantIndices())
407           return V;
408         // fallthrough
409       case PSK_InBounds:
410         if (!GEP->isInBounds())
411           return V;
412         break;
413       }
414       V = GEP->getPointerOperand();
415     } else if (Operator::getOpcode(V) == Instruction::BitCast ||
416                Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
417       V = cast<Operator>(V)->getOperand(0);
418     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
419       if (StripKind == PSK_ZeroIndices || GA->mayBeOverridden())
420         return V;
421       V = GA->getAliasee();
422     } else {
423       return V;
424     }
425     assert(V->getType()->isPointerTy() && "Unexpected operand type!");
426   } while (Visited.insert(V).second);
427
428   return V;
429 }
430 } // namespace
431
432 Value *Value::stripPointerCasts() {
433   return stripPointerCastsAndOffsets<PSK_ZeroIndicesAndAliases>(this);
434 }
435
436 Value *Value::stripPointerCastsNoFollowAliases() {
437   return stripPointerCastsAndOffsets<PSK_ZeroIndices>(this);
438 }
439
440 Value *Value::stripInBoundsConstantOffsets() {
441   return stripPointerCastsAndOffsets<PSK_InBoundsConstantIndices>(this);
442 }
443
444 Value *Value::stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL,
445                                                         APInt &Offset) {
446   if (!getType()->isPointerTy())
447     return this;
448
449   assert(Offset.getBitWidth() == DL.getPointerSizeInBits(cast<PointerType>(
450                                      getType())->getAddressSpace()) &&
451          "The offset must have exactly as many bits as our pointer.");
452
453   // Even though we don't look through PHI nodes, we could be called on an
454   // instruction in an unreachable block, which may be on a cycle.
455   SmallPtrSet<Value *, 4> Visited;
456   Visited.insert(this);
457   Value *V = this;
458   do {
459     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
460       if (!GEP->isInBounds())
461         return V;
462       APInt GEPOffset(Offset);
463       if (!GEP->accumulateConstantOffset(DL, GEPOffset))
464         return V;
465       Offset = GEPOffset;
466       V = GEP->getPointerOperand();
467     } else if (Operator::getOpcode(V) == Instruction::BitCast ||
468                Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
469       V = cast<Operator>(V)->getOperand(0);
470     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
471       V = GA->getAliasee();
472     } else {
473       return V;
474     }
475     assert(V->getType()->isPointerTy() && "Unexpected operand type!");
476   } while (Visited.insert(V).second);
477
478   return V;
479 }
480
481 Value *Value::stripInBoundsOffsets() {
482   return stripPointerCastsAndOffsets<PSK_InBounds>(this);
483 }
484
485 /// \brief Check if Value is always a dereferenceable pointer.
486 ///
487 /// Test if V is always a pointer to allocated and suitably aligned memory for
488 /// a simple load or store.
489 static bool isDereferenceablePointer(const Value *V, const DataLayout *DL,
490                                      SmallPtrSetImpl<const Value *> &Visited) {
491   // Note that it is not safe to speculate into a malloc'd region because
492   // malloc may return null.
493
494   // These are obviously ok.
495   if (isa<AllocaInst>(V)) return true;
496
497   // It's not always safe to follow a bitcast, for example:
498   //   bitcast i8* (alloca i8) to i32*
499   // would result in a 4-byte load from a 1-byte alloca. However,
500   // if we're casting from a pointer from a type of larger size
501   // to a type of smaller size (or the same size), and the alignment
502   // is at least as large as for the resulting pointer type, then
503   // we can look through the bitcast.
504   if (DL)
505     if (const BitCastInst* BC = dyn_cast<BitCastInst>(V)) {
506       Type *STy = BC->getSrcTy()->getPointerElementType(),
507            *DTy = BC->getDestTy()->getPointerElementType();
508       if (STy->isSized() && DTy->isSized() &&
509           (DL->getTypeStoreSize(STy) >=
510            DL->getTypeStoreSize(DTy)) &&
511           (DL->getABITypeAlignment(STy) >=
512            DL->getABITypeAlignment(DTy)))
513         return isDereferenceablePointer(BC->getOperand(0), DL, Visited);
514     }
515
516   // Global variables which can't collapse to null are ok.
517   if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
518     return !GV->hasExternalWeakLinkage();
519
520   // byval arguments are okay. Arguments specifically marked as
521   // dereferenceable are okay too.
522   if (const Argument *A = dyn_cast<Argument>(V)) {
523     if (A->hasByValAttr())
524       return true;
525     else if (uint64_t Bytes = A->getDereferenceableBytes()) {
526       Type *Ty = V->getType()->getPointerElementType();
527       if (Ty->isSized() && DL && DL->getTypeStoreSize(Ty) <= Bytes)
528         return true;
529     }
530
531     return false;
532   }
533
534   // Return values from call sites specifically marked as dereferenceable are
535   // also okay.
536   if (ImmutableCallSite CS = V) {
537     if (uint64_t Bytes = CS.getDereferenceableBytes(0)) {
538       Type *Ty = V->getType()->getPointerElementType();
539       if (Ty->isSized() && DL && DL->getTypeStoreSize(Ty) <= Bytes)
540         return true;
541     }
542   }
543
544   // For GEPs, determine if the indexing lands within the allocated object.
545   if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
546     // Conservatively require that the base pointer be fully dereferenceable.
547     if (!Visited.insert(GEP->getOperand(0)).second)
548       return false;
549     if (!isDereferenceablePointer(GEP->getOperand(0), DL, Visited))
550       return false;
551     // Check the indices.
552     gep_type_iterator GTI = gep_type_begin(GEP);
553     for (User::const_op_iterator I = GEP->op_begin()+1,
554          E = GEP->op_end(); I != E; ++I) {
555       Value *Index = *I;
556       Type *Ty = *GTI++;
557       // Struct indices can't be out of bounds.
558       if (isa<StructType>(Ty))
559         continue;
560       ConstantInt *CI = dyn_cast<ConstantInt>(Index);
561       if (!CI)
562         return false;
563       // Zero is always ok.
564       if (CI->isZero())
565         continue;
566       // Check to see that it's within the bounds of an array.
567       ArrayType *ATy = dyn_cast<ArrayType>(Ty);
568       if (!ATy)
569         return false;
570       if (CI->getValue().getActiveBits() > 64)
571         return false;
572       if (CI->getZExtValue() >= ATy->getNumElements())
573         return false;
574     }
575     // Indices check out; this is dereferenceable.
576     return true;
577   }
578
579   if (const AddrSpaceCastInst *ASC = dyn_cast<AddrSpaceCastInst>(V))
580     return isDereferenceablePointer(ASC->getOperand(0), DL, Visited);
581
582   // If we don't know, assume the worst.
583   return false;
584 }
585
586 bool Value::isDereferenceablePointer(const DataLayout *DL) const {
587   // When dereferenceability information is provided by a dereferenceable
588   // attribute, we know exactly how many bytes are dereferenceable. If we can
589   // determine the exact offset to the attributed variable, we can use that
590   // information here.
591   Type *Ty = getType()->getPointerElementType();
592   if (Ty->isSized() && DL) {
593     APInt Offset(DL->getTypeStoreSizeInBits(getType()), 0);
594     const Value *BV = stripAndAccumulateInBoundsConstantOffsets(*DL, Offset);
595
596     APInt DerefBytes(Offset.getBitWidth(), 0);
597     if (const Argument *A = dyn_cast<Argument>(BV))
598       DerefBytes = A->getDereferenceableBytes();
599     else if (ImmutableCallSite CS = BV)
600       DerefBytes = CS.getDereferenceableBytes(0);
601
602     if (DerefBytes.getBoolValue() && Offset.isNonNegative()) {
603       if (DerefBytes.uge(Offset + DL->getTypeStoreSize(Ty)))
604         return true;
605     }
606   }
607
608   SmallPtrSet<const Value *, 32> Visited;
609   return ::isDereferenceablePointer(this, DL, Visited);
610 }
611
612 Value *Value::DoPHITranslation(const BasicBlock *CurBB,
613                                const BasicBlock *PredBB) {
614   PHINode *PN = dyn_cast<PHINode>(this);
615   if (PN && PN->getParent() == CurBB)
616     return PN->getIncomingValueForBlock(PredBB);
617   return this;
618 }
619
620 LLVMContext &Value::getContext() const { return VTy->getContext(); }
621
622 void Value::reverseUseList() {
623   if (!UseList || !UseList->Next)
624     // No need to reverse 0 or 1 uses.
625     return;
626
627   Use *Head = UseList;
628   Use *Current = UseList->Next;
629   Head->Next = nullptr;
630   while (Current) {
631     Use *Next = Current->Next;
632     Current->Next = Head;
633     Head->setPrev(&Current->Next);
634     Head = Current;
635     Current = Next;
636   }
637   UseList = Head;
638   Head->setPrev(&UseList);
639 }
640
641 //===----------------------------------------------------------------------===//
642 //                             ValueHandleBase Class
643 //===----------------------------------------------------------------------===//
644
645 void ValueHandleBase::AddToExistingUseList(ValueHandleBase **List) {
646   assert(List && "Handle list is null?");
647
648   // Splice ourselves into the list.
649   Next = *List;
650   *List = this;
651   setPrevPtr(List);
652   if (Next) {
653     Next->setPrevPtr(&Next);
654     assert(VP.getPointer() == Next->VP.getPointer() && "Added to wrong list?");
655   }
656 }
657
658 void ValueHandleBase::AddToExistingUseListAfter(ValueHandleBase *List) {
659   assert(List && "Must insert after existing node");
660
661   Next = List->Next;
662   setPrevPtr(&List->Next);
663   List->Next = this;
664   if (Next)
665     Next->setPrevPtr(&Next);
666 }
667
668 void ValueHandleBase::AddToUseList() {
669   assert(VP.getPointer() && "Null pointer doesn't have a use list!");
670
671   LLVMContextImpl *pImpl = VP.getPointer()->getContext().pImpl;
672
673   if (VP.getPointer()->HasValueHandle) {
674     // If this value already has a ValueHandle, then it must be in the
675     // ValueHandles map already.
676     ValueHandleBase *&Entry = pImpl->ValueHandles[VP.getPointer()];
677     assert(Entry && "Value doesn't have any handles?");
678     AddToExistingUseList(&Entry);
679     return;
680   }
681
682   // Ok, it doesn't have any handles yet, so we must insert it into the
683   // DenseMap.  However, doing this insertion could cause the DenseMap to
684   // reallocate itself, which would invalidate all of the PrevP pointers that
685   // point into the old table.  Handle this by checking for reallocation and
686   // updating the stale pointers only if needed.
687   DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles;
688   const void *OldBucketPtr = Handles.getPointerIntoBucketsArray();
689
690   ValueHandleBase *&Entry = Handles[VP.getPointer()];
691   assert(!Entry && "Value really did already have handles?");
692   AddToExistingUseList(&Entry);
693   VP.getPointer()->HasValueHandle = true;
694
695   // If reallocation didn't happen or if this was the first insertion, don't
696   // walk the table.
697   if (Handles.isPointerIntoBucketsArray(OldBucketPtr) ||
698       Handles.size() == 1) {
699     return;
700   }
701
702   // Okay, reallocation did happen.  Fix the Prev Pointers.
703   for (DenseMap<Value*, ValueHandleBase*>::iterator I = Handles.begin(),
704        E = Handles.end(); I != E; ++I) {
705     assert(I->second && I->first == I->second->VP.getPointer() &&
706            "List invariant broken!");
707     I->second->setPrevPtr(&I->second);
708   }
709 }
710
711 void ValueHandleBase::RemoveFromUseList() {
712   assert(VP.getPointer() && VP.getPointer()->HasValueHandle &&
713          "Pointer doesn't have a use list!");
714
715   // Unlink this from its use list.
716   ValueHandleBase **PrevPtr = getPrevPtr();
717   assert(*PrevPtr == this && "List invariant broken");
718
719   *PrevPtr = Next;
720   if (Next) {
721     assert(Next->getPrevPtr() == &Next && "List invariant broken");
722     Next->setPrevPtr(PrevPtr);
723     return;
724   }
725
726   // If the Next pointer was null, then it is possible that this was the last
727   // ValueHandle watching VP.  If so, delete its entry from the ValueHandles
728   // map.
729   LLVMContextImpl *pImpl = VP.getPointer()->getContext().pImpl;
730   DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles;
731   if (Handles.isPointerIntoBucketsArray(PrevPtr)) {
732     Handles.erase(VP.getPointer());
733     VP.getPointer()->HasValueHandle = false;
734   }
735 }
736
737
738 void ValueHandleBase::ValueIsDeleted(Value *V) {
739   assert(V->HasValueHandle && "Should only be called if ValueHandles present");
740
741   // Get the linked list base, which is guaranteed to exist since the
742   // HasValueHandle flag is set.
743   LLVMContextImpl *pImpl = V->getContext().pImpl;
744   ValueHandleBase *Entry = pImpl->ValueHandles[V];
745   assert(Entry && "Value bit set but no entries exist");
746
747   // We use a local ValueHandleBase as an iterator so that ValueHandles can add
748   // and remove themselves from the list without breaking our iteration.  This
749   // is not really an AssertingVH; we just have to give ValueHandleBase a kind.
750   // Note that we deliberately do not the support the case when dropping a value
751   // handle results in a new value handle being permanently added to the list
752   // (as might occur in theory for CallbackVH's): the new value handle will not
753   // be processed and the checking code will mete out righteous punishment if
754   // the handle is still present once we have finished processing all the other
755   // value handles (it is fine to momentarily add then remove a value handle).
756   for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
757     Iterator.RemoveFromUseList();
758     Iterator.AddToExistingUseListAfter(Entry);
759     assert(Entry->Next == &Iterator && "Loop invariant broken.");
760
761     switch (Entry->getKind()) {
762     case Assert:
763       break;
764     case Tracking:
765       // Mark that this value has been deleted by setting it to an invalid Value
766       // pointer.
767       Entry->operator=(DenseMapInfo<Value *>::getTombstoneKey());
768       break;
769     case Weak:
770       // Weak just goes to null, which will unlink it from the list.
771       Entry->operator=(nullptr);
772       break;
773     case Callback:
774       // Forward to the subclass's implementation.
775       static_cast<CallbackVH*>(Entry)->deleted();
776       break;
777     }
778   }
779
780   // All callbacks, weak references, and assertingVHs should be dropped by now.
781   if (V->HasValueHandle) {
782 #ifndef NDEBUG      // Only in +Asserts mode...
783     dbgs() << "While deleting: " << *V->getType() << " %" << V->getName()
784            << "\n";
785     if (pImpl->ValueHandles[V]->getKind() == Assert)
786       llvm_unreachable("An asserting value handle still pointed to this"
787                        " value!");
788
789 #endif
790     llvm_unreachable("All references to V were not removed?");
791   }
792 }
793
794
795 void ValueHandleBase::ValueIsRAUWd(Value *Old, Value *New) {
796   assert(Old->HasValueHandle &&"Should only be called if ValueHandles present");
797   assert(Old != New && "Changing value into itself!");
798   assert(Old->getType() == New->getType() &&
799          "replaceAllUses of value with new value of different type!");
800
801   // Get the linked list base, which is guaranteed to exist since the
802   // HasValueHandle flag is set.
803   LLVMContextImpl *pImpl = Old->getContext().pImpl;
804   ValueHandleBase *Entry = pImpl->ValueHandles[Old];
805
806   assert(Entry && "Value bit set but no entries exist");
807
808   // We use a local ValueHandleBase as an iterator so that
809   // ValueHandles can add and remove themselves from the list without
810   // breaking our iteration.  This is not really an AssertingVH; we
811   // just have to give ValueHandleBase some kind.
812   for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
813     Iterator.RemoveFromUseList();
814     Iterator.AddToExistingUseListAfter(Entry);
815     assert(Entry->Next == &Iterator && "Loop invariant broken.");
816
817     switch (Entry->getKind()) {
818     case Assert:
819       // Asserting handle does not follow RAUW implicitly.
820       break;
821     case Tracking:
822       // Tracking goes to new value like a WeakVH. Note that this may make it
823       // something incompatible with its templated type. We don't want to have a
824       // virtual (or inline) interface to handle this though, so instead we make
825       // the TrackingVH accessors guarantee that a client never sees this value.
826
827       // FALLTHROUGH
828     case Weak:
829       // Weak goes to the new value, which will unlink it from Old's list.
830       Entry->operator=(New);
831       break;
832     case Callback:
833       // Forward to the subclass's implementation.
834       static_cast<CallbackVH*>(Entry)->allUsesReplacedWith(New);
835       break;
836     }
837   }
838
839 #ifndef NDEBUG
840   // If any new tracking or weak value handles were added while processing the
841   // list, then complain about it now.
842   if (Old->HasValueHandle)
843     for (Entry = pImpl->ValueHandles[Old]; Entry; Entry = Entry->Next)
844       switch (Entry->getKind()) {
845       case Tracking:
846       case Weak:
847         dbgs() << "After RAUW from " << *Old->getType() << " %"
848                << Old->getName() << " to " << *New->getType() << " %"
849                << New->getName() << "\n";
850         llvm_unreachable("A tracking or weak value handle still pointed to the"
851                          " old value!\n");
852       default:
853         break;
854       }
855 #endif
856 }
857
858 // Pin the vtable to this file.
859 void CallbackVH::anchor() {}