1 //===-- Local.cpp - Functions to perform local transformations ------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This family of functions perform various local transformations to the
13 //===----------------------------------------------------------------------===//
15 #include "llvm/Transforms/Utils/Local.h"
16 #include "llvm/Constants.h"
17 #include "llvm/GlobalAlias.h"
18 #include "llvm/GlobalVariable.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/Intrinsics.h"
22 #include "llvm/IntrinsicInst.h"
23 #include "llvm/ADT/DenseMap.h"
24 #include "llvm/ADT/SmallPtrSet.h"
25 #include "llvm/Analysis/Dominators.h"
26 #include "llvm/Analysis/ConstantFolding.h"
27 #include "llvm/Analysis/InstructionSimplify.h"
28 #include "llvm/Analysis/ProfileInfo.h"
29 #include "llvm/Analysis/ValueTracking.h"
30 #include "llvm/Target/TargetData.h"
31 #include "llvm/Support/CFG.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/GetElementPtrTypeIterator.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Support/ValueHandle.h"
36 #include "llvm/Support/raw_ostream.h"
39 //===----------------------------------------------------------------------===//
40 // Local constant propagation.
43 // ConstantFoldTerminator - If a terminator instruction is predicated on a
44 // constant value, convert it into an unconditional branch to the constant
47 bool llvm::ConstantFoldTerminator(BasicBlock *BB) {
48 TerminatorInst *T = BB->getTerminator();
50 // Branch - See if we are conditional jumping on constant
51 if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
52 if (BI->isUnconditional()) return false; // Can't optimize uncond branch
53 BasicBlock *Dest1 = BI->getSuccessor(0);
54 BasicBlock *Dest2 = BI->getSuccessor(1);
56 if (ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition())) {
57 // Are we branching on constant?
58 // YES. Change to unconditional branch...
59 BasicBlock *Destination = Cond->getZExtValue() ? Dest1 : Dest2;
60 BasicBlock *OldDest = Cond->getZExtValue() ? Dest2 : Dest1;
62 //cerr << "Function: " << T->getParent()->getParent()
63 // << "\nRemoving branch from " << T->getParent()
64 // << "\n\nTo: " << OldDest << endl;
66 // Let the basic block know that we are letting go of it. Based on this,
67 // it will adjust it's PHI nodes.
68 assert(BI->getParent() && "Terminator not inserted in block!");
69 OldDest->removePredecessor(BI->getParent());
71 // Replace the conditional branch with an unconditional one.
72 BranchInst::Create(Destination, BI);
73 BI->eraseFromParent();
77 if (Dest2 == Dest1) { // Conditional branch to same location?
78 // This branch matches something like this:
79 // br bool %cond, label %Dest, label %Dest
80 // and changes it into: br label %Dest
82 // Let the basic block know that we are letting go of one copy of it.
83 assert(BI->getParent() && "Terminator not inserted in block!");
84 Dest1->removePredecessor(BI->getParent());
86 // Replace the conditional branch with an unconditional one.
87 BranchInst::Create(Dest1, BI);
88 BI->eraseFromParent();
94 if (SwitchInst *SI = dyn_cast<SwitchInst>(T)) {
95 // If we are switching on a constant, we can convert the switch into a
96 // single branch instruction!
97 ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition());
98 BasicBlock *TheOnlyDest = SI->getSuccessor(0); // The default dest
99 BasicBlock *DefaultDest = TheOnlyDest;
100 assert(TheOnlyDest == SI->getDefaultDest() &&
101 "Default destination is not successor #0?");
103 // Figure out which case it goes to.
104 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
105 // Found case matching a constant operand?
106 if (SI->getSuccessorValue(i) == CI) {
107 TheOnlyDest = SI->getSuccessor(i);
111 // Check to see if this branch is going to the same place as the default
112 // dest. If so, eliminate it as an explicit compare.
113 if (SI->getSuccessor(i) == DefaultDest) {
114 // Remove this entry.
115 DefaultDest->removePredecessor(SI->getParent());
117 --i; --e; // Don't skip an entry...
121 // Otherwise, check to see if the switch only branches to one destination.
122 // We do this by reseting "TheOnlyDest" to null when we find two non-equal
124 if (SI->getSuccessor(i) != TheOnlyDest) TheOnlyDest = 0;
127 if (CI && !TheOnlyDest) {
128 // Branching on a constant, but not any of the cases, go to the default
130 TheOnlyDest = SI->getDefaultDest();
133 // If we found a single destination that we can fold the switch into, do so
136 // Insert the new branch.
137 BranchInst::Create(TheOnlyDest, SI);
138 BasicBlock *BB = SI->getParent();
140 // Remove entries from PHI nodes which we no longer branch to...
141 for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
142 // Found case matching a constant operand?
143 BasicBlock *Succ = SI->getSuccessor(i);
144 if (Succ == TheOnlyDest)
145 TheOnlyDest = 0; // Don't modify the first branch to TheOnlyDest
147 Succ->removePredecessor(BB);
150 // Delete the old switch.
151 BB->getInstList().erase(SI);
155 if (SI->getNumSuccessors() == 2) {
156 // Otherwise, we can fold this switch into a conditional branch
157 // instruction if it has only one non-default destination.
158 Value *Cond = new ICmpInst(SI, ICmpInst::ICMP_EQ, SI->getCondition(),
159 SI->getSuccessorValue(1), "cond");
160 // Insert the new branch.
161 BranchInst::Create(SI->getSuccessor(1), SI->getSuccessor(0), Cond, SI);
163 // Delete the old switch.
164 SI->eraseFromParent();
170 if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(T)) {
171 // indirectbr blockaddress(@F, @BB) -> br label @BB
172 if (BlockAddress *BA =
173 dyn_cast<BlockAddress>(IBI->getAddress()->stripPointerCasts())) {
174 BasicBlock *TheOnlyDest = BA->getBasicBlock();
175 // Insert the new branch.
176 BranchInst::Create(TheOnlyDest, IBI);
178 for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
179 if (IBI->getDestination(i) == TheOnlyDest)
182 IBI->getDestination(i)->removePredecessor(IBI->getParent());
184 IBI->eraseFromParent();
186 // If we didn't find our destination in the IBI successor list, then we
187 // have undefined behavior. Replace the unconditional branch with an
188 // 'unreachable' instruction.
190 BB->getTerminator()->eraseFromParent();
191 new UnreachableInst(BB->getContext(), BB);
202 //===----------------------------------------------------------------------===//
203 // Local dead code elimination.
206 /// isInstructionTriviallyDead - Return true if the result produced by the
207 /// instruction is not used, and the instruction has no side effects.
209 bool llvm::isInstructionTriviallyDead(Instruction *I) {
210 if (!I->use_empty() || isa<TerminatorInst>(I)) return false;
212 // We don't want debug info removed by anything this general.
213 if (isa<DbgInfoIntrinsic>(I)) return false;
215 if (!I->mayHaveSideEffects()) return true;
217 // Special case intrinsics that "may have side effects" but can be deleted
219 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
220 // Safe to delete llvm.stacksave if dead.
221 if (II->getIntrinsicID() == Intrinsic::stacksave)
226 /// RecursivelyDeleteTriviallyDeadInstructions - If the specified value is a
227 /// trivially dead instruction, delete it. If that makes any of its operands
228 /// trivially dead, delete them too, recursively. Return true if any
229 /// instructions were deleted.
230 bool llvm::RecursivelyDeleteTriviallyDeadInstructions(Value *V) {
231 Instruction *I = dyn_cast<Instruction>(V);
232 if (!I || !I->use_empty() || !isInstructionTriviallyDead(I))
235 SmallVector<Instruction*, 16> DeadInsts;
236 DeadInsts.push_back(I);
239 I = DeadInsts.pop_back_val();
241 // Null out all of the instruction's operands to see if any operand becomes
243 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
244 Value *OpV = I->getOperand(i);
247 if (!OpV->use_empty()) continue;
249 // If the operand is an instruction that became dead as we nulled out the
250 // operand, and if it is 'trivially' dead, delete it in a future loop
252 if (Instruction *OpI = dyn_cast<Instruction>(OpV))
253 if (isInstructionTriviallyDead(OpI))
254 DeadInsts.push_back(OpI);
257 I->eraseFromParent();
258 } while (!DeadInsts.empty());
263 /// areAllUsesEqual - Check whether the uses of a value are all the same.
264 /// This is similar to Instruction::hasOneUse() except this will also return
265 /// true when there are multiple uses that all refer to the same value.
266 static bool areAllUsesEqual(Instruction *I) {
267 Value::use_iterator UI = I->use_begin();
268 Value::use_iterator UE = I->use_end();
273 for (++UI; UI != UE; ++UI) {
280 /// RecursivelyDeleteDeadPHINode - If the specified value is an effectively
281 /// dead PHI node, due to being a def-use chain of single-use nodes that
282 /// either forms a cycle or is terminated by a trivially dead instruction,
283 /// delete it. If that makes any of its operands trivially dead, delete them
284 /// too, recursively. Return true if the PHI node is actually deleted.
285 bool llvm::RecursivelyDeleteDeadPHINode(PHINode *PN) {
286 // We can remove a PHI if it is on a cycle in the def-use graph
287 // where each node in the cycle has degree one, i.e. only one use,
288 // and is an instruction with no side effects.
289 if (!areAllUsesEqual(PN))
292 bool Changed = false;
293 SmallPtrSet<PHINode *, 4> PHIs;
295 for (Instruction *J = cast<Instruction>(*PN->use_begin());
296 areAllUsesEqual(J) && !J->mayHaveSideEffects();
297 J = cast<Instruction>(*J->use_begin()))
298 // If we find a PHI more than once, we're on a cycle that
299 // won't prove fruitful.
300 if (PHINode *JP = dyn_cast<PHINode>(J))
301 if (!PHIs.insert(JP)) {
302 // Break the cycle and delete the PHI and its operands.
303 JP->replaceAllUsesWith(UndefValue::get(JP->getType()));
304 (void)RecursivelyDeleteTriviallyDeadInstructions(JP);
311 /// SimplifyInstructionsInBlock - Scan the specified basic block and try to
312 /// simplify any instructions in it and recursively delete dead instructions.
314 /// This returns true if it changed the code, note that it can delete
315 /// instructions in other blocks as well in this block.
316 bool llvm::SimplifyInstructionsInBlock(BasicBlock *BB, const TargetData *TD) {
317 bool MadeChange = false;
318 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
319 Instruction *Inst = BI++;
321 if (Value *V = SimplifyInstruction(Inst, TD)) {
323 ReplaceAndSimplifyAllUses(Inst, V, TD);
330 MadeChange |= RecursivelyDeleteTriviallyDeadInstructions(Inst);
335 //===----------------------------------------------------------------------===//
336 // Control Flow Graph Restructuring.
340 /// RemovePredecessorAndSimplify - Like BasicBlock::removePredecessor, this
341 /// method is called when we're about to delete Pred as a predecessor of BB. If
342 /// BB contains any PHI nodes, this drops the entries in the PHI nodes for Pred.
344 /// Unlike the removePredecessor method, this attempts to simplify uses of PHI
345 /// nodes that collapse into identity values. For example, if we have:
346 /// x = phi(1, 0, 0, 0)
349 /// .. and delete the predecessor corresponding to the '1', this will attempt to
350 /// recursively fold the and to 0.
351 void llvm::RemovePredecessorAndSimplify(BasicBlock *BB, BasicBlock *Pred,
353 // This only adjusts blocks with PHI nodes.
354 if (!isa<PHINode>(BB->begin()))
357 // Remove the entries for Pred from the PHI nodes in BB, but do not simplify
358 // them down. This will leave us with single entry phi nodes and other phis
359 // that can be removed.
360 BB->removePredecessor(Pred, true);
362 WeakVH PhiIt = &BB->front();
363 while (PHINode *PN = dyn_cast<PHINode>(PhiIt)) {
364 PhiIt = &*++BasicBlock::iterator(cast<Instruction>(PhiIt));
366 Value *PNV = SimplifyInstruction(PN, TD);
367 if (PNV == 0) continue;
369 // If we're able to simplify the phi to a single value, substitute the new
370 // value into all of its uses.
371 assert(PNV != PN && "SimplifyInstruction broken!");
373 Value *OldPhiIt = PhiIt;
374 ReplaceAndSimplifyAllUses(PN, PNV, TD);
376 // If recursive simplification ended up deleting the next PHI node we would
377 // iterate to, then our iterator is invalid, restart scanning from the top
379 if (PhiIt != OldPhiIt) PhiIt = &BB->front();
384 /// MergeBasicBlockIntoOnlyPred - DestBB is a block with one predecessor and its
385 /// predecessor is known to have one successor (DestBB!). Eliminate the edge
386 /// between them, moving the instructions in the predecessor into DestBB and
387 /// deleting the predecessor block.
389 void llvm::MergeBasicBlockIntoOnlyPred(BasicBlock *DestBB, Pass *P) {
390 // If BB has single-entry PHI nodes, fold them.
391 while (PHINode *PN = dyn_cast<PHINode>(DestBB->begin())) {
392 Value *NewVal = PN->getIncomingValue(0);
393 // Replace self referencing PHI with undef, it must be dead.
394 if (NewVal == PN) NewVal = UndefValue::get(PN->getType());
395 PN->replaceAllUsesWith(NewVal);
396 PN->eraseFromParent();
399 BasicBlock *PredBB = DestBB->getSinglePredecessor();
400 assert(PredBB && "Block doesn't have a single predecessor!");
402 // Splice all the instructions from PredBB to DestBB.
403 PredBB->getTerminator()->eraseFromParent();
404 DestBB->getInstList().splice(DestBB->begin(), PredBB->getInstList());
406 // Zap anything that took the address of DestBB. Not doing this will give the
407 // address an invalid value.
408 if (DestBB->hasAddressTaken()) {
409 BlockAddress *BA = BlockAddress::get(DestBB);
410 Constant *Replacement =
411 ConstantInt::get(llvm::Type::getInt32Ty(BA->getContext()), 1);
412 BA->replaceAllUsesWith(ConstantExpr::getIntToPtr(Replacement,
414 BA->destroyConstant();
417 // Anything that branched to PredBB now branches to DestBB.
418 PredBB->replaceAllUsesWith(DestBB);
421 DominatorTree *DT = P->getAnalysisIfAvailable<DominatorTree>();
423 BasicBlock *PredBBIDom = DT->getNode(PredBB)->getIDom()->getBlock();
424 DT->changeImmediateDominator(DestBB, PredBBIDom);
425 DT->eraseNode(PredBB);
427 ProfileInfo *PI = P->getAnalysisIfAvailable<ProfileInfo>();
429 PI->replaceAllUses(PredBB, DestBB);
430 PI->removeEdge(ProfileInfo::getEdge(PredBB, DestBB));
434 PredBB->eraseFromParent();
437 /// CanPropagatePredecessorsForPHIs - Return true if we can fold BB, an
438 /// almost-empty BB ending in an unconditional branch to Succ, into succ.
440 /// Assumption: Succ is the single successor for BB.
442 static bool CanPropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
443 assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");
445 DEBUG(dbgs() << "Looking to fold " << BB->getName() << " into "
446 << Succ->getName() << "\n");
447 // Shortcut, if there is only a single predecessor it must be BB and merging
449 if (Succ->getSinglePredecessor()) return true;
451 // Make a list of the predecessors of BB
452 typedef SmallPtrSet<BasicBlock*, 16> BlockSet;
453 BlockSet BBPreds(pred_begin(BB), pred_end(BB));
455 // Use that list to make another list of common predecessors of BB and Succ
456 BlockSet CommonPreds;
457 for (pred_iterator PI = pred_begin(Succ), PE = pred_end(Succ);
460 if (BBPreds.count(P))
461 CommonPreds.insert(P);
464 // Shortcut, if there are no common predecessors, merging is always safe
465 if (CommonPreds.empty())
468 // Look at all the phi nodes in Succ, to see if they present a conflict when
469 // merging these blocks
470 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
471 PHINode *PN = cast<PHINode>(I);
473 // If the incoming value from BB is again a PHINode in
474 // BB which has the same incoming value for *PI as PN does, we can
475 // merge the phi nodes and then the blocks can still be merged
476 PHINode *BBPN = dyn_cast<PHINode>(PN->getIncomingValueForBlock(BB));
477 if (BBPN && BBPN->getParent() == BB) {
478 for (BlockSet::iterator PI = CommonPreds.begin(), PE = CommonPreds.end();
480 if (BBPN->getIncomingValueForBlock(*PI)
481 != PN->getIncomingValueForBlock(*PI)) {
482 DEBUG(dbgs() << "Can't fold, phi node " << PN->getName() << " in "
483 << Succ->getName() << " is conflicting with "
484 << BBPN->getName() << " with regard to common predecessor "
485 << (*PI)->getName() << "\n");
490 Value* Val = PN->getIncomingValueForBlock(BB);
491 for (BlockSet::iterator PI = CommonPreds.begin(), PE = CommonPreds.end();
493 // See if the incoming value for the common predecessor is equal to the
494 // one for BB, in which case this phi node will not prevent the merging
496 if (Val != PN->getIncomingValueForBlock(*PI)) {
497 DEBUG(dbgs() << "Can't fold, phi node " << PN->getName() << " in "
498 << Succ->getName() << " is conflicting with regard to common "
499 << "predecessor " << (*PI)->getName() << "\n");
509 /// TryToSimplifyUncondBranchFromEmptyBlock - BB is known to contain an
510 /// unconditional branch, and contains no instructions other than PHI nodes,
511 /// potential debug intrinsics and the branch. If possible, eliminate BB by
512 /// rewriting all the predecessors to branch to the successor block and return
513 /// true. If we can't transform, return false.
514 bool llvm::TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB) {
515 assert(BB != &BB->getParent()->getEntryBlock() &&
516 "TryToSimplifyUncondBranchFromEmptyBlock called on entry block!");
518 // We can't eliminate infinite loops.
519 BasicBlock *Succ = cast<BranchInst>(BB->getTerminator())->getSuccessor(0);
520 if (BB == Succ) return false;
522 // Check to see if merging these blocks would cause conflicts for any of the
523 // phi nodes in BB or Succ. If not, we can safely merge.
524 if (!CanPropagatePredecessorsForPHIs(BB, Succ)) return false;
526 // Check for cases where Succ has multiple predecessors and a PHI node in BB
527 // has uses which will not disappear when the PHI nodes are merged. It is
528 // possible to handle such cases, but difficult: it requires checking whether
529 // BB dominates Succ, which is non-trivial to calculate in the case where
530 // Succ has multiple predecessors. Also, it requires checking whether
531 // constructing the necessary self-referential PHI node doesn't intoduce any
532 // conflicts; this isn't too difficult, but the previous code for doing this
535 // Note that if this check finds a live use, BB dominates Succ, so BB is
536 // something like a loop pre-header (or rarely, a part of an irreducible CFG);
537 // folding the branch isn't profitable in that case anyway.
538 if (!Succ->getSinglePredecessor()) {
539 BasicBlock::iterator BBI = BB->begin();
540 while (isa<PHINode>(*BBI)) {
541 for (Value::use_iterator UI = BBI->use_begin(), E = BBI->use_end();
543 if (PHINode* PN = dyn_cast<PHINode>(*UI)) {
544 if (PN->getIncomingBlock(UI) != BB)
554 DEBUG(dbgs() << "Killing Trivial BB: \n" << *BB);
556 if (isa<PHINode>(Succ->begin())) {
557 // If there is more than one pred of succ, and there are PHI nodes in
558 // the successor, then we need to add incoming edges for the PHI nodes
560 const SmallVector<BasicBlock*, 16> BBPreds(pred_begin(BB), pred_end(BB));
562 // Loop over all of the PHI nodes in the successor of BB.
563 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
564 PHINode *PN = cast<PHINode>(I);
565 Value *OldVal = PN->removeIncomingValue(BB, false);
566 assert(OldVal && "No entry in PHI for Pred BB!");
568 // If this incoming value is one of the PHI nodes in BB, the new entries
569 // in the PHI node are the entries from the old PHI.
570 if (isa<PHINode>(OldVal) && cast<PHINode>(OldVal)->getParent() == BB) {
571 PHINode *OldValPN = cast<PHINode>(OldVal);
572 for (unsigned i = 0, e = OldValPN->getNumIncomingValues(); i != e; ++i)
573 // Note that, since we are merging phi nodes and BB and Succ might
574 // have common predecessors, we could end up with a phi node with
575 // identical incoming branches. This will be cleaned up later (and
576 // will trigger asserts if we try to clean it up now, without also
577 // simplifying the corresponding conditional branch).
578 PN->addIncoming(OldValPN->getIncomingValue(i),
579 OldValPN->getIncomingBlock(i));
581 // Add an incoming value for each of the new incoming values.
582 for (unsigned i = 0, e = BBPreds.size(); i != e; ++i)
583 PN->addIncoming(OldVal, BBPreds[i]);
588 while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
589 if (Succ->getSinglePredecessor()) {
590 // BB is the only predecessor of Succ, so Succ will end up with exactly
591 // the same predecessors BB had.
592 Succ->getInstList().splice(Succ->begin(),
593 BB->getInstList(), BB->begin());
595 // We explicitly check for such uses in CanPropagatePredecessorsForPHIs.
596 assert(PN->use_empty() && "There shouldn't be any uses here!");
597 PN->eraseFromParent();
601 // Everything that jumped to BB now goes to Succ.
602 BB->replaceAllUsesWith(Succ);
603 if (!Succ->hasName()) Succ->takeName(BB);
604 BB->eraseFromParent(); // Delete the old basic block.
608 /// EliminateDuplicatePHINodes - Check for and eliminate duplicate PHI
609 /// nodes in this block. This doesn't try to be clever about PHI nodes
610 /// which differ only in the order of the incoming values, but instcombine
611 /// orders them so it usually won't matter.
613 bool llvm::EliminateDuplicatePHINodes(BasicBlock *BB) {
614 bool Changed = false;
616 // This implementation doesn't currently consider undef operands
617 // specially. Theroetically, two phis which are identical except for
618 // one having an undef where the other doesn't could be collapsed.
620 // Map from PHI hash values to PHI nodes. If multiple PHIs have
621 // the same hash value, the element is the first PHI in the
622 // linked list in CollisionMap.
623 DenseMap<uintptr_t, PHINode *> HashMap;
625 // Maintain linked lists of PHI nodes with common hash values.
626 DenseMap<PHINode *, PHINode *> CollisionMap;
629 for (BasicBlock::iterator I = BB->begin();
630 PHINode *PN = dyn_cast<PHINode>(I++); ) {
631 // Compute a hash value on the operands. Instcombine will likely have sorted
632 // them, which helps expose duplicates, but we have to check all the
633 // operands to be safe in case instcombine hasn't run.
635 for (User::op_iterator I = PN->op_begin(), E = PN->op_end(); I != E; ++I) {
636 // This hash algorithm is quite weak as hash functions go, but it seems
637 // to do a good enough job for this particular purpose, and is very quick.
638 Hash ^= reinterpret_cast<uintptr_t>(static_cast<Value *>(*I));
639 Hash = (Hash << 7) | (Hash >> (sizeof(uintptr_t) * CHAR_BIT - 7));
641 // If we've never seen this hash value before, it's a unique PHI.
642 std::pair<DenseMap<uintptr_t, PHINode *>::iterator, bool> Pair =
643 HashMap.insert(std::make_pair(Hash, PN));
644 if (Pair.second) continue;
645 // Otherwise it's either a duplicate or a hash collision.
646 for (PHINode *OtherPN = Pair.first->second; ; ) {
647 if (OtherPN->isIdenticalTo(PN)) {
648 // A duplicate. Replace this PHI with its duplicate.
649 PN->replaceAllUsesWith(OtherPN);
650 PN->eraseFromParent();
654 // A non-duplicate hash collision.
655 DenseMap<PHINode *, PHINode *>::iterator I = CollisionMap.find(OtherPN);
656 if (I == CollisionMap.end()) {
657 // Set this PHI to be the head of the linked list of colliding PHIs.
658 PHINode *Old = Pair.first->second;
659 Pair.first->second = PN;
660 CollisionMap[PN] = Old;
663 // Procede to the next PHI in the list.
671 /// enforceKnownAlignment - If the specified pointer points to an object that
672 /// we control, modify the object's alignment to PrefAlign. This isn't
673 /// often possible though. If alignment is important, a more reliable approach
674 /// is to simply align all global variables and allocation instructions to
675 /// their preferred alignment from the beginning.
677 static unsigned enforceKnownAlignment(Value *V, unsigned Align,
678 unsigned PrefAlign) {
680 User *U = dyn_cast<User>(V);
681 if (!U) return Align;
683 switch (Operator::getOpcode(U)) {
685 case Instruction::BitCast:
686 return enforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
687 case Instruction::GetElementPtr: {
688 // If all indexes are zero, it is just the alignment of the base pointer.
689 bool AllZeroOperands = true;
690 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
691 if (!isa<Constant>(*i) ||
692 !cast<Constant>(*i)->isNullValue()) {
693 AllZeroOperands = false;
697 if (AllZeroOperands) {
698 // Treat this like a bitcast.
699 return enforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
703 case Instruction::Alloca: {
704 AllocaInst *AI = cast<AllocaInst>(V);
705 // If there is a requested alignment and if this is an alloca, round up.
706 if (AI->getAlignment() >= PrefAlign)
707 return AI->getAlignment();
708 AI->setAlignment(PrefAlign);
713 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
714 // If there is a large requested alignment and we can, bump up the alignment
716 if (GV->isDeclaration()) return Align;
718 if (GV->getAlignment() >= PrefAlign)
719 return GV->getAlignment();
720 // We can only increase the alignment of the global if it has no alignment
721 // specified or if it is not assigned a section. If it is assigned a
722 // section, the global could be densely packed with other objects in the
723 // section, increasing the alignment could cause padding issues.
724 if (!GV->hasSection() || GV->getAlignment() == 0)
725 GV->setAlignment(PrefAlign);
726 return GV->getAlignment();
732 /// getOrEnforceKnownAlignment - If the specified pointer has an alignment that
733 /// we can determine, return it, otherwise return 0. If PrefAlign is specified,
734 /// and it is more than the alignment of the ultimate object, see if we can
735 /// increase the alignment of the ultimate object, making this check succeed.
736 unsigned llvm::getOrEnforceKnownAlignment(Value *V, unsigned PrefAlign,
737 const TargetData *TD) {
738 assert(V->getType()->isPointerTy() &&
739 "getOrEnforceKnownAlignment expects a pointer!");
740 unsigned BitWidth = TD ? TD->getPointerSizeInBits() : 64;
741 APInt Mask = APInt::getAllOnesValue(BitWidth);
742 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
743 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD);
744 unsigned TrailZ = KnownZero.countTrailingOnes();
746 // Avoid trouble with rediculously large TrailZ values, such as
747 // those computed from a null pointer.
748 TrailZ = std::min(TrailZ, unsigned(sizeof(unsigned) * CHAR_BIT - 1));
750 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
752 // LLVM doesn't support alignments larger than this currently.
753 Align = std::min(Align, +Value::MaximumAlignment);
755 if (PrefAlign > Align)
756 Align = enforceKnownAlignment(V, Align, PrefAlign);
758 // We don't need to make any adjustment.