Chris Lattner | 28537df | 2002-05-07 18:07:59 +0000 | [diff] [blame] | 1 | //===-- Local.cpp - Functions to perform local transformations ------------===// |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 2 | // |
John Criswell | 482202a | 2003-10-20 19:43:21 +0000 | [diff] [blame] | 3 | // The LLVM Compiler Infrastructure |
| 4 | // |
Chris Lattner | f3ebc3f | 2007-12-29 20:36:04 +0000 | [diff] [blame] | 5 | // This file is distributed under the University of Illinois Open Source |
| 6 | // License. See LICENSE.TXT for details. |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 7 | // |
John Criswell | 482202a | 2003-10-20 19:43:21 +0000 | [diff] [blame] | 8 | //===----------------------------------------------------------------------===// |
Chris Lattner | 28537df | 2002-05-07 18:07:59 +0000 | [diff] [blame] | 9 | // |
| 10 | // This family of functions perform various local transformations to the |
| 11 | // program. |
| 12 | // |
| 13 | //===----------------------------------------------------------------------===// |
| 14 | |
| 15 | #include "llvm/Transforms/Utils/Local.h" |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 16 | #include "llvm/ADT/DenseMap.h" |
Benjamin Kramer | 2b2cdd7 | 2015-06-18 16:01:00 +0000 | [diff] [blame] | 17 | #include "llvm/ADT/DenseSet.h" |
| 18 | #include "llvm/ADT/Hashing.h" |
Evgeniy Stepanov | 4fbc0d08 | 2012-12-21 11:18:49 +0000 | [diff] [blame] | 19 | #include "llvm/ADT/STLExtras.h" |
Fiona Glaser | f74cc40 | 2015-09-28 18:56:07 +0000 | [diff] [blame] | 20 | #include "llvm/ADT/SetVector.h" |
Chandler Carruth | be81023 | 2013-01-02 10:22:59 +0000 | [diff] [blame] | 21 | #include "llvm/ADT/SmallPtrSet.h" |
Peter Collingbourne | 8d642de | 2013-08-12 22:38:43 +0000 | [diff] [blame] | 22 | #include "llvm/ADT/Statistic.h" |
David Majnemer | 70497c6 | 2015-12-02 23:06:39 +0000 | [diff] [blame] | 23 | #include "llvm/Analysis/EHPersonalities.h" |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 24 | #include "llvm/Analysis/InstructionSimplify.h" |
| 25 | #include "llvm/Analysis/MemoryBuiltins.h" |
David Majnemer | d9833ea | 2016-01-10 07:13:04 +0000 | [diff] [blame] | 26 | #include "llvm/Analysis/LazyValueInfo.h" |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 27 | #include "llvm/Analysis/ValueTracking.h" |
Chandler Carruth | 1305dc3 | 2014-03-04 11:45:46 +0000 | [diff] [blame] | 28 | #include "llvm/IR/CFG.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 29 | #include "llvm/IR/Constants.h" |
Chandler Carruth | 12664a0 | 2014-03-06 00:22:06 +0000 | [diff] [blame] | 30 | #include "llvm/IR/DIBuilder.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 31 | #include "llvm/IR/DataLayout.h" |
Chandler Carruth | 9a4c9e5 | 2014-03-06 00:46:21 +0000 | [diff] [blame] | 32 | #include "llvm/IR/DebugInfo.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 33 | #include "llvm/IR/DerivedTypes.h" |
Chandler Carruth | 5ad5f15 | 2014-01-13 09:26:24 +0000 | [diff] [blame] | 34 | #include "llvm/IR/Dominators.h" |
Chandler Carruth | 03eb0de | 2014-03-04 10:40:04 +0000 | [diff] [blame] | 35 | #include "llvm/IR/GetElementPtrTypeIterator.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 36 | #include "llvm/IR/GlobalAlias.h" |
| 37 | #include "llvm/IR/GlobalVariable.h" |
| 38 | #include "llvm/IR/IRBuilder.h" |
| 39 | #include "llvm/IR/Instructions.h" |
| 40 | #include "llvm/IR/IntrinsicInst.h" |
| 41 | #include "llvm/IR/Intrinsics.h" |
| 42 | #include "llvm/IR/MDBuilder.h" |
| 43 | #include "llvm/IR/Metadata.h" |
| 44 | #include "llvm/IR/Operator.h" |
David Majnemer | 9f50625 | 2016-06-25 08:34:38 +0000 | [diff] [blame] | 45 | #include "llvm/IR/PatternMatch.h" |
Chandler Carruth | 4220e9c | 2014-03-04 11:17:44 +0000 | [diff] [blame] | 46 | #include "llvm/IR/ValueHandle.h" |
Chris Lattner | cbd18fc | 2009-11-10 05:59:26 +0000 | [diff] [blame] | 47 | #include "llvm/Support/Debug.h" |
Chris Lattner | c13c7b9 | 2005-09-26 05:27:10 +0000 | [diff] [blame] | 48 | #include "llvm/Support/MathExtras.h" |
Chris Lattner | cbd18fc | 2009-11-10 05:59:26 +0000 | [diff] [blame] | 49 | #include "llvm/Support/raw_ostream.h" |
Chris Lattner | 04efa4b | 2003-12-19 05:56:28 +0000 | [diff] [blame] | 50 | using namespace llvm; |
David Majnemer | 9f50625 | 2016-06-25 08:34:38 +0000 | [diff] [blame] | 51 | using namespace llvm::PatternMatch; |
Brian Gaeke | 960707c | 2003-11-11 22:41:34 +0000 | [diff] [blame] | 52 | |
Chandler Carruth | e96dd89 | 2014-04-21 22:55:11 +0000 | [diff] [blame] | 53 | #define DEBUG_TYPE "local" |
| 54 | |
Peter Collingbourne | 8d642de | 2013-08-12 22:38:43 +0000 | [diff] [blame] | 55 | STATISTIC(NumRemoved, "Number of unreachable basic blocks removed"); |
| 56 | |
Chris Lattner | 28537df | 2002-05-07 18:07:59 +0000 | [diff] [blame] | 57 | //===----------------------------------------------------------------------===// |
Chris Lattner | c6c481c | 2008-11-27 22:57:53 +0000 | [diff] [blame] | 58 | // Local constant propagation. |
Chris Lattner | 28537df | 2002-05-07 18:07:59 +0000 | [diff] [blame] | 59 | // |
| 60 | |
Frits van Bommel | ad96455 | 2011-05-22 16:24:18 +0000 | [diff] [blame] | 61 | /// ConstantFoldTerminator - If a terminator instruction is predicated on a |
| 62 | /// constant value, convert it into an unconditional branch to the constant |
| 63 | /// destination. This is a nontrivial operation because the successors of this |
| 64 | /// basic block must have their PHI nodes updated. |
| 65 | /// Also calls RecursivelyDeleteTriviallyDeadInstructions() on any branch/switch |
| 66 | /// conditions and indirectbr addresses this might make dead if |
| 67 | /// DeleteDeadConditions is true. |
Benjamin Kramer | 8bcc971 | 2012-08-29 15:32:21 +0000 | [diff] [blame] | 68 | bool llvm::ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions, |
| 69 | const TargetLibraryInfo *TLI) { |
Chris Lattner | 4b009ad | 2002-05-21 20:04:50 +0000 | [diff] [blame] | 70 | TerminatorInst *T = BB->getTerminator(); |
Devang Patel | 1fabbe9 | 2011-05-18 17:26:46 +0000 | [diff] [blame] | 71 | IRBuilder<> Builder(T); |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 72 | |
Chris Lattner | 28537df | 2002-05-07 18:07:59 +0000 | [diff] [blame] | 73 | // Branch - See if we are conditional jumping on constant |
| 74 | if (BranchInst *BI = dyn_cast<BranchInst>(T)) { |
| 75 | if (BI->isUnconditional()) return false; // Can't optimize uncond branch |
Gabor Greif | 97f1720 | 2009-01-30 18:21:13 +0000 | [diff] [blame] | 76 | BasicBlock *Dest1 = BI->getSuccessor(0); |
| 77 | BasicBlock *Dest2 = BI->getSuccessor(1); |
Chris Lattner | 28537df | 2002-05-07 18:07:59 +0000 | [diff] [blame] | 78 | |
Zhou Sheng | 75b871f | 2007-01-11 12:24:14 +0000 | [diff] [blame] | 79 | if (ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition())) { |
Chris Lattner | 28537df | 2002-05-07 18:07:59 +0000 | [diff] [blame] | 80 | // Are we branching on constant? |
| 81 | // YES. Change to unconditional branch... |
Reid Spencer | cddc9df | 2007-01-12 04:24:46 +0000 | [diff] [blame] | 82 | BasicBlock *Destination = Cond->getZExtValue() ? Dest1 : Dest2; |
| 83 | BasicBlock *OldDest = Cond->getZExtValue() ? Dest2 : Dest1; |
Chris Lattner | 28537df | 2002-05-07 18:07:59 +0000 | [diff] [blame] | 84 | |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 85 | //cerr << "Function: " << T->getParent()->getParent() |
| 86 | // << "\nRemoving branch from " << T->getParent() |
Chris Lattner | 28537df | 2002-05-07 18:07:59 +0000 | [diff] [blame] | 87 | // << "\n\nTo: " << OldDest << endl; |
| 88 | |
| 89 | // Let the basic block know that we are letting go of it. Based on this, |
| 90 | // it will adjust it's PHI nodes. |
Jay Foad | 6a85be2 | 2011-04-19 15:23:29 +0000 | [diff] [blame] | 91 | OldDest->removePredecessor(BB); |
Chris Lattner | 28537df | 2002-05-07 18:07:59 +0000 | [diff] [blame] | 92 | |
Jay Foad | 89afb43 | 2011-01-07 20:25:56 +0000 | [diff] [blame] | 93 | // Replace the conditional branch with an unconditional one. |
Devang Patel | 1fabbe9 | 2011-05-18 17:26:46 +0000 | [diff] [blame] | 94 | Builder.CreateBr(Destination); |
Jay Foad | 89afb43 | 2011-01-07 20:25:56 +0000 | [diff] [blame] | 95 | BI->eraseFromParent(); |
Chris Lattner | 28537df | 2002-05-07 18:07:59 +0000 | [diff] [blame] | 96 | return true; |
Chris Lattner | 54a4b84 | 2009-11-01 03:40:38 +0000 | [diff] [blame] | 97 | } |
Jakub Staszak | 8e1a6e7 | 2013-07-22 23:16:36 +0000 | [diff] [blame] | 98 | |
Chris Lattner | 54a4b84 | 2009-11-01 03:40:38 +0000 | [diff] [blame] | 99 | if (Dest2 == Dest1) { // Conditional branch to same location? |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 100 | // This branch matches something like this: |
Chris Lattner | 28537df | 2002-05-07 18:07:59 +0000 | [diff] [blame] | 101 | // br bool %cond, label %Dest, label %Dest |
| 102 | // and changes it into: br label %Dest |
| 103 | |
| 104 | // Let the basic block know that we are letting go of one copy of it. |
| 105 | assert(BI->getParent() && "Terminator not inserted in block!"); |
| 106 | Dest1->removePredecessor(BI->getParent()); |
| 107 | |
Jay Foad | 89afb43 | 2011-01-07 20:25:56 +0000 | [diff] [blame] | 108 | // Replace the conditional branch with an unconditional one. |
Devang Patel | 1fabbe9 | 2011-05-18 17:26:46 +0000 | [diff] [blame] | 109 | Builder.CreateBr(Dest1); |
Frits van Bommel | ad96455 | 2011-05-22 16:24:18 +0000 | [diff] [blame] | 110 | Value *Cond = BI->getCondition(); |
Jay Foad | 89afb43 | 2011-01-07 20:25:56 +0000 | [diff] [blame] | 111 | BI->eraseFromParent(); |
Frits van Bommel | ad96455 | 2011-05-22 16:24:18 +0000 | [diff] [blame] | 112 | if (DeleteDeadConditions) |
Benjamin Kramer | 8bcc971 | 2012-08-29 15:32:21 +0000 | [diff] [blame] | 113 | RecursivelyDeleteTriviallyDeadInstructions(Cond, TLI); |
Chris Lattner | 28537df | 2002-05-07 18:07:59 +0000 | [diff] [blame] | 114 | return true; |
| 115 | } |
Chris Lattner | 54a4b84 | 2009-11-01 03:40:38 +0000 | [diff] [blame] | 116 | return false; |
| 117 | } |
Jakub Staszak | 8e1a6e7 | 2013-07-22 23:16:36 +0000 | [diff] [blame] | 118 | |
Chris Lattner | 54a4b84 | 2009-11-01 03:40:38 +0000 | [diff] [blame] | 119 | if (SwitchInst *SI = dyn_cast<SwitchInst>(T)) { |
Hans Wennborg | 90b827c | 2015-01-26 19:52:24 +0000 | [diff] [blame] | 120 | // If we are switching on a constant, we can convert the switch to an |
| 121 | // unconditional branch. |
Chris Lattner | 821deee | 2003-08-17 20:21:14 +0000 | [diff] [blame] | 122 | ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition()); |
Hans Wennborg | 90b827c | 2015-01-26 19:52:24 +0000 | [diff] [blame] | 123 | BasicBlock *DefaultDest = SI->getDefaultDest(); |
| 124 | BasicBlock *TheOnlyDest = DefaultDest; |
| 125 | |
| 126 | // If the default is unreachable, ignore it when searching for TheOnlyDest. |
| 127 | if (isa<UnreachableInst>(DefaultDest->getFirstNonPHIOrDbg()) && |
| 128 | SI->getNumCases() > 0) { |
Chandler Carruth | 927d8e6 | 2017-04-12 07:27:28 +0000 | [diff] [blame] | 129 | TheOnlyDest = SI->case_begin()->getCaseSuccessor(); |
Hans Wennborg | 90b827c | 2015-01-26 19:52:24 +0000 | [diff] [blame] | 130 | } |
Chris Lattner | 031340a | 2003-08-17 19:41:53 +0000 | [diff] [blame] | 131 | |
Chris Lattner | 54a4b84 | 2009-11-01 03:40:38 +0000 | [diff] [blame] | 132 | // Figure out which case it goes to. |
Chandler Carruth | 0d256c0 | 2017-03-26 02:49:23 +0000 | [diff] [blame] | 133 | for (auto i = SI->case_begin(), e = SI->case_end(); i != e;) { |
Chris Lattner | 821deee | 2003-08-17 20:21:14 +0000 | [diff] [blame] | 134 | // Found case matching a constant operand? |
Chandler Carruth | 927d8e6 | 2017-04-12 07:27:28 +0000 | [diff] [blame] | 135 | if (i->getCaseValue() == CI) { |
| 136 | TheOnlyDest = i->getCaseSuccessor(); |
Chris Lattner | 821deee | 2003-08-17 20:21:14 +0000 | [diff] [blame] | 137 | break; |
| 138 | } |
Chris Lattner | 031340a | 2003-08-17 19:41:53 +0000 | [diff] [blame] | 139 | |
Chris Lattner | c54d608 | 2003-08-23 23:18:19 +0000 | [diff] [blame] | 140 | // Check to see if this branch is going to the same place as the default |
| 141 | // dest. If so, eliminate it as an explicit compare. |
Chandler Carruth | 927d8e6 | 2017-04-12 07:27:28 +0000 | [diff] [blame] | 142 | if (i->getCaseSuccessor() == DefaultDest) { |
Duncan P. N. Exon Smith | de36e80 | 2014-11-11 21:30:22 +0000 | [diff] [blame] | 143 | MDNode *MD = SI->getMetadata(LLVMContext::MD_prof); |
Justin Bogner | a41a7b3 | 2013-12-10 00:13:41 +0000 | [diff] [blame] | 144 | unsigned NCases = SI->getNumCases(); |
| 145 | // Fold the case metadata into the default if there will be any branches |
| 146 | // left, unless the metadata doesn't match the switch. |
| 147 | if (NCases > 1 && MD && MD->getNumOperands() == 2 + NCases) { |
Manman Ren | 49dbe25 | 2012-09-12 17:04:11 +0000 | [diff] [blame] | 148 | // Collect branch weights into a vector. |
| 149 | SmallVector<uint32_t, 8> Weights; |
| 150 | for (unsigned MD_i = 1, MD_e = MD->getNumOperands(); MD_i < MD_e; |
| 151 | ++MD_i) { |
David Majnemer | 9f50625 | 2016-06-25 08:34:38 +0000 | [diff] [blame] | 152 | auto *CI = mdconst::extract<ConstantInt>(MD->getOperand(MD_i)); |
Manman Ren | 49dbe25 | 2012-09-12 17:04:11 +0000 | [diff] [blame] | 153 | Weights.push_back(CI->getValue().getZExtValue()); |
| 154 | } |
| 155 | // Merge weight of this case to the default weight. |
Chandler Carruth | 927d8e6 | 2017-04-12 07:27:28 +0000 | [diff] [blame] | 156 | unsigned idx = i->getCaseIndex(); |
Manman Ren | 49dbe25 | 2012-09-12 17:04:11 +0000 | [diff] [blame] | 157 | Weights[0] += Weights[idx+1]; |
| 158 | // Remove weight for this case. |
| 159 | std::swap(Weights[idx+1], Weights.back()); |
| 160 | Weights.pop_back(); |
| 161 | SI->setMetadata(LLVMContext::MD_prof, |
| 162 | MDBuilder(BB->getContext()). |
| 163 | createBranchWeights(Weights)); |
| 164 | } |
Chris Lattner | 54a4b84 | 2009-11-01 03:40:38 +0000 | [diff] [blame] | 165 | // Remove this entry. |
Chris Lattner | c54d608 | 2003-08-23 23:18:19 +0000 | [diff] [blame] | 166 | DefaultDest->removePredecessor(SI->getParent()); |
Chandler Carruth | 0d256c0 | 2017-03-26 02:49:23 +0000 | [diff] [blame] | 167 | i = SI->removeCase(i); |
| 168 | e = SI->case_end(); |
Chris Lattner | c54d608 | 2003-08-23 23:18:19 +0000 | [diff] [blame] | 169 | continue; |
| 170 | } |
| 171 | |
Chris Lattner | 821deee | 2003-08-17 20:21:14 +0000 | [diff] [blame] | 172 | // Otherwise, check to see if the switch only branches to one destination. |
| 173 | // We do this by reseting "TheOnlyDest" to null when we find two non-equal |
| 174 | // destinations. |
Chandler Carruth | 927d8e6 | 2017-04-12 07:27:28 +0000 | [diff] [blame] | 175 | if (i->getCaseSuccessor() != TheOnlyDest) |
| 176 | TheOnlyDest = nullptr; |
Chandler Carruth | 0d256c0 | 2017-03-26 02:49:23 +0000 | [diff] [blame] | 177 | |
| 178 | // Increment this iterator as we haven't removed the case. |
| 179 | ++i; |
Chris Lattner | 031340a | 2003-08-17 19:41:53 +0000 | [diff] [blame] | 180 | } |
| 181 | |
Chris Lattner | 821deee | 2003-08-17 20:21:14 +0000 | [diff] [blame] | 182 | if (CI && !TheOnlyDest) { |
| 183 | // Branching on a constant, but not any of the cases, go to the default |
| 184 | // successor. |
| 185 | TheOnlyDest = SI->getDefaultDest(); |
| 186 | } |
| 187 | |
| 188 | // If we found a single destination that we can fold the switch into, do so |
| 189 | // now. |
| 190 | if (TheOnlyDest) { |
Chris Lattner | 54a4b84 | 2009-11-01 03:40:38 +0000 | [diff] [blame] | 191 | // Insert the new branch. |
Devang Patel | 1fabbe9 | 2011-05-18 17:26:46 +0000 | [diff] [blame] | 192 | Builder.CreateBr(TheOnlyDest); |
Chris Lattner | 821deee | 2003-08-17 20:21:14 +0000 | [diff] [blame] | 193 | BasicBlock *BB = SI->getParent(); |
| 194 | |
| 195 | // Remove entries from PHI nodes which we no longer branch to... |
Pete Cooper | ebcd748 | 2015-08-06 20:22:46 +0000 | [diff] [blame] | 196 | for (BasicBlock *Succ : SI->successors()) { |
Chris Lattner | 821deee | 2003-08-17 20:21:14 +0000 | [diff] [blame] | 197 | // Found case matching a constant operand? |
Chris Lattner | 821deee | 2003-08-17 20:21:14 +0000 | [diff] [blame] | 198 | if (Succ == TheOnlyDest) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 199 | TheOnlyDest = nullptr; // Don't modify the first branch to TheOnlyDest |
Chris Lattner | 821deee | 2003-08-17 20:21:14 +0000 | [diff] [blame] | 200 | else |
| 201 | Succ->removePredecessor(BB); |
| 202 | } |
| 203 | |
Chris Lattner | 54a4b84 | 2009-11-01 03:40:38 +0000 | [diff] [blame] | 204 | // Delete the old switch. |
Frits van Bommel | ad96455 | 2011-05-22 16:24:18 +0000 | [diff] [blame] | 205 | Value *Cond = SI->getCondition(); |
| 206 | SI->eraseFromParent(); |
| 207 | if (DeleteDeadConditions) |
Benjamin Kramer | 8bcc971 | 2012-08-29 15:32:21 +0000 | [diff] [blame] | 208 | RecursivelyDeleteTriviallyDeadInstructions(Cond, TLI); |
Chris Lattner | 821deee | 2003-08-17 20:21:14 +0000 | [diff] [blame] | 209 | return true; |
Chris Lattner | 54a4b84 | 2009-11-01 03:40:38 +0000 | [diff] [blame] | 210 | } |
Jakub Staszak | 8e1a6e7 | 2013-07-22 23:16:36 +0000 | [diff] [blame] | 211 | |
Stepan Dyatkovskiy | 513aaa5 | 2012-02-01 07:49:51 +0000 | [diff] [blame] | 212 | if (SI->getNumCases() == 1) { |
Chris Lattner | 821deee | 2003-08-17 20:21:14 +0000 | [diff] [blame] | 213 | // Otherwise, we can fold this switch into a conditional branch |
| 214 | // instruction if it has only one non-default destination. |
Chandler Carruth | 927d8e6 | 2017-04-12 07:27:28 +0000 | [diff] [blame] | 215 | auto FirstCase = *SI->case_begin(); |
Bob Wilson | e407736 | 2013-09-09 19:14:35 +0000 | [diff] [blame] | 216 | Value *Cond = Builder.CreateICmpEQ(SI->getCondition(), |
| 217 | FirstCase.getCaseValue(), "cond"); |
Devang Patel | 1fabbe9 | 2011-05-18 17:26:46 +0000 | [diff] [blame] | 218 | |
Bob Wilson | e407736 | 2013-09-09 19:14:35 +0000 | [diff] [blame] | 219 | // Insert the new branch. |
| 220 | BranchInst *NewBr = Builder.CreateCondBr(Cond, |
| 221 | FirstCase.getCaseSuccessor(), |
| 222 | SI->getDefaultDest()); |
Duncan P. N. Exon Smith | de36e80 | 2014-11-11 21:30:22 +0000 | [diff] [blame] | 223 | MDNode *MD = SI->getMetadata(LLVMContext::MD_prof); |
Bob Wilson | e407736 | 2013-09-09 19:14:35 +0000 | [diff] [blame] | 224 | if (MD && MD->getNumOperands() == 3) { |
Duncan P. N. Exon Smith | 5bf8fef | 2014-12-09 18:38:53 +0000 | [diff] [blame] | 225 | ConstantInt *SICase = |
| 226 | mdconst::dyn_extract<ConstantInt>(MD->getOperand(2)); |
| 227 | ConstantInt *SIDef = |
| 228 | mdconst::dyn_extract<ConstantInt>(MD->getOperand(1)); |
Bob Wilson | e407736 | 2013-09-09 19:14:35 +0000 | [diff] [blame] | 229 | assert(SICase && SIDef); |
| 230 | // The TrueWeight should be the weight for the single case of SI. |
| 231 | NewBr->setMetadata(LLVMContext::MD_prof, |
| 232 | MDBuilder(BB->getContext()). |
| 233 | createBranchWeights(SICase->getValue().getZExtValue(), |
| 234 | SIDef->getValue().getZExtValue())); |
Stepan Dyatkovskiy | 7a50155 | 2012-05-23 08:18:26 +0000 | [diff] [blame] | 235 | } |
Bob Wilson | e407736 | 2013-09-09 19:14:35 +0000 | [diff] [blame] | 236 | |
Chen Li | eafbc9d | 2015-08-07 19:30:12 +0000 | [diff] [blame] | 237 | // Update make.implicit metadata to the newly-created conditional branch. |
| 238 | MDNode *MakeImplicitMD = SI->getMetadata(LLVMContext::MD_make_implicit); |
| 239 | if (MakeImplicitMD) |
| 240 | NewBr->setMetadata(LLVMContext::MD_make_implicit, MakeImplicitMD); |
| 241 | |
Bob Wilson | e407736 | 2013-09-09 19:14:35 +0000 | [diff] [blame] | 242 | // Delete the old switch. |
| 243 | SI->eraseFromParent(); |
| 244 | return true; |
Chris Lattner | 821deee | 2003-08-17 20:21:14 +0000 | [diff] [blame] | 245 | } |
Chris Lattner | 54a4b84 | 2009-11-01 03:40:38 +0000 | [diff] [blame] | 246 | return false; |
Chris Lattner | 28537df | 2002-05-07 18:07:59 +0000 | [diff] [blame] | 247 | } |
Chris Lattner | 54a4b84 | 2009-11-01 03:40:38 +0000 | [diff] [blame] | 248 | |
| 249 | if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(T)) { |
| 250 | // indirectbr blockaddress(@F, @BB) -> br label @BB |
| 251 | if (BlockAddress *BA = |
| 252 | dyn_cast<BlockAddress>(IBI->getAddress()->stripPointerCasts())) { |
| 253 | BasicBlock *TheOnlyDest = BA->getBasicBlock(); |
| 254 | // Insert the new branch. |
Devang Patel | 1fabbe9 | 2011-05-18 17:26:46 +0000 | [diff] [blame] | 255 | Builder.CreateBr(TheOnlyDest); |
Jakub Staszak | 8e1a6e7 | 2013-07-22 23:16:36 +0000 | [diff] [blame] | 256 | |
Chris Lattner | 54a4b84 | 2009-11-01 03:40:38 +0000 | [diff] [blame] | 257 | for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) { |
| 258 | if (IBI->getDestination(i) == TheOnlyDest) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 259 | TheOnlyDest = nullptr; |
Chris Lattner | 54a4b84 | 2009-11-01 03:40:38 +0000 | [diff] [blame] | 260 | else |
| 261 | IBI->getDestination(i)->removePredecessor(IBI->getParent()); |
| 262 | } |
Frits van Bommel | ad96455 | 2011-05-22 16:24:18 +0000 | [diff] [blame] | 263 | Value *Address = IBI->getAddress(); |
Chris Lattner | 54a4b84 | 2009-11-01 03:40:38 +0000 | [diff] [blame] | 264 | IBI->eraseFromParent(); |
Frits van Bommel | ad96455 | 2011-05-22 16:24:18 +0000 | [diff] [blame] | 265 | if (DeleteDeadConditions) |
Benjamin Kramer | 8bcc971 | 2012-08-29 15:32:21 +0000 | [diff] [blame] | 266 | RecursivelyDeleteTriviallyDeadInstructions(Address, TLI); |
Jakub Staszak | 8e1a6e7 | 2013-07-22 23:16:36 +0000 | [diff] [blame] | 267 | |
Chris Lattner | 54a4b84 | 2009-11-01 03:40:38 +0000 | [diff] [blame] | 268 | // If we didn't find our destination in the IBI successor list, then we |
| 269 | // have undefined behavior. Replace the unconditional branch with an |
| 270 | // 'unreachable' instruction. |
| 271 | if (TheOnlyDest) { |
| 272 | BB->getTerminator()->eraseFromParent(); |
| 273 | new UnreachableInst(BB->getContext(), BB); |
| 274 | } |
Jakub Staszak | 8e1a6e7 | 2013-07-22 23:16:36 +0000 | [diff] [blame] | 275 | |
Chris Lattner | 54a4b84 | 2009-11-01 03:40:38 +0000 | [diff] [blame] | 276 | return true; |
| 277 | } |
| 278 | } |
Jakub Staszak | 8e1a6e7 | 2013-07-22 23:16:36 +0000 | [diff] [blame] | 279 | |
Chris Lattner | 28537df | 2002-05-07 18:07:59 +0000 | [diff] [blame] | 280 | return false; |
| 281 | } |
| 282 | |
Chris Lattner | 28537df | 2002-05-07 18:07:59 +0000 | [diff] [blame] | 283 | |
| 284 | //===----------------------------------------------------------------------===// |
Chris Lattner | 852d6d6 | 2009-11-10 22:26:15 +0000 | [diff] [blame] | 285 | // Local dead code elimination. |
Chris Lattner | 28537df | 2002-05-07 18:07:59 +0000 | [diff] [blame] | 286 | // |
| 287 | |
Chris Lattner | c6c481c | 2008-11-27 22:57:53 +0000 | [diff] [blame] | 288 | /// isInstructionTriviallyDead - Return true if the result produced by the |
| 289 | /// instruction is not used, and the instruction has no side effects. |
| 290 | /// |
Benjamin Kramer | 8bcc971 | 2012-08-29 15:32:21 +0000 | [diff] [blame] | 291 | bool llvm::isInstructionTriviallyDead(Instruction *I, |
| 292 | const TargetLibraryInfo *TLI) { |
Daniel Berlin | e3e69e1 | 2017-03-10 00:32:33 +0000 | [diff] [blame] | 293 | if (!I->use_empty()) |
| 294 | return false; |
| 295 | return wouldInstructionBeTriviallyDead(I, TLI); |
| 296 | } |
| 297 | |
| 298 | bool llvm::wouldInstructionBeTriviallyDead(Instruction *I, |
| 299 | const TargetLibraryInfo *TLI) { |
| 300 | if (isa<TerminatorInst>(I)) |
| 301 | return false; |
Jeff Cohen | 5f4ef3c | 2005-07-27 06:12:32 +0000 | [diff] [blame] | 302 | |
David Majnemer | 654e130 | 2015-07-31 17:58:14 +0000 | [diff] [blame] | 303 | // We don't want the landingpad-like instructions removed by anything this |
| 304 | // general. |
| 305 | if (I->isEHPad()) |
Bill Wendling | d9fb470 | 2011-08-15 20:10:51 +0000 | [diff] [blame] | 306 | return false; |
| 307 | |
Devang Patel | c1431e6 | 2011-03-18 23:28:02 +0000 | [diff] [blame] | 308 | // We don't want debug info removed by anything this general, unless |
| 309 | // debug info is empty. |
| 310 | if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(I)) { |
Nick Lewycky | 99890a2 | 2011-08-02 21:19:27 +0000 | [diff] [blame] | 311 | if (DDI->getAddress()) |
Devang Patel | c1431e6 | 2011-03-18 23:28:02 +0000 | [diff] [blame] | 312 | return false; |
Devang Patel | 17bbd7f | 2011-03-21 22:04:45 +0000 | [diff] [blame] | 313 | return true; |
Nick Lewycky | 99890a2 | 2011-08-02 21:19:27 +0000 | [diff] [blame] | 314 | } |
Devang Patel | 17bbd7f | 2011-03-21 22:04:45 +0000 | [diff] [blame] | 315 | if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(I)) { |
Devang Patel | c1431e6 | 2011-03-18 23:28:02 +0000 | [diff] [blame] | 316 | if (DVI->getValue()) |
| 317 | return false; |
Devang Patel | 17bbd7f | 2011-03-21 22:04:45 +0000 | [diff] [blame] | 318 | return true; |
Devang Patel | c1431e6 | 2011-03-18 23:28:02 +0000 | [diff] [blame] | 319 | } |
| 320 | |
Daniel Berlin | e3e69e1 | 2017-03-10 00:32:33 +0000 | [diff] [blame] | 321 | if (!I->mayHaveSideEffects()) |
| 322 | return true; |
Duncan Sands | 1efabaa | 2009-05-06 06:49:50 +0000 | [diff] [blame] | 323 | |
| 324 | // Special case intrinsics that "may have side effects" but can be deleted |
| 325 | // when dead. |
Nick Lewycky | 99890a2 | 2011-08-02 21:19:27 +0000 | [diff] [blame] | 326 | if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) { |
Chris Lattner | e966583 | 2007-12-29 00:59:12 +0000 | [diff] [blame] | 327 | // Safe to delete llvm.stacksave if dead. |
| 328 | if (II->getIntrinsicID() == Intrinsic::stacksave) |
| 329 | return true; |
Nick Lewycky | 99890a2 | 2011-08-02 21:19:27 +0000 | [diff] [blame] | 330 | |
| 331 | // Lifetime intrinsics are dead when their right-hand is undef. |
| 332 | if (II->getIntrinsicID() == Intrinsic::lifetime_start || |
| 333 | II->getIntrinsicID() == Intrinsic::lifetime_end) |
| 334 | return isa<UndefValue>(II->getArgOperand(1)); |
Hal Finkel | 9304691 | 2014-07-25 21:13:35 +0000 | [diff] [blame] | 335 | |
Sanjoy Das | 107aefc | 2016-04-29 22:23:16 +0000 | [diff] [blame] | 336 | // Assumptions are dead if their condition is trivially true. Guards on |
| 337 | // true are operationally no-ops. In the future we can consider more |
| 338 | // sophisticated tradeoffs for guards considering potential for check |
| 339 | // widening, but for now we keep things simple. |
| 340 | if (II->getIntrinsicID() == Intrinsic::assume || |
| 341 | II->getIntrinsicID() == Intrinsic::experimental_guard) { |
Hal Finkel | 9304691 | 2014-07-25 21:13:35 +0000 | [diff] [blame] | 342 | if (ConstantInt *Cond = dyn_cast<ConstantInt>(II->getArgOperand(0))) |
| 343 | return !Cond->isZero(); |
| 344 | |
| 345 | return false; |
| 346 | } |
Nick Lewycky | 99890a2 | 2011-08-02 21:19:27 +0000 | [diff] [blame] | 347 | } |
Nick Lewycky | dd1d3df | 2011-10-24 04:35:36 +0000 | [diff] [blame] | 348 | |
Daniel Berlin | e3e69e1 | 2017-03-10 00:32:33 +0000 | [diff] [blame] | 349 | if (isAllocLikeFn(I, TLI)) |
| 350 | return true; |
Nick Lewycky | dd1d3df | 2011-10-24 04:35:36 +0000 | [diff] [blame] | 351 | |
Benjamin Kramer | 8bcc971 | 2012-08-29 15:32:21 +0000 | [diff] [blame] | 352 | if (CallInst *CI = isFreeCall(I, TLI)) |
Nick Lewycky | dd1d3df | 2011-10-24 04:35:36 +0000 | [diff] [blame] | 353 | if (Constant *C = dyn_cast<Constant>(CI->getArgOperand(0))) |
| 354 | return C->isNullValue() || isa<UndefValue>(C); |
| 355 | |
Eli Friedman | b6befc3 | 2016-11-02 20:48:11 +0000 | [diff] [blame] | 356 | if (CallSite CS = CallSite(I)) |
| 357 | if (isMathLibCallNoop(CS, TLI)) |
| 358 | return true; |
| 359 | |
Chris Lattner | a36d525 | 2005-05-06 05:27:34 +0000 | [diff] [blame] | 360 | return false; |
Chris Lattner | 28537df | 2002-05-07 18:07:59 +0000 | [diff] [blame] | 361 | } |
| 362 | |
Chris Lattner | c6c481c | 2008-11-27 22:57:53 +0000 | [diff] [blame] | 363 | /// RecursivelyDeleteTriviallyDeadInstructions - If the specified value is a |
| 364 | /// trivially dead instruction, delete it. If that makes any of its operands |
Dan Gohman | cb99fe9 | 2010-01-05 15:45:31 +0000 | [diff] [blame] | 365 | /// trivially dead, delete them too, recursively. Return true if any |
| 366 | /// instructions were deleted. |
Benjamin Kramer | 8bcc971 | 2012-08-29 15:32:21 +0000 | [diff] [blame] | 367 | bool |
| 368 | llvm::RecursivelyDeleteTriviallyDeadInstructions(Value *V, |
| 369 | const TargetLibraryInfo *TLI) { |
Chris Lattner | c6c481c | 2008-11-27 22:57:53 +0000 | [diff] [blame] | 370 | Instruction *I = dyn_cast<Instruction>(V); |
Benjamin Kramer | 8bcc971 | 2012-08-29 15:32:21 +0000 | [diff] [blame] | 371 | if (!I || !I->use_empty() || !isInstructionTriviallyDead(I, TLI)) |
Dan Gohman | cb99fe9 | 2010-01-05 15:45:31 +0000 | [diff] [blame] | 372 | return false; |
Jakub Staszak | 8e1a6e7 | 2013-07-22 23:16:36 +0000 | [diff] [blame] | 373 | |
Chris Lattner | e9f6c35 | 2008-11-28 01:20:46 +0000 | [diff] [blame] | 374 | SmallVector<Instruction*, 16> DeadInsts; |
| 375 | DeadInsts.push_back(I); |
Jakub Staszak | 8e1a6e7 | 2013-07-22 23:16:36 +0000 | [diff] [blame] | 376 | |
Dan Gohman | 2894387 | 2010-01-05 16:27:25 +0000 | [diff] [blame] | 377 | do { |
Dan Gohman | 9a6fef0 | 2009-05-06 17:22:41 +0000 | [diff] [blame] | 378 | I = DeadInsts.pop_back_val(); |
Chris Lattner | d4b5ba6 | 2008-11-28 00:58:15 +0000 | [diff] [blame] | 379 | |
Chris Lattner | e9f6c35 | 2008-11-28 01:20:46 +0000 | [diff] [blame] | 380 | // Null out all of the instruction's operands to see if any operand becomes |
| 381 | // dead as we go. |
| 382 | for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { |
| 383 | Value *OpV = I->getOperand(i); |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 384 | I->setOperand(i, nullptr); |
Jakub Staszak | 8e1a6e7 | 2013-07-22 23:16:36 +0000 | [diff] [blame] | 385 | |
Chris Lattner | e9f6c35 | 2008-11-28 01:20:46 +0000 | [diff] [blame] | 386 | if (!OpV->use_empty()) continue; |
Jakub Staszak | 8e1a6e7 | 2013-07-22 23:16:36 +0000 | [diff] [blame] | 387 | |
Chris Lattner | e9f6c35 | 2008-11-28 01:20:46 +0000 | [diff] [blame] | 388 | // If the operand is an instruction that became dead as we nulled out the |
| 389 | // operand, and if it is 'trivially' dead, delete it in a future loop |
| 390 | // iteration. |
| 391 | if (Instruction *OpI = dyn_cast<Instruction>(OpV)) |
Benjamin Kramer | 8bcc971 | 2012-08-29 15:32:21 +0000 | [diff] [blame] | 392 | if (isInstructionTriviallyDead(OpI, TLI)) |
Chris Lattner | e9f6c35 | 2008-11-28 01:20:46 +0000 | [diff] [blame] | 393 | DeadInsts.push_back(OpI); |
| 394 | } |
Jakub Staszak | 8e1a6e7 | 2013-07-22 23:16:36 +0000 | [diff] [blame] | 395 | |
Chris Lattner | e9f6c35 | 2008-11-28 01:20:46 +0000 | [diff] [blame] | 396 | I->eraseFromParent(); |
Dan Gohman | 2894387 | 2010-01-05 16:27:25 +0000 | [diff] [blame] | 397 | } while (!DeadInsts.empty()); |
Dan Gohman | cb99fe9 | 2010-01-05 15:45:31 +0000 | [diff] [blame] | 398 | |
| 399 | return true; |
Chris Lattner | 28537df | 2002-05-07 18:07:59 +0000 | [diff] [blame] | 400 | } |
Chris Lattner | 99d6809 | 2008-11-27 07:43:12 +0000 | [diff] [blame] | 401 | |
Nick Lewycky | c8a1569 | 2011-02-20 08:38:20 +0000 | [diff] [blame] | 402 | /// areAllUsesEqual - Check whether the uses of a value are all the same. |
| 403 | /// This is similar to Instruction::hasOneUse() except this will also return |
Duncan Sands | 6dcd49b | 2011-02-21 16:27:36 +0000 | [diff] [blame] | 404 | /// true when there are no uses or multiple uses that all refer to the same |
| 405 | /// value. |
Nick Lewycky | c8a1569 | 2011-02-20 08:38:20 +0000 | [diff] [blame] | 406 | static bool areAllUsesEqual(Instruction *I) { |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 407 | Value::user_iterator UI = I->user_begin(); |
| 408 | Value::user_iterator UE = I->user_end(); |
Nick Lewycky | c8a1569 | 2011-02-20 08:38:20 +0000 | [diff] [blame] | 409 | if (UI == UE) |
Duncan Sands | 6dcd49b | 2011-02-21 16:27:36 +0000 | [diff] [blame] | 410 | return true; |
Nick Lewycky | c8a1569 | 2011-02-20 08:38:20 +0000 | [diff] [blame] | 411 | |
| 412 | User *TheUse = *UI; |
| 413 | for (++UI; UI != UE; ++UI) { |
| 414 | if (*UI != TheUse) |
| 415 | return false; |
| 416 | } |
| 417 | return true; |
| 418 | } |
| 419 | |
Dan Gohman | ff08995 | 2009-05-02 18:29:22 +0000 | [diff] [blame] | 420 | /// RecursivelyDeleteDeadPHINode - If the specified value is an effectively |
| 421 | /// dead PHI node, due to being a def-use chain of single-use nodes that |
| 422 | /// either forms a cycle or is terminated by a trivially dead instruction, |
| 423 | /// delete it. If that makes any of its operands trivially dead, delete them |
Duncan Sands | ecbbf08 | 2011-02-21 17:32:05 +0000 | [diff] [blame] | 424 | /// too, recursively. Return true if a change was made. |
Benjamin Kramer | 8bcc971 | 2012-08-29 15:32:21 +0000 | [diff] [blame] | 425 | bool llvm::RecursivelyDeleteDeadPHINode(PHINode *PN, |
| 426 | const TargetLibraryInfo *TLI) { |
Duncan Sands | 6dcd49b | 2011-02-21 16:27:36 +0000 | [diff] [blame] | 427 | SmallPtrSet<Instruction*, 4> Visited; |
| 428 | for (Instruction *I = PN; areAllUsesEqual(I) && !I->mayHaveSideEffects(); |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 429 | I = cast<Instruction>(*I->user_begin())) { |
Duncan Sands | 6dcd49b | 2011-02-21 16:27:36 +0000 | [diff] [blame] | 430 | if (I->use_empty()) |
Benjamin Kramer | 8bcc971 | 2012-08-29 15:32:21 +0000 | [diff] [blame] | 431 | return RecursivelyDeleteTriviallyDeadInstructions(I, TLI); |
Nick Lewycky | 183c24c | 2011-02-20 18:05:56 +0000 | [diff] [blame] | 432 | |
Duncan Sands | 6dcd49b | 2011-02-21 16:27:36 +0000 | [diff] [blame] | 433 | // If we find an instruction more than once, we're on a cycle that |
Dan Gohman | ff08995 | 2009-05-02 18:29:22 +0000 | [diff] [blame] | 434 | // won't prove fruitful. |
David Blaikie | 70573dc | 2014-11-19 07:49:26 +0000 | [diff] [blame] | 435 | if (!Visited.insert(I).second) { |
Duncan Sands | 6dcd49b | 2011-02-21 16:27:36 +0000 | [diff] [blame] | 436 | // Break the cycle and delete the instruction and its operands. |
| 437 | I->replaceAllUsesWith(UndefValue::get(I->getType())); |
Benjamin Kramer | 8bcc971 | 2012-08-29 15:32:21 +0000 | [diff] [blame] | 438 | (void)RecursivelyDeleteTriviallyDeadInstructions(I, TLI); |
Duncan Sands | ecbbf08 | 2011-02-21 17:32:05 +0000 | [diff] [blame] | 439 | return true; |
Duncan Sands | 6dcd49b | 2011-02-21 16:27:36 +0000 | [diff] [blame] | 440 | } |
| 441 | } |
| 442 | return false; |
Dan Gohman | ff08995 | 2009-05-02 18:29:22 +0000 | [diff] [blame] | 443 | } |
Chris Lattner | c6c481c | 2008-11-27 22:57:53 +0000 | [diff] [blame] | 444 | |
Fiona Glaser | f74cc40 | 2015-09-28 18:56:07 +0000 | [diff] [blame] | 445 | static bool |
| 446 | simplifyAndDCEInstruction(Instruction *I, |
| 447 | SmallSetVector<Instruction *, 16> &WorkList, |
| 448 | const DataLayout &DL, |
| 449 | const TargetLibraryInfo *TLI) { |
| 450 | if (isInstructionTriviallyDead(I, TLI)) { |
| 451 | // Null out all of the instruction's operands to see if any operand becomes |
| 452 | // dead as we go. |
| 453 | for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { |
| 454 | Value *OpV = I->getOperand(i); |
| 455 | I->setOperand(i, nullptr); |
| 456 | |
| 457 | if (!OpV->use_empty() || I == OpV) |
| 458 | continue; |
| 459 | |
| 460 | // If the operand is an instruction that became dead as we nulled out the |
| 461 | // operand, and if it is 'trivially' dead, delete it in a future loop |
| 462 | // iteration. |
| 463 | if (Instruction *OpI = dyn_cast<Instruction>(OpV)) |
| 464 | if (isInstructionTriviallyDead(OpI, TLI)) |
| 465 | WorkList.insert(OpI); |
| 466 | } |
| 467 | |
| 468 | I->eraseFromParent(); |
| 469 | |
| 470 | return true; |
| 471 | } |
| 472 | |
| 473 | if (Value *SimpleV = SimplifyInstruction(I, DL)) { |
| 474 | // Add the users to the worklist. CAREFUL: an instruction can use itself, |
| 475 | // in the case of a phi node. |
David Majnemer | b8da3a2 | 2016-06-25 00:04:10 +0000 | [diff] [blame] | 476 | for (User *U : I->users()) { |
| 477 | if (U != I) { |
Fiona Glaser | f74cc40 | 2015-09-28 18:56:07 +0000 | [diff] [blame] | 478 | WorkList.insert(cast<Instruction>(U)); |
David Majnemer | b8da3a2 | 2016-06-25 00:04:10 +0000 | [diff] [blame] | 479 | } |
| 480 | } |
Fiona Glaser | f74cc40 | 2015-09-28 18:56:07 +0000 | [diff] [blame] | 481 | |
| 482 | // Replace the instruction with its simplified value. |
David Majnemer | b8da3a2 | 2016-06-25 00:04:10 +0000 | [diff] [blame] | 483 | bool Changed = false; |
| 484 | if (!I->use_empty()) { |
| 485 | I->replaceAllUsesWith(SimpleV); |
| 486 | Changed = true; |
| 487 | } |
| 488 | if (isInstructionTriviallyDead(I, TLI)) { |
| 489 | I->eraseFromParent(); |
| 490 | Changed = true; |
| 491 | } |
| 492 | return Changed; |
Fiona Glaser | f74cc40 | 2015-09-28 18:56:07 +0000 | [diff] [blame] | 493 | } |
| 494 | return false; |
| 495 | } |
| 496 | |
Chris Lattner | 7c743f2 | 2010-01-12 19:40:54 +0000 | [diff] [blame] | 497 | /// SimplifyInstructionsInBlock - Scan the specified basic block and try to |
| 498 | /// simplify any instructions in it and recursively delete dead instructions. |
| 499 | /// |
| 500 | /// This returns true if it changed the code, note that it can delete |
| 501 | /// instructions in other blocks as well in this block. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 502 | bool llvm::SimplifyInstructionsInBlock(BasicBlock *BB, |
Benjamin Kramer | 8bcc971 | 2012-08-29 15:32:21 +0000 | [diff] [blame] | 503 | const TargetLibraryInfo *TLI) { |
Chris Lattner | 7c743f2 | 2010-01-12 19:40:54 +0000 | [diff] [blame] | 504 | bool MadeChange = false; |
Fiona Glaser | f74cc40 | 2015-09-28 18:56:07 +0000 | [diff] [blame] | 505 | const DataLayout &DL = BB->getModule()->getDataLayout(); |
Chandler Carruth | 0c72e3f | 2012-03-25 03:29:25 +0000 | [diff] [blame] | 506 | |
| 507 | #ifndef NDEBUG |
| 508 | // In debug builds, ensure that the terminator of the block is never replaced |
| 509 | // or deleted by these simplifications. The idea of simplification is that it |
| 510 | // cannot introduce new instructions, and there is no way to replace the |
| 511 | // terminator of a block without introducing a new instruction. |
Duncan P. N. Exon Smith | 5b4c837 | 2015-10-13 02:39:05 +0000 | [diff] [blame] | 512 | AssertingVH<Instruction> TerminatorVH(&BB->back()); |
Chandler Carruth | 0c72e3f | 2012-03-25 03:29:25 +0000 | [diff] [blame] | 513 | #endif |
| 514 | |
Fiona Glaser | f74cc40 | 2015-09-28 18:56:07 +0000 | [diff] [blame] | 515 | SmallSetVector<Instruction *, 16> WorkList; |
| 516 | // Iterate over the original function, only adding insts to the worklist |
| 517 | // if they actually need to be revisited. This avoids having to pre-init |
| 518 | // the worklist with the entire function's worth of instructions. |
Chad Rosier | 56def25 | 2016-05-21 21:12:06 +0000 | [diff] [blame] | 519 | for (BasicBlock::iterator BI = BB->begin(), E = std::prev(BB->end()); |
| 520 | BI != E;) { |
Chandler Carruth | 17fc6ef | 2012-03-24 23:03:27 +0000 | [diff] [blame] | 521 | assert(!BI->isTerminator()); |
Fiona Glaser | f74cc40 | 2015-09-28 18:56:07 +0000 | [diff] [blame] | 522 | Instruction *I = &*BI; |
| 523 | ++BI; |
Chandler Carruth | cf1b585 | 2012-03-24 21:11:24 +0000 | [diff] [blame] | 524 | |
Fiona Glaser | f74cc40 | 2015-09-28 18:56:07 +0000 | [diff] [blame] | 525 | // We're visiting this instruction now, so make sure it's not in the |
| 526 | // worklist from an earlier visit. |
| 527 | if (!WorkList.count(I)) |
| 528 | MadeChange |= simplifyAndDCEInstruction(I, WorkList, DL, TLI); |
| 529 | } |
Eli Friedman | 17bf492 | 2011-04-02 22:45:17 +0000 | [diff] [blame] | 530 | |
Fiona Glaser | f74cc40 | 2015-09-28 18:56:07 +0000 | [diff] [blame] | 531 | while (!WorkList.empty()) { |
| 532 | Instruction *I = WorkList.pop_back_val(); |
| 533 | MadeChange |= simplifyAndDCEInstruction(I, WorkList, DL, TLI); |
Chris Lattner | 7c743f2 | 2010-01-12 19:40:54 +0000 | [diff] [blame] | 534 | } |
| 535 | return MadeChange; |
| 536 | } |
| 537 | |
Chris Lattner | 99d6809 | 2008-11-27 07:43:12 +0000 | [diff] [blame] | 538 | //===----------------------------------------------------------------------===// |
Chris Lattner | 852d6d6 | 2009-11-10 22:26:15 +0000 | [diff] [blame] | 539 | // Control Flow Graph Restructuring. |
Chris Lattner | 99d6809 | 2008-11-27 07:43:12 +0000 | [diff] [blame] | 540 | // |
| 541 | |
Chris Lattner | 852d6d6 | 2009-11-10 22:26:15 +0000 | [diff] [blame] | 542 | |
| 543 | /// RemovePredecessorAndSimplify - Like BasicBlock::removePredecessor, this |
| 544 | /// method is called when we're about to delete Pred as a predecessor of BB. If |
| 545 | /// BB contains any PHI nodes, this drops the entries in the PHI nodes for Pred. |
| 546 | /// |
| 547 | /// Unlike the removePredecessor method, this attempts to simplify uses of PHI |
| 548 | /// nodes that collapse into identity values. For example, if we have: |
| 549 | /// x = phi(1, 0, 0, 0) |
| 550 | /// y = and x, z |
| 551 | /// |
| 552 | /// .. and delete the predecessor corresponding to the '1', this will attempt to |
| 553 | /// recursively fold the and to 0. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 554 | void llvm::RemovePredecessorAndSimplify(BasicBlock *BB, BasicBlock *Pred) { |
Chris Lattner | 852d6d6 | 2009-11-10 22:26:15 +0000 | [diff] [blame] | 555 | // This only adjusts blocks with PHI nodes. |
| 556 | if (!isa<PHINode>(BB->begin())) |
| 557 | return; |
Jakub Staszak | 8e1a6e7 | 2013-07-22 23:16:36 +0000 | [diff] [blame] | 558 | |
Chris Lattner | 852d6d6 | 2009-11-10 22:26:15 +0000 | [diff] [blame] | 559 | // Remove the entries for Pred from the PHI nodes in BB, but do not simplify |
| 560 | // them down. This will leave us with single entry phi nodes and other phis |
| 561 | // that can be removed. |
| 562 | BB->removePredecessor(Pred, true); |
Jakub Staszak | 8e1a6e7 | 2013-07-22 23:16:36 +0000 | [diff] [blame] | 563 | |
Chris Lattner | 852d6d6 | 2009-11-10 22:26:15 +0000 | [diff] [blame] | 564 | WeakVH PhiIt = &BB->front(); |
| 565 | while (PHINode *PN = dyn_cast<PHINode>(PhiIt)) { |
| 566 | PhiIt = &*++BasicBlock::iterator(cast<Instruction>(PhiIt)); |
Chris Lattner | e41ab07 | 2010-07-15 06:06:04 +0000 | [diff] [blame] | 567 | Value *OldPhiIt = PhiIt; |
Chandler Carruth | cf1b585 | 2012-03-24 21:11:24 +0000 | [diff] [blame] | 568 | |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 569 | if (!recursivelySimplifyInstruction(PN)) |
Chandler Carruth | cf1b585 | 2012-03-24 21:11:24 +0000 | [diff] [blame] | 570 | continue; |
| 571 | |
Chris Lattner | 852d6d6 | 2009-11-10 22:26:15 +0000 | [diff] [blame] | 572 | // If recursive simplification ended up deleting the next PHI node we would |
| 573 | // iterate to, then our iterator is invalid, restart scanning from the top |
| 574 | // of the block. |
Chris Lattner | e41ab07 | 2010-07-15 06:06:04 +0000 | [diff] [blame] | 575 | if (PhiIt != OldPhiIt) PhiIt = &BB->front(); |
Chris Lattner | 852d6d6 | 2009-11-10 22:26:15 +0000 | [diff] [blame] | 576 | } |
| 577 | } |
| 578 | |
| 579 | |
Chris Lattner | 99d6809 | 2008-11-27 07:43:12 +0000 | [diff] [blame] | 580 | /// MergeBasicBlockIntoOnlyPred - DestBB is a block with one predecessor and its |
| 581 | /// predecessor is known to have one successor (DestBB!). Eliminate the edge |
| 582 | /// between them, moving the instructions in the predecessor into DestBB and |
| 583 | /// deleting the predecessor block. |
| 584 | /// |
Chandler Carruth | 10f28f2 | 2015-01-20 01:37:09 +0000 | [diff] [blame] | 585 | void llvm::MergeBasicBlockIntoOnlyPred(BasicBlock *DestBB, DominatorTree *DT) { |
Chris Lattner | 99d6809 | 2008-11-27 07:43:12 +0000 | [diff] [blame] | 586 | // If BB has single-entry PHI nodes, fold them. |
| 587 | while (PHINode *PN = dyn_cast<PHINode>(DestBB->begin())) { |
| 588 | Value *NewVal = PN->getIncomingValue(0); |
| 589 | // Replace self referencing PHI with undef, it must be dead. |
Owen Anderson | b292b8c | 2009-07-30 23:03:37 +0000 | [diff] [blame] | 590 | if (NewVal == PN) NewVal = UndefValue::get(PN->getType()); |
Chris Lattner | 99d6809 | 2008-11-27 07:43:12 +0000 | [diff] [blame] | 591 | PN->replaceAllUsesWith(NewVal); |
| 592 | PN->eraseFromParent(); |
| 593 | } |
Jakub Staszak | 8e1a6e7 | 2013-07-22 23:16:36 +0000 | [diff] [blame] | 594 | |
Chris Lattner | 99d6809 | 2008-11-27 07:43:12 +0000 | [diff] [blame] | 595 | BasicBlock *PredBB = DestBB->getSinglePredecessor(); |
| 596 | assert(PredBB && "Block doesn't have a single predecessor!"); |
Jakub Staszak | 8e1a6e7 | 2013-07-22 23:16:36 +0000 | [diff] [blame] | 597 | |
Chris Lattner | 6fbfe58 | 2010-02-15 20:47:49 +0000 | [diff] [blame] | 598 | // Zap anything that took the address of DestBB. Not doing this will give the |
| 599 | // address an invalid value. |
| 600 | if (DestBB->hasAddressTaken()) { |
| 601 | BlockAddress *BA = BlockAddress::get(DestBB); |
| 602 | Constant *Replacement = |
| 603 | ConstantInt::get(llvm::Type::getInt32Ty(BA->getContext()), 1); |
| 604 | BA->replaceAllUsesWith(ConstantExpr::getIntToPtr(Replacement, |
| 605 | BA->getType())); |
| 606 | BA->destroyConstant(); |
| 607 | } |
Jakub Staszak | 8e1a6e7 | 2013-07-22 23:16:36 +0000 | [diff] [blame] | 608 | |
Chris Lattner | 99d6809 | 2008-11-27 07:43:12 +0000 | [diff] [blame] | 609 | // Anything that branched to PredBB now branches to DestBB. |
| 610 | PredBB->replaceAllUsesWith(DestBB); |
Jakub Staszak | 8e1a6e7 | 2013-07-22 23:16:36 +0000 | [diff] [blame] | 611 | |
Jay Foad | 61ea0e4 | 2011-06-23 09:09:15 +0000 | [diff] [blame] | 612 | // Splice all the instructions from PredBB to DestBB. |
| 613 | PredBB->getTerminator()->eraseFromParent(); |
Bill Wendling | 90dd90a | 2013-10-21 04:09:17 +0000 | [diff] [blame] | 614 | DestBB->getInstList().splice(DestBB->begin(), PredBB->getInstList()); |
Jay Foad | 61ea0e4 | 2011-06-23 09:09:15 +0000 | [diff] [blame] | 615 | |
Owen Anderson | a8d1c3e | 2014-07-12 07:12:47 +0000 | [diff] [blame] | 616 | // If the PredBB is the entry block of the function, move DestBB up to |
| 617 | // become the entry block after we erase PredBB. |
| 618 | if (PredBB == &DestBB->getParent()->getEntryBlock()) |
| 619 | DestBB->moveAfter(PredBB); |
| 620 | |
Chandler Carruth | 10f28f2 | 2015-01-20 01:37:09 +0000 | [diff] [blame] | 621 | if (DT) { |
| 622 | BasicBlock *PredBBIDom = DT->getNode(PredBB)->getIDom()->getBlock(); |
| 623 | DT->changeImmediateDominator(DestBB, PredBBIDom); |
| 624 | DT->eraseNode(PredBB); |
Andreas Neustifter | f8cb758 | 2009-09-16 09:26:52 +0000 | [diff] [blame] | 625 | } |
Chris Lattner | 99d6809 | 2008-11-27 07:43:12 +0000 | [diff] [blame] | 626 | // Nuke BB. |
| 627 | PredBB->eraseFromParent(); |
| 628 | } |
Devang Patel | caf4485 | 2009-02-10 07:00:59 +0000 | [diff] [blame] | 629 | |
Duncan Sands | e773c08 | 2013-07-11 08:28:20 +0000 | [diff] [blame] | 630 | /// CanMergeValues - Return true if we can choose one of these values to use |
| 631 | /// in place of the other. Note that we will always choose the non-undef |
| 632 | /// value to keep. |
| 633 | static bool CanMergeValues(Value *First, Value *Second) { |
| 634 | return First == Second || isa<UndefValue>(First) || isa<UndefValue>(Second); |
| 635 | } |
| 636 | |
Chris Lattner | cbd18fc | 2009-11-10 05:59:26 +0000 | [diff] [blame] | 637 | /// CanPropagatePredecessorsForPHIs - Return true if we can fold BB, an |
Mark Lacey | a262655 | 2013-08-14 22:11:42 +0000 | [diff] [blame] | 638 | /// almost-empty BB ending in an unconditional branch to Succ, into Succ. |
Chris Lattner | cbd18fc | 2009-11-10 05:59:26 +0000 | [diff] [blame] | 639 | /// |
| 640 | /// Assumption: Succ is the single successor for BB. |
| 641 | /// |
| 642 | static bool CanPropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) { |
| 643 | assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!"); |
| 644 | |
Jakub Staszak | 8e1a6e7 | 2013-07-22 23:16:36 +0000 | [diff] [blame] | 645 | DEBUG(dbgs() << "Looking to fold " << BB->getName() << " into " |
Chris Lattner | cbd18fc | 2009-11-10 05:59:26 +0000 | [diff] [blame] | 646 | << Succ->getName() << "\n"); |
| 647 | // Shortcut, if there is only a single predecessor it must be BB and merging |
| 648 | // is always safe |
| 649 | if (Succ->getSinglePredecessor()) return true; |
| 650 | |
| 651 | // Make a list of the predecessors of BB |
Benjamin Kramer | b5188f1 | 2011-12-06 16:14:29 +0000 | [diff] [blame] | 652 | SmallPtrSet<BasicBlock*, 16> BBPreds(pred_begin(BB), pred_end(BB)); |
Chris Lattner | cbd18fc | 2009-11-10 05:59:26 +0000 | [diff] [blame] | 653 | |
Chris Lattner | cbd18fc | 2009-11-10 05:59:26 +0000 | [diff] [blame] | 654 | // Look at all the phi nodes in Succ, to see if they present a conflict when |
| 655 | // merging these blocks |
| 656 | for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) { |
| 657 | PHINode *PN = cast<PHINode>(I); |
| 658 | |
| 659 | // If the incoming value from BB is again a PHINode in |
| 660 | // BB which has the same incoming value for *PI as PN does, we can |
| 661 | // merge the phi nodes and then the blocks can still be merged |
| 662 | PHINode *BBPN = dyn_cast<PHINode>(PN->getIncomingValueForBlock(BB)); |
| 663 | if (BBPN && BBPN->getParent() == BB) { |
Benjamin Kramer | b5188f1 | 2011-12-06 16:14:29 +0000 | [diff] [blame] | 664 | for (unsigned PI = 0, PE = PN->getNumIncomingValues(); PI != PE; ++PI) { |
| 665 | BasicBlock *IBB = PN->getIncomingBlock(PI); |
| 666 | if (BBPreds.count(IBB) && |
Duncan Sands | e773c08 | 2013-07-11 08:28:20 +0000 | [diff] [blame] | 667 | !CanMergeValues(BBPN->getIncomingValueForBlock(IBB), |
| 668 | PN->getIncomingValue(PI))) { |
Jakub Staszak | 8e1a6e7 | 2013-07-22 23:16:36 +0000 | [diff] [blame] | 669 | DEBUG(dbgs() << "Can't fold, phi node " << PN->getName() << " in " |
| 670 | << Succ->getName() << " is conflicting with " |
Chris Lattner | cbd18fc | 2009-11-10 05:59:26 +0000 | [diff] [blame] | 671 | << BBPN->getName() << " with regard to common predecessor " |
Benjamin Kramer | b5188f1 | 2011-12-06 16:14:29 +0000 | [diff] [blame] | 672 | << IBB->getName() << "\n"); |
Chris Lattner | cbd18fc | 2009-11-10 05:59:26 +0000 | [diff] [blame] | 673 | return false; |
| 674 | } |
| 675 | } |
| 676 | } else { |
| 677 | Value* Val = PN->getIncomingValueForBlock(BB); |
Benjamin Kramer | b5188f1 | 2011-12-06 16:14:29 +0000 | [diff] [blame] | 678 | for (unsigned PI = 0, PE = PN->getNumIncomingValues(); PI != PE; ++PI) { |
Chris Lattner | cbd18fc | 2009-11-10 05:59:26 +0000 | [diff] [blame] | 679 | // See if the incoming value for the common predecessor is equal to the |
| 680 | // one for BB, in which case this phi node will not prevent the merging |
| 681 | // of the block. |
Benjamin Kramer | b5188f1 | 2011-12-06 16:14:29 +0000 | [diff] [blame] | 682 | BasicBlock *IBB = PN->getIncomingBlock(PI); |
Duncan Sands | e773c08 | 2013-07-11 08:28:20 +0000 | [diff] [blame] | 683 | if (BBPreds.count(IBB) && |
| 684 | !CanMergeValues(Val, PN->getIncomingValue(PI))) { |
Jakub Staszak | 8e1a6e7 | 2013-07-22 23:16:36 +0000 | [diff] [blame] | 685 | DEBUG(dbgs() << "Can't fold, phi node " << PN->getName() << " in " |
Chris Lattner | cbd18fc | 2009-11-10 05:59:26 +0000 | [diff] [blame] | 686 | << Succ->getName() << " is conflicting with regard to common " |
Benjamin Kramer | b5188f1 | 2011-12-06 16:14:29 +0000 | [diff] [blame] | 687 | << "predecessor " << IBB->getName() << "\n"); |
Chris Lattner | cbd18fc | 2009-11-10 05:59:26 +0000 | [diff] [blame] | 688 | return false; |
| 689 | } |
| 690 | } |
| 691 | } |
| 692 | } |
| 693 | |
| 694 | return true; |
| 695 | } |
| 696 | |
Duncan Sands | e773c08 | 2013-07-11 08:28:20 +0000 | [diff] [blame] | 697 | typedef SmallVector<BasicBlock *, 16> PredBlockVector; |
| 698 | typedef DenseMap<BasicBlock *, Value *> IncomingValueMap; |
| 699 | |
| 700 | /// \brief Determines the value to use as the phi node input for a block. |
| 701 | /// |
| 702 | /// Select between \p OldVal any value that we know flows from \p BB |
| 703 | /// to a particular phi on the basis of which one (if either) is not |
| 704 | /// undef. Update IncomingValues based on the selected value. |
| 705 | /// |
| 706 | /// \param OldVal The value we are considering selecting. |
| 707 | /// \param BB The block that the value flows in from. |
| 708 | /// \param IncomingValues A map from block-to-value for other phi inputs |
| 709 | /// that we have examined. |
| 710 | /// |
| 711 | /// \returns the selected value. |
| 712 | static Value *selectIncomingValueForBlock(Value *OldVal, BasicBlock *BB, |
| 713 | IncomingValueMap &IncomingValues) { |
| 714 | if (!isa<UndefValue>(OldVal)) { |
| 715 | assert((!IncomingValues.count(BB) || |
| 716 | IncomingValues.find(BB)->second == OldVal) && |
| 717 | "Expected OldVal to match incoming value from BB!"); |
| 718 | |
| 719 | IncomingValues.insert(std::make_pair(BB, OldVal)); |
| 720 | return OldVal; |
| 721 | } |
| 722 | |
| 723 | IncomingValueMap::const_iterator It = IncomingValues.find(BB); |
| 724 | if (It != IncomingValues.end()) return It->second; |
| 725 | |
| 726 | return OldVal; |
| 727 | } |
| 728 | |
| 729 | /// \brief Create a map from block to value for the operands of a |
| 730 | /// given phi. |
| 731 | /// |
| 732 | /// Create a map from block to value for each non-undef value flowing |
| 733 | /// into \p PN. |
| 734 | /// |
| 735 | /// \param PN The phi we are collecting the map for. |
| 736 | /// \param IncomingValues [out] The map from block to value for this phi. |
| 737 | static void gatherIncomingValuesToPhi(PHINode *PN, |
| 738 | IncomingValueMap &IncomingValues) { |
| 739 | for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { |
| 740 | BasicBlock *BB = PN->getIncomingBlock(i); |
| 741 | Value *V = PN->getIncomingValue(i); |
| 742 | |
| 743 | if (!isa<UndefValue>(V)) |
| 744 | IncomingValues.insert(std::make_pair(BB, V)); |
| 745 | } |
| 746 | } |
| 747 | |
| 748 | /// \brief Replace the incoming undef values to a phi with the values |
| 749 | /// from a block-to-value map. |
| 750 | /// |
| 751 | /// \param PN The phi we are replacing the undefs in. |
| 752 | /// \param IncomingValues A map from block to value. |
| 753 | static void replaceUndefValuesInPhi(PHINode *PN, |
| 754 | const IncomingValueMap &IncomingValues) { |
| 755 | for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { |
| 756 | Value *V = PN->getIncomingValue(i); |
| 757 | |
| 758 | if (!isa<UndefValue>(V)) continue; |
| 759 | |
| 760 | BasicBlock *BB = PN->getIncomingBlock(i); |
| 761 | IncomingValueMap::const_iterator It = IncomingValues.find(BB); |
| 762 | if (It == IncomingValues.end()) continue; |
| 763 | |
| 764 | PN->setIncomingValue(i, It->second); |
| 765 | } |
| 766 | } |
| 767 | |
| 768 | /// \brief Replace a value flowing from a block to a phi with |
| 769 | /// potentially multiple instances of that value flowing from the |
| 770 | /// block's predecessors to the phi. |
| 771 | /// |
| 772 | /// \param BB The block with the value flowing into the phi. |
| 773 | /// \param BBPreds The predecessors of BB. |
| 774 | /// \param PN The phi that we are updating. |
| 775 | static void redirectValuesFromPredecessorsToPhi(BasicBlock *BB, |
| 776 | const PredBlockVector &BBPreds, |
| 777 | PHINode *PN) { |
| 778 | Value *OldVal = PN->removeIncomingValue(BB, false); |
| 779 | assert(OldVal && "No entry in PHI for Pred BB!"); |
| 780 | |
| 781 | IncomingValueMap IncomingValues; |
| 782 | |
| 783 | // We are merging two blocks - BB, and the block containing PN - and |
| 784 | // as a result we need to redirect edges from the predecessors of BB |
| 785 | // to go to the block containing PN, and update PN |
| 786 | // accordingly. Since we allow merging blocks in the case where the |
| 787 | // predecessor and successor blocks both share some predecessors, |
| 788 | // and where some of those common predecessors might have undef |
| 789 | // values flowing into PN, we want to rewrite those values to be |
| 790 | // consistent with the non-undef values. |
| 791 | |
| 792 | gatherIncomingValuesToPhi(PN, IncomingValues); |
| 793 | |
| 794 | // If this incoming value is one of the PHI nodes in BB, the new entries |
| 795 | // in the PHI node are the entries from the old PHI. |
| 796 | if (isa<PHINode>(OldVal) && cast<PHINode>(OldVal)->getParent() == BB) { |
| 797 | PHINode *OldValPN = cast<PHINode>(OldVal); |
| 798 | for (unsigned i = 0, e = OldValPN->getNumIncomingValues(); i != e; ++i) { |
| 799 | // Note that, since we are merging phi nodes and BB and Succ might |
| 800 | // have common predecessors, we could end up with a phi node with |
| 801 | // identical incoming branches. This will be cleaned up later (and |
| 802 | // will trigger asserts if we try to clean it up now, without also |
| 803 | // simplifying the corresponding conditional branch). |
| 804 | BasicBlock *PredBB = OldValPN->getIncomingBlock(i); |
| 805 | Value *PredVal = OldValPN->getIncomingValue(i); |
| 806 | Value *Selected = selectIncomingValueForBlock(PredVal, PredBB, |
| 807 | IncomingValues); |
| 808 | |
| 809 | // And add a new incoming value for this predecessor for the |
| 810 | // newly retargeted branch. |
| 811 | PN->addIncoming(Selected, PredBB); |
| 812 | } |
| 813 | } else { |
| 814 | for (unsigned i = 0, e = BBPreds.size(); i != e; ++i) { |
| 815 | // Update existing incoming values in PN for this |
| 816 | // predecessor of BB. |
| 817 | BasicBlock *PredBB = BBPreds[i]; |
| 818 | Value *Selected = selectIncomingValueForBlock(OldVal, PredBB, |
| 819 | IncomingValues); |
| 820 | |
| 821 | // And add a new incoming value for this predecessor for the |
| 822 | // newly retargeted branch. |
| 823 | PN->addIncoming(Selected, PredBB); |
| 824 | } |
| 825 | } |
| 826 | |
| 827 | replaceUndefValuesInPhi(PN, IncomingValues); |
| 828 | } |
| 829 | |
Chris Lattner | cbd18fc | 2009-11-10 05:59:26 +0000 | [diff] [blame] | 830 | /// TryToSimplifyUncondBranchFromEmptyBlock - BB is known to contain an |
| 831 | /// unconditional branch, and contains no instructions other than PHI nodes, |
Rafael Espindola | b10a0f2 | 2011-06-30 20:14:24 +0000 | [diff] [blame] | 832 | /// potential side-effect free intrinsics and the branch. If possible, |
| 833 | /// eliminate BB by rewriting all the predecessors to branch to the successor |
| 834 | /// block and return true. If we can't transform, return false. |
Chris Lattner | cbd18fc | 2009-11-10 05:59:26 +0000 | [diff] [blame] | 835 | bool llvm::TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB) { |
Dan Gohman | 4a63fad | 2010-08-14 00:29:42 +0000 | [diff] [blame] | 836 | assert(BB != &BB->getParent()->getEntryBlock() && |
| 837 | "TryToSimplifyUncondBranchFromEmptyBlock called on entry block!"); |
| 838 | |
Chris Lattner | cbd18fc | 2009-11-10 05:59:26 +0000 | [diff] [blame] | 839 | // We can't eliminate infinite loops. |
| 840 | BasicBlock *Succ = cast<BranchInst>(BB->getTerminator())->getSuccessor(0); |
| 841 | if (BB == Succ) return false; |
Jakub Staszak | 8e1a6e7 | 2013-07-22 23:16:36 +0000 | [diff] [blame] | 842 | |
Reid Kleckner | bca59d2 | 2016-05-02 19:43:22 +0000 | [diff] [blame] | 843 | // Check to see if merging these blocks would cause conflicts for any of the |
| 844 | // phi nodes in BB or Succ. If not, we can safely merge. |
| 845 | if (!CanPropagatePredecessorsForPHIs(BB, Succ)) return false; |
Chris Lattner | cbd18fc | 2009-11-10 05:59:26 +0000 | [diff] [blame] | 846 | |
Reid Kleckner | bca59d2 | 2016-05-02 19:43:22 +0000 | [diff] [blame] | 847 | // Check for cases where Succ has multiple predecessors and a PHI node in BB |
| 848 | // has uses which will not disappear when the PHI nodes are merged. It is |
| 849 | // possible to handle such cases, but difficult: it requires checking whether |
| 850 | // BB dominates Succ, which is non-trivial to calculate in the case where |
| 851 | // Succ has multiple predecessors. Also, it requires checking whether |
| 852 | // constructing the necessary self-referential PHI node doesn't introduce any |
| 853 | // conflicts; this isn't too difficult, but the previous code for doing this |
| 854 | // was incorrect. |
| 855 | // |
| 856 | // Note that if this check finds a live use, BB dominates Succ, so BB is |
| 857 | // something like a loop pre-header (or rarely, a part of an irreducible CFG); |
| 858 | // folding the branch isn't profitable in that case anyway. |
| 859 | if (!Succ->getSinglePredecessor()) { |
| 860 | BasicBlock::iterator BBI = BB->begin(); |
| 861 | while (isa<PHINode>(*BBI)) { |
| 862 | for (Use &U : BBI->uses()) { |
| 863 | if (PHINode* PN = dyn_cast<PHINode>(U.getUser())) { |
| 864 | if (PN->getIncomingBlock(U) != BB) |
Hans Wennborg | b759932 | 2016-05-02 17:22:54 +0000 | [diff] [blame] | 865 | return false; |
Reid Kleckner | bca59d2 | 2016-05-02 19:43:22 +0000 | [diff] [blame] | 866 | } else { |
| 867 | return false; |
Hans Wennborg | b759932 | 2016-05-02 17:22:54 +0000 | [diff] [blame] | 868 | } |
Hans Wennborg | b759932 | 2016-05-02 17:22:54 +0000 | [diff] [blame] | 869 | } |
Reid Kleckner | bca59d2 | 2016-05-02 19:43:22 +0000 | [diff] [blame] | 870 | ++BBI; |
Hans Wennborg | b759932 | 2016-05-02 17:22:54 +0000 | [diff] [blame] | 871 | } |
Hans Wennborg | b759932 | 2016-05-02 17:22:54 +0000 | [diff] [blame] | 872 | } |
Reid Kleckner | bca59d2 | 2016-05-02 19:43:22 +0000 | [diff] [blame] | 873 | |
| 874 | DEBUG(dbgs() << "Killing Trivial BB: \n" << *BB); |
| 875 | |
| 876 | if (isa<PHINode>(Succ->begin())) { |
| 877 | // If there is more than one pred of succ, and there are PHI nodes in |
| 878 | // the successor, then we need to add incoming edges for the PHI nodes |
| 879 | // |
| 880 | const PredBlockVector BBPreds(pred_begin(BB), pred_end(BB)); |
| 881 | |
| 882 | // Loop over all of the PHI nodes in the successor of BB. |
| 883 | for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) { |
| 884 | PHINode *PN = cast<PHINode>(I); |
| 885 | |
| 886 | redirectValuesFromPredecessorsToPhi(BB, BBPreds, PN); |
| 887 | } |
| 888 | } |
| 889 | |
| 890 | if (Succ->getSinglePredecessor()) { |
| 891 | // BB is the only predecessor of Succ, so Succ will end up with exactly |
| 892 | // the same predecessors BB had. |
| 893 | |
| 894 | // Copy over any phi, debug or lifetime instruction. |
| 895 | BB->getTerminator()->eraseFromParent(); |
| 896 | Succ->getInstList().splice(Succ->getFirstNonPHI()->getIterator(), |
| 897 | BB->getInstList()); |
| 898 | } else { |
| 899 | while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) { |
| 900 | // We explicitly check for such uses in CanPropagatePredecessorsForPHIs. |
| 901 | assert(PN->use_empty() && "There shouldn't be any uses here!"); |
| 902 | PN->eraseFromParent(); |
| 903 | } |
| 904 | } |
| 905 | |
Florian Hahn | 77382be | 2016-11-18 13:12:07 +0000 | [diff] [blame] | 906 | // If the unconditional branch we replaced contains llvm.loop metadata, we |
| 907 | // add the metadata to the branch instructions in the predecessors. |
| 908 | unsigned LoopMDKind = BB->getContext().getMDKindID("llvm.loop"); |
| 909 | Instruction *TI = BB->getTerminator(); |
| 910 | if (TI) |
| 911 | if (MDNode *LoopMD = TI->getMetadata(LoopMDKind)) |
| 912 | for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) { |
| 913 | BasicBlock *Pred = *PI; |
| 914 | Pred->getTerminator()->setMetadata(LoopMDKind, LoopMD); |
| 915 | } |
| 916 | |
Reid Kleckner | bca59d2 | 2016-05-02 19:43:22 +0000 | [diff] [blame] | 917 | // Everything that jumped to BB now goes to Succ. |
| 918 | BB->replaceAllUsesWith(Succ); |
| 919 | if (!Succ->hasName()) Succ->takeName(BB); |
| 920 | BB->eraseFromParent(); // Delete the old basic block. |
| 921 | return true; |
Chris Lattner | cbd18fc | 2009-11-10 05:59:26 +0000 | [diff] [blame] | 922 | } |
| 923 | |
Jim Grosbach | d831ef4 | 2009-12-02 17:06:45 +0000 | [diff] [blame] | 924 | /// EliminateDuplicatePHINodes - Check for and eliminate duplicate PHI |
| 925 | /// nodes in this block. This doesn't try to be clever about PHI nodes |
| 926 | /// which differ only in the order of the incoming values, but instcombine |
| 927 | /// orders them so it usually won't matter. |
| 928 | /// |
| 929 | bool llvm::EliminateDuplicatePHINodes(BasicBlock *BB) { |
Jim Grosbach | d831ef4 | 2009-12-02 17:06:45 +0000 | [diff] [blame] | 930 | // This implementation doesn't currently consider undef operands |
Nick Lewycky | fa44dc6 | 2011-06-28 03:57:31 +0000 | [diff] [blame] | 931 | // specially. Theoretically, two phis which are identical except for |
Jim Grosbach | d831ef4 | 2009-12-02 17:06:45 +0000 | [diff] [blame] | 932 | // one having an undef where the other doesn't could be collapsed. |
| 933 | |
Benjamin Kramer | 2b2cdd7 | 2015-06-18 16:01:00 +0000 | [diff] [blame] | 934 | struct PHIDenseMapInfo { |
| 935 | static PHINode *getEmptyKey() { |
| 936 | return DenseMapInfo<PHINode *>::getEmptyKey(); |
| 937 | } |
| 938 | static PHINode *getTombstoneKey() { |
| 939 | return DenseMapInfo<PHINode *>::getTombstoneKey(); |
| 940 | } |
| 941 | static unsigned getHashValue(PHINode *PN) { |
| 942 | // Compute a hash value on the operands. Instcombine will likely have |
| 943 | // sorted them, which helps expose duplicates, but we have to check all |
| 944 | // the operands to be safe in case instcombine hasn't run. |
| 945 | return static_cast<unsigned>(hash_combine( |
| 946 | hash_combine_range(PN->value_op_begin(), PN->value_op_end()), |
| 947 | hash_combine_range(PN->block_begin(), PN->block_end()))); |
| 948 | } |
| 949 | static bool isEqual(PHINode *LHS, PHINode *RHS) { |
| 950 | if (LHS == getEmptyKey() || LHS == getTombstoneKey() || |
| 951 | RHS == getEmptyKey() || RHS == getTombstoneKey()) |
| 952 | return LHS == RHS; |
| 953 | return LHS->isIdenticalTo(RHS); |
| 954 | } |
| 955 | }; |
Jim Grosbach | d831ef4 | 2009-12-02 17:06:45 +0000 | [diff] [blame] | 956 | |
Benjamin Kramer | 2b2cdd7 | 2015-06-18 16:01:00 +0000 | [diff] [blame] | 957 | // Set of unique PHINodes. |
| 958 | DenseSet<PHINode *, PHIDenseMapInfo> PHISet; |
Jim Grosbach | d831ef4 | 2009-12-02 17:06:45 +0000 | [diff] [blame] | 959 | |
| 960 | // Examine each PHI. |
Benjamin Kramer | 2b2cdd7 | 2015-06-18 16:01:00 +0000 | [diff] [blame] | 961 | bool Changed = false; |
| 962 | for (auto I = BB->begin(); PHINode *PN = dyn_cast<PHINode>(I++);) { |
| 963 | auto Inserted = PHISet.insert(PN); |
| 964 | if (!Inserted.second) { |
| 965 | // A duplicate. Replace this PHI with its duplicate. |
| 966 | PN->replaceAllUsesWith(*Inserted.first); |
| 967 | PN->eraseFromParent(); |
| 968 | Changed = true; |
Benjamin Kramer | f175e04 | 2015-09-02 19:52:23 +0000 | [diff] [blame] | 969 | |
| 970 | // The RAUW can change PHIs that we already visited. Start over from the |
| 971 | // beginning. |
| 972 | PHISet.clear(); |
| 973 | I = BB->begin(); |
Jim Grosbach | d831ef4 | 2009-12-02 17:06:45 +0000 | [diff] [blame] | 974 | } |
| 975 | } |
| 976 | |
| 977 | return Changed; |
| 978 | } |
Chris Lattner | 6fcd32e | 2010-12-25 20:37:57 +0000 | [diff] [blame] | 979 | |
| 980 | /// enforceKnownAlignment - If the specified pointer points to an object that |
| 981 | /// we control, modify the object's alignment to PrefAlign. This isn't |
| 982 | /// often possible though. If alignment is important, a more reliable approach |
| 983 | /// is to simply align all global variables and allocation instructions to |
| 984 | /// their preferred alignment from the beginning. |
| 985 | /// |
Benjamin Kramer | 570dd78 | 2010-12-30 22:34:44 +0000 | [diff] [blame] | 986 | static unsigned enforceKnownAlignment(Value *V, unsigned Align, |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 987 | unsigned PrefAlign, |
| 988 | const DataLayout &DL) { |
James Y Knight | ac03dca | 2016-01-15 16:33:06 +0000 | [diff] [blame] | 989 | assert(PrefAlign > Align); |
| 990 | |
Eli Friedman | 19ace4c | 2011-06-15 21:08:25 +0000 | [diff] [blame] | 991 | V = V->stripPointerCasts(); |
Chris Lattner | 6fcd32e | 2010-12-25 20:37:57 +0000 | [diff] [blame] | 992 | |
Eli Friedman | 19ace4c | 2011-06-15 21:08:25 +0000 | [diff] [blame] | 993 | if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) { |
James Y Knight | ac03dca | 2016-01-15 16:33:06 +0000 | [diff] [blame] | 994 | // TODO: ideally, computeKnownBits ought to have used |
| 995 | // AllocaInst::getAlignment() in its computation already, making |
| 996 | // the below max redundant. But, as it turns out, |
| 997 | // stripPointerCasts recurses through infinite layers of bitcasts, |
| 998 | // while computeKnownBits is not allowed to traverse more than 6 |
| 999 | // levels. |
| 1000 | Align = std::max(AI->getAlignment(), Align); |
| 1001 | if (PrefAlign <= Align) |
| 1002 | return Align; |
| 1003 | |
Lang Hames | de7ab80 | 2011-10-10 23:42:08 +0000 | [diff] [blame] | 1004 | // If the preferred alignment is greater than the natural stack alignment |
| 1005 | // then don't round up. This avoids dynamic stack realignment. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 1006 | if (DL.exceedsNaturalStackAlignment(PrefAlign)) |
Lang Hames | de7ab80 | 2011-10-10 23:42:08 +0000 | [diff] [blame] | 1007 | return Align; |
Chris Lattner | 6fcd32e | 2010-12-25 20:37:57 +0000 | [diff] [blame] | 1008 | AI->setAlignment(PrefAlign); |
| 1009 | return PrefAlign; |
| 1010 | } |
Chris Lattner | 6fcd32e | 2010-12-25 20:37:57 +0000 | [diff] [blame] | 1011 | |
Rafael Espindola | 99e05cf | 2014-05-13 18:45:48 +0000 | [diff] [blame] | 1012 | if (auto *GO = dyn_cast<GlobalObject>(V)) { |
James Y Knight | ac03dca | 2016-01-15 16:33:06 +0000 | [diff] [blame] | 1013 | // TODO: as above, this shouldn't be necessary. |
| 1014 | Align = std::max(GO->getAlignment(), Align); |
| 1015 | if (PrefAlign <= Align) |
| 1016 | return Align; |
| 1017 | |
Chris Lattner | 6fcd32e | 2010-12-25 20:37:57 +0000 | [diff] [blame] | 1018 | // If there is a large requested alignment and we can, bump up the alignment |
Reid Kleckner | 486fa39 | 2015-07-14 00:11:08 +0000 | [diff] [blame] | 1019 | // of the global. If the memory we set aside for the global may not be the |
| 1020 | // memory used by the final program then it is impossible for us to reliably |
| 1021 | // enforce the preferred alignment. |
James Y Knight | ac03dca | 2016-01-15 16:33:06 +0000 | [diff] [blame] | 1022 | if (!GO->canIncreaseAlignment()) |
Rafael Espindola | fc13db4 | 2014-05-09 16:01:06 +0000 | [diff] [blame] | 1023 | return Align; |
Jakub Staszak | 8e1a6e7 | 2013-07-22 23:16:36 +0000 | [diff] [blame] | 1024 | |
James Y Knight | ac03dca | 2016-01-15 16:33:06 +0000 | [diff] [blame] | 1025 | GO->setAlignment(PrefAlign); |
| 1026 | return PrefAlign; |
Chris Lattner | 6fcd32e | 2010-12-25 20:37:57 +0000 | [diff] [blame] | 1027 | } |
| 1028 | |
| 1029 | return Align; |
| 1030 | } |
| 1031 | |
Chris Lattner | 6fcd32e | 2010-12-25 20:37:57 +0000 | [diff] [blame] | 1032 | unsigned llvm::getOrEnforceKnownAlignment(Value *V, unsigned PrefAlign, |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 1033 | const DataLayout &DL, |
Hal Finkel | 60db058 | 2014-09-07 18:57:58 +0000 | [diff] [blame] | 1034 | const Instruction *CxtI, |
Daniel Jasper | aec2fa3 | 2016-12-19 08:22:17 +0000 | [diff] [blame] | 1035 | AssumptionCache *AC, |
Hal Finkel | 60db058 | 2014-09-07 18:57:58 +0000 | [diff] [blame] | 1036 | const DominatorTree *DT) { |
Chris Lattner | 6fcd32e | 2010-12-25 20:37:57 +0000 | [diff] [blame] | 1037 | assert(V->getType()->isPointerTy() && |
| 1038 | "getOrEnforceKnownAlignment expects a pointer!"); |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 1039 | unsigned BitWidth = DL.getPointerTypeSizeInBits(V->getType()); |
Matt Arsenault | 87dc607 | 2013-08-01 22:42:18 +0000 | [diff] [blame] | 1040 | |
Chris Lattner | 6fcd32e | 2010-12-25 20:37:57 +0000 | [diff] [blame] | 1041 | APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0); |
Daniel Jasper | aec2fa3 | 2016-12-19 08:22:17 +0000 | [diff] [blame] | 1042 | computeKnownBits(V, KnownZero, KnownOne, DL, 0, AC, CxtI, DT); |
Chris Lattner | 6fcd32e | 2010-12-25 20:37:57 +0000 | [diff] [blame] | 1043 | unsigned TrailZ = KnownZero.countTrailingOnes(); |
Jakub Staszak | 8e1a6e7 | 2013-07-22 23:16:36 +0000 | [diff] [blame] | 1044 | |
Matt Arsenault | f64212b | 2013-07-23 22:20:57 +0000 | [diff] [blame] | 1045 | // Avoid trouble with ridiculously large TrailZ values, such as |
Chris Lattner | 6fcd32e | 2010-12-25 20:37:57 +0000 | [diff] [blame] | 1046 | // those computed from a null pointer. |
| 1047 | TrailZ = std::min(TrailZ, unsigned(sizeof(unsigned) * CHAR_BIT - 1)); |
Jakub Staszak | 8e1a6e7 | 2013-07-22 23:16:36 +0000 | [diff] [blame] | 1048 | |
Chris Lattner | 6fcd32e | 2010-12-25 20:37:57 +0000 | [diff] [blame] | 1049 | unsigned Align = 1u << std::min(BitWidth - 1, TrailZ); |
Jakub Staszak | 8e1a6e7 | 2013-07-22 23:16:36 +0000 | [diff] [blame] | 1050 | |
Chris Lattner | 6fcd32e | 2010-12-25 20:37:57 +0000 | [diff] [blame] | 1051 | // LLVM doesn't support alignments larger than this currently. |
| 1052 | Align = std::min(Align, +Value::MaximumAlignment); |
Jakub Staszak | 8e1a6e7 | 2013-07-22 23:16:36 +0000 | [diff] [blame] | 1053 | |
Chris Lattner | 6fcd32e | 2010-12-25 20:37:57 +0000 | [diff] [blame] | 1054 | if (PrefAlign > Align) |
Matt Arsenault | 87dc607 | 2013-08-01 22:42:18 +0000 | [diff] [blame] | 1055 | Align = enforceKnownAlignment(V, Align, PrefAlign, DL); |
Jakub Staszak | 8e1a6e7 | 2013-07-22 23:16:36 +0000 | [diff] [blame] | 1056 | |
Chris Lattner | 6fcd32e | 2010-12-25 20:37:57 +0000 | [diff] [blame] | 1057 | // We don't need to make any adjustment. |
| 1058 | return Align; |
| 1059 | } |
| 1060 | |
Devang Patel | 8c0b16b | 2011-03-17 21:58:19 +0000 | [diff] [blame] | 1061 | ///===---------------------------------------------------------------------===// |
| 1062 | /// Dbg Intrinsic utilities |
| 1063 | /// |
| 1064 | |
Adrian Prantl | 29b9de7 | 2013-04-26 17:48:33 +0000 | [diff] [blame] | 1065 | /// See if there is a dbg.value intrinsic for DIVar before I. |
Adrian Prantl | a5b2a64 | 2016-02-17 20:02:25 +0000 | [diff] [blame] | 1066 | static bool LdStHasDebugValue(DILocalVariable *DIVar, DIExpression *DIExpr, |
| 1067 | Instruction *I) { |
Adrian Prantl | 29b9de7 | 2013-04-26 17:48:33 +0000 | [diff] [blame] | 1068 | // Since we can't guarantee that the original dbg.declare instrinsic |
| 1069 | // is removed by LowerDbgDeclare(), we need to make sure that we are |
| 1070 | // not inserting the same dbg.value intrinsic over and over. |
| 1071 | llvm::BasicBlock::InstListType::iterator PrevI(I); |
| 1072 | if (PrevI != I->getParent()->getInstList().begin()) { |
| 1073 | --PrevI; |
| 1074 | if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(PrevI)) |
| 1075 | if (DVI->getValue() == I->getOperand(0) && |
| 1076 | DVI->getOffset() == 0 && |
Adrian Prantl | a5b2a64 | 2016-02-17 20:02:25 +0000 | [diff] [blame] | 1077 | DVI->getVariable() == DIVar && |
| 1078 | DVI->getExpression() == DIExpr) |
Adrian Prantl | 29b9de7 | 2013-04-26 17:48:33 +0000 | [diff] [blame] | 1079 | return true; |
| 1080 | } |
| 1081 | return false; |
| 1082 | } |
| 1083 | |
Keith Walker | ba15989 | 2016-09-22 14:13:25 +0000 | [diff] [blame] | 1084 | /// See if there is a dbg.value intrinsic for DIVar for the PHI node. |
| 1085 | static bool PhiHasDebugValue(DILocalVariable *DIVar, |
| 1086 | DIExpression *DIExpr, |
| 1087 | PHINode *APN) { |
| 1088 | // Since we can't guarantee that the original dbg.declare instrinsic |
| 1089 | // is removed by LowerDbgDeclare(), we need to make sure that we are |
| 1090 | // not inserting the same dbg.value intrinsic over and over. |
Adrian Prantl | fa9e84e | 2017-03-16 20:11:54 +0000 | [diff] [blame] | 1091 | SmallVector<DbgValueInst *, 1> DbgValues; |
| 1092 | findDbgValues(DbgValues, APN); |
| 1093 | for (auto *DVI : DbgValues) { |
| 1094 | assert(DVI->getValue() == APN); |
| 1095 | assert(DVI->getOffset() == 0); |
| 1096 | if ((DVI->getVariable() == DIVar) && (DVI->getExpression() == DIExpr)) |
| 1097 | return true; |
| 1098 | } |
| 1099 | return false; |
Keith Walker | ba15989 | 2016-09-22 14:13:25 +0000 | [diff] [blame] | 1100 | } |
| 1101 | |
Adrian Prantl | d00333a | 2013-04-26 18:10:50 +0000 | [diff] [blame] | 1102 | /// Inserts a llvm.dbg.value intrinsic before a store to an alloca'd value |
Devang Patel | 8c0b16b | 2011-03-17 21:58:19 +0000 | [diff] [blame] | 1103 | /// that has an associated llvm.dbg.decl intrinsic. |
Keith Walker | ba15989 | 2016-09-22 14:13:25 +0000 | [diff] [blame] | 1104 | void llvm::ConvertDebugDeclareToDebugValue(DbgDeclareInst *DDI, |
Devang Patel | 8c0b16b | 2011-03-17 21:58:19 +0000 | [diff] [blame] | 1105 | StoreInst *SI, DIBuilder &Builder) { |
Duncan P. N. Exon Smith | 60635e3 | 2015-04-21 18:44:06 +0000 | [diff] [blame] | 1106 | auto *DIVar = DDI->getVariable(); |
| 1107 | auto *DIExpr = DDI->getExpression(); |
Duncan P. N. Exon Smith | d4a19a3 | 2015-04-21 18:24:23 +0000 | [diff] [blame] | 1108 | assert(DIVar && "Missing variable"); |
Devang Patel | 8c0b16b | 2011-03-17 21:58:19 +0000 | [diff] [blame] | 1109 | |
Devang Patel | 8e60ff1 | 2011-05-16 21:24:05 +0000 | [diff] [blame] | 1110 | // If an argument is zero extended then use argument directly. The ZExt |
| 1111 | // may be zapped by an optimization pass in future. |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1112 | Argument *ExtendedArg = nullptr; |
Devang Patel | 8e60ff1 | 2011-05-16 21:24:05 +0000 | [diff] [blame] | 1113 | if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0))) |
| 1114 | ExtendedArg = dyn_cast<Argument>(ZExt->getOperand(0)); |
| 1115 | if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0))) |
| 1116 | ExtendedArg = dyn_cast<Argument>(SExt->getOperand(0)); |
Keno Fischer | 9aae445 | 2016-01-12 22:46:09 +0000 | [diff] [blame] | 1117 | if (ExtendedArg) { |
Adrian Prantl | 941fa75 | 2016-12-05 18:04:47 +0000 | [diff] [blame] | 1118 | // We're now only describing a subset of the variable. The fragment we're |
Keno Fischer | 9aae445 | 2016-01-12 22:46:09 +0000 | [diff] [blame] | 1119 | // describing will always be smaller than the variable size, because |
| 1120 | // VariableSize == Size of Alloca described by DDI. Since SI stores |
| 1121 | // to the alloca described by DDI, if it's first operand is an extend, |
| 1122 | // we're guaranteed that before extension, the value was narrower than |
| 1123 | // the size of the alloca, hence the size of the described variable. |
Adrian Prantl | a5b2a64 | 2016-02-17 20:02:25 +0000 | [diff] [blame] | 1124 | SmallVector<uint64_t, 3> Ops; |
Adrian Prantl | 941fa75 | 2016-12-05 18:04:47 +0000 | [diff] [blame] | 1125 | unsigned FragmentOffset = 0; |
| 1126 | // If this already is a bit fragment, we drop the bit fragment from the |
| 1127 | // expression and record the offset. |
Adrian Prantl | 49797ca | 2016-12-22 05:27:12 +0000 | [diff] [blame] | 1128 | auto Fragment = DIExpr->getFragmentInfo(); |
| 1129 | if (Fragment) { |
Adrian Prantl | a5b2a64 | 2016-02-17 20:02:25 +0000 | [diff] [blame] | 1130 | Ops.append(DIExpr->elements_begin(), DIExpr->elements_end()-3); |
Adrian Prantl | 49797ca | 2016-12-22 05:27:12 +0000 | [diff] [blame] | 1131 | FragmentOffset = Fragment->OffsetInBits; |
Keno Fischer | 9aae445 | 2016-01-12 22:46:09 +0000 | [diff] [blame] | 1132 | } else { |
Adrian Prantl | a5b2a64 | 2016-02-17 20:02:25 +0000 | [diff] [blame] | 1133 | Ops.append(DIExpr->elements_begin(), DIExpr->elements_end()); |
Keno Fischer | 9aae445 | 2016-01-12 22:46:09 +0000 | [diff] [blame] | 1134 | } |
Adrian Prantl | 941fa75 | 2016-12-05 18:04:47 +0000 | [diff] [blame] | 1135 | Ops.push_back(dwarf::DW_OP_LLVM_fragment); |
| 1136 | Ops.push_back(FragmentOffset); |
Keno Fischer | 9aae445 | 2016-01-12 22:46:09 +0000 | [diff] [blame] | 1137 | const DataLayout &DL = DDI->getModule()->getDataLayout(); |
Adrian Prantl | 941fa75 | 2016-12-05 18:04:47 +0000 | [diff] [blame] | 1138 | Ops.push_back(DL.getTypeSizeInBits(ExtendedArg->getType())); |
Adrian Prantl | a5b2a64 | 2016-02-17 20:02:25 +0000 | [diff] [blame] | 1139 | auto NewDIExpr = Builder.createExpression(Ops); |
| 1140 | if (!LdStHasDebugValue(DIVar, NewDIExpr, SI)) |
| 1141 | Builder.insertDbgValueIntrinsic(ExtendedArg, 0, DIVar, NewDIExpr, |
| 1142 | DDI->getDebugLoc(), SI); |
| 1143 | } else if (!LdStHasDebugValue(DIVar, DIExpr, SI)) |
Aaron Ballman | a2f9943 | 2015-04-16 13:29:36 +0000 | [diff] [blame] | 1144 | Builder.insertDbgValueIntrinsic(SI->getOperand(0), 0, DIVar, DIExpr, |
| 1145 | DDI->getDebugLoc(), SI); |
Devang Patel | 8c0b16b | 2011-03-17 21:58:19 +0000 | [diff] [blame] | 1146 | } |
| 1147 | |
Adrian Prantl | d00333a | 2013-04-26 18:10:50 +0000 | [diff] [blame] | 1148 | /// Inserts a llvm.dbg.value intrinsic before a load of an alloca'd value |
Devang Patel | 2c7ee27 | 2011-03-18 23:45:43 +0000 | [diff] [blame] | 1149 | /// that has an associated llvm.dbg.decl intrinsic. |
Keith Walker | ba15989 | 2016-09-22 14:13:25 +0000 | [diff] [blame] | 1150 | void llvm::ConvertDebugDeclareToDebugValue(DbgDeclareInst *DDI, |
Devang Patel | 2c7ee27 | 2011-03-18 23:45:43 +0000 | [diff] [blame] | 1151 | LoadInst *LI, DIBuilder &Builder) { |
Duncan P. N. Exon Smith | 60635e3 | 2015-04-21 18:44:06 +0000 | [diff] [blame] | 1152 | auto *DIVar = DDI->getVariable(); |
| 1153 | auto *DIExpr = DDI->getExpression(); |
Duncan P. N. Exon Smith | d4a19a3 | 2015-04-21 18:24:23 +0000 | [diff] [blame] | 1154 | assert(DIVar && "Missing variable"); |
Devang Patel | 2c7ee27 | 2011-03-18 23:45:43 +0000 | [diff] [blame] | 1155 | |
Adrian Prantl | a5b2a64 | 2016-02-17 20:02:25 +0000 | [diff] [blame] | 1156 | if (LdStHasDebugValue(DIVar, DIExpr, LI)) |
Keith Walker | ba15989 | 2016-09-22 14:13:25 +0000 | [diff] [blame] | 1157 | return; |
Adrian Prantl | 29b9de7 | 2013-04-26 17:48:33 +0000 | [diff] [blame] | 1158 | |
Keno Fischer | 00cbf9a | 2015-12-19 02:02:44 +0000 | [diff] [blame] | 1159 | // We are now tracking the loaded value instead of the address. In the |
| 1160 | // future if multi-location support is added to the IR, it might be |
| 1161 | // preferable to keep tracking both the loaded value and the original |
| 1162 | // address in case the alloca can not be elided. |
| 1163 | Instruction *DbgValue = Builder.insertDbgValueIntrinsic( |
| 1164 | LI, 0, DIVar, DIExpr, DDI->getDebugLoc(), (Instruction *)nullptr); |
| 1165 | DbgValue->insertAfter(LI); |
Keith Walker | ba15989 | 2016-09-22 14:13:25 +0000 | [diff] [blame] | 1166 | } |
| 1167 | |
| 1168 | /// Inserts a llvm.dbg.value intrinsic after a phi |
| 1169 | /// that has an associated llvm.dbg.decl intrinsic. |
| 1170 | void llvm::ConvertDebugDeclareToDebugValue(DbgDeclareInst *DDI, |
| 1171 | PHINode *APN, DIBuilder &Builder) { |
| 1172 | auto *DIVar = DDI->getVariable(); |
| 1173 | auto *DIExpr = DDI->getExpression(); |
| 1174 | assert(DIVar && "Missing variable"); |
| 1175 | |
| 1176 | if (PhiHasDebugValue(DIVar, DIExpr, APN)) |
| 1177 | return; |
| 1178 | |
Reid Kleckner | 6481822 | 2016-09-27 18:45:31 +0000 | [diff] [blame] | 1179 | BasicBlock *BB = APN->getParent(); |
Keith Walker | ba15989 | 2016-09-22 14:13:25 +0000 | [diff] [blame] | 1180 | auto InsertionPt = BB->getFirstInsertionPt(); |
Reid Kleckner | 6481822 | 2016-09-27 18:45:31 +0000 | [diff] [blame] | 1181 | |
| 1182 | // The block may be a catchswitch block, which does not have a valid |
| 1183 | // insertion point. |
| 1184 | // FIXME: Insert dbg.value markers in the successors when appropriate. |
| 1185 | if (InsertionPt != BB->end()) |
| 1186 | Builder.insertDbgValueIntrinsic(APN, 0, DIVar, DIExpr, DDI->getDebugLoc(), |
| 1187 | &*InsertionPt); |
Keith Walker | c941252 | 2016-09-19 09:49:30 +0000 | [diff] [blame] | 1188 | } |
| 1189 | |
Adrian Prantl | 232897f | 2014-04-25 23:00:25 +0000 | [diff] [blame] | 1190 | /// Determine whether this alloca is either a VLA or an array. |
| 1191 | static bool isArray(AllocaInst *AI) { |
| 1192 | return AI->isArrayAllocation() || |
| 1193 | AI->getType()->getElementType()->isArrayTy(); |
| 1194 | } |
| 1195 | |
Devang Patel | aad34d8 | 2011-03-17 22:18:16 +0000 | [diff] [blame] | 1196 | /// LowerDbgDeclare - Lowers llvm.dbg.declare intrinsics into appropriate set |
| 1197 | /// of llvm.dbg.value intrinsics. |
| 1198 | bool llvm::LowerDbgDeclare(Function &F) { |
Duncan P. N. Exon Smith | 5bf8fef | 2014-12-09 18:38:53 +0000 | [diff] [blame] | 1199 | DIBuilder DIB(*F.getParent(), /*AllowUnresolved*/ false); |
Devang Patel | aad34d8 | 2011-03-17 22:18:16 +0000 | [diff] [blame] | 1200 | SmallVector<DbgDeclareInst *, 4> Dbgs; |
Adrian Prantl | 79c8e8f | 2014-03-27 23:30:04 +0000 | [diff] [blame] | 1201 | for (auto &FI : F) |
Duncan P. N. Exon Smith | 5b4c837 | 2015-10-13 02:39:05 +0000 | [diff] [blame] | 1202 | for (Instruction &BI : FI) |
| 1203 | if (auto DDI = dyn_cast<DbgDeclareInst>(&BI)) |
Devang Patel | aad34d8 | 2011-03-17 22:18:16 +0000 | [diff] [blame] | 1204 | Dbgs.push_back(DDI); |
Adrian Prantl | 79c8e8f | 2014-03-27 23:30:04 +0000 | [diff] [blame] | 1205 | |
Devang Patel | aad34d8 | 2011-03-17 22:18:16 +0000 | [diff] [blame] | 1206 | if (Dbgs.empty()) |
| 1207 | return false; |
| 1208 | |
Adrian Prantl | 79c8e8f | 2014-03-27 23:30:04 +0000 | [diff] [blame] | 1209 | for (auto &I : Dbgs) { |
| 1210 | DbgDeclareInst *DDI = I; |
Adrian Prantl | 8e10fdb | 2013-11-18 23:04:38 +0000 | [diff] [blame] | 1211 | AllocaInst *AI = dyn_cast_or_null<AllocaInst>(DDI->getAddress()); |
| 1212 | // If this is an alloca for a scalar variable, insert a dbg.value |
| 1213 | // at each load and store to the alloca and erase the dbg.declare. |
Adrian Prantl | 32da889 | 2014-04-25 20:49:25 +0000 | [diff] [blame] | 1214 | // The dbg.values allow tracking a variable even if it is not |
| 1215 | // stored on the stack, while the dbg.declare can only describe |
| 1216 | // the stack slot (and at a lexical-scope granularity). Later |
| 1217 | // passes will attempt to elide the stack slot. |
Adrian Prantl | 232897f | 2014-04-25 23:00:25 +0000 | [diff] [blame] | 1218 | if (AI && !isArray(AI)) { |
Keno Fischer | 1dd319f | 2016-01-14 19:12:27 +0000 | [diff] [blame] | 1219 | for (auto &AIUse : AI->uses()) { |
| 1220 | User *U = AIUse.getUser(); |
| 1221 | if (StoreInst *SI = dyn_cast<StoreInst>(U)) { |
| 1222 | if (AIUse.getOperandNo() == 1) |
| 1223 | ConvertDebugDeclareToDebugValue(DDI, SI, DIB); |
| 1224 | } else if (LoadInst *LI = dyn_cast<LoadInst>(U)) { |
Devang Patel | 2c7ee27 | 2011-03-18 23:45:43 +0000 | [diff] [blame] | 1225 | ConvertDebugDeclareToDebugValue(DDI, LI, DIB); |
Keno Fischer | 1dd319f | 2016-01-14 19:12:27 +0000 | [diff] [blame] | 1226 | } else if (CallInst *CI = dyn_cast<CallInst>(U)) { |
NAKAMURA Takumi | 335a7bc | 2014-10-28 11:53:30 +0000 | [diff] [blame] | 1227 | // This is a call by-value or some other instruction that |
| 1228 | // takes a pointer to the variable. Insert a *value* |
| 1229 | // intrinsic that describes the alloca. |
Duncan P. N. Exon Smith | 60635e3 | 2015-04-21 18:44:06 +0000 | [diff] [blame] | 1230 | DIB.insertDbgValueIntrinsic(AI, 0, DDI->getVariable(), |
Adrian Prantl | 6825fb6 | 2017-04-18 01:21:53 +0000 | [diff] [blame^] | 1231 | DDI->getExpression(), DDI->getDebugLoc(), |
| 1232 | CI); |
Adrian Prantl | 87b7eb9 | 2014-10-01 18:55:02 +0000 | [diff] [blame] | 1233 | } |
Keno Fischer | 1dd319f | 2016-01-14 19:12:27 +0000 | [diff] [blame] | 1234 | } |
Adrian Prantl | 32da889 | 2014-04-25 20:49:25 +0000 | [diff] [blame] | 1235 | DDI->eraseFromParent(); |
Devang Patel | aad34d8 | 2011-03-17 22:18:16 +0000 | [diff] [blame] | 1236 | } |
Devang Patel | aad34d8 | 2011-03-17 22:18:16 +0000 | [diff] [blame] | 1237 | } |
| 1238 | return true; |
| 1239 | } |
Cameron Zwarich | 843bc7d | 2011-05-24 03:10:43 +0000 | [diff] [blame] | 1240 | |
| 1241 | /// FindAllocaDbgDeclare - Finds the llvm.dbg.declare intrinsic describing the |
| 1242 | /// alloca 'V', if any. |
| 1243 | DbgDeclareInst *llvm::FindAllocaDbgDeclare(Value *V) { |
Duncan P. N. Exon Smith | 5bf8fef | 2014-12-09 18:38:53 +0000 | [diff] [blame] | 1244 | if (auto *L = LocalAsMetadata::getIfExists(V)) |
| 1245 | if (auto *MDV = MetadataAsValue::getIfExists(V->getContext(), L)) |
| 1246 | for (User *U : MDV->users()) |
| 1247 | if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(U)) |
| 1248 | return DDI; |
Cameron Zwarich | 843bc7d | 2011-05-24 03:10:43 +0000 | [diff] [blame] | 1249 | |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1250 | return nullptr; |
Cameron Zwarich | 843bc7d | 2011-05-24 03:10:43 +0000 | [diff] [blame] | 1251 | } |
Alexey Samsonov | 3d43b63 | 2012-12-12 14:31:53 +0000 | [diff] [blame] | 1252 | |
Adrian Prantl | fa9e84e | 2017-03-16 20:11:54 +0000 | [diff] [blame] | 1253 | void llvm::findDbgValues(SmallVectorImpl<DbgValueInst *> &DbgValues, Value *V) { |
Keith Walker | ba15989 | 2016-09-22 14:13:25 +0000 | [diff] [blame] | 1254 | if (auto *L = LocalAsMetadata::getIfExists(V)) |
| 1255 | if (auto *MDV = MetadataAsValue::getIfExists(V->getContext(), L)) |
| 1256 | for (User *U : MDV->users()) |
| 1257 | if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(U)) |
Adrian Prantl | fa9e84e | 2017-03-16 20:11:54 +0000 | [diff] [blame] | 1258 | DbgValues.push_back(DVI); |
Keith Walker | ba15989 | 2016-09-22 14:13:25 +0000 | [diff] [blame] | 1259 | } |
| 1260 | |
Adrian Prantl | 47ea647 | 2017-03-16 21:14:09 +0000 | [diff] [blame] | 1261 | static void appendOffset(SmallVectorImpl<uint64_t> &Ops, int64_t Offset) { |
Evgeniy Stepanov | 72d961a | 2016-06-16 22:34:00 +0000 | [diff] [blame] | 1262 | if (Offset > 0) { |
Adrian Prantl | 47ea647 | 2017-03-16 21:14:09 +0000 | [diff] [blame] | 1263 | Ops.push_back(dwarf::DW_OP_plus); |
| 1264 | Ops.push_back(Offset); |
Evgeniy Stepanov | 72d961a | 2016-06-16 22:34:00 +0000 | [diff] [blame] | 1265 | } else if (Offset < 0) { |
Adrian Prantl | 47ea647 | 2017-03-16 21:14:09 +0000 | [diff] [blame] | 1266 | Ops.push_back(dwarf::DW_OP_minus); |
| 1267 | Ops.push_back(-Offset); |
Evgeniy Stepanov | 72d961a | 2016-06-16 22:34:00 +0000 | [diff] [blame] | 1268 | } |
| 1269 | } |
| 1270 | |
Adrian Prantl | 47ea647 | 2017-03-16 21:14:09 +0000 | [diff] [blame] | 1271 | /// Prepend \p DIExpr with a deref and offset operation. |
| 1272 | static DIExpression *prependDIExpr(DIBuilder &Builder, DIExpression *DIExpr, |
| 1273 | bool Deref, int64_t Offset) { |
Evgeniy Stepanov | 72d961a | 2016-06-16 22:34:00 +0000 | [diff] [blame] | 1274 | if (!Deref && !Offset) |
| 1275 | return DIExpr; |
| 1276 | // Create a copy of the original DIDescriptor for user variable, prepending |
| 1277 | // "deref" operation to a list of address elements, as new llvm.dbg.declare |
| 1278 | // will take a value storing address of the memory for variable, not |
| 1279 | // alloca itself. |
Adrian Prantl | 47ea647 | 2017-03-16 21:14:09 +0000 | [diff] [blame] | 1280 | SmallVector<uint64_t, 4> Ops; |
Evgeniy Stepanov | 72d961a | 2016-06-16 22:34:00 +0000 | [diff] [blame] | 1281 | if (Deref) |
Adrian Prantl | 47ea647 | 2017-03-16 21:14:09 +0000 | [diff] [blame] | 1282 | Ops.push_back(dwarf::DW_OP_deref); |
| 1283 | appendOffset(Ops, Offset); |
Evgeniy Stepanov | 72d961a | 2016-06-16 22:34:00 +0000 | [diff] [blame] | 1284 | if (DIExpr) |
Adrian Prantl | 47ea647 | 2017-03-16 21:14:09 +0000 | [diff] [blame] | 1285 | Ops.append(DIExpr->elements_begin(), DIExpr->elements_end()); |
| 1286 | return Builder.createExpression(Ops); |
Evgeniy Stepanov | 72d961a | 2016-06-16 22:34:00 +0000 | [diff] [blame] | 1287 | } |
| 1288 | |
Evgeniy Stepanov | 42f3b12 | 2015-12-01 00:40:05 +0000 | [diff] [blame] | 1289 | bool llvm::replaceDbgDeclare(Value *Address, Value *NewAddress, |
| 1290 | Instruction *InsertBefore, DIBuilder &Builder, |
| 1291 | bool Deref, int Offset) { |
| 1292 | DbgDeclareInst *DDI = FindAllocaDbgDeclare(Address); |
Alexey Samsonov | 3d43b63 | 2012-12-12 14:31:53 +0000 | [diff] [blame] | 1293 | if (!DDI) |
| 1294 | return false; |
Adrian Prantl | 3e2659e | 2015-01-30 19:37:48 +0000 | [diff] [blame] | 1295 | DebugLoc Loc = DDI->getDebugLoc(); |
Duncan P. N. Exon Smith | 60635e3 | 2015-04-21 18:44:06 +0000 | [diff] [blame] | 1296 | auto *DIVar = DDI->getVariable(); |
| 1297 | auto *DIExpr = DDI->getExpression(); |
Duncan P. N. Exon Smith | d4a19a3 | 2015-04-21 18:24:23 +0000 | [diff] [blame] | 1298 | assert(DIVar && "Missing variable"); |
Alexey Samsonov | 3d43b63 | 2012-12-12 14:31:53 +0000 | [diff] [blame] | 1299 | |
Adrian Prantl | 47ea647 | 2017-03-16 21:14:09 +0000 | [diff] [blame] | 1300 | DIExpr = prependDIExpr(Builder, DIExpr, Deref, Offset); |
Alexey Samsonov | 3d43b63 | 2012-12-12 14:31:53 +0000 | [diff] [blame] | 1301 | |
Evgeniy Stepanov | d8b86f7 | 2015-09-29 00:30:19 +0000 | [diff] [blame] | 1302 | // Insert llvm.dbg.declare immediately after the original alloca, and remove |
| 1303 | // old llvm.dbg.declare. |
Evgeniy Stepanov | 42f3b12 | 2015-12-01 00:40:05 +0000 | [diff] [blame] | 1304 | Builder.insertDeclare(NewAddress, DIVar, DIExpr, Loc, InsertBefore); |
Alexey Samsonov | 3d43b63 | 2012-12-12 14:31:53 +0000 | [diff] [blame] | 1305 | DDI->eraseFromParent(); |
| 1306 | return true; |
| 1307 | } |
Evgeniy Stepanov | 4fbc0d08 | 2012-12-21 11:18:49 +0000 | [diff] [blame] | 1308 | |
Evgeniy Stepanov | 42f3b12 | 2015-12-01 00:40:05 +0000 | [diff] [blame] | 1309 | bool llvm::replaceDbgDeclareForAlloca(AllocaInst *AI, Value *NewAllocaAddress, |
| 1310 | DIBuilder &Builder, bool Deref, int Offset) { |
| 1311 | return replaceDbgDeclare(AI, NewAllocaAddress, AI->getNextNode(), Builder, |
| 1312 | Deref, Offset); |
| 1313 | } |
| 1314 | |
Evgeniy Stepanov | 72d961a | 2016-06-16 22:34:00 +0000 | [diff] [blame] | 1315 | static void replaceOneDbgValueForAlloca(DbgValueInst *DVI, Value *NewAddress, |
| 1316 | DIBuilder &Builder, int Offset) { |
| 1317 | DebugLoc Loc = DVI->getDebugLoc(); |
| 1318 | auto *DIVar = DVI->getVariable(); |
| 1319 | auto *DIExpr = DVI->getExpression(); |
| 1320 | assert(DIVar && "Missing variable"); |
| 1321 | |
| 1322 | // This is an alloca-based llvm.dbg.value. The first thing it should do with |
| 1323 | // the alloca pointer is dereference it. Otherwise we don't know how to handle |
| 1324 | // it and give up. |
| 1325 | if (!DIExpr || DIExpr->getNumElements() < 1 || |
| 1326 | DIExpr->getElement(0) != dwarf::DW_OP_deref) |
| 1327 | return; |
| 1328 | |
| 1329 | // Insert the offset immediately after the first deref. |
| 1330 | // We could just change the offset argument of dbg.value, but it's unsigned... |
| 1331 | if (Offset) { |
Adrian Prantl | 47ea647 | 2017-03-16 21:14:09 +0000 | [diff] [blame] | 1332 | SmallVector<uint64_t, 4> Ops; |
| 1333 | Ops.push_back(dwarf::DW_OP_deref); |
| 1334 | appendOffset(Ops, Offset); |
| 1335 | Ops.append(DIExpr->elements_begin() + 1, DIExpr->elements_end()); |
| 1336 | DIExpr = Builder.createExpression(Ops); |
Evgeniy Stepanov | 72d961a | 2016-06-16 22:34:00 +0000 | [diff] [blame] | 1337 | } |
| 1338 | |
| 1339 | Builder.insertDbgValueIntrinsic(NewAddress, DVI->getOffset(), DIVar, DIExpr, |
| 1340 | Loc, DVI); |
| 1341 | DVI->eraseFromParent(); |
| 1342 | } |
| 1343 | |
| 1344 | void llvm::replaceDbgValueForAlloca(AllocaInst *AI, Value *NewAllocaAddress, |
| 1345 | DIBuilder &Builder, int Offset) { |
| 1346 | if (auto *L = LocalAsMetadata::getIfExists(AI)) |
| 1347 | if (auto *MDV = MetadataAsValue::getIfExists(AI->getContext(), L)) |
| 1348 | for (auto UI = MDV->use_begin(), UE = MDV->use_end(); UI != UE;) { |
| 1349 | Use &U = *UI++; |
| 1350 | if (auto *DVI = dyn_cast<DbgValueInst>(U.getUser())) |
| 1351 | replaceOneDbgValueForAlloca(DVI, NewAllocaAddress, Builder, Offset); |
| 1352 | } |
| 1353 | } |
| 1354 | |
Adrian Prantl | 47ea647 | 2017-03-16 21:14:09 +0000 | [diff] [blame] | 1355 | void llvm::salvageDebugInfo(Instruction &I) { |
| 1356 | SmallVector<DbgValueInst *, 1> DbgValues; |
| 1357 | auto &M = *I.getModule(); |
| 1358 | |
| 1359 | auto MDWrap = [&](Value *V) { |
| 1360 | return MetadataAsValue::get(I.getContext(), ValueAsMetadata::get(V)); |
| 1361 | }; |
| 1362 | |
Adrian Prantl | 6d80a26 | 2017-03-20 16:39:41 +0000 | [diff] [blame] | 1363 | if (isa<BitCastInst>(&I)) { |
| 1364 | findDbgValues(DbgValues, &I); |
Adrian Prantl | 47ea647 | 2017-03-16 21:14:09 +0000 | [diff] [blame] | 1365 | for (auto *DVI : DbgValues) { |
| 1366 | // Bitcasts are entirely irrelevant for debug info. Rewrite the dbg.value |
| 1367 | // to use the cast's source. |
| 1368 | DVI->setOperand(0, MDWrap(I.getOperand(0))); |
| 1369 | DEBUG(dbgs() << "SALVAGE: " << *DVI << '\n'); |
| 1370 | } |
| 1371 | } else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) { |
Adrian Prantl | 6d80a26 | 2017-03-20 16:39:41 +0000 | [diff] [blame] | 1372 | findDbgValues(DbgValues, &I); |
Adrian Prantl | 47ea647 | 2017-03-16 21:14:09 +0000 | [diff] [blame] | 1373 | for (auto *DVI : DbgValues) { |
| 1374 | unsigned BitWidth = |
| 1375 | M.getDataLayout().getPointerSizeInBits(GEP->getPointerAddressSpace()); |
| 1376 | APInt Offset(BitWidth, 0); |
| 1377 | // Rewrite a constant GEP into a DIExpression. |
| 1378 | if (GEP->accumulateConstantOffset(M.getDataLayout(), Offset)) { |
| 1379 | auto *DIExpr = DVI->getExpression(); |
| 1380 | DIBuilder DIB(M, /*AllowUnresolved*/ false); |
| 1381 | // GEP offsets are i32 and thus alwaus fit into an int64_t. |
| 1382 | DIExpr = prependDIExpr(DIB, DIExpr, NoDeref, Offset.getSExtValue()); |
| 1383 | DVI->setOperand(0, MDWrap(I.getOperand(0))); |
| 1384 | DVI->setOperand(3, MetadataAsValue::get(I.getContext(), DIExpr)); |
| 1385 | DEBUG(dbgs() << "SALVAGE: " << *DVI << '\n'); |
| 1386 | } |
| 1387 | } |
Adrian Prantl | 6d80a26 | 2017-03-20 16:39:41 +0000 | [diff] [blame] | 1388 | } else if (isa<LoadInst>(&I)) { |
| 1389 | findDbgValues(DbgValues, &I); |
Adrian Prantl | 47ea647 | 2017-03-16 21:14:09 +0000 | [diff] [blame] | 1390 | for (auto *DVI : DbgValues) { |
| 1391 | // Rewrite the load into DW_OP_deref. |
| 1392 | auto *DIExpr = DVI->getExpression(); |
| 1393 | DIBuilder DIB(M, /*AllowUnresolved*/ false); |
| 1394 | DIExpr = prependDIExpr(DIB, DIExpr, WithDeref, 0); |
| 1395 | DVI->setOperand(0, MDWrap(I.getOperand(0))); |
| 1396 | DVI->setOperand(3, MetadataAsValue::get(I.getContext(), DIExpr)); |
| 1397 | DEBUG(dbgs() << "SALVAGE: " << *DVI << '\n'); |
| 1398 | } |
| 1399 | } |
| 1400 | } |
| 1401 | |
David Majnemer | 35c46d3 | 2016-01-24 05:26:18 +0000 | [diff] [blame] | 1402 | unsigned llvm::removeAllNonTerminatorAndEHPadInstructions(BasicBlock *BB) { |
| 1403 | unsigned NumDeadInst = 0; |
| 1404 | // Delete the instructions backwards, as it has a reduced likelihood of |
| 1405 | // having to update as many def-use and use-def chains. |
| 1406 | Instruction *EndInst = BB->getTerminator(); // Last not to be deleted. |
Duncan P. N. Exon Smith | e9bc579 | 2016-02-21 20:39:50 +0000 | [diff] [blame] | 1407 | while (EndInst != &BB->front()) { |
David Majnemer | 35c46d3 | 2016-01-24 05:26:18 +0000 | [diff] [blame] | 1408 | // Delete the next to last instruction. |
| 1409 | Instruction *Inst = &*--EndInst->getIterator(); |
| 1410 | if (!Inst->use_empty() && !Inst->getType()->isTokenTy()) |
| 1411 | Inst->replaceAllUsesWith(UndefValue::get(Inst->getType())); |
| 1412 | if (Inst->isEHPad() || Inst->getType()->isTokenTy()) { |
| 1413 | EndInst = Inst; |
| 1414 | continue; |
| 1415 | } |
| 1416 | if (!isa<DbgInfoIntrinsic>(Inst)) |
| 1417 | ++NumDeadInst; |
| 1418 | Inst->eraseFromParent(); |
| 1419 | } |
| 1420 | return NumDeadInst; |
| 1421 | } |
| 1422 | |
Michael Zolotukhin | 5020c99 | 2016-11-18 21:01:12 +0000 | [diff] [blame] | 1423 | unsigned llvm::changeToUnreachable(Instruction *I, bool UseLLVMTrap, |
| 1424 | bool PreserveLCSSA) { |
Peter Collingbourne | 8d642de | 2013-08-12 22:38:43 +0000 | [diff] [blame] | 1425 | BasicBlock *BB = I->getParent(); |
| 1426 | // Loop over all of the successors, removing BB's entry from any PHI |
| 1427 | // nodes. |
David Majnemer | 9f50625 | 2016-06-25 08:34:38 +0000 | [diff] [blame] | 1428 | for (BasicBlock *Successor : successors(BB)) |
Michael Zolotukhin | 5020c99 | 2016-11-18 21:01:12 +0000 | [diff] [blame] | 1429 | Successor->removePredecessor(BB, PreserveLCSSA); |
Peter Collingbourne | 8d642de | 2013-08-12 22:38:43 +0000 | [diff] [blame] | 1430 | |
David Majnemer | e14e7bc | 2016-06-25 08:19:55 +0000 | [diff] [blame] | 1431 | // Insert a call to llvm.trap right before this. This turns the undefined |
| 1432 | // behavior into a hard fail instead of falling through into random code. |
| 1433 | if (UseLLVMTrap) { |
| 1434 | Function *TrapFn = |
| 1435 | Intrinsic::getDeclaration(BB->getParent()->getParent(), Intrinsic::trap); |
| 1436 | CallInst *CallTrap = CallInst::Create(TrapFn, "", I); |
| 1437 | CallTrap->setDebugLoc(I->getDebugLoc()); |
| 1438 | } |
Peter Collingbourne | 8d642de | 2013-08-12 22:38:43 +0000 | [diff] [blame] | 1439 | new UnreachableInst(I->getContext(), I); |
| 1440 | |
| 1441 | // All instructions after this are dead. |
David Majnemer | 88542a0 | 2016-01-24 06:26:47 +0000 | [diff] [blame] | 1442 | unsigned NumInstrsRemoved = 0; |
Duncan P. N. Exon Smith | 5b4c837 | 2015-10-13 02:39:05 +0000 | [diff] [blame] | 1443 | BasicBlock::iterator BBI = I->getIterator(), BBE = BB->end(); |
Peter Collingbourne | 8d642de | 2013-08-12 22:38:43 +0000 | [diff] [blame] | 1444 | while (BBI != BBE) { |
| 1445 | if (!BBI->use_empty()) |
| 1446 | BBI->replaceAllUsesWith(UndefValue::get(BBI->getType())); |
| 1447 | BB->getInstList().erase(BBI++); |
David Majnemer | 88542a0 | 2016-01-24 06:26:47 +0000 | [diff] [blame] | 1448 | ++NumInstrsRemoved; |
Peter Collingbourne | 8d642de | 2013-08-12 22:38:43 +0000 | [diff] [blame] | 1449 | } |
David Majnemer | 88542a0 | 2016-01-24 06:26:47 +0000 | [diff] [blame] | 1450 | return NumInstrsRemoved; |
Peter Collingbourne | 8d642de | 2013-08-12 22:38:43 +0000 | [diff] [blame] | 1451 | } |
| 1452 | |
| 1453 | /// changeToCall - Convert the specified invoke into a normal call. |
| 1454 | static void changeToCall(InvokeInst *II) { |
Sanjoy Das | ccd1456 | 2015-12-10 06:39:02 +0000 | [diff] [blame] | 1455 | SmallVector<Value*, 8> Args(II->arg_begin(), II->arg_end()); |
Sanjoy Das | 8a954a0 | 2015-12-08 22:26:08 +0000 | [diff] [blame] | 1456 | SmallVector<OperandBundleDef, 1> OpBundles; |
| 1457 | II->getOperandBundlesAsDefs(OpBundles); |
| 1458 | CallInst *NewCall = CallInst::Create(II->getCalledValue(), Args, OpBundles, |
| 1459 | "", II); |
Peter Collingbourne | 8d642de | 2013-08-12 22:38:43 +0000 | [diff] [blame] | 1460 | NewCall->takeName(II); |
| 1461 | NewCall->setCallingConv(II->getCallingConv()); |
| 1462 | NewCall->setAttributes(II->getAttributes()); |
| 1463 | NewCall->setDebugLoc(II->getDebugLoc()); |
| 1464 | II->replaceAllUsesWith(NewCall); |
| 1465 | |
| 1466 | // Follow the call by a branch to the normal destination. |
| 1467 | BranchInst::Create(II->getNormalDest(), II); |
| 1468 | |
| 1469 | // Update PHI nodes in the unwind destination |
| 1470 | II->getUnwindDest()->removePredecessor(II->getParent()); |
| 1471 | II->eraseFromParent(); |
| 1472 | } |
| 1473 | |
Kuba Brecka | ddfdba3 | 2016-11-14 21:41:13 +0000 | [diff] [blame] | 1474 | BasicBlock *llvm::changeToInvokeAndSplitBasicBlock(CallInst *CI, |
| 1475 | BasicBlock *UnwindEdge) { |
| 1476 | BasicBlock *BB = CI->getParent(); |
| 1477 | |
| 1478 | // Convert this function call into an invoke instruction. First, split the |
| 1479 | // basic block. |
| 1480 | BasicBlock *Split = |
| 1481 | BB->splitBasicBlock(CI->getIterator(), CI->getName() + ".noexc"); |
| 1482 | |
| 1483 | // Delete the unconditional branch inserted by splitBasicBlock |
| 1484 | BB->getInstList().pop_back(); |
| 1485 | |
| 1486 | // Create the new invoke instruction. |
| 1487 | SmallVector<Value *, 8> InvokeArgs(CI->arg_begin(), CI->arg_end()); |
| 1488 | SmallVector<OperandBundleDef, 1> OpBundles; |
| 1489 | |
| 1490 | CI->getOperandBundlesAsDefs(OpBundles); |
| 1491 | |
| 1492 | // Note: we're round tripping operand bundles through memory here, and that |
| 1493 | // can potentially be avoided with a cleverer API design that we do not have |
| 1494 | // as of this time. |
| 1495 | |
| 1496 | InvokeInst *II = InvokeInst::Create(CI->getCalledValue(), Split, UnwindEdge, |
| 1497 | InvokeArgs, OpBundles, CI->getName(), BB); |
| 1498 | II->setDebugLoc(CI->getDebugLoc()); |
| 1499 | II->setCallingConv(CI->getCallingConv()); |
| 1500 | II->setAttributes(CI->getAttributes()); |
| 1501 | |
| 1502 | // Make sure that anything using the call now uses the invoke! This also |
| 1503 | // updates the CallGraph if present, because it uses a WeakVH. |
| 1504 | CI->replaceAllUsesWith(II); |
| 1505 | |
| 1506 | // Delete the original call |
| 1507 | Split->getInstList().pop_front(); |
| 1508 | return Split; |
| 1509 | } |
| 1510 | |
David Majnemer | 7fddecc | 2015-06-17 20:52:32 +0000 | [diff] [blame] | 1511 | static bool markAliveBlocks(Function &F, |
Craig Topper | 71b7b68 | 2014-08-21 05:55:13 +0000 | [diff] [blame] | 1512 | SmallPtrSetImpl<BasicBlock*> &Reachable) { |
Peter Collingbourne | 8d642de | 2013-08-12 22:38:43 +0000 | [diff] [blame] | 1513 | |
Evgeniy Stepanov | 4fbc0d08 | 2012-12-21 11:18:49 +0000 | [diff] [blame] | 1514 | SmallVector<BasicBlock*, 128> Worklist; |
Duncan P. N. Exon Smith | 5b4c837 | 2015-10-13 02:39:05 +0000 | [diff] [blame] | 1515 | BasicBlock *BB = &F.front(); |
Peter Collingbourne | 8d642de | 2013-08-12 22:38:43 +0000 | [diff] [blame] | 1516 | Worklist.push_back(BB); |
| 1517 | Reachable.insert(BB); |
| 1518 | bool Changed = false; |
Evgeniy Stepanov | 4fbc0d08 | 2012-12-21 11:18:49 +0000 | [diff] [blame] | 1519 | do { |
Peter Collingbourne | 8d642de | 2013-08-12 22:38:43 +0000 | [diff] [blame] | 1520 | BB = Worklist.pop_back_val(); |
| 1521 | |
| 1522 | // Do a quick scan of the basic block, turning any obviously unreachable |
| 1523 | // instructions into LLVM unreachable insts. The instruction combining pass |
| 1524 | // canonicalizes unreachable insts into stores to null or undef. |
David Majnemer | 9f50625 | 2016-06-25 08:34:38 +0000 | [diff] [blame] | 1525 | for (Instruction &I : *BB) { |
Hal Finkel | 9304691 | 2014-07-25 21:13:35 +0000 | [diff] [blame] | 1526 | // Assumptions that are known to be false are equivalent to unreachable. |
| 1527 | // Also, if the condition is undefined, then we make the choice most |
| 1528 | // beneficial to the optimizer, and choose that to also be unreachable. |
David Majnemer | 9f50625 | 2016-06-25 08:34:38 +0000 | [diff] [blame] | 1529 | if (auto *II = dyn_cast<IntrinsicInst>(&I)) { |
Hal Finkel | 9304691 | 2014-07-25 21:13:35 +0000 | [diff] [blame] | 1530 | if (II->getIntrinsicID() == Intrinsic::assume) { |
David Majnemer | 9f50625 | 2016-06-25 08:34:38 +0000 | [diff] [blame] | 1531 | if (match(II->getArgOperand(0), m_CombineOr(m_Zero(), m_Undef()))) { |
David Majnemer | e14e7bc | 2016-06-25 08:19:55 +0000 | [diff] [blame] | 1532 | // Don't insert a call to llvm.trap right before the unreachable. |
David Majnemer | 9f50625 | 2016-06-25 08:34:38 +0000 | [diff] [blame] | 1533 | changeToUnreachable(II, false); |
Hal Finkel | 9304691 | 2014-07-25 21:13:35 +0000 | [diff] [blame] | 1534 | Changed = true; |
| 1535 | break; |
| 1536 | } |
| 1537 | } |
| 1538 | |
Sanjoy Das | 54a3a00 | 2016-04-21 05:09:12 +0000 | [diff] [blame] | 1539 | if (II->getIntrinsicID() == Intrinsic::experimental_guard) { |
| 1540 | // A call to the guard intrinsic bails out of the current compilation |
| 1541 | // unit if the predicate passed to it is false. If the predicate is a |
| 1542 | // constant false, then we know the guard will bail out of the current |
| 1543 | // compile unconditionally, so all code following it is dead. |
| 1544 | // |
| 1545 | // Note: unlike in llvm.assume, it is not "obviously profitable" for |
| 1546 | // guards to treat `undef` as `false` since a guard on `undef` can |
| 1547 | // still be useful for widening. |
David Majnemer | 9f50625 | 2016-06-25 08:34:38 +0000 | [diff] [blame] | 1548 | if (match(II->getArgOperand(0), m_Zero())) |
| 1549 | if (!isa<UnreachableInst>(II->getNextNode())) { |
David Majnemer | e14e7bc | 2016-06-25 08:19:55 +0000 | [diff] [blame] | 1550 | changeToUnreachable(II->getNextNode(), /*UseLLVMTrap=*/ false); |
Sanjoy Das | 54a3a00 | 2016-04-21 05:09:12 +0000 | [diff] [blame] | 1551 | Changed = true; |
| 1552 | break; |
| 1553 | } |
| 1554 | } |
| 1555 | } |
| 1556 | |
David Majnemer | 9f50625 | 2016-06-25 08:34:38 +0000 | [diff] [blame] | 1557 | if (auto *CI = dyn_cast<CallInst>(&I)) { |
David Majnemer | 1fea77c | 2016-06-25 07:37:27 +0000 | [diff] [blame] | 1558 | Value *Callee = CI->getCalledValue(); |
| 1559 | if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) { |
David Majnemer | e14e7bc | 2016-06-25 08:19:55 +0000 | [diff] [blame] | 1560 | changeToUnreachable(CI, /*UseLLVMTrap=*/false); |
David Majnemer | 1fea77c | 2016-06-25 07:37:27 +0000 | [diff] [blame] | 1561 | Changed = true; |
| 1562 | break; |
| 1563 | } |
Peter Collingbourne | 8d642de | 2013-08-12 22:38:43 +0000 | [diff] [blame] | 1564 | if (CI->doesNotReturn()) { |
| 1565 | // If we found a call to a no-return function, insert an unreachable |
| 1566 | // instruction after it. Make sure there isn't *already* one there |
| 1567 | // though. |
David Majnemer | 9f50625 | 2016-06-25 08:34:38 +0000 | [diff] [blame] | 1568 | if (!isa<UnreachableInst>(CI->getNextNode())) { |
David Majnemer | e14e7bc | 2016-06-25 08:19:55 +0000 | [diff] [blame] | 1569 | // Don't insert a call to llvm.trap right before the unreachable. |
David Majnemer | 9f50625 | 2016-06-25 08:34:38 +0000 | [diff] [blame] | 1570 | changeToUnreachable(CI->getNextNode(), false); |
Peter Collingbourne | 8d642de | 2013-08-12 22:38:43 +0000 | [diff] [blame] | 1571 | Changed = true; |
| 1572 | } |
| 1573 | break; |
| 1574 | } |
| 1575 | } |
| 1576 | |
| 1577 | // Store to undef and store to null are undefined and used to signal that |
| 1578 | // they should be changed to unreachable by passes that can't modify the |
| 1579 | // CFG. |
David Majnemer | 9f50625 | 2016-06-25 08:34:38 +0000 | [diff] [blame] | 1580 | if (auto *SI = dyn_cast<StoreInst>(&I)) { |
Peter Collingbourne | 8d642de | 2013-08-12 22:38:43 +0000 | [diff] [blame] | 1581 | // Don't touch volatile stores. |
| 1582 | if (SI->isVolatile()) continue; |
| 1583 | |
| 1584 | Value *Ptr = SI->getOperand(1); |
| 1585 | |
| 1586 | if (isa<UndefValue>(Ptr) || |
| 1587 | (isa<ConstantPointerNull>(Ptr) && |
| 1588 | SI->getPointerAddressSpace() == 0)) { |
David Majnemer | e14e7bc | 2016-06-25 08:19:55 +0000 | [diff] [blame] | 1589 | changeToUnreachable(SI, true); |
Peter Collingbourne | 8d642de | 2013-08-12 22:38:43 +0000 | [diff] [blame] | 1590 | Changed = true; |
| 1591 | break; |
| 1592 | } |
| 1593 | } |
| 1594 | } |
| 1595 | |
David Majnemer | 2fa8651 | 2016-01-05 06:27:50 +0000 | [diff] [blame] | 1596 | TerminatorInst *Terminator = BB->getTerminator(); |
| 1597 | if (auto *II = dyn_cast<InvokeInst>(Terminator)) { |
| 1598 | // Turn invokes that call 'nounwind' functions into ordinary calls. |
Peter Collingbourne | 8d642de | 2013-08-12 22:38:43 +0000 | [diff] [blame] | 1599 | Value *Callee = II->getCalledValue(); |
| 1600 | if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) { |
David Majnemer | e14e7bc | 2016-06-25 08:19:55 +0000 | [diff] [blame] | 1601 | changeToUnreachable(II, true); |
Peter Collingbourne | 8d642de | 2013-08-12 22:38:43 +0000 | [diff] [blame] | 1602 | Changed = true; |
David Majnemer | 7fddecc | 2015-06-17 20:52:32 +0000 | [diff] [blame] | 1603 | } else if (II->doesNotThrow() && canSimplifyInvokeNoUnwind(&F)) { |
Peter Collingbourne | 8d642de | 2013-08-12 22:38:43 +0000 | [diff] [blame] | 1604 | if (II->use_empty() && II->onlyReadsMemory()) { |
| 1605 | // jump to the normal destination branch. |
| 1606 | BranchInst::Create(II->getNormalDest(), II); |
| 1607 | II->getUnwindDest()->removePredecessor(II->getParent()); |
| 1608 | II->eraseFromParent(); |
| 1609 | } else |
| 1610 | changeToCall(II); |
| 1611 | Changed = true; |
| 1612 | } |
David Majnemer | 2fa8651 | 2016-01-05 06:27:50 +0000 | [diff] [blame] | 1613 | } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Terminator)) { |
| 1614 | // Remove catchpads which cannot be reached. |
David Majnemer | 59eb733 | 2016-01-05 07:42:17 +0000 | [diff] [blame] | 1615 | struct CatchPadDenseMapInfo { |
| 1616 | static CatchPadInst *getEmptyKey() { |
| 1617 | return DenseMapInfo<CatchPadInst *>::getEmptyKey(); |
| 1618 | } |
| 1619 | static CatchPadInst *getTombstoneKey() { |
| 1620 | return DenseMapInfo<CatchPadInst *>::getTombstoneKey(); |
| 1621 | } |
| 1622 | static unsigned getHashValue(CatchPadInst *CatchPad) { |
| 1623 | return static_cast<unsigned>(hash_combine_range( |
| 1624 | CatchPad->value_op_begin(), CatchPad->value_op_end())); |
| 1625 | } |
| 1626 | static bool isEqual(CatchPadInst *LHS, CatchPadInst *RHS) { |
| 1627 | if (LHS == getEmptyKey() || LHS == getTombstoneKey() || |
| 1628 | RHS == getEmptyKey() || RHS == getTombstoneKey()) |
| 1629 | return LHS == RHS; |
| 1630 | return LHS->isIdenticalTo(RHS); |
| 1631 | } |
| 1632 | }; |
| 1633 | |
| 1634 | // Set of unique CatchPads. |
| 1635 | SmallDenseMap<CatchPadInst *, detail::DenseSetEmpty, 4, |
| 1636 | CatchPadDenseMapInfo, detail::DenseSetPair<CatchPadInst *>> |
| 1637 | HandlerSet; |
| 1638 | detail::DenseSetEmpty Empty; |
David Majnemer | 2fa8651 | 2016-01-05 06:27:50 +0000 | [diff] [blame] | 1639 | for (CatchSwitchInst::handler_iterator I = CatchSwitch->handler_begin(), |
| 1640 | E = CatchSwitch->handler_end(); |
| 1641 | I != E; ++I) { |
| 1642 | BasicBlock *HandlerBB = *I; |
David Majnemer | 59eb733 | 2016-01-05 07:42:17 +0000 | [diff] [blame] | 1643 | auto *CatchPad = cast<CatchPadInst>(HandlerBB->getFirstNonPHI()); |
| 1644 | if (!HandlerSet.insert({CatchPad, Empty}).second) { |
David Majnemer | 2fa8651 | 2016-01-05 06:27:50 +0000 | [diff] [blame] | 1645 | CatchSwitch->removeHandler(I); |
| 1646 | --I; |
| 1647 | --E; |
| 1648 | Changed = true; |
| 1649 | } |
| 1650 | } |
Peter Collingbourne | 8d642de | 2013-08-12 22:38:43 +0000 | [diff] [blame] | 1651 | } |
| 1652 | |
| 1653 | Changed |= ConstantFoldTerminator(BB, true); |
David Majnemer | 9f50625 | 2016-06-25 08:34:38 +0000 | [diff] [blame] | 1654 | for (BasicBlock *Successor : successors(BB)) |
| 1655 | if (Reachable.insert(Successor).second) |
| 1656 | Worklist.push_back(Successor); |
Evgeniy Stepanov | 4fbc0d08 | 2012-12-21 11:18:49 +0000 | [diff] [blame] | 1657 | } while (!Worklist.empty()); |
Peter Collingbourne | 8d642de | 2013-08-12 22:38:43 +0000 | [diff] [blame] | 1658 | return Changed; |
| 1659 | } |
Evgeniy Stepanov | 4fbc0d08 | 2012-12-21 11:18:49 +0000 | [diff] [blame] | 1660 | |
Joseph Tremoulet | 09af67a | 2015-09-27 01:47:46 +0000 | [diff] [blame] | 1661 | void llvm::removeUnwindEdge(BasicBlock *BB) { |
| 1662 | TerminatorInst *TI = BB->getTerminator(); |
| 1663 | |
| 1664 | if (auto *II = dyn_cast<InvokeInst>(TI)) { |
| 1665 | changeToCall(II); |
| 1666 | return; |
| 1667 | } |
| 1668 | |
| 1669 | TerminatorInst *NewTI; |
| 1670 | BasicBlock *UnwindDest; |
| 1671 | |
| 1672 | if (auto *CRI = dyn_cast<CleanupReturnInst>(TI)) { |
| 1673 | NewTI = CleanupReturnInst::Create(CRI->getCleanupPad(), nullptr, CRI); |
| 1674 | UnwindDest = CRI->getUnwindDest(); |
David Majnemer | 8a1c45d | 2015-12-12 05:38:55 +0000 | [diff] [blame] | 1675 | } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(TI)) { |
| 1676 | auto *NewCatchSwitch = CatchSwitchInst::Create( |
| 1677 | CatchSwitch->getParentPad(), nullptr, CatchSwitch->getNumHandlers(), |
| 1678 | CatchSwitch->getName(), CatchSwitch); |
| 1679 | for (BasicBlock *PadBB : CatchSwitch->handlers()) |
| 1680 | NewCatchSwitch->addHandler(PadBB); |
| 1681 | |
| 1682 | NewTI = NewCatchSwitch; |
| 1683 | UnwindDest = CatchSwitch->getUnwindDest(); |
Joseph Tremoulet | 09af67a | 2015-09-27 01:47:46 +0000 | [diff] [blame] | 1684 | } else { |
| 1685 | llvm_unreachable("Could not find unwind successor"); |
| 1686 | } |
| 1687 | |
| 1688 | NewTI->takeName(TI); |
| 1689 | NewTI->setDebugLoc(TI->getDebugLoc()); |
| 1690 | UnwindDest->removePredecessor(BB); |
David Majnemer | 8a1c45d | 2015-12-12 05:38:55 +0000 | [diff] [blame] | 1691 | TI->replaceAllUsesWith(NewTI); |
Joseph Tremoulet | 09af67a | 2015-09-27 01:47:46 +0000 | [diff] [blame] | 1692 | TI->eraseFromParent(); |
| 1693 | } |
| 1694 | |
Peter Collingbourne | 8d642de | 2013-08-12 22:38:43 +0000 | [diff] [blame] | 1695 | /// removeUnreachableBlocksFromFn - Remove blocks that are not reachable, even |
| 1696 | /// if they are in a dead cycle. Return true if a change was made, false |
| 1697 | /// otherwise. |
Igor Laevsky | 87f0d0e | 2016-06-16 16:25:53 +0000 | [diff] [blame] | 1698 | bool llvm::removeUnreachableBlocks(Function &F, LazyValueInfo *LVI) { |
Matthias Braun | b30f2f51 | 2016-01-30 01:24:31 +0000 | [diff] [blame] | 1699 | SmallPtrSet<BasicBlock*, 16> Reachable; |
David Majnemer | 7fddecc | 2015-06-17 20:52:32 +0000 | [diff] [blame] | 1700 | bool Changed = markAliveBlocks(F, Reachable); |
Peter Collingbourne | 8d642de | 2013-08-12 22:38:43 +0000 | [diff] [blame] | 1701 | |
| 1702 | // If there are unreachable blocks in the CFG... |
Evgeniy Stepanov | 4fbc0d08 | 2012-12-21 11:18:49 +0000 | [diff] [blame] | 1703 | if (Reachable.size() == F.size()) |
Peter Collingbourne | 8d642de | 2013-08-12 22:38:43 +0000 | [diff] [blame] | 1704 | return Changed; |
Evgeniy Stepanov | 4fbc0d08 | 2012-12-21 11:18:49 +0000 | [diff] [blame] | 1705 | |
| 1706 | assert(Reachable.size() < F.size()); |
Peter Collingbourne | 8d642de | 2013-08-12 22:38:43 +0000 | [diff] [blame] | 1707 | NumRemoved += F.size()-Reachable.size(); |
| 1708 | |
| 1709 | // Loop over all of the basic blocks that are not reachable, dropping all of |
| 1710 | // their internal references... |
| 1711 | for (Function::iterator BB = ++F.begin(), E = F.end(); BB != E; ++BB) { |
Duncan P. N. Exon Smith | 5b4c837 | 2015-10-13 02:39:05 +0000 | [diff] [blame] | 1712 | if (Reachable.count(&*BB)) |
Evgeniy Stepanov | 4fbc0d08 | 2012-12-21 11:18:49 +0000 | [diff] [blame] | 1713 | continue; |
| 1714 | |
David Majnemer | 9f50625 | 2016-06-25 08:34:38 +0000 | [diff] [blame] | 1715 | for (BasicBlock *Successor : successors(&*BB)) |
| 1716 | if (Reachable.count(Successor)) |
| 1717 | Successor->removePredecessor(&*BB); |
David Majnemer | d9833ea | 2016-01-10 07:13:04 +0000 | [diff] [blame] | 1718 | if (LVI) |
| 1719 | LVI->eraseBlock(&*BB); |
Peter Collingbourne | 8d642de | 2013-08-12 22:38:43 +0000 | [diff] [blame] | 1720 | BB->dropAllReferences(); |
Evgeniy Stepanov | 4fbc0d08 | 2012-12-21 11:18:49 +0000 | [diff] [blame] | 1721 | } |
Evgeniy Stepanov | 2a066af | 2013-03-22 08:43:04 +0000 | [diff] [blame] | 1722 | |
Peter Collingbourne | 8d642de | 2013-08-12 22:38:43 +0000 | [diff] [blame] | 1723 | for (Function::iterator I = ++F.begin(); I != F.end();) |
Duncan P. N. Exon Smith | 5b4c837 | 2015-10-13 02:39:05 +0000 | [diff] [blame] | 1724 | if (!Reachable.count(&*I)) |
Evgeniy Stepanov | 2a066af | 2013-03-22 08:43:04 +0000 | [diff] [blame] | 1725 | I = F.getBasicBlockList().erase(I); |
| 1726 | else |
| 1727 | ++I; |
| 1728 | |
Evgeniy Stepanov | 4fbc0d08 | 2012-12-21 11:18:49 +0000 | [diff] [blame] | 1729 | return true; |
| 1730 | } |
Rafael Espindola | ea46c32 | 2014-08-15 15:46:38 +0000 | [diff] [blame] | 1731 | |
Piotr Padlewski | dc9b2cf | 2015-10-02 22:12:22 +0000 | [diff] [blame] | 1732 | void llvm::combineMetadata(Instruction *K, const Instruction *J, |
| 1733 | ArrayRef<unsigned> KnownIDs) { |
Duncan P. N. Exon Smith | de36e80 | 2014-11-11 21:30:22 +0000 | [diff] [blame] | 1734 | SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata; |
Adrian Prantl | cbdfdb7 | 2015-08-20 22:00:30 +0000 | [diff] [blame] | 1735 | K->dropUnknownNonDebugMetadata(KnownIDs); |
Rafael Espindola | ea46c32 | 2014-08-15 15:46:38 +0000 | [diff] [blame] | 1736 | K->getAllMetadataOtherThanDebugLoc(Metadata); |
David Majnemer | 6f014d3 | 2016-07-25 02:21:19 +0000 | [diff] [blame] | 1737 | for (const auto &MD : Metadata) { |
| 1738 | unsigned Kind = MD.first; |
Duncan P. N. Exon Smith | de36e80 | 2014-11-11 21:30:22 +0000 | [diff] [blame] | 1739 | MDNode *JMD = J->getMetadata(Kind); |
David Majnemer | 6f014d3 | 2016-07-25 02:21:19 +0000 | [diff] [blame] | 1740 | MDNode *KMD = MD.second; |
Rafael Espindola | ea46c32 | 2014-08-15 15:46:38 +0000 | [diff] [blame] | 1741 | |
| 1742 | switch (Kind) { |
| 1743 | default: |
| 1744 | K->setMetadata(Kind, nullptr); // Remove unknown metadata |
| 1745 | break; |
| 1746 | case LLVMContext::MD_dbg: |
| 1747 | llvm_unreachable("getAllMetadataOtherThanDebugLoc returned a MD_dbg"); |
| 1748 | case LLVMContext::MD_tbaa: |
| 1749 | K->setMetadata(Kind, MDNode::getMostGenericTBAA(JMD, KMD)); |
| 1750 | break; |
| 1751 | case LLVMContext::MD_alias_scope: |
Bjorn Steinbrink | 5ec7522 | 2015-02-08 17:07:14 +0000 | [diff] [blame] | 1752 | K->setMetadata(Kind, MDNode::getMostGenericAliasScope(JMD, KMD)); |
| 1753 | break; |
Rafael Espindola | ea46c32 | 2014-08-15 15:46:38 +0000 | [diff] [blame] | 1754 | case LLVMContext::MD_noalias: |
Hal Finkel | e4c0c16 | 2016-04-26 02:06:06 +0000 | [diff] [blame] | 1755 | case LLVMContext::MD_mem_parallel_loop_access: |
Rafael Espindola | ea46c32 | 2014-08-15 15:46:38 +0000 | [diff] [blame] | 1756 | K->setMetadata(Kind, MDNode::intersect(JMD, KMD)); |
| 1757 | break; |
| 1758 | case LLVMContext::MD_range: |
| 1759 | K->setMetadata(Kind, MDNode::getMostGenericRange(JMD, KMD)); |
| 1760 | break; |
| 1761 | case LLVMContext::MD_fpmath: |
| 1762 | K->setMetadata(Kind, MDNode::getMostGenericFPMath(JMD, KMD)); |
| 1763 | break; |
| 1764 | case LLVMContext::MD_invariant_load: |
| 1765 | // Only set the !invariant.load if it is present in both instructions. |
| 1766 | K->setMetadata(Kind, JMD); |
| 1767 | break; |
Philip Reames | d7c2136 | 2014-10-21 21:02:19 +0000 | [diff] [blame] | 1768 | case LLVMContext::MD_nonnull: |
| 1769 | // Only set the !nonnull if it is present in both instructions. |
| 1770 | K->setMetadata(Kind, JMD); |
| 1771 | break; |
Piotr Padlewski | dc9b2cf | 2015-10-02 22:12:22 +0000 | [diff] [blame] | 1772 | case LLVMContext::MD_invariant_group: |
| 1773 | // Preserve !invariant.group in K. |
| 1774 | break; |
Artur Pilipenko | 5c5011d | 2015-11-02 17:53:51 +0000 | [diff] [blame] | 1775 | case LLVMContext::MD_align: |
| 1776 | K->setMetadata(Kind, |
| 1777 | MDNode::getMostGenericAlignmentOrDereferenceable(JMD, KMD)); |
| 1778 | break; |
| 1779 | case LLVMContext::MD_dereferenceable: |
| 1780 | case LLVMContext::MD_dereferenceable_or_null: |
| 1781 | K->setMetadata(Kind, |
| 1782 | MDNode::getMostGenericAlignmentOrDereferenceable(JMD, KMD)); |
| 1783 | break; |
Rafael Espindola | ea46c32 | 2014-08-15 15:46:38 +0000 | [diff] [blame] | 1784 | } |
| 1785 | } |
Piotr Padlewski | dc9b2cf | 2015-10-02 22:12:22 +0000 | [diff] [blame] | 1786 | // Set !invariant.group from J if J has it. If both instructions have it |
| 1787 | // then we will just pick it from J - even when they are different. |
| 1788 | // Also make sure that K is load or store - f.e. combining bitcast with load |
| 1789 | // could produce bitcast with invariant.group metadata, which is invalid. |
| 1790 | // FIXME: we should try to preserve both invariant.group md if they are |
| 1791 | // different, but right now instruction can only have one invariant.group. |
| 1792 | if (auto *JMD = J->getMetadata(LLVMContext::MD_invariant_group)) |
| 1793 | if (isa<LoadInst>(K) || isa<StoreInst>(K)) |
| 1794 | K->setMetadata(LLVMContext::MD_invariant_group, JMD); |
Rafael Espindola | ea46c32 | 2014-08-15 15:46:38 +0000 | [diff] [blame] | 1795 | } |
Philip Reames | 7c78ef7 | 2015-05-22 23:53:24 +0000 | [diff] [blame] | 1796 | |
Eli Friedman | 02419a9 | 2016-08-08 04:10:22 +0000 | [diff] [blame] | 1797 | void llvm::combineMetadataForCSE(Instruction *K, const Instruction *J) { |
| 1798 | unsigned KnownIDs[] = { |
| 1799 | LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope, |
| 1800 | LLVMContext::MD_noalias, LLVMContext::MD_range, |
| 1801 | LLVMContext::MD_invariant_load, LLVMContext::MD_nonnull, |
| 1802 | LLVMContext::MD_invariant_group, LLVMContext::MD_align, |
| 1803 | LLVMContext::MD_dereferenceable, |
| 1804 | LLVMContext::MD_dereferenceable_or_null}; |
| 1805 | combineMetadata(K, J, KnownIDs); |
| 1806 | } |
| 1807 | |
Philip Reames | 7c78ef7 | 2015-05-22 23:53:24 +0000 | [diff] [blame] | 1808 | unsigned llvm::replaceDominatedUsesWith(Value *From, Value *To, |
| 1809 | DominatorTree &DT, |
| 1810 | const BasicBlockEdge &Root) { |
| 1811 | assert(From->getType() == To->getType()); |
| 1812 | |
| 1813 | unsigned Count = 0; |
| 1814 | for (Value::use_iterator UI = From->use_begin(), UE = From->use_end(); |
| 1815 | UI != UE; ) { |
| 1816 | Use &U = *UI++; |
| 1817 | if (DT.dominates(Root, U)) { |
| 1818 | U.set(To); |
| 1819 | DEBUG(dbgs() << "Replace dominated use of '" |
| 1820 | << From->getName() << "' as " |
| 1821 | << *To << " in " << *U << "\n"); |
| 1822 | ++Count; |
| 1823 | } |
| 1824 | } |
| 1825 | return Count; |
| 1826 | } |
Piotr Padlewski | 28ffcbe | 2015-09-02 19:59:59 +0000 | [diff] [blame] | 1827 | |
| 1828 | unsigned llvm::replaceDominatedUsesWith(Value *From, Value *To, |
| 1829 | DominatorTree &DT, |
Dehao Chen | db38107 | 2016-09-08 15:25:12 +0000 | [diff] [blame] | 1830 | const BasicBlock *BB) { |
Piotr Padlewski | 28ffcbe | 2015-09-02 19:59:59 +0000 | [diff] [blame] | 1831 | assert(From->getType() == To->getType()); |
| 1832 | |
| 1833 | unsigned Count = 0; |
| 1834 | for (Value::use_iterator UI = From->use_begin(), UE = From->use_end(); |
| 1835 | UI != UE;) { |
| 1836 | Use &U = *UI++; |
| 1837 | auto *I = cast<Instruction>(U.getUser()); |
Dehao Chen | db38107 | 2016-09-08 15:25:12 +0000 | [diff] [blame] | 1838 | if (DT.properlyDominates(BB, I->getParent())) { |
Piotr Padlewski | 28ffcbe | 2015-09-02 19:59:59 +0000 | [diff] [blame] | 1839 | U.set(To); |
| 1840 | DEBUG(dbgs() << "Replace dominated use of '" << From->getName() << "' as " |
| 1841 | << *To << " in " << *U << "\n"); |
| 1842 | ++Count; |
| 1843 | } |
| 1844 | } |
| 1845 | return Count; |
| 1846 | } |
Sanjoy Das | c21a05a | 2015-10-08 23:18:30 +0000 | [diff] [blame] | 1847 | |
| 1848 | bool llvm::callsGCLeafFunction(ImmutableCallSite CS) { |
Sanjoy Das | c21a05a | 2015-10-08 23:18:30 +0000 | [diff] [blame] | 1849 | // Check if the function is specifically marked as a gc leaf function. |
Manuel Jacob | 3eedd11 | 2016-01-05 23:59:08 +0000 | [diff] [blame] | 1850 | if (CS.hasFnAttr("gc-leaf-function")) |
| 1851 | return true; |
Sanjoy Das | d4c7833 | 2016-03-25 20:12:13 +0000 | [diff] [blame] | 1852 | if (const Function *F = CS.getCalledFunction()) { |
| 1853 | if (F->hasFnAttribute("gc-leaf-function")) |
| 1854 | return true; |
| 1855 | |
| 1856 | if (auto IID = F->getIntrinsicID()) |
| 1857 | // Most LLVM intrinsics do not take safepoints. |
| 1858 | return IID != Intrinsic::experimental_gc_statepoint && |
| 1859 | IID != Intrinsic::experimental_deoptimize; |
| 1860 | } |
Sanjoy Das | c21a05a | 2015-10-08 23:18:30 +0000 | [diff] [blame] | 1861 | |
| 1862 | return false; |
| 1863 | } |
James Molloy | f01488e | 2016-01-15 09:20:19 +0000 | [diff] [blame] | 1864 | |
Benjamin Kramer | b7d3311 | 2016-08-06 11:13:10 +0000 | [diff] [blame] | 1865 | namespace { |
James Molloy | f01488e | 2016-01-15 09:20:19 +0000 | [diff] [blame] | 1866 | /// A potential constituent of a bitreverse or bswap expression. See |
| 1867 | /// collectBitParts for a fuller explanation. |
| 1868 | struct BitPart { |
| 1869 | BitPart(Value *P, unsigned BW) : Provider(P) { |
| 1870 | Provenance.resize(BW); |
| 1871 | } |
| 1872 | |
| 1873 | /// The Value that this is a bitreverse/bswap of. |
| 1874 | Value *Provider; |
| 1875 | /// The "provenance" of each bit. Provenance[A] = B means that bit A |
| 1876 | /// in Provider becomes bit B in the result of this expression. |
| 1877 | SmallVector<int8_t, 32> Provenance; // int8_t means max size is i128. |
| 1878 | |
| 1879 | enum { Unset = -1 }; |
| 1880 | }; |
Benjamin Kramer | b7d3311 | 2016-08-06 11:13:10 +0000 | [diff] [blame] | 1881 | } // end anonymous namespace |
James Molloy | f01488e | 2016-01-15 09:20:19 +0000 | [diff] [blame] | 1882 | |
| 1883 | /// Analyze the specified subexpression and see if it is capable of providing |
| 1884 | /// pieces of a bswap or bitreverse. The subexpression provides a potential |
| 1885 | /// piece of a bswap or bitreverse if it can be proven that each non-zero bit in |
| 1886 | /// the output of the expression came from a corresponding bit in some other |
| 1887 | /// value. This function is recursive, and the end result is a mapping of |
| 1888 | /// bitnumber to bitnumber. It is the caller's responsibility to validate that |
| 1889 | /// the bitnumber to bitnumber mapping is correct for a bswap or bitreverse. |
| 1890 | /// |
| 1891 | /// For example, if the current subexpression if "(shl i32 %X, 24)" then we know |
| 1892 | /// that the expression deposits the low byte of %X into the high byte of the |
| 1893 | /// result and that all other bits are zero. This expression is accepted and a |
| 1894 | /// BitPart is returned with Provider set to %X and Provenance[24-31] set to |
| 1895 | /// [0-7]. |
| 1896 | /// |
| 1897 | /// To avoid revisiting values, the BitPart results are memoized into the |
| 1898 | /// provided map. To avoid unnecessary copying of BitParts, BitParts are |
| 1899 | /// constructed in-place in the \c BPS map. Because of this \c BPS needs to |
| 1900 | /// store BitParts objects, not pointers. As we need the concept of a nullptr |
| 1901 | /// BitParts (Value has been analyzed and the analysis failed), we an Optional |
| 1902 | /// type instead to provide the same functionality. |
| 1903 | /// |
| 1904 | /// Because we pass around references into \c BPS, we must use a container that |
| 1905 | /// does not invalidate internal references (std::map instead of DenseMap). |
| 1906 | /// |
| 1907 | static const Optional<BitPart> & |
| 1908 | collectBitParts(Value *V, bool MatchBSwaps, bool MatchBitReversals, |
| 1909 | std::map<Value *, Optional<BitPart>> &BPS) { |
| 1910 | auto I = BPS.find(V); |
| 1911 | if (I != BPS.end()) |
| 1912 | return I->second; |
| 1913 | |
| 1914 | auto &Result = BPS[V] = None; |
| 1915 | auto BitWidth = cast<IntegerType>(V->getType())->getBitWidth(); |
| 1916 | |
| 1917 | if (Instruction *I = dyn_cast<Instruction>(V)) { |
| 1918 | // If this is an or instruction, it may be an inner node of the bswap. |
| 1919 | if (I->getOpcode() == Instruction::Or) { |
| 1920 | auto &A = collectBitParts(I->getOperand(0), MatchBSwaps, |
| 1921 | MatchBitReversals, BPS); |
| 1922 | auto &B = collectBitParts(I->getOperand(1), MatchBSwaps, |
| 1923 | MatchBitReversals, BPS); |
| 1924 | if (!A || !B) |
| 1925 | return Result; |
| 1926 | |
| 1927 | // Try and merge the two together. |
| 1928 | if (!A->Provider || A->Provider != B->Provider) |
| 1929 | return Result; |
| 1930 | |
| 1931 | Result = BitPart(A->Provider, BitWidth); |
| 1932 | for (unsigned i = 0; i < A->Provenance.size(); ++i) { |
| 1933 | if (A->Provenance[i] != BitPart::Unset && |
| 1934 | B->Provenance[i] != BitPart::Unset && |
| 1935 | A->Provenance[i] != B->Provenance[i]) |
| 1936 | return Result = None; |
| 1937 | |
| 1938 | if (A->Provenance[i] == BitPart::Unset) |
| 1939 | Result->Provenance[i] = B->Provenance[i]; |
| 1940 | else |
| 1941 | Result->Provenance[i] = A->Provenance[i]; |
| 1942 | } |
| 1943 | |
| 1944 | return Result; |
| 1945 | } |
| 1946 | |
| 1947 | // If this is a logical shift by a constant, recurse then shift the result. |
| 1948 | if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) { |
| 1949 | unsigned BitShift = |
| 1950 | cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U); |
| 1951 | // Ensure the shift amount is defined. |
| 1952 | if (BitShift > BitWidth) |
| 1953 | return Result; |
| 1954 | |
| 1955 | auto &Res = collectBitParts(I->getOperand(0), MatchBSwaps, |
| 1956 | MatchBitReversals, BPS); |
| 1957 | if (!Res) |
| 1958 | return Result; |
| 1959 | Result = Res; |
| 1960 | |
| 1961 | // Perform the "shift" on BitProvenance. |
| 1962 | auto &P = Result->Provenance; |
| 1963 | if (I->getOpcode() == Instruction::Shl) { |
| 1964 | P.erase(std::prev(P.end(), BitShift), P.end()); |
| 1965 | P.insert(P.begin(), BitShift, BitPart::Unset); |
| 1966 | } else { |
| 1967 | P.erase(P.begin(), std::next(P.begin(), BitShift)); |
| 1968 | P.insert(P.end(), BitShift, BitPart::Unset); |
| 1969 | } |
| 1970 | |
| 1971 | return Result; |
| 1972 | } |
| 1973 | |
| 1974 | // If this is a logical 'and' with a mask that clears bits, recurse then |
| 1975 | // unset the appropriate bits. |
| 1976 | if (I->getOpcode() == Instruction::And && |
| 1977 | isa<ConstantInt>(I->getOperand(1))) { |
| 1978 | APInt Bit(I->getType()->getPrimitiveSizeInBits(), 1); |
| 1979 | const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue(); |
| 1980 | |
| 1981 | // Check that the mask allows a multiple of 8 bits for a bswap, for an |
| 1982 | // early exit. |
| 1983 | unsigned NumMaskedBits = AndMask.countPopulation(); |
| 1984 | if (!MatchBitReversals && NumMaskedBits % 8 != 0) |
| 1985 | return Result; |
| 1986 | |
| 1987 | auto &Res = collectBitParts(I->getOperand(0), MatchBSwaps, |
| 1988 | MatchBitReversals, BPS); |
| 1989 | if (!Res) |
| 1990 | return Result; |
| 1991 | Result = Res; |
| 1992 | |
| 1993 | for (unsigned i = 0; i < BitWidth; ++i, Bit <<= 1) |
| 1994 | // If the AndMask is zero for this bit, clear the bit. |
| 1995 | if ((AndMask & Bit) == 0) |
| 1996 | Result->Provenance[i] = BitPart::Unset; |
Chad Rosier | e5819e2 | 2016-05-26 14:58:51 +0000 | [diff] [blame] | 1997 | return Result; |
| 1998 | } |
James Molloy | f01488e | 2016-01-15 09:20:19 +0000 | [diff] [blame] | 1999 | |
Chad Rosier | e5819e2 | 2016-05-26 14:58:51 +0000 | [diff] [blame] | 2000 | // If this is a zext instruction zero extend the result. |
| 2001 | if (I->getOpcode() == Instruction::ZExt) { |
| 2002 | auto &Res = collectBitParts(I->getOperand(0), MatchBSwaps, |
| 2003 | MatchBitReversals, BPS); |
| 2004 | if (!Res) |
| 2005 | return Result; |
| 2006 | |
| 2007 | Result = BitPart(Res->Provider, BitWidth); |
| 2008 | auto NarrowBitWidth = |
| 2009 | cast<IntegerType>(cast<ZExtInst>(I)->getSrcTy())->getBitWidth(); |
| 2010 | for (unsigned i = 0; i < NarrowBitWidth; ++i) |
| 2011 | Result->Provenance[i] = Res->Provenance[i]; |
| 2012 | for (unsigned i = NarrowBitWidth; i < BitWidth; ++i) |
| 2013 | Result->Provenance[i] = BitPart::Unset; |
James Molloy | f01488e | 2016-01-15 09:20:19 +0000 | [diff] [blame] | 2014 | return Result; |
| 2015 | } |
| 2016 | } |
| 2017 | |
| 2018 | // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be |
| 2019 | // the input value to the bswap/bitreverse. |
| 2020 | Result = BitPart(V, BitWidth); |
| 2021 | for (unsigned i = 0; i < BitWidth; ++i) |
| 2022 | Result->Provenance[i] = i; |
| 2023 | return Result; |
| 2024 | } |
| 2025 | |
| 2026 | static bool bitTransformIsCorrectForBSwap(unsigned From, unsigned To, |
| 2027 | unsigned BitWidth) { |
| 2028 | if (From % 8 != To % 8) |
| 2029 | return false; |
| 2030 | // Convert from bit indices to byte indices and check for a byte reversal. |
| 2031 | From >>= 3; |
| 2032 | To >>= 3; |
| 2033 | BitWidth >>= 3; |
| 2034 | return From == BitWidth - To - 1; |
| 2035 | } |
| 2036 | |
| 2037 | static bool bitTransformIsCorrectForBitReverse(unsigned From, unsigned To, |
| 2038 | unsigned BitWidth) { |
| 2039 | return From == BitWidth - To - 1; |
| 2040 | } |
| 2041 | |
| 2042 | /// Given an OR instruction, check to see if this is a bitreverse |
| 2043 | /// idiom. If so, insert the new intrinsic and return true. |
Chad Rosier | a00df49 | 2016-05-25 16:22:14 +0000 | [diff] [blame] | 2044 | bool llvm::recognizeBSwapOrBitReverseIdiom( |
James Molloy | f01488e | 2016-01-15 09:20:19 +0000 | [diff] [blame] | 2045 | Instruction *I, bool MatchBSwaps, bool MatchBitReversals, |
| 2046 | SmallVectorImpl<Instruction *> &InsertedInsts) { |
| 2047 | if (Operator::getOpcode(I) != Instruction::Or) |
| 2048 | return false; |
| 2049 | if (!MatchBSwaps && !MatchBitReversals) |
| 2050 | return false; |
| 2051 | IntegerType *ITy = dyn_cast<IntegerType>(I->getType()); |
| 2052 | if (!ITy || ITy->getBitWidth() > 128) |
| 2053 | return false; // Can't do vectors or integers > 128 bits. |
| 2054 | unsigned BW = ITy->getBitWidth(); |
| 2055 | |
Chad Rosier | e5819e2 | 2016-05-26 14:58:51 +0000 | [diff] [blame] | 2056 | unsigned DemandedBW = BW; |
| 2057 | IntegerType *DemandedTy = ITy; |
| 2058 | if (I->hasOneUse()) { |
| 2059 | if (TruncInst *Trunc = dyn_cast<TruncInst>(I->user_back())) { |
| 2060 | DemandedTy = cast<IntegerType>(Trunc->getType()); |
| 2061 | DemandedBW = DemandedTy->getBitWidth(); |
| 2062 | } |
| 2063 | } |
| 2064 | |
James Molloy | f01488e | 2016-01-15 09:20:19 +0000 | [diff] [blame] | 2065 | // Try to find all the pieces corresponding to the bswap. |
| 2066 | std::map<Value *, Optional<BitPart>> BPS; |
| 2067 | auto Res = collectBitParts(I, MatchBSwaps, MatchBitReversals, BPS); |
| 2068 | if (!Res) |
| 2069 | return false; |
| 2070 | auto &BitProvenance = Res->Provenance; |
| 2071 | |
| 2072 | // Now, is the bit permutation correct for a bswap or a bitreverse? We can |
| 2073 | // only byteswap values with an even number of bytes. |
Chad Rosier | e5819e2 | 2016-05-26 14:58:51 +0000 | [diff] [blame] | 2074 | bool OKForBSwap = DemandedBW % 16 == 0, OKForBitReverse = true; |
| 2075 | for (unsigned i = 0; i < DemandedBW; ++i) { |
| 2076 | OKForBSwap &= |
| 2077 | bitTransformIsCorrectForBSwap(BitProvenance[i], i, DemandedBW); |
James Molloy | f01488e | 2016-01-15 09:20:19 +0000 | [diff] [blame] | 2078 | OKForBitReverse &= |
Chad Rosier | e5819e2 | 2016-05-26 14:58:51 +0000 | [diff] [blame] | 2079 | bitTransformIsCorrectForBitReverse(BitProvenance[i], i, DemandedBW); |
James Molloy | f01488e | 2016-01-15 09:20:19 +0000 | [diff] [blame] | 2080 | } |
| 2081 | |
| 2082 | Intrinsic::ID Intrin; |
| 2083 | if (OKForBSwap && MatchBSwaps) |
| 2084 | Intrin = Intrinsic::bswap; |
| 2085 | else if (OKForBitReverse && MatchBitReversals) |
| 2086 | Intrin = Intrinsic::bitreverse; |
| 2087 | else |
| 2088 | return false; |
| 2089 | |
Chad Rosier | e5819e2 | 2016-05-26 14:58:51 +0000 | [diff] [blame] | 2090 | if (ITy != DemandedTy) { |
| 2091 | Function *F = Intrinsic::getDeclaration(I->getModule(), Intrin, DemandedTy); |
| 2092 | Value *Provider = Res->Provider; |
| 2093 | IntegerType *ProviderTy = cast<IntegerType>(Provider->getType()); |
| 2094 | // We may need to truncate the provider. |
| 2095 | if (DemandedTy != ProviderTy) { |
| 2096 | auto *Trunc = CastInst::Create(Instruction::Trunc, Provider, DemandedTy, |
| 2097 | "trunc", I); |
| 2098 | InsertedInsts.push_back(Trunc); |
| 2099 | Provider = Trunc; |
| 2100 | } |
| 2101 | auto *CI = CallInst::Create(F, Provider, "rev", I); |
| 2102 | InsertedInsts.push_back(CI); |
| 2103 | auto *ExtInst = CastInst::Create(Instruction::ZExt, CI, ITy, "zext", I); |
| 2104 | InsertedInsts.push_back(ExtInst); |
| 2105 | return true; |
| 2106 | } |
| 2107 | |
James Molloy | f01488e | 2016-01-15 09:20:19 +0000 | [diff] [blame] | 2108 | Function *F = Intrinsic::getDeclaration(I->getModule(), Intrin, ITy); |
| 2109 | InsertedInsts.push_back(CallInst::Create(F, Res->Provider, "rev", I)); |
| 2110 | return true; |
| 2111 | } |
Marcin Koscielnicki | 3feda22 | 2016-06-18 10:10:37 +0000 | [diff] [blame] | 2112 | |
| 2113 | // CodeGen has special handling for some string functions that may replace |
| 2114 | // them with target-specific intrinsics. Since that'd skip our interceptors |
| 2115 | // in ASan/MSan/TSan/DFSan, and thus make us miss some memory accesses, |
| 2116 | // we mark affected calls as NoBuiltin, which will disable optimization |
| 2117 | // in CodeGen. |
Evgeniy Stepanov | d240a88 | 2016-07-28 23:45:15 +0000 | [diff] [blame] | 2118 | void llvm::maybeMarkSanitizerLibraryCallNoBuiltin( |
| 2119 | CallInst *CI, const TargetLibraryInfo *TLI) { |
Marcin Koscielnicki | 3feda22 | 2016-06-18 10:10:37 +0000 | [diff] [blame] | 2120 | Function *F = CI->getCalledFunction(); |
David L. Jones | d21529f | 2017-01-23 23:16:46 +0000 | [diff] [blame] | 2121 | LibFunc Func; |
Evgeniy Stepanov | d240a88 | 2016-07-28 23:45:15 +0000 | [diff] [blame] | 2122 | if (F && !F->hasLocalLinkage() && F->hasName() && |
| 2123 | TLI->getLibFunc(F->getName(), Func) && TLI->hasOptimizedCodeGen(Func) && |
| 2124 | !F->doesNotAccessMemory()) |
Reid Kleckner | b518054 | 2017-03-21 16:57:19 +0000 | [diff] [blame] | 2125 | CI->addAttribute(AttributeList::FunctionIndex, Attribute::NoBuiltin); |
Marcin Koscielnicki | 3feda22 | 2016-06-18 10:10:37 +0000 | [diff] [blame] | 2126 | } |