blob: 8c5442762643b76b0f046dcd57c8b08c324a77fe [file] [log] [blame]
Chris Lattner28537df2002-05-07 18:07:59 +00001//===-- Local.cpp - Functions to perform local transformations ------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner28537df2002-05-07 18:07:59 +00009//
10// This family of functions perform various local transformations to the
11// program.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/Transforms/Utils/Local.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000016#include "llvm/ADT/DenseMap.h"
Benjamin Kramer2b2cdd72015-06-18 16:01:00 +000017#include "llvm/ADT/DenseSet.h"
18#include "llvm/ADT/Hashing.h"
Evgeniy Stepanov4fbc0d082012-12-21 11:18:49 +000019#include "llvm/ADT/STLExtras.h"
Fiona Glaserf74cc402015-09-28 18:56:07 +000020#include "llvm/ADT/SetVector.h"
Chandler Carruthbe810232013-01-02 10:22:59 +000021#include "llvm/ADT/SmallPtrSet.h"
Peter Collingbourne8d642de2013-08-12 22:38:43 +000022#include "llvm/ADT/Statistic.h"
David Majnemer70497c62015-12-02 23:06:39 +000023#include "llvm/Analysis/EHPersonalities.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000024#include "llvm/Analysis/InstructionSimplify.h"
25#include "llvm/Analysis/MemoryBuiltins.h"
David Majnemerd9833ea2016-01-10 07:13:04 +000026#include "llvm/Analysis/LazyValueInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000027#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000028#include "llvm/IR/CFG.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000029#include "llvm/IR/Constants.h"
Chandler Carruth12664a02014-03-06 00:22:06 +000030#include "llvm/IR/DIBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000031#include "llvm/IR/DataLayout.h"
Chandler Carruth9a4c9e52014-03-06 00:46:21 +000032#include "llvm/IR/DebugInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000033#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000034#include "llvm/IR/Dominators.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000035#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000036#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 Majnemer9f506252016-06-25 08:34:38 +000045#include "llvm/IR/PatternMatch.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000046#include "llvm/IR/ValueHandle.h"
Chris Lattnercbd18fc2009-11-10 05:59:26 +000047#include "llvm/Support/Debug.h"
Chris Lattnerc13c7b92005-09-26 05:27:10 +000048#include "llvm/Support/MathExtras.h"
Chris Lattnercbd18fc2009-11-10 05:59:26 +000049#include "llvm/Support/raw_ostream.h"
Chris Lattner04efa4b2003-12-19 05:56:28 +000050using namespace llvm;
David Majnemer9f506252016-06-25 08:34:38 +000051using namespace llvm::PatternMatch;
Brian Gaeke960707c2003-11-11 22:41:34 +000052
Chandler Carruthe96dd892014-04-21 22:55:11 +000053#define DEBUG_TYPE "local"
54
Peter Collingbourne8d642de2013-08-12 22:38:43 +000055STATISTIC(NumRemoved, "Number of unreachable basic blocks removed");
56
Chris Lattner28537df2002-05-07 18:07:59 +000057//===----------------------------------------------------------------------===//
Chris Lattnerc6c481c2008-11-27 22:57:53 +000058// Local constant propagation.
Chris Lattner28537df2002-05-07 18:07:59 +000059//
60
Frits van Bommelad964552011-05-22 16:24:18 +000061/// 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 Kramer8bcc9712012-08-29 15:32:21 +000068bool llvm::ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions,
69 const TargetLibraryInfo *TLI) {
Chris Lattner4b009ad2002-05-21 20:04:50 +000070 TerminatorInst *T = BB->getTerminator();
Devang Patel1fabbe92011-05-18 17:26:46 +000071 IRBuilder<> Builder(T);
Misha Brukmanb1c93172005-04-21 23:48:37 +000072
Chris Lattner28537df2002-05-07 18:07:59 +000073 // 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 Greif97f17202009-01-30 18:21:13 +000076 BasicBlock *Dest1 = BI->getSuccessor(0);
77 BasicBlock *Dest2 = BI->getSuccessor(1);
Chris Lattner28537df2002-05-07 18:07:59 +000078
Zhou Sheng75b871f2007-01-11 12:24:14 +000079 if (ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition())) {
Chris Lattner28537df2002-05-07 18:07:59 +000080 // Are we branching on constant?
81 // YES. Change to unconditional branch...
Reid Spencercddc9df2007-01-12 04:24:46 +000082 BasicBlock *Destination = Cond->getZExtValue() ? Dest1 : Dest2;
83 BasicBlock *OldDest = Cond->getZExtValue() ? Dest2 : Dest1;
Chris Lattner28537df2002-05-07 18:07:59 +000084
Misha Brukmanb1c93172005-04-21 23:48:37 +000085 //cerr << "Function: " << T->getParent()->getParent()
86 // << "\nRemoving branch from " << T->getParent()
Chris Lattner28537df2002-05-07 18:07:59 +000087 // << "\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 Foad6a85be22011-04-19 15:23:29 +000091 OldDest->removePredecessor(BB);
Chris Lattner28537df2002-05-07 18:07:59 +000092
Jay Foad89afb432011-01-07 20:25:56 +000093 // Replace the conditional branch with an unconditional one.
Devang Patel1fabbe92011-05-18 17:26:46 +000094 Builder.CreateBr(Destination);
Jay Foad89afb432011-01-07 20:25:56 +000095 BI->eraseFromParent();
Chris Lattner28537df2002-05-07 18:07:59 +000096 return true;
Chris Lattner54a4b842009-11-01 03:40:38 +000097 }
Jakub Staszak8e1a6e72013-07-22 23:16:36 +000098
Chris Lattner54a4b842009-11-01 03:40:38 +000099 if (Dest2 == Dest1) { // Conditional branch to same location?
Misha Brukmanb1c93172005-04-21 23:48:37 +0000100 // This branch matches something like this:
Chris Lattner28537df2002-05-07 18:07:59 +0000101 // 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 Foad89afb432011-01-07 20:25:56 +0000108 // Replace the conditional branch with an unconditional one.
Devang Patel1fabbe92011-05-18 17:26:46 +0000109 Builder.CreateBr(Dest1);
Frits van Bommelad964552011-05-22 16:24:18 +0000110 Value *Cond = BI->getCondition();
Jay Foad89afb432011-01-07 20:25:56 +0000111 BI->eraseFromParent();
Frits van Bommelad964552011-05-22 16:24:18 +0000112 if (DeleteDeadConditions)
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000113 RecursivelyDeleteTriviallyDeadInstructions(Cond, TLI);
Chris Lattner28537df2002-05-07 18:07:59 +0000114 return true;
115 }
Chris Lattner54a4b842009-11-01 03:40:38 +0000116 return false;
117 }
Jakub Staszak8e1a6e72013-07-22 23:16:36 +0000118
Chris Lattner54a4b842009-11-01 03:40:38 +0000119 if (SwitchInst *SI = dyn_cast<SwitchInst>(T)) {
Hans Wennborg90b827c2015-01-26 19:52:24 +0000120 // If we are switching on a constant, we can convert the switch to an
121 // unconditional branch.
Chris Lattner821deee2003-08-17 20:21:14 +0000122 ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition());
Hans Wennborg90b827c2015-01-26 19:52:24 +0000123 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 Carruth927d8e62017-04-12 07:27:28 +0000129 TheOnlyDest = SI->case_begin()->getCaseSuccessor();
Hans Wennborg90b827c2015-01-26 19:52:24 +0000130 }
Chris Lattner031340a2003-08-17 19:41:53 +0000131
Chris Lattner54a4b842009-11-01 03:40:38 +0000132 // Figure out which case it goes to.
Chandler Carruth0d256c02017-03-26 02:49:23 +0000133 for (auto i = SI->case_begin(), e = SI->case_end(); i != e;) {
Chris Lattner821deee2003-08-17 20:21:14 +0000134 // Found case matching a constant operand?
Chandler Carruth927d8e62017-04-12 07:27:28 +0000135 if (i->getCaseValue() == CI) {
136 TheOnlyDest = i->getCaseSuccessor();
Chris Lattner821deee2003-08-17 20:21:14 +0000137 break;
138 }
Chris Lattner031340a2003-08-17 19:41:53 +0000139
Chris Lattnerc54d6082003-08-23 23:18:19 +0000140 // 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 Carruth927d8e62017-04-12 07:27:28 +0000142 if (i->getCaseSuccessor() == DefaultDest) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000143 MDNode *MD = SI->getMetadata(LLVMContext::MD_prof);
Justin Bognera41a7b32013-12-10 00:13:41 +0000144 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 Ren49dbe252012-09-12 17:04:11 +0000148 // 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 Majnemer9f506252016-06-25 08:34:38 +0000152 auto *CI = mdconst::extract<ConstantInt>(MD->getOperand(MD_i));
Manman Ren49dbe252012-09-12 17:04:11 +0000153 Weights.push_back(CI->getValue().getZExtValue());
154 }
155 // Merge weight of this case to the default weight.
Chandler Carruth927d8e62017-04-12 07:27:28 +0000156 unsigned idx = i->getCaseIndex();
Manman Ren49dbe252012-09-12 17:04:11 +0000157 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 Lattner54a4b842009-11-01 03:40:38 +0000165 // Remove this entry.
Chris Lattnerc54d6082003-08-23 23:18:19 +0000166 DefaultDest->removePredecessor(SI->getParent());
Chandler Carruth0d256c02017-03-26 02:49:23 +0000167 i = SI->removeCase(i);
168 e = SI->case_end();
Chris Lattnerc54d6082003-08-23 23:18:19 +0000169 continue;
170 }
171
Chris Lattner821deee2003-08-17 20:21:14 +0000172 // 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 Carruth927d8e62017-04-12 07:27:28 +0000175 if (i->getCaseSuccessor() != TheOnlyDest)
176 TheOnlyDest = nullptr;
Chandler Carruth0d256c02017-03-26 02:49:23 +0000177
178 // Increment this iterator as we haven't removed the case.
179 ++i;
Chris Lattner031340a2003-08-17 19:41:53 +0000180 }
181
Chris Lattner821deee2003-08-17 20:21:14 +0000182 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 Lattner54a4b842009-11-01 03:40:38 +0000191 // Insert the new branch.
Devang Patel1fabbe92011-05-18 17:26:46 +0000192 Builder.CreateBr(TheOnlyDest);
Chris Lattner821deee2003-08-17 20:21:14 +0000193 BasicBlock *BB = SI->getParent();
194
195 // Remove entries from PHI nodes which we no longer branch to...
Pete Cooperebcd7482015-08-06 20:22:46 +0000196 for (BasicBlock *Succ : SI->successors()) {
Chris Lattner821deee2003-08-17 20:21:14 +0000197 // Found case matching a constant operand?
Chris Lattner821deee2003-08-17 20:21:14 +0000198 if (Succ == TheOnlyDest)
Craig Topperf40110f2014-04-25 05:29:35 +0000199 TheOnlyDest = nullptr; // Don't modify the first branch to TheOnlyDest
Chris Lattner821deee2003-08-17 20:21:14 +0000200 else
201 Succ->removePredecessor(BB);
202 }
203
Chris Lattner54a4b842009-11-01 03:40:38 +0000204 // Delete the old switch.
Frits van Bommelad964552011-05-22 16:24:18 +0000205 Value *Cond = SI->getCondition();
206 SI->eraseFromParent();
207 if (DeleteDeadConditions)
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000208 RecursivelyDeleteTriviallyDeadInstructions(Cond, TLI);
Chris Lattner821deee2003-08-17 20:21:14 +0000209 return true;
Chris Lattner54a4b842009-11-01 03:40:38 +0000210 }
Jakub Staszak8e1a6e72013-07-22 23:16:36 +0000211
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +0000212 if (SI->getNumCases() == 1) {
Chris Lattner821deee2003-08-17 20:21:14 +0000213 // Otherwise, we can fold this switch into a conditional branch
214 // instruction if it has only one non-default destination.
Chandler Carruth927d8e62017-04-12 07:27:28 +0000215 auto FirstCase = *SI->case_begin();
Bob Wilsone4077362013-09-09 19:14:35 +0000216 Value *Cond = Builder.CreateICmpEQ(SI->getCondition(),
217 FirstCase.getCaseValue(), "cond");
Devang Patel1fabbe92011-05-18 17:26:46 +0000218
Bob Wilsone4077362013-09-09 19:14:35 +0000219 // Insert the new branch.
220 BranchInst *NewBr = Builder.CreateCondBr(Cond,
221 FirstCase.getCaseSuccessor(),
222 SI->getDefaultDest());
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000223 MDNode *MD = SI->getMetadata(LLVMContext::MD_prof);
Bob Wilsone4077362013-09-09 19:14:35 +0000224 if (MD && MD->getNumOperands() == 3) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000225 ConstantInt *SICase =
226 mdconst::dyn_extract<ConstantInt>(MD->getOperand(2));
227 ConstantInt *SIDef =
228 mdconst::dyn_extract<ConstantInt>(MD->getOperand(1));
Bob Wilsone4077362013-09-09 19:14:35 +0000229 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 Dyatkovskiy7a501552012-05-23 08:18:26 +0000235 }
Bob Wilsone4077362013-09-09 19:14:35 +0000236
Chen Lieafbc9d2015-08-07 19:30:12 +0000237 // 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 Wilsone4077362013-09-09 19:14:35 +0000242 // Delete the old switch.
243 SI->eraseFromParent();
244 return true;
Chris Lattner821deee2003-08-17 20:21:14 +0000245 }
Chris Lattner54a4b842009-11-01 03:40:38 +0000246 return false;
Chris Lattner28537df2002-05-07 18:07:59 +0000247 }
Chris Lattner54a4b842009-11-01 03:40:38 +0000248
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 Patel1fabbe92011-05-18 17:26:46 +0000255 Builder.CreateBr(TheOnlyDest);
Jakub Staszak8e1a6e72013-07-22 23:16:36 +0000256
Chris Lattner54a4b842009-11-01 03:40:38 +0000257 for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
258 if (IBI->getDestination(i) == TheOnlyDest)
Craig Topperf40110f2014-04-25 05:29:35 +0000259 TheOnlyDest = nullptr;
Chris Lattner54a4b842009-11-01 03:40:38 +0000260 else
261 IBI->getDestination(i)->removePredecessor(IBI->getParent());
262 }
Frits van Bommelad964552011-05-22 16:24:18 +0000263 Value *Address = IBI->getAddress();
Chris Lattner54a4b842009-11-01 03:40:38 +0000264 IBI->eraseFromParent();
Frits van Bommelad964552011-05-22 16:24:18 +0000265 if (DeleteDeadConditions)
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000266 RecursivelyDeleteTriviallyDeadInstructions(Address, TLI);
Jakub Staszak8e1a6e72013-07-22 23:16:36 +0000267
Chris Lattner54a4b842009-11-01 03:40:38 +0000268 // 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 Staszak8e1a6e72013-07-22 23:16:36 +0000275
Chris Lattner54a4b842009-11-01 03:40:38 +0000276 return true;
277 }
278 }
Jakub Staszak8e1a6e72013-07-22 23:16:36 +0000279
Chris Lattner28537df2002-05-07 18:07:59 +0000280 return false;
281}
282
Chris Lattner28537df2002-05-07 18:07:59 +0000283
284//===----------------------------------------------------------------------===//
Chris Lattner852d6d62009-11-10 22:26:15 +0000285// Local dead code elimination.
Chris Lattner28537df2002-05-07 18:07:59 +0000286//
287
Chris Lattnerc6c481c2008-11-27 22:57:53 +0000288/// isInstructionTriviallyDead - Return true if the result produced by the
289/// instruction is not used, and the instruction has no side effects.
290///
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000291bool llvm::isInstructionTriviallyDead(Instruction *I,
292 const TargetLibraryInfo *TLI) {
Daniel Berline3e69e12017-03-10 00:32:33 +0000293 if (!I->use_empty())
294 return false;
295 return wouldInstructionBeTriviallyDead(I, TLI);
296}
297
298bool llvm::wouldInstructionBeTriviallyDead(Instruction *I,
299 const TargetLibraryInfo *TLI) {
300 if (isa<TerminatorInst>(I))
301 return false;
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000302
David Majnemer654e1302015-07-31 17:58:14 +0000303 // We don't want the landingpad-like instructions removed by anything this
304 // general.
305 if (I->isEHPad())
Bill Wendlingd9fb4702011-08-15 20:10:51 +0000306 return false;
307
Devang Patelc1431e62011-03-18 23:28:02 +0000308 // 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 Lewycky99890a22011-08-02 21:19:27 +0000311 if (DDI->getAddress())
Devang Patelc1431e62011-03-18 23:28:02 +0000312 return false;
Devang Patel17bbd7f2011-03-21 22:04:45 +0000313 return true;
Nick Lewycky99890a22011-08-02 21:19:27 +0000314 }
Devang Patel17bbd7f2011-03-21 22:04:45 +0000315 if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(I)) {
Devang Patelc1431e62011-03-18 23:28:02 +0000316 if (DVI->getValue())
317 return false;
Devang Patel17bbd7f2011-03-21 22:04:45 +0000318 return true;
Devang Patelc1431e62011-03-18 23:28:02 +0000319 }
320
Daniel Berline3e69e12017-03-10 00:32:33 +0000321 if (!I->mayHaveSideEffects())
322 return true;
Duncan Sands1efabaa2009-05-06 06:49:50 +0000323
324 // Special case intrinsics that "may have side effects" but can be deleted
325 // when dead.
Nick Lewycky99890a22011-08-02 21:19:27 +0000326 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
Chris Lattnere9665832007-12-29 00:59:12 +0000327 // Safe to delete llvm.stacksave if dead.
328 if (II->getIntrinsicID() == Intrinsic::stacksave)
329 return true;
Nick Lewycky99890a22011-08-02 21:19:27 +0000330
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 Finkel93046912014-07-25 21:13:35 +0000335
Sanjoy Das107aefc2016-04-29 22:23:16 +0000336 // 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 Finkel93046912014-07-25 21:13:35 +0000342 if (ConstantInt *Cond = dyn_cast<ConstantInt>(II->getArgOperand(0)))
343 return !Cond->isZero();
344
345 return false;
346 }
Nick Lewycky99890a22011-08-02 21:19:27 +0000347 }
Nick Lewyckydd1d3df2011-10-24 04:35:36 +0000348
Daniel Berline3e69e12017-03-10 00:32:33 +0000349 if (isAllocLikeFn(I, TLI))
350 return true;
Nick Lewyckydd1d3df2011-10-24 04:35:36 +0000351
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000352 if (CallInst *CI = isFreeCall(I, TLI))
Nick Lewyckydd1d3df2011-10-24 04:35:36 +0000353 if (Constant *C = dyn_cast<Constant>(CI->getArgOperand(0)))
354 return C->isNullValue() || isa<UndefValue>(C);
355
Eli Friedmanb6befc32016-11-02 20:48:11 +0000356 if (CallSite CS = CallSite(I))
357 if (isMathLibCallNoop(CS, TLI))
358 return true;
359
Chris Lattnera36d5252005-05-06 05:27:34 +0000360 return false;
Chris Lattner28537df2002-05-07 18:07:59 +0000361}
362
Chris Lattnerc6c481c2008-11-27 22:57:53 +0000363/// RecursivelyDeleteTriviallyDeadInstructions - If the specified value is a
364/// trivially dead instruction, delete it. If that makes any of its operands
Dan Gohmancb99fe92010-01-05 15:45:31 +0000365/// trivially dead, delete them too, recursively. Return true if any
366/// instructions were deleted.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000367bool
368llvm::RecursivelyDeleteTriviallyDeadInstructions(Value *V,
369 const TargetLibraryInfo *TLI) {
Chris Lattnerc6c481c2008-11-27 22:57:53 +0000370 Instruction *I = dyn_cast<Instruction>(V);
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000371 if (!I || !I->use_empty() || !isInstructionTriviallyDead(I, TLI))
Dan Gohmancb99fe92010-01-05 15:45:31 +0000372 return false;
Jakub Staszak8e1a6e72013-07-22 23:16:36 +0000373
Chris Lattnere9f6c352008-11-28 01:20:46 +0000374 SmallVector<Instruction*, 16> DeadInsts;
375 DeadInsts.push_back(I);
Jakub Staszak8e1a6e72013-07-22 23:16:36 +0000376
Dan Gohman28943872010-01-05 16:27:25 +0000377 do {
Dan Gohman9a6fef02009-05-06 17:22:41 +0000378 I = DeadInsts.pop_back_val();
Chris Lattnerd4b5ba62008-11-28 00:58:15 +0000379
Chris Lattnere9f6c352008-11-28 01:20:46 +0000380 // 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 Topperf40110f2014-04-25 05:29:35 +0000384 I->setOperand(i, nullptr);
Jakub Staszak8e1a6e72013-07-22 23:16:36 +0000385
Chris Lattnere9f6c352008-11-28 01:20:46 +0000386 if (!OpV->use_empty()) continue;
Jakub Staszak8e1a6e72013-07-22 23:16:36 +0000387
Chris Lattnere9f6c352008-11-28 01:20:46 +0000388 // 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 Kramer8bcc9712012-08-29 15:32:21 +0000392 if (isInstructionTriviallyDead(OpI, TLI))
Chris Lattnere9f6c352008-11-28 01:20:46 +0000393 DeadInsts.push_back(OpI);
394 }
Jakub Staszak8e1a6e72013-07-22 23:16:36 +0000395
Chris Lattnere9f6c352008-11-28 01:20:46 +0000396 I->eraseFromParent();
Dan Gohman28943872010-01-05 16:27:25 +0000397 } while (!DeadInsts.empty());
Dan Gohmancb99fe92010-01-05 15:45:31 +0000398
399 return true;
Chris Lattner28537df2002-05-07 18:07:59 +0000400}
Chris Lattner99d68092008-11-27 07:43:12 +0000401
Nick Lewyckyc8a15692011-02-20 08:38:20 +0000402/// 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 Sands6dcd49b2011-02-21 16:27:36 +0000404/// true when there are no uses or multiple uses that all refer to the same
405/// value.
Nick Lewyckyc8a15692011-02-20 08:38:20 +0000406static bool areAllUsesEqual(Instruction *I) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000407 Value::user_iterator UI = I->user_begin();
408 Value::user_iterator UE = I->user_end();
Nick Lewyckyc8a15692011-02-20 08:38:20 +0000409 if (UI == UE)
Duncan Sands6dcd49b2011-02-21 16:27:36 +0000410 return true;
Nick Lewyckyc8a15692011-02-20 08:38:20 +0000411
412 User *TheUse = *UI;
413 for (++UI; UI != UE; ++UI) {
414 if (*UI != TheUse)
415 return false;
416 }
417 return true;
418}
419
Dan Gohmanff089952009-05-02 18:29:22 +0000420/// 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 Sandsecbbf082011-02-21 17:32:05 +0000424/// too, recursively. Return true if a change was made.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000425bool llvm::RecursivelyDeleteDeadPHINode(PHINode *PN,
426 const TargetLibraryInfo *TLI) {
Duncan Sands6dcd49b2011-02-21 16:27:36 +0000427 SmallPtrSet<Instruction*, 4> Visited;
428 for (Instruction *I = PN; areAllUsesEqual(I) && !I->mayHaveSideEffects();
Chandler Carruthcdf47882014-03-09 03:16:01 +0000429 I = cast<Instruction>(*I->user_begin())) {
Duncan Sands6dcd49b2011-02-21 16:27:36 +0000430 if (I->use_empty())
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000431 return RecursivelyDeleteTriviallyDeadInstructions(I, TLI);
Nick Lewycky183c24c2011-02-20 18:05:56 +0000432
Duncan Sands6dcd49b2011-02-21 16:27:36 +0000433 // If we find an instruction more than once, we're on a cycle that
Dan Gohmanff089952009-05-02 18:29:22 +0000434 // won't prove fruitful.
David Blaikie70573dc2014-11-19 07:49:26 +0000435 if (!Visited.insert(I).second) {
Duncan Sands6dcd49b2011-02-21 16:27:36 +0000436 // Break the cycle and delete the instruction and its operands.
437 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000438 (void)RecursivelyDeleteTriviallyDeadInstructions(I, TLI);
Duncan Sandsecbbf082011-02-21 17:32:05 +0000439 return true;
Duncan Sands6dcd49b2011-02-21 16:27:36 +0000440 }
441 }
442 return false;
Dan Gohmanff089952009-05-02 18:29:22 +0000443}
Chris Lattnerc6c481c2008-11-27 22:57:53 +0000444
Fiona Glaserf74cc402015-09-28 18:56:07 +0000445static bool
446simplifyAndDCEInstruction(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 Majnemerb8da3a22016-06-25 00:04:10 +0000476 for (User *U : I->users()) {
477 if (U != I) {
Fiona Glaserf74cc402015-09-28 18:56:07 +0000478 WorkList.insert(cast<Instruction>(U));
David Majnemerb8da3a22016-06-25 00:04:10 +0000479 }
480 }
Fiona Glaserf74cc402015-09-28 18:56:07 +0000481
482 // Replace the instruction with its simplified value.
David Majnemerb8da3a22016-06-25 00:04:10 +0000483 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 Glaserf74cc402015-09-28 18:56:07 +0000493 }
494 return false;
495}
496
Chris Lattner7c743f22010-01-12 19:40:54 +0000497/// 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 Aminia28d91d2015-03-10 02:37:25 +0000502bool llvm::SimplifyInstructionsInBlock(BasicBlock *BB,
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000503 const TargetLibraryInfo *TLI) {
Chris Lattner7c743f22010-01-12 19:40:54 +0000504 bool MadeChange = false;
Fiona Glaserf74cc402015-09-28 18:56:07 +0000505 const DataLayout &DL = BB->getModule()->getDataLayout();
Chandler Carruth0c72e3f2012-03-25 03:29:25 +0000506
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 Smith5b4c8372015-10-13 02:39:05 +0000512 AssertingVH<Instruction> TerminatorVH(&BB->back());
Chandler Carruth0c72e3f2012-03-25 03:29:25 +0000513#endif
514
Fiona Glaserf74cc402015-09-28 18:56:07 +0000515 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 Rosier56def252016-05-21 21:12:06 +0000519 for (BasicBlock::iterator BI = BB->begin(), E = std::prev(BB->end());
520 BI != E;) {
Chandler Carruth17fc6ef2012-03-24 23:03:27 +0000521 assert(!BI->isTerminator());
Fiona Glaserf74cc402015-09-28 18:56:07 +0000522 Instruction *I = &*BI;
523 ++BI;
Chandler Carruthcf1b5852012-03-24 21:11:24 +0000524
Fiona Glaserf74cc402015-09-28 18:56:07 +0000525 // 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 Friedman17bf4922011-04-02 22:45:17 +0000530
Fiona Glaserf74cc402015-09-28 18:56:07 +0000531 while (!WorkList.empty()) {
532 Instruction *I = WorkList.pop_back_val();
533 MadeChange |= simplifyAndDCEInstruction(I, WorkList, DL, TLI);
Chris Lattner7c743f22010-01-12 19:40:54 +0000534 }
535 return MadeChange;
536}
537
Chris Lattner99d68092008-11-27 07:43:12 +0000538//===----------------------------------------------------------------------===//
Chris Lattner852d6d62009-11-10 22:26:15 +0000539// Control Flow Graph Restructuring.
Chris Lattner99d68092008-11-27 07:43:12 +0000540//
541
Chris Lattner852d6d62009-11-10 22:26:15 +0000542
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 Aminia28d91d2015-03-10 02:37:25 +0000554void llvm::RemovePredecessorAndSimplify(BasicBlock *BB, BasicBlock *Pred) {
Chris Lattner852d6d62009-11-10 22:26:15 +0000555 // This only adjusts blocks with PHI nodes.
556 if (!isa<PHINode>(BB->begin()))
557 return;
Jakub Staszak8e1a6e72013-07-22 23:16:36 +0000558
Chris Lattner852d6d62009-11-10 22:26:15 +0000559 // 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 Staszak8e1a6e72013-07-22 23:16:36 +0000563
Chris Lattner852d6d62009-11-10 22:26:15 +0000564 WeakVH PhiIt = &BB->front();
565 while (PHINode *PN = dyn_cast<PHINode>(PhiIt)) {
566 PhiIt = &*++BasicBlock::iterator(cast<Instruction>(PhiIt));
Chris Lattnere41ab072010-07-15 06:06:04 +0000567 Value *OldPhiIt = PhiIt;
Chandler Carruthcf1b5852012-03-24 21:11:24 +0000568
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000569 if (!recursivelySimplifyInstruction(PN))
Chandler Carruthcf1b5852012-03-24 21:11:24 +0000570 continue;
571
Chris Lattner852d6d62009-11-10 22:26:15 +0000572 // 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 Lattnere41ab072010-07-15 06:06:04 +0000575 if (PhiIt != OldPhiIt) PhiIt = &BB->front();
Chris Lattner852d6d62009-11-10 22:26:15 +0000576 }
577}
578
579
Chris Lattner99d68092008-11-27 07:43:12 +0000580/// 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 Carruth10f28f22015-01-20 01:37:09 +0000585void llvm::MergeBasicBlockIntoOnlyPred(BasicBlock *DestBB, DominatorTree *DT) {
Chris Lattner99d68092008-11-27 07:43:12 +0000586 // 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 Andersonb292b8c2009-07-30 23:03:37 +0000590 if (NewVal == PN) NewVal = UndefValue::get(PN->getType());
Chris Lattner99d68092008-11-27 07:43:12 +0000591 PN->replaceAllUsesWith(NewVal);
592 PN->eraseFromParent();
593 }
Jakub Staszak8e1a6e72013-07-22 23:16:36 +0000594
Chris Lattner99d68092008-11-27 07:43:12 +0000595 BasicBlock *PredBB = DestBB->getSinglePredecessor();
596 assert(PredBB && "Block doesn't have a single predecessor!");
Jakub Staszak8e1a6e72013-07-22 23:16:36 +0000597
Chris Lattner6fbfe582010-02-15 20:47:49 +0000598 // 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 Staszak8e1a6e72013-07-22 23:16:36 +0000608
Chris Lattner99d68092008-11-27 07:43:12 +0000609 // Anything that branched to PredBB now branches to DestBB.
610 PredBB->replaceAllUsesWith(DestBB);
Jakub Staszak8e1a6e72013-07-22 23:16:36 +0000611
Jay Foad61ea0e42011-06-23 09:09:15 +0000612 // Splice all the instructions from PredBB to DestBB.
613 PredBB->getTerminator()->eraseFromParent();
Bill Wendling90dd90a2013-10-21 04:09:17 +0000614 DestBB->getInstList().splice(DestBB->begin(), PredBB->getInstList());
Jay Foad61ea0e42011-06-23 09:09:15 +0000615
Owen Andersona8d1c3e2014-07-12 07:12:47 +0000616 // 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 Carruth10f28f22015-01-20 01:37:09 +0000621 if (DT) {
622 BasicBlock *PredBBIDom = DT->getNode(PredBB)->getIDom()->getBlock();
623 DT->changeImmediateDominator(DestBB, PredBBIDom);
624 DT->eraseNode(PredBB);
Andreas Neustifterf8cb7582009-09-16 09:26:52 +0000625 }
Chris Lattner99d68092008-11-27 07:43:12 +0000626 // Nuke BB.
627 PredBB->eraseFromParent();
628}
Devang Patelcaf44852009-02-10 07:00:59 +0000629
Duncan Sandse773c082013-07-11 08:28:20 +0000630/// 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.
633static bool CanMergeValues(Value *First, Value *Second) {
634 return First == Second || isa<UndefValue>(First) || isa<UndefValue>(Second);
635}
636
Chris Lattnercbd18fc2009-11-10 05:59:26 +0000637/// CanPropagatePredecessorsForPHIs - Return true if we can fold BB, an
Mark Laceya2626552013-08-14 22:11:42 +0000638/// almost-empty BB ending in an unconditional branch to Succ, into Succ.
Chris Lattnercbd18fc2009-11-10 05:59:26 +0000639///
640/// Assumption: Succ is the single successor for BB.
641///
642static bool CanPropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
643 assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");
644
Jakub Staszak8e1a6e72013-07-22 23:16:36 +0000645 DEBUG(dbgs() << "Looking to fold " << BB->getName() << " into "
Chris Lattnercbd18fc2009-11-10 05:59:26 +0000646 << 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 Kramerb5188f12011-12-06 16:14:29 +0000652 SmallPtrSet<BasicBlock*, 16> BBPreds(pred_begin(BB), pred_end(BB));
Chris Lattnercbd18fc2009-11-10 05:59:26 +0000653
Chris Lattnercbd18fc2009-11-10 05:59:26 +0000654 // 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 Kramerb5188f12011-12-06 16:14:29 +0000664 for (unsigned PI = 0, PE = PN->getNumIncomingValues(); PI != PE; ++PI) {
665 BasicBlock *IBB = PN->getIncomingBlock(PI);
666 if (BBPreds.count(IBB) &&
Duncan Sandse773c082013-07-11 08:28:20 +0000667 !CanMergeValues(BBPN->getIncomingValueForBlock(IBB),
668 PN->getIncomingValue(PI))) {
Jakub Staszak8e1a6e72013-07-22 23:16:36 +0000669 DEBUG(dbgs() << "Can't fold, phi node " << PN->getName() << " in "
670 << Succ->getName() << " is conflicting with "
Chris Lattnercbd18fc2009-11-10 05:59:26 +0000671 << BBPN->getName() << " with regard to common predecessor "
Benjamin Kramerb5188f12011-12-06 16:14:29 +0000672 << IBB->getName() << "\n");
Chris Lattnercbd18fc2009-11-10 05:59:26 +0000673 return false;
674 }
675 }
676 } else {
677 Value* Val = PN->getIncomingValueForBlock(BB);
Benjamin Kramerb5188f12011-12-06 16:14:29 +0000678 for (unsigned PI = 0, PE = PN->getNumIncomingValues(); PI != PE; ++PI) {
Chris Lattnercbd18fc2009-11-10 05:59:26 +0000679 // 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 Kramerb5188f12011-12-06 16:14:29 +0000682 BasicBlock *IBB = PN->getIncomingBlock(PI);
Duncan Sandse773c082013-07-11 08:28:20 +0000683 if (BBPreds.count(IBB) &&
684 !CanMergeValues(Val, PN->getIncomingValue(PI))) {
Jakub Staszak8e1a6e72013-07-22 23:16:36 +0000685 DEBUG(dbgs() << "Can't fold, phi node " << PN->getName() << " in "
Chris Lattnercbd18fc2009-11-10 05:59:26 +0000686 << Succ->getName() << " is conflicting with regard to common "
Benjamin Kramerb5188f12011-12-06 16:14:29 +0000687 << "predecessor " << IBB->getName() << "\n");
Chris Lattnercbd18fc2009-11-10 05:59:26 +0000688 return false;
689 }
690 }
691 }
692 }
693
694 return true;
695}
696
Duncan Sandse773c082013-07-11 08:28:20 +0000697typedef SmallVector<BasicBlock *, 16> PredBlockVector;
698typedef 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.
712static 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.
737static 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.
753static 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.
775static 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 Lattnercbd18fc2009-11-10 05:59:26 +0000830/// TryToSimplifyUncondBranchFromEmptyBlock - BB is known to contain an
831/// unconditional branch, and contains no instructions other than PHI nodes,
Rafael Espindolab10a0f22011-06-30 20:14:24 +0000832/// 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 Lattnercbd18fc2009-11-10 05:59:26 +0000835bool llvm::TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB) {
Dan Gohman4a63fad2010-08-14 00:29:42 +0000836 assert(BB != &BB->getParent()->getEntryBlock() &&
837 "TryToSimplifyUncondBranchFromEmptyBlock called on entry block!");
838
Chris Lattnercbd18fc2009-11-10 05:59:26 +0000839 // We can't eliminate infinite loops.
840 BasicBlock *Succ = cast<BranchInst>(BB->getTerminator())->getSuccessor(0);
841 if (BB == Succ) return false;
Jakub Staszak8e1a6e72013-07-22 23:16:36 +0000842
Reid Klecknerbca59d22016-05-02 19:43:22 +0000843 // 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 Lattnercbd18fc2009-11-10 05:59:26 +0000846
Reid Klecknerbca59d22016-05-02 19:43:22 +0000847 // 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 Wennborgb7599322016-05-02 17:22:54 +0000865 return false;
Reid Klecknerbca59d22016-05-02 19:43:22 +0000866 } else {
867 return false;
Hans Wennborgb7599322016-05-02 17:22:54 +0000868 }
Hans Wennborgb7599322016-05-02 17:22:54 +0000869 }
Reid Klecknerbca59d22016-05-02 19:43:22 +0000870 ++BBI;
Hans Wennborgb7599322016-05-02 17:22:54 +0000871 }
Hans Wennborgb7599322016-05-02 17:22:54 +0000872 }
Reid Klecknerbca59d22016-05-02 19:43:22 +0000873
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 Hahn77382be2016-11-18 13:12:07 +0000906 // 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 Klecknerbca59d22016-05-02 19:43:22 +0000917 // 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 Lattnercbd18fc2009-11-10 05:59:26 +0000922}
923
Jim Grosbachd831ef42009-12-02 17:06:45 +0000924/// 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///
929bool llvm::EliminateDuplicatePHINodes(BasicBlock *BB) {
Jim Grosbachd831ef42009-12-02 17:06:45 +0000930 // This implementation doesn't currently consider undef operands
Nick Lewyckyfa44dc62011-06-28 03:57:31 +0000931 // specially. Theoretically, two phis which are identical except for
Jim Grosbachd831ef42009-12-02 17:06:45 +0000932 // one having an undef where the other doesn't could be collapsed.
933
Benjamin Kramer2b2cdd72015-06-18 16:01:00 +0000934 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 Grosbachd831ef42009-12-02 17:06:45 +0000956
Benjamin Kramer2b2cdd72015-06-18 16:01:00 +0000957 // Set of unique PHINodes.
958 DenseSet<PHINode *, PHIDenseMapInfo> PHISet;
Jim Grosbachd831ef42009-12-02 17:06:45 +0000959
960 // Examine each PHI.
Benjamin Kramer2b2cdd72015-06-18 16:01:00 +0000961 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 Kramerf175e042015-09-02 19:52:23 +0000969
970 // The RAUW can change PHIs that we already visited. Start over from the
971 // beginning.
972 PHISet.clear();
973 I = BB->begin();
Jim Grosbachd831ef42009-12-02 17:06:45 +0000974 }
975 }
976
977 return Changed;
978}
Chris Lattner6fcd32e2010-12-25 20:37:57 +0000979
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 Kramer570dd782010-12-30 22:34:44 +0000986static unsigned enforceKnownAlignment(Value *V, unsigned Align,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000987 unsigned PrefAlign,
988 const DataLayout &DL) {
James Y Knightac03dca2016-01-15 16:33:06 +0000989 assert(PrefAlign > Align);
990
Eli Friedman19ace4c2011-06-15 21:08:25 +0000991 V = V->stripPointerCasts();
Chris Lattner6fcd32e2010-12-25 20:37:57 +0000992
Eli Friedman19ace4c2011-06-15 21:08:25 +0000993 if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
James Y Knightac03dca2016-01-15 16:33:06 +0000994 // 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 Hamesde7ab802011-10-10 23:42:08 +00001004 // If the preferred alignment is greater than the natural stack alignment
1005 // then don't round up. This avoids dynamic stack realignment.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001006 if (DL.exceedsNaturalStackAlignment(PrefAlign))
Lang Hamesde7ab802011-10-10 23:42:08 +00001007 return Align;
Chris Lattner6fcd32e2010-12-25 20:37:57 +00001008 AI->setAlignment(PrefAlign);
1009 return PrefAlign;
1010 }
Chris Lattner6fcd32e2010-12-25 20:37:57 +00001011
Rafael Espindola99e05cf2014-05-13 18:45:48 +00001012 if (auto *GO = dyn_cast<GlobalObject>(V)) {
James Y Knightac03dca2016-01-15 16:33:06 +00001013 // TODO: as above, this shouldn't be necessary.
1014 Align = std::max(GO->getAlignment(), Align);
1015 if (PrefAlign <= Align)
1016 return Align;
1017
Chris Lattner6fcd32e2010-12-25 20:37:57 +00001018 // If there is a large requested alignment and we can, bump up the alignment
Reid Kleckner486fa392015-07-14 00:11:08 +00001019 // 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 Knightac03dca2016-01-15 16:33:06 +00001022 if (!GO->canIncreaseAlignment())
Rafael Espindolafc13db42014-05-09 16:01:06 +00001023 return Align;
Jakub Staszak8e1a6e72013-07-22 23:16:36 +00001024
James Y Knightac03dca2016-01-15 16:33:06 +00001025 GO->setAlignment(PrefAlign);
1026 return PrefAlign;
Chris Lattner6fcd32e2010-12-25 20:37:57 +00001027 }
1028
1029 return Align;
1030}
1031
Chris Lattner6fcd32e2010-12-25 20:37:57 +00001032unsigned llvm::getOrEnforceKnownAlignment(Value *V, unsigned PrefAlign,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001033 const DataLayout &DL,
Hal Finkel60db0582014-09-07 18:57:58 +00001034 const Instruction *CxtI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001035 AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001036 const DominatorTree *DT) {
Chris Lattner6fcd32e2010-12-25 20:37:57 +00001037 assert(V->getType()->isPointerTy() &&
1038 "getOrEnforceKnownAlignment expects a pointer!");
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001039 unsigned BitWidth = DL.getPointerTypeSizeInBits(V->getType());
Matt Arsenault87dc6072013-08-01 22:42:18 +00001040
Chris Lattner6fcd32e2010-12-25 20:37:57 +00001041 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001042 computeKnownBits(V, KnownZero, KnownOne, DL, 0, AC, CxtI, DT);
Chris Lattner6fcd32e2010-12-25 20:37:57 +00001043 unsigned TrailZ = KnownZero.countTrailingOnes();
Jakub Staszak8e1a6e72013-07-22 23:16:36 +00001044
Matt Arsenaultf64212b2013-07-23 22:20:57 +00001045 // Avoid trouble with ridiculously large TrailZ values, such as
Chris Lattner6fcd32e2010-12-25 20:37:57 +00001046 // those computed from a null pointer.
1047 TrailZ = std::min(TrailZ, unsigned(sizeof(unsigned) * CHAR_BIT - 1));
Jakub Staszak8e1a6e72013-07-22 23:16:36 +00001048
Chris Lattner6fcd32e2010-12-25 20:37:57 +00001049 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
Jakub Staszak8e1a6e72013-07-22 23:16:36 +00001050
Chris Lattner6fcd32e2010-12-25 20:37:57 +00001051 // LLVM doesn't support alignments larger than this currently.
1052 Align = std::min(Align, +Value::MaximumAlignment);
Jakub Staszak8e1a6e72013-07-22 23:16:36 +00001053
Chris Lattner6fcd32e2010-12-25 20:37:57 +00001054 if (PrefAlign > Align)
Matt Arsenault87dc6072013-08-01 22:42:18 +00001055 Align = enforceKnownAlignment(V, Align, PrefAlign, DL);
Jakub Staszak8e1a6e72013-07-22 23:16:36 +00001056
Chris Lattner6fcd32e2010-12-25 20:37:57 +00001057 // We don't need to make any adjustment.
1058 return Align;
1059}
1060
Devang Patel8c0b16b2011-03-17 21:58:19 +00001061///===---------------------------------------------------------------------===//
1062/// Dbg Intrinsic utilities
1063///
1064
Adrian Prantl29b9de72013-04-26 17:48:33 +00001065/// See if there is a dbg.value intrinsic for DIVar before I.
Adrian Prantla5b2a642016-02-17 20:02:25 +00001066static bool LdStHasDebugValue(DILocalVariable *DIVar, DIExpression *DIExpr,
1067 Instruction *I) {
Adrian Prantl29b9de72013-04-26 17:48:33 +00001068 // 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 Prantla5b2a642016-02-17 20:02:25 +00001077 DVI->getVariable() == DIVar &&
1078 DVI->getExpression() == DIExpr)
Adrian Prantl29b9de72013-04-26 17:48:33 +00001079 return true;
1080 }
1081 return false;
1082}
1083
Keith Walkerba159892016-09-22 14:13:25 +00001084/// See if there is a dbg.value intrinsic for DIVar for the PHI node.
1085static 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 Prantlfa9e84e2017-03-16 20:11:54 +00001091 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 Walkerba159892016-09-22 14:13:25 +00001100}
1101
Adrian Prantld00333a2013-04-26 18:10:50 +00001102/// Inserts a llvm.dbg.value intrinsic before a store to an alloca'd value
Devang Patel8c0b16b2011-03-17 21:58:19 +00001103/// that has an associated llvm.dbg.decl intrinsic.
Keith Walkerba159892016-09-22 14:13:25 +00001104void llvm::ConvertDebugDeclareToDebugValue(DbgDeclareInst *DDI,
Devang Patel8c0b16b2011-03-17 21:58:19 +00001105 StoreInst *SI, DIBuilder &Builder) {
Duncan P. N. Exon Smith60635e32015-04-21 18:44:06 +00001106 auto *DIVar = DDI->getVariable();
1107 auto *DIExpr = DDI->getExpression();
Duncan P. N. Exon Smithd4a19a32015-04-21 18:24:23 +00001108 assert(DIVar && "Missing variable");
Devang Patel8c0b16b2011-03-17 21:58:19 +00001109
Devang Patel8e60ff12011-05-16 21:24:05 +00001110 // If an argument is zero extended then use argument directly. The ZExt
1111 // may be zapped by an optimization pass in future.
Craig Topperf40110f2014-04-25 05:29:35 +00001112 Argument *ExtendedArg = nullptr;
Devang Patel8e60ff12011-05-16 21:24:05 +00001113 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 Fischer9aae4452016-01-12 22:46:09 +00001117 if (ExtendedArg) {
Adrian Prantl941fa752016-12-05 18:04:47 +00001118 // We're now only describing a subset of the variable. The fragment we're
Keno Fischer9aae4452016-01-12 22:46:09 +00001119 // 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 Prantla5b2a642016-02-17 20:02:25 +00001124 SmallVector<uint64_t, 3> Ops;
Adrian Prantl941fa752016-12-05 18:04:47 +00001125 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 Prantl49797ca2016-12-22 05:27:12 +00001128 auto Fragment = DIExpr->getFragmentInfo();
1129 if (Fragment) {
Adrian Prantla5b2a642016-02-17 20:02:25 +00001130 Ops.append(DIExpr->elements_begin(), DIExpr->elements_end()-3);
Adrian Prantl49797ca2016-12-22 05:27:12 +00001131 FragmentOffset = Fragment->OffsetInBits;
Keno Fischer9aae4452016-01-12 22:46:09 +00001132 } else {
Adrian Prantla5b2a642016-02-17 20:02:25 +00001133 Ops.append(DIExpr->elements_begin(), DIExpr->elements_end());
Keno Fischer9aae4452016-01-12 22:46:09 +00001134 }
Adrian Prantl941fa752016-12-05 18:04:47 +00001135 Ops.push_back(dwarf::DW_OP_LLVM_fragment);
1136 Ops.push_back(FragmentOffset);
Keno Fischer9aae4452016-01-12 22:46:09 +00001137 const DataLayout &DL = DDI->getModule()->getDataLayout();
Adrian Prantl941fa752016-12-05 18:04:47 +00001138 Ops.push_back(DL.getTypeSizeInBits(ExtendedArg->getType()));
Adrian Prantla5b2a642016-02-17 20:02:25 +00001139 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 Ballmana2f99432015-04-16 13:29:36 +00001144 Builder.insertDbgValueIntrinsic(SI->getOperand(0), 0, DIVar, DIExpr,
1145 DDI->getDebugLoc(), SI);
Devang Patel8c0b16b2011-03-17 21:58:19 +00001146}
1147
Adrian Prantld00333a2013-04-26 18:10:50 +00001148/// Inserts a llvm.dbg.value intrinsic before a load of an alloca'd value
Devang Patel2c7ee272011-03-18 23:45:43 +00001149/// that has an associated llvm.dbg.decl intrinsic.
Keith Walkerba159892016-09-22 14:13:25 +00001150void llvm::ConvertDebugDeclareToDebugValue(DbgDeclareInst *DDI,
Devang Patel2c7ee272011-03-18 23:45:43 +00001151 LoadInst *LI, DIBuilder &Builder) {
Duncan P. N. Exon Smith60635e32015-04-21 18:44:06 +00001152 auto *DIVar = DDI->getVariable();
1153 auto *DIExpr = DDI->getExpression();
Duncan P. N. Exon Smithd4a19a32015-04-21 18:24:23 +00001154 assert(DIVar && "Missing variable");
Devang Patel2c7ee272011-03-18 23:45:43 +00001155
Adrian Prantla5b2a642016-02-17 20:02:25 +00001156 if (LdStHasDebugValue(DIVar, DIExpr, LI))
Keith Walkerba159892016-09-22 14:13:25 +00001157 return;
Adrian Prantl29b9de72013-04-26 17:48:33 +00001158
Keno Fischer00cbf9a2015-12-19 02:02:44 +00001159 // 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 Walkerba159892016-09-22 14:13:25 +00001166}
1167
1168/// Inserts a llvm.dbg.value intrinsic after a phi
1169/// that has an associated llvm.dbg.decl intrinsic.
1170void 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 Kleckner64818222016-09-27 18:45:31 +00001179 BasicBlock *BB = APN->getParent();
Keith Walkerba159892016-09-22 14:13:25 +00001180 auto InsertionPt = BB->getFirstInsertionPt();
Reid Kleckner64818222016-09-27 18:45:31 +00001181
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 Walkerc9412522016-09-19 09:49:30 +00001188}
1189
Adrian Prantl232897f2014-04-25 23:00:25 +00001190/// Determine whether this alloca is either a VLA or an array.
1191static bool isArray(AllocaInst *AI) {
1192 return AI->isArrayAllocation() ||
1193 AI->getType()->getElementType()->isArrayTy();
1194}
1195
Devang Patelaad34d82011-03-17 22:18:16 +00001196/// LowerDbgDeclare - Lowers llvm.dbg.declare intrinsics into appropriate set
1197/// of llvm.dbg.value intrinsics.
1198bool llvm::LowerDbgDeclare(Function &F) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001199 DIBuilder DIB(*F.getParent(), /*AllowUnresolved*/ false);
Devang Patelaad34d82011-03-17 22:18:16 +00001200 SmallVector<DbgDeclareInst *, 4> Dbgs;
Adrian Prantl79c8e8f2014-03-27 23:30:04 +00001201 for (auto &FI : F)
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001202 for (Instruction &BI : FI)
1203 if (auto DDI = dyn_cast<DbgDeclareInst>(&BI))
Devang Patelaad34d82011-03-17 22:18:16 +00001204 Dbgs.push_back(DDI);
Adrian Prantl79c8e8f2014-03-27 23:30:04 +00001205
Devang Patelaad34d82011-03-17 22:18:16 +00001206 if (Dbgs.empty())
1207 return false;
1208
Adrian Prantl79c8e8f2014-03-27 23:30:04 +00001209 for (auto &I : Dbgs) {
1210 DbgDeclareInst *DDI = I;
Adrian Prantl8e10fdb2013-11-18 23:04:38 +00001211 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 Prantl32da8892014-04-25 20:49:25 +00001214 // 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 Prantl232897f2014-04-25 23:00:25 +00001218 if (AI && !isArray(AI)) {
Keno Fischer1dd319f2016-01-14 19:12:27 +00001219 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 Patel2c7ee272011-03-18 23:45:43 +00001225 ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
Keno Fischer1dd319f2016-01-14 19:12:27 +00001226 } else if (CallInst *CI = dyn_cast<CallInst>(U)) {
NAKAMURA Takumi335a7bc2014-10-28 11:53:30 +00001227 // 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 Smith60635e32015-04-21 18:44:06 +00001230 DIB.insertDbgValueIntrinsic(AI, 0, DDI->getVariable(),
Adrian Prantl6825fb62017-04-18 01:21:53 +00001231 DDI->getExpression(), DDI->getDebugLoc(),
1232 CI);
Adrian Prantl87b7eb92014-10-01 18:55:02 +00001233 }
Keno Fischer1dd319f2016-01-14 19:12:27 +00001234 }
Adrian Prantl32da8892014-04-25 20:49:25 +00001235 DDI->eraseFromParent();
Devang Patelaad34d82011-03-17 22:18:16 +00001236 }
Devang Patelaad34d82011-03-17 22:18:16 +00001237 }
1238 return true;
1239}
Cameron Zwarich843bc7d2011-05-24 03:10:43 +00001240
1241/// FindAllocaDbgDeclare - Finds the llvm.dbg.declare intrinsic describing the
1242/// alloca 'V', if any.
1243DbgDeclareInst *llvm::FindAllocaDbgDeclare(Value *V) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001244 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 Zwarich843bc7d2011-05-24 03:10:43 +00001249
Craig Topperf40110f2014-04-25 05:29:35 +00001250 return nullptr;
Cameron Zwarich843bc7d2011-05-24 03:10:43 +00001251}
Alexey Samsonov3d43b632012-12-12 14:31:53 +00001252
Adrian Prantlfa9e84e2017-03-16 20:11:54 +00001253void llvm::findDbgValues(SmallVectorImpl<DbgValueInst *> &DbgValues, Value *V) {
Keith Walkerba159892016-09-22 14:13:25 +00001254 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 Prantlfa9e84e2017-03-16 20:11:54 +00001258 DbgValues.push_back(DVI);
Keith Walkerba159892016-09-22 14:13:25 +00001259}
1260
Adrian Prantl47ea6472017-03-16 21:14:09 +00001261static void appendOffset(SmallVectorImpl<uint64_t> &Ops, int64_t Offset) {
Evgeniy Stepanov72d961a2016-06-16 22:34:00 +00001262 if (Offset > 0) {
Adrian Prantl47ea6472017-03-16 21:14:09 +00001263 Ops.push_back(dwarf::DW_OP_plus);
1264 Ops.push_back(Offset);
Evgeniy Stepanov72d961a2016-06-16 22:34:00 +00001265 } else if (Offset < 0) {
Adrian Prantl47ea6472017-03-16 21:14:09 +00001266 Ops.push_back(dwarf::DW_OP_minus);
1267 Ops.push_back(-Offset);
Evgeniy Stepanov72d961a2016-06-16 22:34:00 +00001268 }
1269}
1270
Adrian Prantl47ea6472017-03-16 21:14:09 +00001271/// Prepend \p DIExpr with a deref and offset operation.
1272static DIExpression *prependDIExpr(DIBuilder &Builder, DIExpression *DIExpr,
1273 bool Deref, int64_t Offset) {
Evgeniy Stepanov72d961a2016-06-16 22:34:00 +00001274 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 Prantl47ea6472017-03-16 21:14:09 +00001280 SmallVector<uint64_t, 4> Ops;
Evgeniy Stepanov72d961a2016-06-16 22:34:00 +00001281 if (Deref)
Adrian Prantl47ea6472017-03-16 21:14:09 +00001282 Ops.push_back(dwarf::DW_OP_deref);
1283 appendOffset(Ops, Offset);
Evgeniy Stepanov72d961a2016-06-16 22:34:00 +00001284 if (DIExpr)
Adrian Prantl47ea6472017-03-16 21:14:09 +00001285 Ops.append(DIExpr->elements_begin(), DIExpr->elements_end());
1286 return Builder.createExpression(Ops);
Evgeniy Stepanov72d961a2016-06-16 22:34:00 +00001287}
1288
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +00001289bool llvm::replaceDbgDeclare(Value *Address, Value *NewAddress,
1290 Instruction *InsertBefore, DIBuilder &Builder,
1291 bool Deref, int Offset) {
1292 DbgDeclareInst *DDI = FindAllocaDbgDeclare(Address);
Alexey Samsonov3d43b632012-12-12 14:31:53 +00001293 if (!DDI)
1294 return false;
Adrian Prantl3e2659e2015-01-30 19:37:48 +00001295 DebugLoc Loc = DDI->getDebugLoc();
Duncan P. N. Exon Smith60635e32015-04-21 18:44:06 +00001296 auto *DIVar = DDI->getVariable();
1297 auto *DIExpr = DDI->getExpression();
Duncan P. N. Exon Smithd4a19a32015-04-21 18:24:23 +00001298 assert(DIVar && "Missing variable");
Alexey Samsonov3d43b632012-12-12 14:31:53 +00001299
Adrian Prantl47ea6472017-03-16 21:14:09 +00001300 DIExpr = prependDIExpr(Builder, DIExpr, Deref, Offset);
Alexey Samsonov3d43b632012-12-12 14:31:53 +00001301
Evgeniy Stepanovd8b86f72015-09-29 00:30:19 +00001302 // Insert llvm.dbg.declare immediately after the original alloca, and remove
1303 // old llvm.dbg.declare.
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +00001304 Builder.insertDeclare(NewAddress, DIVar, DIExpr, Loc, InsertBefore);
Alexey Samsonov3d43b632012-12-12 14:31:53 +00001305 DDI->eraseFromParent();
1306 return true;
1307}
Evgeniy Stepanov4fbc0d082012-12-21 11:18:49 +00001308
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +00001309bool 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 Stepanov72d961a2016-06-16 22:34:00 +00001315static 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 Prantl47ea6472017-03-16 21:14:09 +00001332 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 Stepanov72d961a2016-06-16 22:34:00 +00001337 }
1338
1339 Builder.insertDbgValueIntrinsic(NewAddress, DVI->getOffset(), DIVar, DIExpr,
1340 Loc, DVI);
1341 DVI->eraseFromParent();
1342}
1343
1344void 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 Prantl47ea6472017-03-16 21:14:09 +00001355void 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 Prantl6d80a262017-03-20 16:39:41 +00001363 if (isa<BitCastInst>(&I)) {
1364 findDbgValues(DbgValues, &I);
Adrian Prantl47ea6472017-03-16 21:14:09 +00001365 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 Prantl6d80a262017-03-20 16:39:41 +00001372 findDbgValues(DbgValues, &I);
Adrian Prantl47ea6472017-03-16 21:14:09 +00001373 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 Prantl6d80a262017-03-20 16:39:41 +00001388 } else if (isa<LoadInst>(&I)) {
1389 findDbgValues(DbgValues, &I);
Adrian Prantl47ea6472017-03-16 21:14:09 +00001390 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 Majnemer35c46d32016-01-24 05:26:18 +00001402unsigned 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 Smithe9bc5792016-02-21 20:39:50 +00001407 while (EndInst != &BB->front()) {
David Majnemer35c46d32016-01-24 05:26:18 +00001408 // 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 Zolotukhin5020c992016-11-18 21:01:12 +00001423unsigned llvm::changeToUnreachable(Instruction *I, bool UseLLVMTrap,
1424 bool PreserveLCSSA) {
Peter Collingbourne8d642de2013-08-12 22:38:43 +00001425 BasicBlock *BB = I->getParent();
1426 // Loop over all of the successors, removing BB's entry from any PHI
1427 // nodes.
David Majnemer9f506252016-06-25 08:34:38 +00001428 for (BasicBlock *Successor : successors(BB))
Michael Zolotukhin5020c992016-11-18 21:01:12 +00001429 Successor->removePredecessor(BB, PreserveLCSSA);
Peter Collingbourne8d642de2013-08-12 22:38:43 +00001430
David Majnemere14e7bc2016-06-25 08:19:55 +00001431 // 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 Collingbourne8d642de2013-08-12 22:38:43 +00001439 new UnreachableInst(I->getContext(), I);
1440
1441 // All instructions after this are dead.
David Majnemer88542a02016-01-24 06:26:47 +00001442 unsigned NumInstrsRemoved = 0;
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001443 BasicBlock::iterator BBI = I->getIterator(), BBE = BB->end();
Peter Collingbourne8d642de2013-08-12 22:38:43 +00001444 while (BBI != BBE) {
1445 if (!BBI->use_empty())
1446 BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
1447 BB->getInstList().erase(BBI++);
David Majnemer88542a02016-01-24 06:26:47 +00001448 ++NumInstrsRemoved;
Peter Collingbourne8d642de2013-08-12 22:38:43 +00001449 }
David Majnemer88542a02016-01-24 06:26:47 +00001450 return NumInstrsRemoved;
Peter Collingbourne8d642de2013-08-12 22:38:43 +00001451}
1452
1453/// changeToCall - Convert the specified invoke into a normal call.
1454static void changeToCall(InvokeInst *II) {
Sanjoy Dasccd14562015-12-10 06:39:02 +00001455 SmallVector<Value*, 8> Args(II->arg_begin(), II->arg_end());
Sanjoy Das8a954a02015-12-08 22:26:08 +00001456 SmallVector<OperandBundleDef, 1> OpBundles;
1457 II->getOperandBundlesAsDefs(OpBundles);
1458 CallInst *NewCall = CallInst::Create(II->getCalledValue(), Args, OpBundles,
1459 "", II);
Peter Collingbourne8d642de2013-08-12 22:38:43 +00001460 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 Breckaddfdba32016-11-14 21:41:13 +00001474BasicBlock *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 Majnemer7fddecc2015-06-17 20:52:32 +00001511static bool markAliveBlocks(Function &F,
Craig Topper71b7b682014-08-21 05:55:13 +00001512 SmallPtrSetImpl<BasicBlock*> &Reachable) {
Peter Collingbourne8d642de2013-08-12 22:38:43 +00001513
Evgeniy Stepanov4fbc0d082012-12-21 11:18:49 +00001514 SmallVector<BasicBlock*, 128> Worklist;
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001515 BasicBlock *BB = &F.front();
Peter Collingbourne8d642de2013-08-12 22:38:43 +00001516 Worklist.push_back(BB);
1517 Reachable.insert(BB);
1518 bool Changed = false;
Evgeniy Stepanov4fbc0d082012-12-21 11:18:49 +00001519 do {
Peter Collingbourne8d642de2013-08-12 22:38:43 +00001520 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 Majnemer9f506252016-06-25 08:34:38 +00001525 for (Instruction &I : *BB) {
Hal Finkel93046912014-07-25 21:13:35 +00001526 // 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 Majnemer9f506252016-06-25 08:34:38 +00001529 if (auto *II = dyn_cast<IntrinsicInst>(&I)) {
Hal Finkel93046912014-07-25 21:13:35 +00001530 if (II->getIntrinsicID() == Intrinsic::assume) {
David Majnemer9f506252016-06-25 08:34:38 +00001531 if (match(II->getArgOperand(0), m_CombineOr(m_Zero(), m_Undef()))) {
David Majnemere14e7bc2016-06-25 08:19:55 +00001532 // Don't insert a call to llvm.trap right before the unreachable.
David Majnemer9f506252016-06-25 08:34:38 +00001533 changeToUnreachable(II, false);
Hal Finkel93046912014-07-25 21:13:35 +00001534 Changed = true;
1535 break;
1536 }
1537 }
1538
Sanjoy Das54a3a002016-04-21 05:09:12 +00001539 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 Majnemer9f506252016-06-25 08:34:38 +00001548 if (match(II->getArgOperand(0), m_Zero()))
1549 if (!isa<UnreachableInst>(II->getNextNode())) {
David Majnemere14e7bc2016-06-25 08:19:55 +00001550 changeToUnreachable(II->getNextNode(), /*UseLLVMTrap=*/ false);
Sanjoy Das54a3a002016-04-21 05:09:12 +00001551 Changed = true;
1552 break;
1553 }
1554 }
1555 }
1556
David Majnemer9f506252016-06-25 08:34:38 +00001557 if (auto *CI = dyn_cast<CallInst>(&I)) {
David Majnemer1fea77c2016-06-25 07:37:27 +00001558 Value *Callee = CI->getCalledValue();
1559 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
David Majnemere14e7bc2016-06-25 08:19:55 +00001560 changeToUnreachable(CI, /*UseLLVMTrap=*/false);
David Majnemer1fea77c2016-06-25 07:37:27 +00001561 Changed = true;
1562 break;
1563 }
Peter Collingbourne8d642de2013-08-12 22:38:43 +00001564 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 Majnemer9f506252016-06-25 08:34:38 +00001568 if (!isa<UnreachableInst>(CI->getNextNode())) {
David Majnemere14e7bc2016-06-25 08:19:55 +00001569 // Don't insert a call to llvm.trap right before the unreachable.
David Majnemer9f506252016-06-25 08:34:38 +00001570 changeToUnreachable(CI->getNextNode(), false);
Peter Collingbourne8d642de2013-08-12 22:38:43 +00001571 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 Majnemer9f506252016-06-25 08:34:38 +00001580 if (auto *SI = dyn_cast<StoreInst>(&I)) {
Peter Collingbourne8d642de2013-08-12 22:38:43 +00001581 // 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 Majnemere14e7bc2016-06-25 08:19:55 +00001589 changeToUnreachable(SI, true);
Peter Collingbourne8d642de2013-08-12 22:38:43 +00001590 Changed = true;
1591 break;
1592 }
1593 }
1594 }
1595
David Majnemer2fa86512016-01-05 06:27:50 +00001596 TerminatorInst *Terminator = BB->getTerminator();
1597 if (auto *II = dyn_cast<InvokeInst>(Terminator)) {
1598 // Turn invokes that call 'nounwind' functions into ordinary calls.
Peter Collingbourne8d642de2013-08-12 22:38:43 +00001599 Value *Callee = II->getCalledValue();
1600 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
David Majnemere14e7bc2016-06-25 08:19:55 +00001601 changeToUnreachable(II, true);
Peter Collingbourne8d642de2013-08-12 22:38:43 +00001602 Changed = true;
David Majnemer7fddecc2015-06-17 20:52:32 +00001603 } else if (II->doesNotThrow() && canSimplifyInvokeNoUnwind(&F)) {
Peter Collingbourne8d642de2013-08-12 22:38:43 +00001604 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 Majnemer2fa86512016-01-05 06:27:50 +00001613 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Terminator)) {
1614 // Remove catchpads which cannot be reached.
David Majnemer59eb7332016-01-05 07:42:17 +00001615 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 Majnemer2fa86512016-01-05 06:27:50 +00001639 for (CatchSwitchInst::handler_iterator I = CatchSwitch->handler_begin(),
1640 E = CatchSwitch->handler_end();
1641 I != E; ++I) {
1642 BasicBlock *HandlerBB = *I;
David Majnemer59eb7332016-01-05 07:42:17 +00001643 auto *CatchPad = cast<CatchPadInst>(HandlerBB->getFirstNonPHI());
1644 if (!HandlerSet.insert({CatchPad, Empty}).second) {
David Majnemer2fa86512016-01-05 06:27:50 +00001645 CatchSwitch->removeHandler(I);
1646 --I;
1647 --E;
1648 Changed = true;
1649 }
1650 }
Peter Collingbourne8d642de2013-08-12 22:38:43 +00001651 }
1652
1653 Changed |= ConstantFoldTerminator(BB, true);
David Majnemer9f506252016-06-25 08:34:38 +00001654 for (BasicBlock *Successor : successors(BB))
1655 if (Reachable.insert(Successor).second)
1656 Worklist.push_back(Successor);
Evgeniy Stepanov4fbc0d082012-12-21 11:18:49 +00001657 } while (!Worklist.empty());
Peter Collingbourne8d642de2013-08-12 22:38:43 +00001658 return Changed;
1659}
Evgeniy Stepanov4fbc0d082012-12-21 11:18:49 +00001660
Joseph Tremoulet09af67a2015-09-27 01:47:46 +00001661void 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 Majnemer8a1c45d2015-12-12 05:38:55 +00001675 } 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 Tremoulet09af67a2015-09-27 01:47:46 +00001684 } 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 Majnemer8a1c45d2015-12-12 05:38:55 +00001691 TI->replaceAllUsesWith(NewTI);
Joseph Tremoulet09af67a2015-09-27 01:47:46 +00001692 TI->eraseFromParent();
1693}
1694
Peter Collingbourne8d642de2013-08-12 22:38:43 +00001695/// 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 Laevsky87f0d0e2016-06-16 16:25:53 +00001698bool llvm::removeUnreachableBlocks(Function &F, LazyValueInfo *LVI) {
Matthias Braunb30f2f512016-01-30 01:24:31 +00001699 SmallPtrSet<BasicBlock*, 16> Reachable;
David Majnemer7fddecc2015-06-17 20:52:32 +00001700 bool Changed = markAliveBlocks(F, Reachable);
Peter Collingbourne8d642de2013-08-12 22:38:43 +00001701
1702 // If there are unreachable blocks in the CFG...
Evgeniy Stepanov4fbc0d082012-12-21 11:18:49 +00001703 if (Reachable.size() == F.size())
Peter Collingbourne8d642de2013-08-12 22:38:43 +00001704 return Changed;
Evgeniy Stepanov4fbc0d082012-12-21 11:18:49 +00001705
1706 assert(Reachable.size() < F.size());
Peter Collingbourne8d642de2013-08-12 22:38:43 +00001707 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 Smith5b4c8372015-10-13 02:39:05 +00001712 if (Reachable.count(&*BB))
Evgeniy Stepanov4fbc0d082012-12-21 11:18:49 +00001713 continue;
1714
David Majnemer9f506252016-06-25 08:34:38 +00001715 for (BasicBlock *Successor : successors(&*BB))
1716 if (Reachable.count(Successor))
1717 Successor->removePredecessor(&*BB);
David Majnemerd9833ea2016-01-10 07:13:04 +00001718 if (LVI)
1719 LVI->eraseBlock(&*BB);
Peter Collingbourne8d642de2013-08-12 22:38:43 +00001720 BB->dropAllReferences();
Evgeniy Stepanov4fbc0d082012-12-21 11:18:49 +00001721 }
Evgeniy Stepanov2a066af2013-03-22 08:43:04 +00001722
Peter Collingbourne8d642de2013-08-12 22:38:43 +00001723 for (Function::iterator I = ++F.begin(); I != F.end();)
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001724 if (!Reachable.count(&*I))
Evgeniy Stepanov2a066af2013-03-22 08:43:04 +00001725 I = F.getBasicBlockList().erase(I);
1726 else
1727 ++I;
1728
Evgeniy Stepanov4fbc0d082012-12-21 11:18:49 +00001729 return true;
1730}
Rafael Espindolaea46c322014-08-15 15:46:38 +00001731
Piotr Padlewskidc9b2cf2015-10-02 22:12:22 +00001732void llvm::combineMetadata(Instruction *K, const Instruction *J,
1733 ArrayRef<unsigned> KnownIDs) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001734 SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
Adrian Prantlcbdfdb72015-08-20 22:00:30 +00001735 K->dropUnknownNonDebugMetadata(KnownIDs);
Rafael Espindolaea46c322014-08-15 15:46:38 +00001736 K->getAllMetadataOtherThanDebugLoc(Metadata);
David Majnemer6f014d32016-07-25 02:21:19 +00001737 for (const auto &MD : Metadata) {
1738 unsigned Kind = MD.first;
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001739 MDNode *JMD = J->getMetadata(Kind);
David Majnemer6f014d32016-07-25 02:21:19 +00001740 MDNode *KMD = MD.second;
Rafael Espindolaea46c322014-08-15 15:46:38 +00001741
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 Steinbrink5ec75222015-02-08 17:07:14 +00001752 K->setMetadata(Kind, MDNode::getMostGenericAliasScope(JMD, KMD));
1753 break;
Rafael Espindolaea46c322014-08-15 15:46:38 +00001754 case LLVMContext::MD_noalias:
Hal Finkele4c0c162016-04-26 02:06:06 +00001755 case LLVMContext::MD_mem_parallel_loop_access:
Rafael Espindolaea46c322014-08-15 15:46:38 +00001756 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 Reamesd7c21362014-10-21 21:02:19 +00001768 case LLVMContext::MD_nonnull:
1769 // Only set the !nonnull if it is present in both instructions.
1770 K->setMetadata(Kind, JMD);
1771 break;
Piotr Padlewskidc9b2cf2015-10-02 22:12:22 +00001772 case LLVMContext::MD_invariant_group:
1773 // Preserve !invariant.group in K.
1774 break;
Artur Pilipenko5c5011d2015-11-02 17:53:51 +00001775 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 Espindolaea46c322014-08-15 15:46:38 +00001784 }
1785 }
Piotr Padlewskidc9b2cf2015-10-02 22:12:22 +00001786 // 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 Espindolaea46c322014-08-15 15:46:38 +00001795}
Philip Reames7c78ef72015-05-22 23:53:24 +00001796
Eli Friedman02419a92016-08-08 04:10:22 +00001797void 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 Reames7c78ef72015-05-22 23:53:24 +00001808unsigned 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 Padlewski28ffcbe2015-09-02 19:59:59 +00001827
1828unsigned llvm::replaceDominatedUsesWith(Value *From, Value *To,
1829 DominatorTree &DT,
Dehao Chendb381072016-09-08 15:25:12 +00001830 const BasicBlock *BB) {
Piotr Padlewski28ffcbe2015-09-02 19:59:59 +00001831 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 Chendb381072016-09-08 15:25:12 +00001838 if (DT.properlyDominates(BB, I->getParent())) {
Piotr Padlewski28ffcbe2015-09-02 19:59:59 +00001839 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 Dasc21a05a2015-10-08 23:18:30 +00001847
1848bool llvm::callsGCLeafFunction(ImmutableCallSite CS) {
Sanjoy Dasc21a05a2015-10-08 23:18:30 +00001849 // Check if the function is specifically marked as a gc leaf function.
Manuel Jacob3eedd112016-01-05 23:59:08 +00001850 if (CS.hasFnAttr("gc-leaf-function"))
1851 return true;
Sanjoy Dasd4c78332016-03-25 20:12:13 +00001852 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 Dasc21a05a2015-10-08 23:18:30 +00001861
1862 return false;
1863}
James Molloyf01488e2016-01-15 09:20:19 +00001864
Benjamin Kramerb7d33112016-08-06 11:13:10 +00001865namespace {
James Molloyf01488e2016-01-15 09:20:19 +00001866/// A potential constituent of a bitreverse or bswap expression. See
1867/// collectBitParts for a fuller explanation.
1868struct 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 Kramerb7d33112016-08-06 11:13:10 +00001881} // end anonymous namespace
James Molloyf01488e2016-01-15 09:20:19 +00001882
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///
1907static const Optional<BitPart> &
1908collectBitParts(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 Rosiere5819e22016-05-26 14:58:51 +00001997 return Result;
1998 }
James Molloyf01488e2016-01-15 09:20:19 +00001999
Chad Rosiere5819e22016-05-26 14:58:51 +00002000 // 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 Molloyf01488e2016-01-15 09:20:19 +00002014 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
2026static 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
2037static 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 Rosiera00df492016-05-25 16:22:14 +00002044bool llvm::recognizeBSwapOrBitReverseIdiom(
James Molloyf01488e2016-01-15 09:20:19 +00002045 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 Rosiere5819e22016-05-26 14:58:51 +00002056 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 Molloyf01488e2016-01-15 09:20:19 +00002065 // 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 Rosiere5819e22016-05-26 14:58:51 +00002074 bool OKForBSwap = DemandedBW % 16 == 0, OKForBitReverse = true;
2075 for (unsigned i = 0; i < DemandedBW; ++i) {
2076 OKForBSwap &=
2077 bitTransformIsCorrectForBSwap(BitProvenance[i], i, DemandedBW);
James Molloyf01488e2016-01-15 09:20:19 +00002078 OKForBitReverse &=
Chad Rosiere5819e22016-05-26 14:58:51 +00002079 bitTransformIsCorrectForBitReverse(BitProvenance[i], i, DemandedBW);
James Molloyf01488e2016-01-15 09:20:19 +00002080 }
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 Rosiere5819e22016-05-26 14:58:51 +00002090 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 Molloyf01488e2016-01-15 09:20:19 +00002108 Function *F = Intrinsic::getDeclaration(I->getModule(), Intrin, ITy);
2109 InsertedInsts.push_back(CallInst::Create(F, Res->Provider, "rev", I));
2110 return true;
2111}
Marcin Koscielnicki3feda222016-06-18 10:10:37 +00002112
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 Stepanovd240a882016-07-28 23:45:15 +00002118void llvm::maybeMarkSanitizerLibraryCallNoBuiltin(
2119 CallInst *CI, const TargetLibraryInfo *TLI) {
Marcin Koscielnicki3feda222016-06-18 10:10:37 +00002120 Function *F = CI->getCalledFunction();
David L. Jonesd21529f2017-01-23 23:16:46 +00002121 LibFunc Func;
Evgeniy Stepanovd240a882016-07-28 23:45:15 +00002122 if (F && !F->hasLocalLinkage() && F->hasName() &&
2123 TLI->getLibFunc(F->getName(), Func) && TLI->hasOptimizedCodeGen(Func) &&
2124 !F->doesNotAccessMemory())
Reid Klecknerb5180542017-03-21 16:57:19 +00002125 CI->addAttribute(AttributeList::FunctionIndex, Attribute::NoBuiltin);
Marcin Koscielnicki3feda222016-06-18 10:10:37 +00002126}