blob: bf57fcdbdeeb845c7d0442a4ff4e847e8bd6b1d3 [file] [log] [blame]
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001//===- Local.cpp - Functions to perform local transformations -------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Misha Brukmanb1c93172005-04-21 23:48:37 +00006//
John Criswell482202a2003-10-20 19:43:21 +00007//===----------------------------------------------------------------------===//
Chris Lattner28537df2002-05-07 18:07:59 +00008//
9// This family of functions perform various local transformations to the
10// program.
11//
12//===----------------------------------------------------------------------===//
13
David Blaikie31b98d22018-06-04 21:23:21 +000014#include "llvm/Transforms/Utils/Local.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000015#include "llvm/ADT/APInt.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000016#include "llvm/ADT/DenseMap.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000017#include "llvm/ADT/DenseMapInfo.h"
Benjamin Kramer2b2cdd72015-06-18 16:01:00 +000018#include "llvm/ADT/DenseSet.h"
19#include "llvm/ADT/Hashing.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000020#include "llvm/ADT/None.h"
21#include "llvm/ADT/Optional.h"
Evgeniy Stepanov4fbc0d082012-12-21 11:18:49 +000022#include "llvm/ADT/STLExtras.h"
Fiona Glaserf74cc402015-09-28 18:56:07 +000023#include "llvm/ADT/SetVector.h"
Chandler Carruthbe810232013-01-02 10:22:59 +000024#include "llvm/ADT/SmallPtrSet.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000025#include "llvm/ADT/SmallVector.h"
Peter Collingbourne8d642de2013-08-12 22:38:43 +000026#include "llvm/ADT/Statistic.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000027#include "llvm/ADT/TinyPtrVector.h"
28#include "llvm/Analysis/ConstantFolding.h"
Richard Trieu5f436fc2019-02-06 02:52:52 +000029#include "llvm/Analysis/DomTreeUpdater.h"
David Majnemer70497c62015-12-02 23:06:39 +000030#include "llvm/Analysis/EHPersonalities.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000031#include "llvm/Analysis/InstructionSimplify.h"
David Majnemerd9833ea2016-01-10 07:13:04 +000032#include "llvm/Analysis/LazyValueInfo.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000033#include "llvm/Analysis/MemoryBuiltins.h"
Alina Sbirlea2ab544b2018-08-16 21:58:44 +000034#include "llvm/Analysis/MemorySSAUpdater.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000035#include "llvm/Analysis/TargetLibraryInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000036#include "llvm/Analysis/ValueTracking.h"
Michael Kruse978ba612018-12-20 04:58:07 +000037#include "llvm/Analysis/VectorUtils.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000038#include "llvm/BinaryFormat/Dwarf.h"
39#include "llvm/IR/Argument.h"
40#include "llvm/IR/Attributes.h"
41#include "llvm/IR/BasicBlock.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000042#include "llvm/IR/CFG.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000043#include "llvm/IR/CallSite.h"
44#include "llvm/IR/Constant.h"
Chandler Carruth2abb65a2017-06-26 03:31:31 +000045#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000046#include "llvm/IR/Constants.h"
Chandler Carruth12664a02014-03-06 00:22:06 +000047#include "llvm/IR/DIBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000048#include "llvm/IR/DataLayout.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000049#include "llvm/IR/DebugInfoMetadata.h"
50#include "llvm/IR/DebugLoc.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000051#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000052#include "llvm/IR/Dominators.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000053#include "llvm/IR/Function.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000054#include "llvm/IR/GetElementPtrTypeIterator.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000055#include "llvm/IR/GlobalObject.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000056#include "llvm/IR/IRBuilder.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000057#include "llvm/IR/InstrTypes.h"
58#include "llvm/IR/Instruction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000059#include "llvm/IR/Instructions.h"
60#include "llvm/IR/IntrinsicInst.h"
61#include "llvm/IR/Intrinsics.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000062#include "llvm/IR/LLVMContext.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000063#include "llvm/IR/MDBuilder.h"
64#include "llvm/IR/Metadata.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000065#include "llvm/IR/Module.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000066#include "llvm/IR/Operator.h"
David Majnemer9f506252016-06-25 08:34:38 +000067#include "llvm/IR/PatternMatch.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000068#include "llvm/IR/Type.h"
69#include "llvm/IR/Use.h"
70#include "llvm/IR/User.h"
71#include "llvm/IR/Value.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000072#include "llvm/IR/ValueHandle.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000073#include "llvm/Support/Casting.h"
Chris Lattnercbd18fc2009-11-10 05:59:26 +000074#include "llvm/Support/Debug.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000075#include "llvm/Support/ErrorHandling.h"
Craig Topperb45eabc2017-04-26 16:39:58 +000076#include "llvm/Support/KnownBits.h"
Chris Lattnercbd18fc2009-11-10 05:59:26 +000077#include "llvm/Support/raw_ostream.h"
Vedant Kumar6bfc8692018-01-25 21:37:05 +000078#include "llvm/Transforms/Utils/ValueMapper.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000079#include <algorithm>
80#include <cassert>
81#include <climits>
82#include <cstdint>
83#include <iterator>
84#include <map>
85#include <utility>
86
Chris Lattner04efa4b2003-12-19 05:56:28 +000087using namespace llvm;
David Majnemer9f506252016-06-25 08:34:38 +000088using namespace llvm::PatternMatch;
Brian Gaeke960707c2003-11-11 22:41:34 +000089
Chandler Carruthe96dd892014-04-21 22:55:11 +000090#define DEBUG_TYPE "local"
91
Peter Collingbourne8d642de2013-08-12 22:38:43 +000092STATISTIC(NumRemoved, "Number of unreachable basic blocks removed");
93
David Stuttard411488b2019-05-09 15:02:10 +000094// Max recursion depth for collectBitParts used when detecting bswap and
95// bitreverse idioms
96static const unsigned BitPartRecursionMaxDepth = 64;
97
Chris Lattner28537df2002-05-07 18:07:59 +000098//===----------------------------------------------------------------------===//
Chris Lattnerc6c481c2008-11-27 22:57:53 +000099// Local constant propagation.
Chris Lattner28537df2002-05-07 18:07:59 +0000100//
101
Frits van Bommelad964552011-05-22 16:24:18 +0000102/// ConstantFoldTerminator - If a terminator instruction is predicated on a
103/// constant value, convert it into an unconditional branch to the constant
104/// destination. This is a nontrivial operation because the successors of this
105/// basic block must have their PHI nodes updated.
106/// Also calls RecursivelyDeleteTriviallyDeadInstructions() on any branch/switch
107/// conditions and indirectbr addresses this might make dead if
108/// DeleteDeadConditions is true.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000109bool llvm::ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions,
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +0000110 const TargetLibraryInfo *TLI,
Chijun Sima21a8b602018-08-03 05:08:17 +0000111 DomTreeUpdater *DTU) {
Chandler Carruthedb12a82018-10-15 10:04:59 +0000112 Instruction *T = BB->getTerminator();
Devang Patel1fabbe92011-05-18 17:26:46 +0000113 IRBuilder<> Builder(T);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000114
Chris Lattner28537df2002-05-07 18:07:59 +0000115 // Branch - See if we are conditional jumping on constant
Davide Italiano0512bf52017-12-31 16:51:50 +0000116 if (auto *BI = dyn_cast<BranchInst>(T)) {
Chris Lattner28537df2002-05-07 18:07:59 +0000117 if (BI->isUnconditional()) return false; // Can't optimize uncond branch
Gabor Greif97f17202009-01-30 18:21:13 +0000118 BasicBlock *Dest1 = BI->getSuccessor(0);
119 BasicBlock *Dest2 = BI->getSuccessor(1);
Chris Lattner28537df2002-05-07 18:07:59 +0000120
Davide Italiano0512bf52017-12-31 16:51:50 +0000121 if (auto *Cond = dyn_cast<ConstantInt>(BI->getCondition())) {
Chris Lattner28537df2002-05-07 18:07:59 +0000122 // Are we branching on constant?
123 // YES. Change to unconditional branch...
Reid Spencercddc9df2007-01-12 04:24:46 +0000124 BasicBlock *Destination = Cond->getZExtValue() ? Dest1 : Dest2;
125 BasicBlock *OldDest = Cond->getZExtValue() ? Dest2 : Dest1;
Chris Lattner28537df2002-05-07 18:07:59 +0000126
Chris Lattner28537df2002-05-07 18:07:59 +0000127 // Let the basic block know that we are letting go of it. Based on this,
128 // it will adjust it's PHI nodes.
Jay Foad6a85be22011-04-19 15:23:29 +0000129 OldDest->removePredecessor(BB);
Chris Lattner28537df2002-05-07 18:07:59 +0000130
Jay Foad89afb432011-01-07 20:25:56 +0000131 // Replace the conditional branch with an unconditional one.
Devang Patel1fabbe92011-05-18 17:26:46 +0000132 Builder.CreateBr(Destination);
Jay Foad89afb432011-01-07 20:25:56 +0000133 BI->eraseFromParent();
Chijun Sima21a8b602018-08-03 05:08:17 +0000134 if (DTU)
Chijun Sima70e97162019-02-22 13:48:38 +0000135 DTU->applyUpdatesPermissive({{DominatorTree::Delete, BB, OldDest}});
Chris Lattner28537df2002-05-07 18:07:59 +0000136 return true;
Chris Lattner54a4b842009-11-01 03:40:38 +0000137 }
Jakub Staszak8e1a6e72013-07-22 23:16:36 +0000138
Chris Lattner54a4b842009-11-01 03:40:38 +0000139 if (Dest2 == Dest1) { // Conditional branch to same location?
Misha Brukmanb1c93172005-04-21 23:48:37 +0000140 // This branch matches something like this:
Chris Lattner28537df2002-05-07 18:07:59 +0000141 // br bool %cond, label %Dest, label %Dest
142 // and changes it into: br label %Dest
143
144 // Let the basic block know that we are letting go of one copy of it.
145 assert(BI->getParent() && "Terminator not inserted in block!");
146 Dest1->removePredecessor(BI->getParent());
147
Jay Foad89afb432011-01-07 20:25:56 +0000148 // Replace the conditional branch with an unconditional one.
Devang Patel1fabbe92011-05-18 17:26:46 +0000149 Builder.CreateBr(Dest1);
Frits van Bommelad964552011-05-22 16:24:18 +0000150 Value *Cond = BI->getCondition();
Jay Foad89afb432011-01-07 20:25:56 +0000151 BI->eraseFromParent();
Frits van Bommelad964552011-05-22 16:24:18 +0000152 if (DeleteDeadConditions)
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000153 RecursivelyDeleteTriviallyDeadInstructions(Cond, TLI);
Chris Lattner28537df2002-05-07 18:07:59 +0000154 return true;
155 }
Chris Lattner54a4b842009-11-01 03:40:38 +0000156 return false;
157 }
Jakub Staszak8e1a6e72013-07-22 23:16:36 +0000158
Davide Italiano0512bf52017-12-31 16:51:50 +0000159 if (auto *SI = dyn_cast<SwitchInst>(T)) {
Hans Wennborg90b827c2015-01-26 19:52:24 +0000160 // If we are switching on a constant, we can convert the switch to an
161 // unconditional branch.
Davide Italiano0512bf52017-12-31 16:51:50 +0000162 auto *CI = dyn_cast<ConstantInt>(SI->getCondition());
Hans Wennborg90b827c2015-01-26 19:52:24 +0000163 BasicBlock *DefaultDest = SI->getDefaultDest();
164 BasicBlock *TheOnlyDest = DefaultDest;
165
166 // If the default is unreachable, ignore it when searching for TheOnlyDest.
167 if (isa<UnreachableInst>(DefaultDest->getFirstNonPHIOrDbg()) &&
168 SI->getNumCases() > 0) {
Chandler Carruth927d8e62017-04-12 07:27:28 +0000169 TheOnlyDest = SI->case_begin()->getCaseSuccessor();
Hans Wennborg90b827c2015-01-26 19:52:24 +0000170 }
Chris Lattner031340a2003-08-17 19:41:53 +0000171
Chris Lattner54a4b842009-11-01 03:40:38 +0000172 // Figure out which case it goes to.
Chandler Carruth0d256c02017-03-26 02:49:23 +0000173 for (auto i = SI->case_begin(), e = SI->case_end(); i != e;) {
Chris Lattner821deee2003-08-17 20:21:14 +0000174 // Found case matching a constant operand?
Chandler Carruth927d8e62017-04-12 07:27:28 +0000175 if (i->getCaseValue() == CI) {
176 TheOnlyDest = i->getCaseSuccessor();
Chris Lattner821deee2003-08-17 20:21:14 +0000177 break;
178 }
Chris Lattner031340a2003-08-17 19:41:53 +0000179
Chris Lattnerc54d6082003-08-23 23:18:19 +0000180 // Check to see if this branch is going to the same place as the default
181 // dest. If so, eliminate it as an explicit compare.
Chandler Carruth927d8e62017-04-12 07:27:28 +0000182 if (i->getCaseSuccessor() == DefaultDest) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000183 MDNode *MD = SI->getMetadata(LLVMContext::MD_prof);
Justin Bognera41a7b32013-12-10 00:13:41 +0000184 unsigned NCases = SI->getNumCases();
185 // Fold the case metadata into the default if there will be any branches
186 // left, unless the metadata doesn't match the switch.
187 if (NCases > 1 && MD && MD->getNumOperands() == 2 + NCases) {
Manman Ren49dbe252012-09-12 17:04:11 +0000188 // Collect branch weights into a vector.
189 SmallVector<uint32_t, 8> Weights;
190 for (unsigned MD_i = 1, MD_e = MD->getNumOperands(); MD_i < MD_e;
191 ++MD_i) {
David Majnemer9f506252016-06-25 08:34:38 +0000192 auto *CI = mdconst::extract<ConstantInt>(MD->getOperand(MD_i));
Manman Ren49dbe252012-09-12 17:04:11 +0000193 Weights.push_back(CI->getValue().getZExtValue());
194 }
195 // Merge weight of this case to the default weight.
Chandler Carruth927d8e62017-04-12 07:27:28 +0000196 unsigned idx = i->getCaseIndex();
Manman Ren49dbe252012-09-12 17:04:11 +0000197 Weights[0] += Weights[idx+1];
198 // Remove weight for this case.
199 std::swap(Weights[idx+1], Weights.back());
200 Weights.pop_back();
201 SI->setMetadata(LLVMContext::MD_prof,
202 MDBuilder(BB->getContext()).
203 createBranchWeights(Weights));
204 }
Chris Lattner54a4b842009-11-01 03:40:38 +0000205 // Remove this entry.
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +0000206 BasicBlock *ParentBB = SI->getParent();
207 DefaultDest->removePredecessor(ParentBB);
Chandler Carruth0d256c02017-03-26 02:49:23 +0000208 i = SI->removeCase(i);
209 e = SI->case_end();
Chijun Sima21a8b602018-08-03 05:08:17 +0000210 if (DTU)
Chijun Sima70e97162019-02-22 13:48:38 +0000211 DTU->applyUpdatesPermissive(
212 {{DominatorTree::Delete, ParentBB, DefaultDest}});
Chris Lattnerc54d6082003-08-23 23:18:19 +0000213 continue;
214 }
215
Chris Lattner821deee2003-08-17 20:21:14 +0000216 // Otherwise, check to see if the switch only branches to one destination.
217 // We do this by reseting "TheOnlyDest" to null when we find two non-equal
218 // destinations.
Chandler Carruth927d8e62017-04-12 07:27:28 +0000219 if (i->getCaseSuccessor() != TheOnlyDest)
220 TheOnlyDest = nullptr;
Chandler Carruth0d256c02017-03-26 02:49:23 +0000221
222 // Increment this iterator as we haven't removed the case.
223 ++i;
Chris Lattner031340a2003-08-17 19:41:53 +0000224 }
225
Chris Lattner821deee2003-08-17 20:21:14 +0000226 if (CI && !TheOnlyDest) {
227 // Branching on a constant, but not any of the cases, go to the default
228 // successor.
229 TheOnlyDest = SI->getDefaultDest();
230 }
231
232 // If we found a single destination that we can fold the switch into, do so
233 // now.
234 if (TheOnlyDest) {
Chris Lattner54a4b842009-11-01 03:40:38 +0000235 // Insert the new branch.
Devang Patel1fabbe92011-05-18 17:26:46 +0000236 Builder.CreateBr(TheOnlyDest);
Chris Lattner821deee2003-08-17 20:21:14 +0000237 BasicBlock *BB = SI->getParent();
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +0000238 std::vector <DominatorTree::UpdateType> Updates;
Chijun Sima21a8b602018-08-03 05:08:17 +0000239 if (DTU)
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +0000240 Updates.reserve(SI->getNumSuccessors() - 1);
Chris Lattner821deee2003-08-17 20:21:14 +0000241
242 // Remove entries from PHI nodes which we no longer branch to...
Chandler Carruth96fc1de2018-08-26 08:41:15 +0000243 for (BasicBlock *Succ : successors(SI)) {
Chris Lattner821deee2003-08-17 20:21:14 +0000244 // Found case matching a constant operand?
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +0000245 if (Succ == TheOnlyDest) {
Craig Topperf40110f2014-04-25 05:29:35 +0000246 TheOnlyDest = nullptr; // Don't modify the first branch to TheOnlyDest
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +0000247 } else {
Chris Lattner821deee2003-08-17 20:21:14 +0000248 Succ->removePredecessor(BB);
Chijun Sima21a8b602018-08-03 05:08:17 +0000249 if (DTU)
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +0000250 Updates.push_back({DominatorTree::Delete, BB, Succ});
251 }
Chris Lattner821deee2003-08-17 20:21:14 +0000252 }
253
Chris Lattner54a4b842009-11-01 03:40:38 +0000254 // Delete the old switch.
Frits van Bommelad964552011-05-22 16:24:18 +0000255 Value *Cond = SI->getCondition();
256 SI->eraseFromParent();
257 if (DeleteDeadConditions)
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000258 RecursivelyDeleteTriviallyDeadInstructions(Cond, TLI);
Chijun Sima21a8b602018-08-03 05:08:17 +0000259 if (DTU)
Chijun Sima70e97162019-02-22 13:48:38 +0000260 DTU->applyUpdatesPermissive(Updates);
Chris Lattner821deee2003-08-17 20:21:14 +0000261 return true;
Chris Lattner54a4b842009-11-01 03:40:38 +0000262 }
Jakub Staszak8e1a6e72013-07-22 23:16:36 +0000263
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +0000264 if (SI->getNumCases() == 1) {
Chris Lattner821deee2003-08-17 20:21:14 +0000265 // Otherwise, we can fold this switch into a conditional branch
266 // instruction if it has only one non-default destination.
Chandler Carruth927d8e62017-04-12 07:27:28 +0000267 auto FirstCase = *SI->case_begin();
Bob Wilsone4077362013-09-09 19:14:35 +0000268 Value *Cond = Builder.CreateICmpEQ(SI->getCondition(),
269 FirstCase.getCaseValue(), "cond");
Devang Patel1fabbe92011-05-18 17:26:46 +0000270
Bob Wilsone4077362013-09-09 19:14:35 +0000271 // Insert the new branch.
272 BranchInst *NewBr = Builder.CreateCondBr(Cond,
273 FirstCase.getCaseSuccessor(),
274 SI->getDefaultDest());
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000275 MDNode *MD = SI->getMetadata(LLVMContext::MD_prof);
Bob Wilsone4077362013-09-09 19:14:35 +0000276 if (MD && MD->getNumOperands() == 3) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000277 ConstantInt *SICase =
278 mdconst::dyn_extract<ConstantInt>(MD->getOperand(2));
279 ConstantInt *SIDef =
280 mdconst::dyn_extract<ConstantInt>(MD->getOperand(1));
Bob Wilsone4077362013-09-09 19:14:35 +0000281 assert(SICase && SIDef);
282 // The TrueWeight should be the weight for the single case of SI.
283 NewBr->setMetadata(LLVMContext::MD_prof,
284 MDBuilder(BB->getContext()).
285 createBranchWeights(SICase->getValue().getZExtValue(),
286 SIDef->getValue().getZExtValue()));
Stepan Dyatkovskiy7a501552012-05-23 08:18:26 +0000287 }
Bob Wilsone4077362013-09-09 19:14:35 +0000288
Chen Lieafbc9d2015-08-07 19:30:12 +0000289 // Update make.implicit metadata to the newly-created conditional branch.
290 MDNode *MakeImplicitMD = SI->getMetadata(LLVMContext::MD_make_implicit);
291 if (MakeImplicitMD)
292 NewBr->setMetadata(LLVMContext::MD_make_implicit, MakeImplicitMD);
293
Bob Wilsone4077362013-09-09 19:14:35 +0000294 // Delete the old switch.
295 SI->eraseFromParent();
296 return true;
Chris Lattner821deee2003-08-17 20:21:14 +0000297 }
Chris Lattner54a4b842009-11-01 03:40:38 +0000298 return false;
Chris Lattner28537df2002-05-07 18:07:59 +0000299 }
Chris Lattner54a4b842009-11-01 03:40:38 +0000300
Davide Italiano0512bf52017-12-31 16:51:50 +0000301 if (auto *IBI = dyn_cast<IndirectBrInst>(T)) {
Chris Lattner54a4b842009-11-01 03:40:38 +0000302 // indirectbr blockaddress(@F, @BB) -> br label @BB
Davide Italiano0512bf52017-12-31 16:51:50 +0000303 if (auto *BA =
Chris Lattner54a4b842009-11-01 03:40:38 +0000304 dyn_cast<BlockAddress>(IBI->getAddress()->stripPointerCasts())) {
305 BasicBlock *TheOnlyDest = BA->getBasicBlock();
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +0000306 std::vector <DominatorTree::UpdateType> Updates;
Chijun Sima21a8b602018-08-03 05:08:17 +0000307 if (DTU)
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +0000308 Updates.reserve(IBI->getNumDestinations() - 1);
309
Chris Lattner54a4b842009-11-01 03:40:38 +0000310 // Insert the new branch.
Devang Patel1fabbe92011-05-18 17:26:46 +0000311 Builder.CreateBr(TheOnlyDest);
Jakub Staszak8e1a6e72013-07-22 23:16:36 +0000312
Chris Lattner54a4b842009-11-01 03:40:38 +0000313 for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +0000314 if (IBI->getDestination(i) == TheOnlyDest) {
Craig Topperf40110f2014-04-25 05:29:35 +0000315 TheOnlyDest = nullptr;
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +0000316 } else {
317 BasicBlock *ParentBB = IBI->getParent();
318 BasicBlock *DestBB = IBI->getDestination(i);
319 DestBB->removePredecessor(ParentBB);
Chijun Sima21a8b602018-08-03 05:08:17 +0000320 if (DTU)
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +0000321 Updates.push_back({DominatorTree::Delete, ParentBB, DestBB});
322 }
Chris Lattner54a4b842009-11-01 03:40:38 +0000323 }
Frits van Bommelad964552011-05-22 16:24:18 +0000324 Value *Address = IBI->getAddress();
Chris Lattner54a4b842009-11-01 03:40:38 +0000325 IBI->eraseFromParent();
Frits van Bommelad964552011-05-22 16:24:18 +0000326 if (DeleteDeadConditions)
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000327 RecursivelyDeleteTriviallyDeadInstructions(Address, TLI);
Jakub Staszak8e1a6e72013-07-22 23:16:36 +0000328
Chris Lattner54a4b842009-11-01 03:40:38 +0000329 // If we didn't find our destination in the IBI successor list, then we
330 // have undefined behavior. Replace the unconditional branch with an
331 // 'unreachable' instruction.
332 if (TheOnlyDest) {
333 BB->getTerminator()->eraseFromParent();
334 new UnreachableInst(BB->getContext(), BB);
335 }
Jakub Staszak8e1a6e72013-07-22 23:16:36 +0000336
Chijun Sima21a8b602018-08-03 05:08:17 +0000337 if (DTU)
Chijun Sima70e97162019-02-22 13:48:38 +0000338 DTU->applyUpdatesPermissive(Updates);
Chris Lattner54a4b842009-11-01 03:40:38 +0000339 return true;
340 }
341 }
Jakub Staszak8e1a6e72013-07-22 23:16:36 +0000342
Chris Lattner28537df2002-05-07 18:07:59 +0000343 return false;
344}
345
Chris Lattner28537df2002-05-07 18:07:59 +0000346//===----------------------------------------------------------------------===//
Chris Lattner852d6d62009-11-10 22:26:15 +0000347// Local dead code elimination.
Chris Lattner28537df2002-05-07 18:07:59 +0000348//
349
Chris Lattnerc6c481c2008-11-27 22:57:53 +0000350/// isInstructionTriviallyDead - Return true if the result produced by the
351/// instruction is not used, and the instruction has no side effects.
352///
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000353bool llvm::isInstructionTriviallyDead(Instruction *I,
354 const TargetLibraryInfo *TLI) {
Daniel Berline3e69e12017-03-10 00:32:33 +0000355 if (!I->use_empty())
356 return false;
357 return wouldInstructionBeTriviallyDead(I, TLI);
358}
359
360bool llvm::wouldInstructionBeTriviallyDead(Instruction *I,
361 const TargetLibraryInfo *TLI) {
Chandler Carruth9ae926b2018-08-26 09:51:22 +0000362 if (I->isTerminator())
Daniel Berline3e69e12017-03-10 00:32:33 +0000363 return false;
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000364
David Majnemer654e1302015-07-31 17:58:14 +0000365 // We don't want the landingpad-like instructions removed by anything this
366 // general.
367 if (I->isEHPad())
Bill Wendlingd9fb4702011-08-15 20:10:51 +0000368 return false;
369
Devang Patelc1431e62011-03-18 23:28:02 +0000370 // We don't want debug info removed by anything this general, unless
371 // debug info is empty.
372 if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(I)) {
Nick Lewycky99890a22011-08-02 21:19:27 +0000373 if (DDI->getAddress())
Devang Patelc1431e62011-03-18 23:28:02 +0000374 return false;
Devang Patel17bbd7f2011-03-21 22:04:45 +0000375 return true;
Nick Lewycky99890a22011-08-02 21:19:27 +0000376 }
Devang Patel17bbd7f2011-03-21 22:04:45 +0000377 if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(I)) {
Devang Patelc1431e62011-03-18 23:28:02 +0000378 if (DVI->getValue())
379 return false;
Devang Patel17bbd7f2011-03-21 22:04:45 +0000380 return true;
Devang Patelc1431e62011-03-18 23:28:02 +0000381 }
Shiva Chen2c864552018-05-09 02:40:45 +0000382 if (DbgLabelInst *DLI = dyn_cast<DbgLabelInst>(I)) {
383 if (DLI->getLabel())
384 return false;
385 return true;
386 }
Devang Patelc1431e62011-03-18 23:28:02 +0000387
Daniel Berline3e69e12017-03-10 00:32:33 +0000388 if (!I->mayHaveSideEffects())
389 return true;
Duncan Sands1efabaa2009-05-06 06:49:50 +0000390
391 // Special case intrinsics that "may have side effects" but can be deleted
392 // when dead.
Nick Lewycky99890a22011-08-02 21:19:27 +0000393 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
Piotr Padlewskia26a08c2018-05-18 23:52:57 +0000394 // Safe to delete llvm.stacksave and launder.invariant.group if dead.
395 if (II->getIntrinsicID() == Intrinsic::stacksave ||
396 II->getIntrinsicID() == Intrinsic::launder_invariant_group)
Chris Lattnere9665832007-12-29 00:59:12 +0000397 return true;
Nick Lewycky99890a22011-08-02 21:19:27 +0000398
399 // Lifetime intrinsics are dead when their right-hand is undef.
Vedant Kumarb264d692018-12-21 21:49:40 +0000400 if (II->isLifetimeStartOrEnd())
Nick Lewycky99890a22011-08-02 21:19:27 +0000401 return isa<UndefValue>(II->getArgOperand(1));
Hal Finkel93046912014-07-25 21:13:35 +0000402
Sanjoy Das107aefc2016-04-29 22:23:16 +0000403 // Assumptions are dead if their condition is trivially true. Guards on
404 // true are operationally no-ops. In the future we can consider more
405 // sophisticated tradeoffs for guards considering potential for check
406 // widening, but for now we keep things simple.
407 if (II->getIntrinsicID() == Intrinsic::assume ||
408 II->getIntrinsicID() == Intrinsic::experimental_guard) {
Hal Finkel93046912014-07-25 21:13:35 +0000409 if (ConstantInt *Cond = dyn_cast<ConstantInt>(II->getArgOperand(0)))
410 return !Cond->isZero();
411
412 return false;
413 }
Nick Lewycky99890a22011-08-02 21:19:27 +0000414 }
Nick Lewyckydd1d3df2011-10-24 04:35:36 +0000415
Daniel Berline3e69e12017-03-10 00:32:33 +0000416 if (isAllocLikeFn(I, TLI))
417 return true;
Nick Lewyckydd1d3df2011-10-24 04:35:36 +0000418
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000419 if (CallInst *CI = isFreeCall(I, TLI))
Nick Lewyckydd1d3df2011-10-24 04:35:36 +0000420 if (Constant *C = dyn_cast<Constant>(CI->getArgOperand(0)))
421 return C->isNullValue() || isa<UndefValue>(C);
422
Chandler Carruth751d95f2019-02-11 07:51:44 +0000423 if (auto *Call = dyn_cast<CallBase>(I))
424 if (isMathLibCallNoop(Call, TLI))
Eli Friedmanb6befc32016-11-02 20:48:11 +0000425 return true;
426
Chris Lattnera36d5252005-05-06 05:27:34 +0000427 return false;
Chris Lattner28537df2002-05-07 18:07:59 +0000428}
429
Chris Lattnerc6c481c2008-11-27 22:57:53 +0000430/// RecursivelyDeleteTriviallyDeadInstructions - If the specified value is a
431/// trivially dead instruction, delete it. If that makes any of its operands
Dan Gohmancb99fe92010-01-05 15:45:31 +0000432/// trivially dead, delete them too, recursively. Return true if any
433/// instructions were deleted.
Alina Sbirlea2ab544b2018-08-16 21:58:44 +0000434bool llvm::RecursivelyDeleteTriviallyDeadInstructions(
435 Value *V, const TargetLibraryInfo *TLI, MemorySSAUpdater *MSSAU) {
Chris Lattnerc6c481c2008-11-27 22:57:53 +0000436 Instruction *I = dyn_cast<Instruction>(V);
Fangrui Song709a3e72019-02-10 09:25:56 +0000437 if (!I || !isInstructionTriviallyDead(I, TLI))
Dan Gohmancb99fe92010-01-05 15:45:31 +0000438 return false;
Jakub Staszak8e1a6e72013-07-22 23:16:36 +0000439
Chris Lattnere9f6c352008-11-28 01:20:46 +0000440 SmallVector<Instruction*, 16> DeadInsts;
441 DeadInsts.push_back(I);
Alina Sbirlea2ab544b2018-08-16 21:58:44 +0000442 RecursivelyDeleteTriviallyDeadInstructions(DeadInsts, TLI, MSSAU);
Jakub Staszak8e1a6e72013-07-22 23:16:36 +0000443
Chandler Carruth4cbcbb02018-05-29 20:15:38 +0000444 return true;
445}
446
447void llvm::RecursivelyDeleteTriviallyDeadInstructions(
Alina Sbirlea2ab544b2018-08-16 21:58:44 +0000448 SmallVectorImpl<Instruction *> &DeadInsts, const TargetLibraryInfo *TLI,
449 MemorySSAUpdater *MSSAU) {
Chandler Carruth4cbcbb02018-05-29 20:15:38 +0000450 // Process the dead instruction list until empty.
451 while (!DeadInsts.empty()) {
452 Instruction &I = *DeadInsts.pop_back_val();
453 assert(I.use_empty() && "Instructions with uses are not dead.");
454 assert(isInstructionTriviallyDead(&I, TLI) &&
455 "Live instruction found in dead worklist!");
456
457 // Don't lose the debug info while deleting the instructions.
458 salvageDebugInfo(I);
Chris Lattnerd4b5ba62008-11-28 00:58:15 +0000459
Chris Lattnere9f6c352008-11-28 01:20:46 +0000460 // Null out all of the instruction's operands to see if any operand becomes
461 // dead as we go.
Chandler Carruth4cbcbb02018-05-29 20:15:38 +0000462 for (Use &OpU : I.operands()) {
463 Value *OpV = OpU.get();
464 OpU.set(nullptr);
Jakub Staszak8e1a6e72013-07-22 23:16:36 +0000465
Chandler Carruth4cbcbb02018-05-29 20:15:38 +0000466 if (!OpV->use_empty())
467 continue;
Jakub Staszak8e1a6e72013-07-22 23:16:36 +0000468
Chris Lattnere9f6c352008-11-28 01:20:46 +0000469 // If the operand is an instruction that became dead as we nulled out the
470 // operand, and if it is 'trivially' dead, delete it in a future loop
471 // iteration.
472 if (Instruction *OpI = dyn_cast<Instruction>(OpV))
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000473 if (isInstructionTriviallyDead(OpI, TLI))
Chris Lattnere9f6c352008-11-28 01:20:46 +0000474 DeadInsts.push_back(OpI);
475 }
Alina Sbirlea2ab544b2018-08-16 21:58:44 +0000476 if (MSSAU)
477 MSSAU->removeMemoryAccess(&I);
Jakub Staszak8e1a6e72013-07-22 23:16:36 +0000478
Chandler Carruth4cbcbb02018-05-29 20:15:38 +0000479 I.eraseFromParent();
480 }
Chris Lattner28537df2002-05-07 18:07:59 +0000481}
Chris Lattner99d68092008-11-27 07:43:12 +0000482
Davide Italiano8ec77092018-12-10 22:17:04 +0000483bool llvm::replaceDbgUsesWithUndef(Instruction *I) {
484 SmallVector<DbgVariableIntrinsic *, 1> DbgUsers;
485 findDbgUsers(DbgUsers, I);
486 for (auto *DII : DbgUsers) {
487 Value *Undef = UndefValue::get(I->getType());
488 DII->setOperand(0, MetadataAsValue::get(DII->getContext(),
489 ValueAsMetadata::get(Undef)));
490 }
491 return !DbgUsers.empty();
492}
493
Nick Lewyckyc8a15692011-02-20 08:38:20 +0000494/// areAllUsesEqual - Check whether the uses of a value are all the same.
495/// This is similar to Instruction::hasOneUse() except this will also return
Duncan Sands6dcd49b2011-02-21 16:27:36 +0000496/// true when there are no uses or multiple uses that all refer to the same
497/// value.
Nick Lewyckyc8a15692011-02-20 08:38:20 +0000498static bool areAllUsesEqual(Instruction *I) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000499 Value::user_iterator UI = I->user_begin();
500 Value::user_iterator UE = I->user_end();
Nick Lewyckyc8a15692011-02-20 08:38:20 +0000501 if (UI == UE)
Duncan Sands6dcd49b2011-02-21 16:27:36 +0000502 return true;
Nick Lewyckyc8a15692011-02-20 08:38:20 +0000503
504 User *TheUse = *UI;
505 for (++UI; UI != UE; ++UI) {
506 if (*UI != TheUse)
507 return false;
508 }
509 return true;
510}
511
Dan Gohmanff089952009-05-02 18:29:22 +0000512/// RecursivelyDeleteDeadPHINode - If the specified value is an effectively
513/// dead PHI node, due to being a def-use chain of single-use nodes that
514/// either forms a cycle or is terminated by a trivially dead instruction,
515/// delete it. If that makes any of its operands trivially dead, delete them
Duncan Sandsecbbf082011-02-21 17:32:05 +0000516/// too, recursively. Return true if a change was made.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000517bool llvm::RecursivelyDeleteDeadPHINode(PHINode *PN,
518 const TargetLibraryInfo *TLI) {
Duncan Sands6dcd49b2011-02-21 16:27:36 +0000519 SmallPtrSet<Instruction*, 4> Visited;
520 for (Instruction *I = PN; areAllUsesEqual(I) && !I->mayHaveSideEffects();
Chandler Carruthcdf47882014-03-09 03:16:01 +0000521 I = cast<Instruction>(*I->user_begin())) {
Duncan Sands6dcd49b2011-02-21 16:27:36 +0000522 if (I->use_empty())
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000523 return RecursivelyDeleteTriviallyDeadInstructions(I, TLI);
Nick Lewycky183c24c2011-02-20 18:05:56 +0000524
Duncan Sands6dcd49b2011-02-21 16:27:36 +0000525 // If we find an instruction more than once, we're on a cycle that
Dan Gohmanff089952009-05-02 18:29:22 +0000526 // won't prove fruitful.
David Blaikie70573dc2014-11-19 07:49:26 +0000527 if (!Visited.insert(I).second) {
Duncan Sands6dcd49b2011-02-21 16:27:36 +0000528 // Break the cycle and delete the instruction and its operands.
529 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000530 (void)RecursivelyDeleteTriviallyDeadInstructions(I, TLI);
Duncan Sandsecbbf082011-02-21 17:32:05 +0000531 return true;
Duncan Sands6dcd49b2011-02-21 16:27:36 +0000532 }
533 }
534 return false;
Dan Gohmanff089952009-05-02 18:29:22 +0000535}
Chris Lattnerc6c481c2008-11-27 22:57:53 +0000536
Fiona Glaserf74cc402015-09-28 18:56:07 +0000537static bool
538simplifyAndDCEInstruction(Instruction *I,
539 SmallSetVector<Instruction *, 16> &WorkList,
540 const DataLayout &DL,
541 const TargetLibraryInfo *TLI) {
542 if (isInstructionTriviallyDead(I, TLI)) {
Vedant Kumarf69baf62018-03-02 22:46:48 +0000543 salvageDebugInfo(*I);
544
Fiona Glaserf74cc402015-09-28 18:56:07 +0000545 // Null out all of the instruction's operands to see if any operand becomes
546 // dead as we go.
547 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
548 Value *OpV = I->getOperand(i);
549 I->setOperand(i, nullptr);
550
551 if (!OpV->use_empty() || I == OpV)
552 continue;
553
554 // If the operand is an instruction that became dead as we nulled out the
555 // operand, and if it is 'trivially' dead, delete it in a future loop
556 // iteration.
557 if (Instruction *OpI = dyn_cast<Instruction>(OpV))
558 if (isInstructionTriviallyDead(OpI, TLI))
559 WorkList.insert(OpI);
560 }
561
562 I->eraseFromParent();
563
564 return true;
565 }
566
567 if (Value *SimpleV = SimplifyInstruction(I, DL)) {
568 // Add the users to the worklist. CAREFUL: an instruction can use itself,
569 // in the case of a phi node.
David Majnemerb8da3a22016-06-25 00:04:10 +0000570 for (User *U : I->users()) {
571 if (U != I) {
Fiona Glaserf74cc402015-09-28 18:56:07 +0000572 WorkList.insert(cast<Instruction>(U));
David Majnemerb8da3a22016-06-25 00:04:10 +0000573 }
574 }
Fiona Glaserf74cc402015-09-28 18:56:07 +0000575
576 // Replace the instruction with its simplified value.
David Majnemerb8da3a22016-06-25 00:04:10 +0000577 bool Changed = false;
578 if (!I->use_empty()) {
579 I->replaceAllUsesWith(SimpleV);
580 Changed = true;
581 }
582 if (isInstructionTriviallyDead(I, TLI)) {
583 I->eraseFromParent();
584 Changed = true;
585 }
586 return Changed;
Fiona Glaserf74cc402015-09-28 18:56:07 +0000587 }
588 return false;
589}
590
Chris Lattner7c743f22010-01-12 19:40:54 +0000591/// SimplifyInstructionsInBlock - Scan the specified basic block and try to
592/// simplify any instructions in it and recursively delete dead instructions.
593///
594/// This returns true if it changed the code, note that it can delete
595/// instructions in other blocks as well in this block.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000596bool llvm::SimplifyInstructionsInBlock(BasicBlock *BB,
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000597 const TargetLibraryInfo *TLI) {
Chris Lattner7c743f22010-01-12 19:40:54 +0000598 bool MadeChange = false;
Fiona Glaserf74cc402015-09-28 18:56:07 +0000599 const DataLayout &DL = BB->getModule()->getDataLayout();
Chandler Carruth0c72e3f2012-03-25 03:29:25 +0000600
601#ifndef NDEBUG
602 // In debug builds, ensure that the terminator of the block is never replaced
603 // or deleted by these simplifications. The idea of simplification is that it
604 // cannot introduce new instructions, and there is no way to replace the
605 // terminator of a block without introducing a new instruction.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000606 AssertingVH<Instruction> TerminatorVH(&BB->back());
Chandler Carruth0c72e3f2012-03-25 03:29:25 +0000607#endif
608
Fiona Glaserf74cc402015-09-28 18:56:07 +0000609 SmallSetVector<Instruction *, 16> WorkList;
610 // Iterate over the original function, only adding insts to the worklist
611 // if they actually need to be revisited. This avoids having to pre-init
612 // the worklist with the entire function's worth of instructions.
Chad Rosier56def252016-05-21 21:12:06 +0000613 for (BasicBlock::iterator BI = BB->begin(), E = std::prev(BB->end());
614 BI != E;) {
Chandler Carruth17fc6ef2012-03-24 23:03:27 +0000615 assert(!BI->isTerminator());
Fiona Glaserf74cc402015-09-28 18:56:07 +0000616 Instruction *I = &*BI;
617 ++BI;
Chandler Carruthcf1b5852012-03-24 21:11:24 +0000618
Fiona Glaserf74cc402015-09-28 18:56:07 +0000619 // We're visiting this instruction now, so make sure it's not in the
620 // worklist from an earlier visit.
621 if (!WorkList.count(I))
622 MadeChange |= simplifyAndDCEInstruction(I, WorkList, DL, TLI);
623 }
Eli Friedman17bf4922011-04-02 22:45:17 +0000624
Fiona Glaserf74cc402015-09-28 18:56:07 +0000625 while (!WorkList.empty()) {
626 Instruction *I = WorkList.pop_back_val();
627 MadeChange |= simplifyAndDCEInstruction(I, WorkList, DL, TLI);
Chris Lattner7c743f22010-01-12 19:40:54 +0000628 }
629 return MadeChange;
630}
631
Chris Lattner99d68092008-11-27 07:43:12 +0000632//===----------------------------------------------------------------------===//
Chris Lattner852d6d62009-11-10 22:26:15 +0000633// Control Flow Graph Restructuring.
Chris Lattner99d68092008-11-27 07:43:12 +0000634//
635
Chris Lattner852d6d62009-11-10 22:26:15 +0000636/// RemovePredecessorAndSimplify - Like BasicBlock::removePredecessor, this
637/// method is called when we're about to delete Pred as a predecessor of BB. If
638/// BB contains any PHI nodes, this drops the entries in the PHI nodes for Pred.
639///
640/// Unlike the removePredecessor method, this attempts to simplify uses of PHI
641/// nodes that collapse into identity values. For example, if we have:
642/// x = phi(1, 0, 0, 0)
643/// y = and x, z
644///
645/// .. and delete the predecessor corresponding to the '1', this will attempt to
646/// recursively fold the and to 0.
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +0000647void llvm::RemovePredecessorAndSimplify(BasicBlock *BB, BasicBlock *Pred,
Chijun Sima21a8b602018-08-03 05:08:17 +0000648 DomTreeUpdater *DTU) {
Chris Lattner852d6d62009-11-10 22:26:15 +0000649 // This only adjusts blocks with PHI nodes.
650 if (!isa<PHINode>(BB->begin()))
651 return;
Jakub Staszak8e1a6e72013-07-22 23:16:36 +0000652
Chris Lattner852d6d62009-11-10 22:26:15 +0000653 // Remove the entries for Pred from the PHI nodes in BB, but do not simplify
654 // them down. This will leave us with single entry phi nodes and other phis
655 // that can be removed.
656 BB->removePredecessor(Pred, true);
Jakub Staszak8e1a6e72013-07-22 23:16:36 +0000657
Sanjoy Dase6bca0e2017-05-01 17:07:49 +0000658 WeakTrackingVH PhiIt = &BB->front();
Chris Lattner852d6d62009-11-10 22:26:15 +0000659 while (PHINode *PN = dyn_cast<PHINode>(PhiIt)) {
660 PhiIt = &*++BasicBlock::iterator(cast<Instruction>(PhiIt));
Chris Lattnere41ab072010-07-15 06:06:04 +0000661 Value *OldPhiIt = PhiIt;
Chandler Carruthcf1b5852012-03-24 21:11:24 +0000662
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000663 if (!recursivelySimplifyInstruction(PN))
Chandler Carruthcf1b5852012-03-24 21:11:24 +0000664 continue;
665
Chris Lattner852d6d62009-11-10 22:26:15 +0000666 // If recursive simplification ended up deleting the next PHI node we would
667 // iterate to, then our iterator is invalid, restart scanning from the top
668 // of the block.
Chris Lattnere41ab072010-07-15 06:06:04 +0000669 if (PhiIt != OldPhiIt) PhiIt = &BB->front();
Chris Lattner852d6d62009-11-10 22:26:15 +0000670 }
Chijun Sima21a8b602018-08-03 05:08:17 +0000671 if (DTU)
Chijun Sima70e97162019-02-22 13:48:38 +0000672 DTU->applyUpdatesPermissive({{DominatorTree::Delete, Pred, BB}});
Chris Lattner852d6d62009-11-10 22:26:15 +0000673}
674
Chris Lattner99d68092008-11-27 07:43:12 +0000675/// MergeBasicBlockIntoOnlyPred - DestBB is a block with one predecessor and its
Alina Sbirlea2ab544b2018-08-16 21:58:44 +0000676/// predecessor is known to have one successor (DestBB!). Eliminate the edge
Chris Lattner99d68092008-11-27 07:43:12 +0000677/// between them, moving the instructions in the predecessor into DestBB and
678/// deleting the predecessor block.
Chijun Sima21a8b602018-08-03 05:08:17 +0000679void llvm::MergeBasicBlockIntoOnlyPred(BasicBlock *DestBB,
680 DomTreeUpdater *DTU) {
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +0000681
Chris Lattner99d68092008-11-27 07:43:12 +0000682 // If BB has single-entry PHI nodes, fold them.
683 while (PHINode *PN = dyn_cast<PHINode>(DestBB->begin())) {
684 Value *NewVal = PN->getIncomingValue(0);
685 // Replace self referencing PHI with undef, it must be dead.
Owen Andersonb292b8c2009-07-30 23:03:37 +0000686 if (NewVal == PN) NewVal = UndefValue::get(PN->getType());
Chris Lattner99d68092008-11-27 07:43:12 +0000687 PN->replaceAllUsesWith(NewVal);
688 PN->eraseFromParent();
689 }
Jakub Staszak8e1a6e72013-07-22 23:16:36 +0000690
Chris Lattner99d68092008-11-27 07:43:12 +0000691 BasicBlock *PredBB = DestBB->getSinglePredecessor();
692 assert(PredBB && "Block doesn't have a single predecessor!");
Jakub Staszak8e1a6e72013-07-22 23:16:36 +0000693
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +0000694 bool ReplaceEntryBB = false;
695 if (PredBB == &DestBB->getParent()->getEntryBlock())
696 ReplaceEntryBB = true;
697
Chijun Sima21a8b602018-08-03 05:08:17 +0000698 // DTU updates: Collect all the edges that enter
699 // PredBB. These dominator edges will be redirected to DestBB.
Vedant Kumar4de31bb2018-11-19 19:54:27 +0000700 SmallVector<DominatorTree::UpdateType, 32> Updates;
Chijun Sima21a8b602018-08-03 05:08:17 +0000701
702 if (DTU) {
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +0000703 Updates.push_back({DominatorTree::Delete, PredBB, DestBB});
704 for (auto I = pred_begin(PredBB), E = pred_end(PredBB); I != E; ++I) {
705 Updates.push_back({DominatorTree::Delete, *I, PredBB});
706 // This predecessor of PredBB may already have DestBB as a successor.
707 if (llvm::find(successors(*I), DestBB) == succ_end(*I))
708 Updates.push_back({DominatorTree::Insert, *I, DestBB});
709 }
710 }
711
Chris Lattner6fbfe582010-02-15 20:47:49 +0000712 // Zap anything that took the address of DestBB. Not doing this will give the
713 // address an invalid value.
714 if (DestBB->hasAddressTaken()) {
715 BlockAddress *BA = BlockAddress::get(DestBB);
716 Constant *Replacement =
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000717 ConstantInt::get(Type::getInt32Ty(BA->getContext()), 1);
Chris Lattner6fbfe582010-02-15 20:47:49 +0000718 BA->replaceAllUsesWith(ConstantExpr::getIntToPtr(Replacement,
719 BA->getType()));
720 BA->destroyConstant();
721 }
Jakub Staszak8e1a6e72013-07-22 23:16:36 +0000722
Chris Lattner99d68092008-11-27 07:43:12 +0000723 // Anything that branched to PredBB now branches to DestBB.
724 PredBB->replaceAllUsesWith(DestBB);
Jakub Staszak8e1a6e72013-07-22 23:16:36 +0000725
Jay Foad61ea0e42011-06-23 09:09:15 +0000726 // Splice all the instructions from PredBB to DestBB.
727 PredBB->getTerminator()->eraseFromParent();
Bill Wendling90dd90a2013-10-21 04:09:17 +0000728 DestBB->getInstList().splice(DestBB->begin(), PredBB->getInstList());
Chijun Sima21a8b602018-08-03 05:08:17 +0000729 new UnreachableInst(PredBB->getContext(), PredBB);
Jay Foad61ea0e42011-06-23 09:09:15 +0000730
Owen Andersona8d1c3e2014-07-12 07:12:47 +0000731 // If the PredBB is the entry block of the function, move DestBB up to
732 // become the entry block after we erase PredBB.
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +0000733 if (ReplaceEntryBB)
Owen Andersona8d1c3e2014-07-12 07:12:47 +0000734 DestBB->moveAfter(PredBB);
Evandro Menezes3701df52017-09-28 17:24:40 +0000735
Chijun Sima21a8b602018-08-03 05:08:17 +0000736 if (DTU) {
737 assert(PredBB->getInstList().size() == 1 &&
738 isa<UnreachableInst>(PredBB->getTerminator()) &&
739 "The successor list of PredBB isn't empty before "
740 "applying corresponding DTU updates.");
Chijun Sima70e97162019-02-22 13:48:38 +0000741 DTU->applyUpdatesPermissive(Updates);
Chijun Sima21a8b602018-08-03 05:08:17 +0000742 DTU->deleteBB(PredBB);
743 // Recalculation of DomTree is needed when updating a forward DomTree and
744 // the Entry BB is replaced.
745 if (ReplaceEntryBB && DTU->hasDomTree()) {
746 // The entry block was removed and there is no external interface for
747 // the dominator tree to be notified of this change. In this corner-case
748 // we recalculate the entire tree.
749 DTU->recalculate(*(DestBB->getParent()));
Balaram Makam9ee942f2017-10-26 15:04:53 +0000750 }
Evandro Menezes3701df52017-09-28 17:24:40 +0000751 }
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +0000752
Chijun Sima21a8b602018-08-03 05:08:17 +0000753 else {
754 PredBB->eraseFromParent(); // Nuke BB if DTU is nullptr.
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +0000755 }
Chris Lattner99d68092008-11-27 07:43:12 +0000756}
Devang Patelcaf44852009-02-10 07:00:59 +0000757
Duncan Sandse773c082013-07-11 08:28:20 +0000758/// CanMergeValues - Return true if we can choose one of these values to use
759/// in place of the other. Note that we will always choose the non-undef
760/// value to keep.
761static bool CanMergeValues(Value *First, Value *Second) {
762 return First == Second || isa<UndefValue>(First) || isa<UndefValue>(Second);
763}
764
Chris Lattnercbd18fc2009-11-10 05:59:26 +0000765/// CanPropagatePredecessorsForPHIs - Return true if we can fold BB, an
Mark Laceya2626552013-08-14 22:11:42 +0000766/// almost-empty BB ending in an unconditional branch to Succ, into Succ.
Chris Lattnercbd18fc2009-11-10 05:59:26 +0000767///
768/// Assumption: Succ is the single successor for BB.
Chris Lattnercbd18fc2009-11-10 05:59:26 +0000769static bool CanPropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
770 assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");
771
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000772 LLVM_DEBUG(dbgs() << "Looking to fold " << BB->getName() << " into "
773 << Succ->getName() << "\n");
Chris Lattnercbd18fc2009-11-10 05:59:26 +0000774 // Shortcut, if there is only a single predecessor it must be BB and merging
775 // is always safe
776 if (Succ->getSinglePredecessor()) return true;
777
778 // Make a list of the predecessors of BB
Benjamin Kramerb5188f12011-12-06 16:14:29 +0000779 SmallPtrSet<BasicBlock*, 16> BBPreds(pred_begin(BB), pred_end(BB));
Chris Lattnercbd18fc2009-11-10 05:59:26 +0000780
Chris Lattnercbd18fc2009-11-10 05:59:26 +0000781 // Look at all the phi nodes in Succ, to see if they present a conflict when
782 // merging these blocks
783 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
784 PHINode *PN = cast<PHINode>(I);
785
786 // If the incoming value from BB is again a PHINode in
787 // BB which has the same incoming value for *PI as PN does, we can
788 // merge the phi nodes and then the blocks can still be merged
789 PHINode *BBPN = dyn_cast<PHINode>(PN->getIncomingValueForBlock(BB));
790 if (BBPN && BBPN->getParent() == BB) {
Benjamin Kramerb5188f12011-12-06 16:14:29 +0000791 for (unsigned PI = 0, PE = PN->getNumIncomingValues(); PI != PE; ++PI) {
792 BasicBlock *IBB = PN->getIncomingBlock(PI);
793 if (BBPreds.count(IBB) &&
Duncan Sandse773c082013-07-11 08:28:20 +0000794 !CanMergeValues(BBPN->getIncomingValueForBlock(IBB),
795 PN->getIncomingValue(PI))) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000796 LLVM_DEBUG(dbgs()
797 << "Can't fold, phi node " << PN->getName() << " in "
798 << Succ->getName() << " is conflicting with "
799 << BBPN->getName() << " with regard to common predecessor "
800 << IBB->getName() << "\n");
Chris Lattnercbd18fc2009-11-10 05:59:26 +0000801 return false;
802 }
803 }
804 } else {
805 Value* Val = PN->getIncomingValueForBlock(BB);
Benjamin Kramerb5188f12011-12-06 16:14:29 +0000806 for (unsigned PI = 0, PE = PN->getNumIncomingValues(); PI != PE; ++PI) {
Chris Lattnercbd18fc2009-11-10 05:59:26 +0000807 // See if the incoming value for the common predecessor is equal to the
808 // one for BB, in which case this phi node will not prevent the merging
809 // of the block.
Benjamin Kramerb5188f12011-12-06 16:14:29 +0000810 BasicBlock *IBB = PN->getIncomingBlock(PI);
Duncan Sandse773c082013-07-11 08:28:20 +0000811 if (BBPreds.count(IBB) &&
812 !CanMergeValues(Val, PN->getIncomingValue(PI))) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000813 LLVM_DEBUG(dbgs() << "Can't fold, phi node " << PN->getName()
814 << " in " << Succ->getName()
815 << " is conflicting with regard to common "
816 << "predecessor " << IBB->getName() << "\n");
Chris Lattnercbd18fc2009-11-10 05:59:26 +0000817 return false;
818 }
819 }
820 }
821 }
822
823 return true;
824}
825
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000826using PredBlockVector = SmallVector<BasicBlock *, 16>;
827using IncomingValueMap = DenseMap<BasicBlock *, Value *>;
Duncan Sandse773c082013-07-11 08:28:20 +0000828
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000829/// Determines the value to use as the phi node input for a block.
Duncan Sandse773c082013-07-11 08:28:20 +0000830///
831/// Select between \p OldVal any value that we know flows from \p BB
832/// to a particular phi on the basis of which one (if either) is not
833/// undef. Update IncomingValues based on the selected value.
834///
835/// \param OldVal The value we are considering selecting.
836/// \param BB The block that the value flows in from.
837/// \param IncomingValues A map from block-to-value for other phi inputs
838/// that we have examined.
839///
840/// \returns the selected value.
841static Value *selectIncomingValueForBlock(Value *OldVal, BasicBlock *BB,
842 IncomingValueMap &IncomingValues) {
843 if (!isa<UndefValue>(OldVal)) {
844 assert((!IncomingValues.count(BB) ||
845 IncomingValues.find(BB)->second == OldVal) &&
846 "Expected OldVal to match incoming value from BB!");
847
848 IncomingValues.insert(std::make_pair(BB, OldVal));
849 return OldVal;
850 }
851
852 IncomingValueMap::const_iterator It = IncomingValues.find(BB);
853 if (It != IncomingValues.end()) return It->second;
854
855 return OldVal;
856}
857
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000858/// Create a map from block to value for the operands of a
Duncan Sandse773c082013-07-11 08:28:20 +0000859/// given phi.
860///
861/// Create a map from block to value for each non-undef value flowing
862/// into \p PN.
863///
864/// \param PN The phi we are collecting the map for.
865/// \param IncomingValues [out] The map from block to value for this phi.
866static void gatherIncomingValuesToPhi(PHINode *PN,
867 IncomingValueMap &IncomingValues) {
868 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
869 BasicBlock *BB = PN->getIncomingBlock(i);
870 Value *V = PN->getIncomingValue(i);
871
872 if (!isa<UndefValue>(V))
873 IncomingValues.insert(std::make_pair(BB, V));
874 }
875}
876
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000877/// Replace the incoming undef values to a phi with the values
Duncan Sandse773c082013-07-11 08:28:20 +0000878/// from a block-to-value map.
879///
880/// \param PN The phi we are replacing the undefs in.
881/// \param IncomingValues A map from block to value.
882static void replaceUndefValuesInPhi(PHINode *PN,
883 const IncomingValueMap &IncomingValues) {
884 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
885 Value *V = PN->getIncomingValue(i);
886
887 if (!isa<UndefValue>(V)) continue;
888
889 BasicBlock *BB = PN->getIncomingBlock(i);
890 IncomingValueMap::const_iterator It = IncomingValues.find(BB);
891 if (It == IncomingValues.end()) continue;
892
893 PN->setIncomingValue(i, It->second);
894 }
895}
896
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000897/// Replace a value flowing from a block to a phi with
Duncan Sandse773c082013-07-11 08:28:20 +0000898/// potentially multiple instances of that value flowing from the
899/// block's predecessors to the phi.
900///
901/// \param BB The block with the value flowing into the phi.
902/// \param BBPreds The predecessors of BB.
903/// \param PN The phi that we are updating.
904static void redirectValuesFromPredecessorsToPhi(BasicBlock *BB,
905 const PredBlockVector &BBPreds,
906 PHINode *PN) {
907 Value *OldVal = PN->removeIncomingValue(BB, false);
908 assert(OldVal && "No entry in PHI for Pred BB!");
909
910 IncomingValueMap IncomingValues;
911
912 // We are merging two blocks - BB, and the block containing PN - and
913 // as a result we need to redirect edges from the predecessors of BB
914 // to go to the block containing PN, and update PN
915 // accordingly. Since we allow merging blocks in the case where the
916 // predecessor and successor blocks both share some predecessors,
917 // and where some of those common predecessors might have undef
918 // values flowing into PN, we want to rewrite those values to be
919 // consistent with the non-undef values.
920
921 gatherIncomingValuesToPhi(PN, IncomingValues);
922
923 // If this incoming value is one of the PHI nodes in BB, the new entries
924 // in the PHI node are the entries from the old PHI.
925 if (isa<PHINode>(OldVal) && cast<PHINode>(OldVal)->getParent() == BB) {
926 PHINode *OldValPN = cast<PHINode>(OldVal);
927 for (unsigned i = 0, e = OldValPN->getNumIncomingValues(); i != e; ++i) {
928 // Note that, since we are merging phi nodes and BB and Succ might
929 // have common predecessors, we could end up with a phi node with
930 // identical incoming branches. This will be cleaned up later (and
931 // will trigger asserts if we try to clean it up now, without also
932 // simplifying the corresponding conditional branch).
933 BasicBlock *PredBB = OldValPN->getIncomingBlock(i);
934 Value *PredVal = OldValPN->getIncomingValue(i);
935 Value *Selected = selectIncomingValueForBlock(PredVal, PredBB,
936 IncomingValues);
937
938 // And add a new incoming value for this predecessor for the
939 // newly retargeted branch.
940 PN->addIncoming(Selected, PredBB);
941 }
942 } else {
943 for (unsigned i = 0, e = BBPreds.size(); i != e; ++i) {
944 // Update existing incoming values in PN for this
945 // predecessor of BB.
946 BasicBlock *PredBB = BBPreds[i];
947 Value *Selected = selectIncomingValueForBlock(OldVal, PredBB,
948 IncomingValues);
949
950 // And add a new incoming value for this predecessor for the
951 // newly retargeted branch.
952 PN->addIncoming(Selected, PredBB);
953 }
954 }
955
956 replaceUndefValuesInPhi(PN, IncomingValues);
957}
958
Chris Lattnercbd18fc2009-11-10 05:59:26 +0000959/// TryToSimplifyUncondBranchFromEmptyBlock - BB is known to contain an
960/// unconditional branch, and contains no instructions other than PHI nodes,
Rafael Espindolab10a0f22011-06-30 20:14:24 +0000961/// potential side-effect free intrinsics and the branch. If possible,
962/// eliminate BB by rewriting all the predecessors to branch to the successor
963/// block and return true. If we can't transform, return false.
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +0000964bool llvm::TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB,
Chijun Sima21a8b602018-08-03 05:08:17 +0000965 DomTreeUpdater *DTU) {
Dan Gohman4a63fad2010-08-14 00:29:42 +0000966 assert(BB != &BB->getParent()->getEntryBlock() &&
967 "TryToSimplifyUncondBranchFromEmptyBlock called on entry block!");
968
Chris Lattnercbd18fc2009-11-10 05:59:26 +0000969 // We can't eliminate infinite loops.
970 BasicBlock *Succ = cast<BranchInst>(BB->getTerminator())->getSuccessor(0);
971 if (BB == Succ) return false;
Jakub Staszak8e1a6e72013-07-22 23:16:36 +0000972
Reid Klecknerbca59d22016-05-02 19:43:22 +0000973 // Check to see if merging these blocks would cause conflicts for any of the
974 // phi nodes in BB or Succ. If not, we can safely merge.
975 if (!CanPropagatePredecessorsForPHIs(BB, Succ)) return false;
Chris Lattnercbd18fc2009-11-10 05:59:26 +0000976
Reid Klecknerbca59d22016-05-02 19:43:22 +0000977 // Check for cases where Succ has multiple predecessors and a PHI node in BB
978 // has uses which will not disappear when the PHI nodes are merged. It is
979 // possible to handle such cases, but difficult: it requires checking whether
980 // BB dominates Succ, which is non-trivial to calculate in the case where
981 // Succ has multiple predecessors. Also, it requires checking whether
982 // constructing the necessary self-referential PHI node doesn't introduce any
983 // conflicts; this isn't too difficult, but the previous code for doing this
984 // was incorrect.
985 //
986 // Note that if this check finds a live use, BB dominates Succ, so BB is
987 // something like a loop pre-header (or rarely, a part of an irreducible CFG);
988 // folding the branch isn't profitable in that case anyway.
989 if (!Succ->getSinglePredecessor()) {
990 BasicBlock::iterator BBI = BB->begin();
991 while (isa<PHINode>(*BBI)) {
992 for (Use &U : BBI->uses()) {
993 if (PHINode* PN = dyn_cast<PHINode>(U.getUser())) {
994 if (PN->getIncomingBlock(U) != BB)
Hans Wennborgb7599322016-05-02 17:22:54 +0000995 return false;
Reid Klecknerbca59d22016-05-02 19:43:22 +0000996 } else {
997 return false;
Hans Wennborgb7599322016-05-02 17:22:54 +0000998 }
Hans Wennborgb7599322016-05-02 17:22:54 +0000999 }
Reid Klecknerbca59d22016-05-02 19:43:22 +00001000 ++BBI;
Hans Wennborgb7599322016-05-02 17:22:54 +00001001 }
Hans Wennborgb7599322016-05-02 17:22:54 +00001002 }
Reid Klecknerbca59d22016-05-02 19:43:22 +00001003
Craig Topper784929d2019-02-08 20:48:56 +00001004 // We cannot fold the block if it's a branch to an already present callbr
1005 // successor because that creates duplicate successors.
1006 for (auto I = pred_begin(BB), E = pred_end(BB); I != E; ++I) {
1007 if (auto *CBI = dyn_cast<CallBrInst>((*I)->getTerminator())) {
1008 if (Succ == CBI->getDefaultDest())
1009 return false;
1010 for (unsigned i = 0, e = CBI->getNumIndirectDests(); i != e; ++i)
1011 if (Succ == CBI->getIndirectDest(i))
1012 return false;
1013 }
1014 }
1015
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001016 LLVM_DEBUG(dbgs() << "Killing Trivial BB: \n" << *BB);
Reid Klecknerbca59d22016-05-02 19:43:22 +00001017
Vedant Kumar4de31bb2018-11-19 19:54:27 +00001018 SmallVector<DominatorTree::UpdateType, 32> Updates;
Chijun Sima21a8b602018-08-03 05:08:17 +00001019 if (DTU) {
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +00001020 Updates.push_back({DominatorTree::Delete, BB, Succ});
1021 // All predecessors of BB will be moved to Succ.
1022 for (auto I = pred_begin(BB), E = pred_end(BB); I != E; ++I) {
1023 Updates.push_back({DominatorTree::Delete, *I, BB});
1024 // This predecessor of BB may already have Succ as a successor.
1025 if (llvm::find(successors(*I), Succ) == succ_end(*I))
1026 Updates.push_back({DominatorTree::Insert, *I, Succ});
1027 }
1028 }
1029
Reid Klecknerbca59d22016-05-02 19:43:22 +00001030 if (isa<PHINode>(Succ->begin())) {
1031 // If there is more than one pred of succ, and there are PHI nodes in
1032 // the successor, then we need to add incoming edges for the PHI nodes
1033 //
1034 const PredBlockVector BBPreds(pred_begin(BB), pred_end(BB));
1035
1036 // Loop over all of the PHI nodes in the successor of BB.
1037 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
1038 PHINode *PN = cast<PHINode>(I);
1039
1040 redirectValuesFromPredecessorsToPhi(BB, BBPreds, PN);
1041 }
1042 }
1043
1044 if (Succ->getSinglePredecessor()) {
1045 // BB is the only predecessor of Succ, so Succ will end up with exactly
1046 // the same predecessors BB had.
1047
1048 // Copy over any phi, debug or lifetime instruction.
1049 BB->getTerminator()->eraseFromParent();
1050 Succ->getInstList().splice(Succ->getFirstNonPHI()->getIterator(),
1051 BB->getInstList());
1052 } else {
1053 while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
1054 // We explicitly check for such uses in CanPropagatePredecessorsForPHIs.
1055 assert(PN->use_empty() && "There shouldn't be any uses here!");
1056 PN->eraseFromParent();
1057 }
1058 }
1059
Florian Hahn77382be2016-11-18 13:12:07 +00001060 // If the unconditional branch we replaced contains llvm.loop metadata, we
1061 // add the metadata to the branch instructions in the predecessors.
1062 unsigned LoopMDKind = BB->getContext().getMDKindID("llvm.loop");
1063 Instruction *TI = BB->getTerminator();
Daniel Jasper0a51ec22017-09-30 11:57:19 +00001064 if (TI)
Florian Hahn77382be2016-11-18 13:12:07 +00001065 if (MDNode *LoopMD = TI->getMetadata(LoopMDKind))
1066 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
1067 BasicBlock *Pred = *PI;
1068 Pred->getTerminator()->setMetadata(LoopMDKind, LoopMD);
1069 }
1070
Reid Klecknerbca59d22016-05-02 19:43:22 +00001071 // Everything that jumped to BB now goes to Succ.
1072 BB->replaceAllUsesWith(Succ);
1073 if (!Succ->hasName()) Succ->takeName(BB);
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +00001074
Chijun Sima21a8b602018-08-03 05:08:17 +00001075 // Clear the successor list of BB to match updates applying to DTU later.
1076 if (BB->getTerminator())
1077 BB->getInstList().pop_back();
1078 new UnreachableInst(BB->getContext(), BB);
1079 assert(succ_empty(BB) && "The successor list of BB isn't empty before "
1080 "applying corresponding DTU updates.");
1081
1082 if (DTU) {
Chijun Sima70e97162019-02-22 13:48:38 +00001083 DTU->applyUpdatesPermissive(Updates);
Chijun Sima21a8b602018-08-03 05:08:17 +00001084 DTU->deleteBB(BB);
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +00001085 } else {
1086 BB->eraseFromParent(); // Delete the old basic block.
1087 }
Reid Klecknerbca59d22016-05-02 19:43:22 +00001088 return true;
Chris Lattnercbd18fc2009-11-10 05:59:26 +00001089}
1090
Jim Grosbachd831ef42009-12-02 17:06:45 +00001091/// EliminateDuplicatePHINodes - Check for and eliminate duplicate PHI
1092/// nodes in this block. This doesn't try to be clever about PHI nodes
1093/// which differ only in the order of the incoming values, but instcombine
1094/// orders them so it usually won't matter.
Jim Grosbachd831ef42009-12-02 17:06:45 +00001095bool llvm::EliminateDuplicatePHINodes(BasicBlock *BB) {
Jim Grosbachd831ef42009-12-02 17:06:45 +00001096 // This implementation doesn't currently consider undef operands
Nick Lewyckyfa44dc62011-06-28 03:57:31 +00001097 // specially. Theoretically, two phis which are identical except for
Jim Grosbachd831ef42009-12-02 17:06:45 +00001098 // one having an undef where the other doesn't could be collapsed.
1099
Benjamin Kramer2b2cdd72015-06-18 16:01:00 +00001100 struct PHIDenseMapInfo {
1101 static PHINode *getEmptyKey() {
1102 return DenseMapInfo<PHINode *>::getEmptyKey();
1103 }
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001104
Benjamin Kramer2b2cdd72015-06-18 16:01:00 +00001105 static PHINode *getTombstoneKey() {
1106 return DenseMapInfo<PHINode *>::getTombstoneKey();
1107 }
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001108
Benjamin Kramer2b2cdd72015-06-18 16:01:00 +00001109 static unsigned getHashValue(PHINode *PN) {
1110 // Compute a hash value on the operands. Instcombine will likely have
1111 // sorted them, which helps expose duplicates, but we have to check all
1112 // the operands to be safe in case instcombine hasn't run.
1113 return static_cast<unsigned>(hash_combine(
1114 hash_combine_range(PN->value_op_begin(), PN->value_op_end()),
1115 hash_combine_range(PN->block_begin(), PN->block_end())));
1116 }
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001117
Benjamin Kramer2b2cdd72015-06-18 16:01:00 +00001118 static bool isEqual(PHINode *LHS, PHINode *RHS) {
1119 if (LHS == getEmptyKey() || LHS == getTombstoneKey() ||
1120 RHS == getEmptyKey() || RHS == getTombstoneKey())
1121 return LHS == RHS;
1122 return LHS->isIdenticalTo(RHS);
1123 }
1124 };
Jim Grosbachd831ef42009-12-02 17:06:45 +00001125
Benjamin Kramer2b2cdd72015-06-18 16:01:00 +00001126 // Set of unique PHINodes.
1127 DenseSet<PHINode *, PHIDenseMapInfo> PHISet;
Jim Grosbachd831ef42009-12-02 17:06:45 +00001128
1129 // Examine each PHI.
Benjamin Kramer2b2cdd72015-06-18 16:01:00 +00001130 bool Changed = false;
1131 for (auto I = BB->begin(); PHINode *PN = dyn_cast<PHINode>(I++);) {
1132 auto Inserted = PHISet.insert(PN);
1133 if (!Inserted.second) {
1134 // A duplicate. Replace this PHI with its duplicate.
1135 PN->replaceAllUsesWith(*Inserted.first);
1136 PN->eraseFromParent();
1137 Changed = true;
Benjamin Kramerf175e042015-09-02 19:52:23 +00001138
1139 // The RAUW can change PHIs that we already visited. Start over from the
1140 // beginning.
1141 PHISet.clear();
1142 I = BB->begin();
Jim Grosbachd831ef42009-12-02 17:06:45 +00001143 }
1144 }
1145
1146 return Changed;
1147}
Chris Lattner6fcd32e2010-12-25 20:37:57 +00001148
1149/// enforceKnownAlignment - If the specified pointer points to an object that
1150/// we control, modify the object's alignment to PrefAlign. This isn't
1151/// often possible though. If alignment is important, a more reliable approach
1152/// is to simply align all global variables and allocation instructions to
1153/// their preferred alignment from the beginning.
Benjamin Kramer570dd782010-12-30 22:34:44 +00001154static unsigned enforceKnownAlignment(Value *V, unsigned Align,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001155 unsigned PrefAlign,
1156 const DataLayout &DL) {
James Y Knightac03dca2016-01-15 16:33:06 +00001157 assert(PrefAlign > Align);
1158
Eli Friedman19ace4c2011-06-15 21:08:25 +00001159 V = V->stripPointerCasts();
Chris Lattner6fcd32e2010-12-25 20:37:57 +00001160
Eli Friedman19ace4c2011-06-15 21:08:25 +00001161 if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
James Y Knightac03dca2016-01-15 16:33:06 +00001162 // TODO: ideally, computeKnownBits ought to have used
1163 // AllocaInst::getAlignment() in its computation already, making
1164 // the below max redundant. But, as it turns out,
1165 // stripPointerCasts recurses through infinite layers of bitcasts,
1166 // while computeKnownBits is not allowed to traverse more than 6
1167 // levels.
1168 Align = std::max(AI->getAlignment(), Align);
1169 if (PrefAlign <= Align)
1170 return Align;
1171
Lang Hamesde7ab802011-10-10 23:42:08 +00001172 // If the preferred alignment is greater than the natural stack alignment
1173 // then don't round up. This avoids dynamic stack realignment.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001174 if (DL.exceedsNaturalStackAlignment(PrefAlign))
Lang Hamesde7ab802011-10-10 23:42:08 +00001175 return Align;
Chris Lattner6fcd32e2010-12-25 20:37:57 +00001176 AI->setAlignment(PrefAlign);
1177 return PrefAlign;
1178 }
Chris Lattner6fcd32e2010-12-25 20:37:57 +00001179
Rafael Espindola99e05cf2014-05-13 18:45:48 +00001180 if (auto *GO = dyn_cast<GlobalObject>(V)) {
James Y Knightac03dca2016-01-15 16:33:06 +00001181 // TODO: as above, this shouldn't be necessary.
1182 Align = std::max(GO->getAlignment(), Align);
1183 if (PrefAlign <= Align)
1184 return Align;
1185
Chris Lattner6fcd32e2010-12-25 20:37:57 +00001186 // If there is a large requested alignment and we can, bump up the alignment
Reid Kleckner486fa392015-07-14 00:11:08 +00001187 // of the global. If the memory we set aside for the global may not be the
1188 // memory used by the final program then it is impossible for us to reliably
1189 // enforce the preferred alignment.
James Y Knightac03dca2016-01-15 16:33:06 +00001190 if (!GO->canIncreaseAlignment())
Rafael Espindolafc13db42014-05-09 16:01:06 +00001191 return Align;
Jakub Staszak8e1a6e72013-07-22 23:16:36 +00001192
James Y Knightac03dca2016-01-15 16:33:06 +00001193 GO->setAlignment(PrefAlign);
1194 return PrefAlign;
Chris Lattner6fcd32e2010-12-25 20:37:57 +00001195 }
1196
1197 return Align;
1198}
1199
Chris Lattner6fcd32e2010-12-25 20:37:57 +00001200unsigned llvm::getOrEnforceKnownAlignment(Value *V, unsigned PrefAlign,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001201 const DataLayout &DL,
Hal Finkel60db0582014-09-07 18:57:58 +00001202 const Instruction *CxtI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001203 AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001204 const DominatorTree *DT) {
Chris Lattner6fcd32e2010-12-25 20:37:57 +00001205 assert(V->getType()->isPointerTy() &&
1206 "getOrEnforceKnownAlignment expects a pointer!");
Matt Arsenault87dc6072013-08-01 22:42:18 +00001207
Craig Topper8205a1a2017-05-24 16:53:07 +00001208 KnownBits Known = computeKnownBits(V, DL, 0, AC, CxtI, DT);
Craig Topper8df66c62017-05-12 17:20:30 +00001209 unsigned TrailZ = Known.countMinTrailingZeros();
Jakub Staszak8e1a6e72013-07-22 23:16:36 +00001210
Matt Arsenaultf64212b2013-07-23 22:20:57 +00001211 // Avoid trouble with ridiculously large TrailZ values, such as
Chris Lattner6fcd32e2010-12-25 20:37:57 +00001212 // those computed from a null pointer.
1213 TrailZ = std::min(TrailZ, unsigned(sizeof(unsigned) * CHAR_BIT - 1));
Jakub Staszak8e1a6e72013-07-22 23:16:36 +00001214
Craig Topper8205a1a2017-05-24 16:53:07 +00001215 unsigned Align = 1u << std::min(Known.getBitWidth() - 1, TrailZ);
Jakub Staszak8e1a6e72013-07-22 23:16:36 +00001216
Chris Lattner6fcd32e2010-12-25 20:37:57 +00001217 // LLVM doesn't support alignments larger than this currently.
1218 Align = std::min(Align, +Value::MaximumAlignment);
Jakub Staszak8e1a6e72013-07-22 23:16:36 +00001219
Chris Lattner6fcd32e2010-12-25 20:37:57 +00001220 if (PrefAlign > Align)
Matt Arsenault87dc6072013-08-01 22:42:18 +00001221 Align = enforceKnownAlignment(V, Align, PrefAlign, DL);
Jakub Staszak8e1a6e72013-07-22 23:16:36 +00001222
Chris Lattner6fcd32e2010-12-25 20:37:57 +00001223 // We don't need to make any adjustment.
1224 return Align;
1225}
1226
Devang Patel8c0b16b2011-03-17 21:58:19 +00001227///===---------------------------------------------------------------------===//
1228/// Dbg Intrinsic utilities
1229///
1230
Adrian Prantl29b9de72013-04-26 17:48:33 +00001231/// See if there is a dbg.value intrinsic for DIVar before I.
Adrian Prantla5b2a642016-02-17 20:02:25 +00001232static bool LdStHasDebugValue(DILocalVariable *DIVar, DIExpression *DIExpr,
1233 Instruction *I) {
Adrian Prantl29b9de72013-04-26 17:48:33 +00001234 // Since we can't guarantee that the original dbg.declare instrinsic
1235 // is removed by LowerDbgDeclare(), we need to make sure that we are
1236 // not inserting the same dbg.value intrinsic over and over.
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001237 BasicBlock::InstListType::iterator PrevI(I);
Adrian Prantl29b9de72013-04-26 17:48:33 +00001238 if (PrevI != I->getParent()->getInstList().begin()) {
1239 --PrevI;
1240 if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(PrevI))
1241 if (DVI->getValue() == I->getOperand(0) &&
Adrian Prantla5b2a642016-02-17 20:02:25 +00001242 DVI->getVariable() == DIVar &&
1243 DVI->getExpression() == DIExpr)
Adrian Prantl29b9de72013-04-26 17:48:33 +00001244 return true;
1245 }
1246 return false;
1247}
1248
Keith Walkerba159892016-09-22 14:13:25 +00001249/// See if there is a dbg.value intrinsic for DIVar for the PHI node.
Chandler Carruth2abb65a2017-06-26 03:31:31 +00001250static bool PhiHasDebugValue(DILocalVariable *DIVar,
Keith Walkerba159892016-09-22 14:13:25 +00001251 DIExpression *DIExpr,
1252 PHINode *APN) {
1253 // Since we can't guarantee that the original dbg.declare instrinsic
1254 // is removed by LowerDbgDeclare(), we need to make sure that we are
1255 // not inserting the same dbg.value intrinsic over and over.
Adrian Prantlfa9e84e2017-03-16 20:11:54 +00001256 SmallVector<DbgValueInst *, 1> DbgValues;
1257 findDbgValues(DbgValues, APN);
1258 for (auto *DVI : DbgValues) {
1259 assert(DVI->getValue() == APN);
Adrian Prantlfa9e84e2017-03-16 20:11:54 +00001260 if ((DVI->getVariable() == DIVar) && (DVI->getExpression() == DIExpr))
1261 return true;
1262 }
1263 return false;
Keith Walkerba159892016-09-22 14:13:25 +00001264}
1265
Bjorn Pettersson428caf92018-06-15 13:48:55 +00001266/// Check if the alloc size of \p ValTy is large enough to cover the variable
1267/// (or fragment of the variable) described by \p DII.
1268///
1269/// This is primarily intended as a helper for the different
1270/// ConvertDebugDeclareToDebugValue functions. The dbg.declare/dbg.addr that is
1271/// converted describes an alloca'd variable, so we need to use the
1272/// alloc size of the value when doing the comparison. E.g. an i1 value will be
1273/// identified as covering an n-bit fragment, if the store size of i1 is at
1274/// least n bits.
Hsiangkai Wangef72e482018-08-06 03:59:47 +00001275static bool valueCoversEntireFragment(Type *ValTy, DbgVariableIntrinsic *DII) {
Bjorn Pettersson428caf92018-06-15 13:48:55 +00001276 const DataLayout &DL = DII->getModule()->getDataLayout();
1277 uint64_t ValueSize = DL.getTypeAllocSizeInBits(ValTy);
1278 if (auto FragmentSize = DII->getFragmentSizeInBits())
1279 return ValueSize >= *FragmentSize;
Bjorn Pettersson550517b2018-06-26 06:17:00 +00001280 // We can't always calculate the size of the DI variable (e.g. if it is a
1281 // VLA). Try to use the size of the alloca that the dbg intrinsic describes
1282 // intead.
1283 if (DII->isAddressOfVariable())
1284 if (auto *AI = dyn_cast_or_null<AllocaInst>(DII->getVariableLocation()))
1285 if (auto FragmentSize = AI->getAllocationSizeInBits(DL))
1286 return ValueSize >= *FragmentSize;
1287 // Could not determine size of variable. Conservatively return false.
Bjorn Pettersson428caf92018-06-15 13:48:55 +00001288 return false;
1289}
1290
Adrian Prantld00333a2013-04-26 18:10:50 +00001291/// Inserts a llvm.dbg.value intrinsic before a store to an alloca'd value
Reid Kleckner0fe506b2017-09-21 19:52:03 +00001292/// that has an associated llvm.dbg.declare or llvm.dbg.addr intrinsic.
Hsiangkai Wangef72e482018-08-06 03:59:47 +00001293void llvm::ConvertDebugDeclareToDebugValue(DbgVariableIntrinsic *DII,
Devang Patel8c0b16b2011-03-17 21:58:19 +00001294 StoreInst *SI, DIBuilder &Builder) {
Reid Kleckner0fe506b2017-09-21 19:52:03 +00001295 assert(DII->isAddressOfVariable());
1296 auto *DIVar = DII->getVariable();
Duncan P. N. Exon Smithd4a19a32015-04-21 18:24:23 +00001297 assert(DIVar && "Missing variable");
Reid Kleckner0fe506b2017-09-21 19:52:03 +00001298 auto *DIExpr = DII->getExpression();
Brian Gesiak1c44ed82019-04-02 14:57:56 +00001299 Value *DV = SI->getValueOperand();
Devang Patel8c0b16b2011-03-17 21:58:19 +00001300
Brian Gesiak1c44ed82019-04-02 14:57:56 +00001301 if (!valueCoversEntireFragment(DV->getType(), DII)) {
Bjorn Pettersson428caf92018-06-15 13:48:55 +00001302 // FIXME: If storing to a part of the variable described by the dbg.declare,
1303 // then we want to insert a dbg.value for the corresponding fragment.
1304 LLVM_DEBUG(dbgs() << "Failed to convert dbg.declare to dbg.value: "
1305 << *DII << '\n');
1306 // For now, when there is a store to parts of the variable (but we do not
1307 // know which part) we insert an dbg.value instrinsic to indicate that we
1308 // know nothing about the variable's content.
1309 DV = UndefValue::get(DV->getType());
1310 if (!LdStHasDebugValue(DIVar, DIExpr, SI))
1311 Builder.insertDbgValueIntrinsic(DV, DIVar, DIExpr, DII->getDebugLoc(),
1312 SI);
1313 return;
1314 }
1315
David Blaikie441cfee2017-05-15 21:34:01 +00001316 if (!LdStHasDebugValue(DIVar, DIExpr, SI))
Reid Kleckner0fe506b2017-09-21 19:52:03 +00001317 Builder.insertDbgValueIntrinsic(DV, DIVar, DIExpr, DII->getDebugLoc(),
David Blaikie441cfee2017-05-15 21:34:01 +00001318 SI);
Devang Patel8c0b16b2011-03-17 21:58:19 +00001319}
1320
Adrian Prantld00333a2013-04-26 18:10:50 +00001321/// Inserts a llvm.dbg.value intrinsic before a load of an alloca'd value
Reid Kleckner0fe506b2017-09-21 19:52:03 +00001322/// that has an associated llvm.dbg.declare or llvm.dbg.addr intrinsic.
Hsiangkai Wangef72e482018-08-06 03:59:47 +00001323void llvm::ConvertDebugDeclareToDebugValue(DbgVariableIntrinsic *DII,
Devang Patel2c7ee272011-03-18 23:45:43 +00001324 LoadInst *LI, DIBuilder &Builder) {
Reid Kleckner0fe506b2017-09-21 19:52:03 +00001325 auto *DIVar = DII->getVariable();
1326 auto *DIExpr = DII->getExpression();
Duncan P. N. Exon Smithd4a19a32015-04-21 18:24:23 +00001327 assert(DIVar && "Missing variable");
Devang Patel2c7ee272011-03-18 23:45:43 +00001328
Adrian Prantla5b2a642016-02-17 20:02:25 +00001329 if (LdStHasDebugValue(DIVar, DIExpr, LI))
Keith Walkerba159892016-09-22 14:13:25 +00001330 return;
Adrian Prantl29b9de72013-04-26 17:48:33 +00001331
Bjorn Pettersson550517b2018-06-26 06:17:00 +00001332 if (!valueCoversEntireFragment(LI->getType(), DII)) {
1333 // FIXME: If only referring to a part of the variable described by the
1334 // dbg.declare, then we want to insert a dbg.value for the corresponding
1335 // fragment.
1336 LLVM_DEBUG(dbgs() << "Failed to convert dbg.declare to dbg.value: "
1337 << *DII << '\n');
1338 return;
1339 }
1340
Keno Fischer00cbf9a2015-12-19 02:02:44 +00001341 // We are now tracking the loaded value instead of the address. In the
1342 // future if multi-location support is added to the IR, it might be
1343 // preferable to keep tracking both the loaded value and the original
1344 // address in case the alloca can not be elided.
1345 Instruction *DbgValue = Builder.insertDbgValueIntrinsic(
Reid Kleckner0fe506b2017-09-21 19:52:03 +00001346 LI, DIVar, DIExpr, DII->getDebugLoc(), (Instruction *)nullptr);
Keno Fischer00cbf9a2015-12-19 02:02:44 +00001347 DbgValue->insertAfter(LI);
Keith Walkerba159892016-09-22 14:13:25 +00001348}
1349
Reid Kleckner0fe506b2017-09-21 19:52:03 +00001350/// Inserts a llvm.dbg.value intrinsic after a phi that has an associated
1351/// llvm.dbg.declare or llvm.dbg.addr intrinsic.
Hsiangkai Wangef72e482018-08-06 03:59:47 +00001352void llvm::ConvertDebugDeclareToDebugValue(DbgVariableIntrinsic *DII,
Keith Walkerba159892016-09-22 14:13:25 +00001353 PHINode *APN, DIBuilder &Builder) {
Reid Kleckner0fe506b2017-09-21 19:52:03 +00001354 auto *DIVar = DII->getVariable();
1355 auto *DIExpr = DII->getExpression();
Keith Walkerba159892016-09-22 14:13:25 +00001356 assert(DIVar && "Missing variable");
1357
1358 if (PhiHasDebugValue(DIVar, DIExpr, APN))
1359 return;
1360
Bjorn Pettersson550517b2018-06-26 06:17:00 +00001361 if (!valueCoversEntireFragment(APN->getType(), DII)) {
1362 // FIXME: If only referring to a part of the variable described by the
1363 // dbg.declare, then we want to insert a dbg.value for the corresponding
1364 // fragment.
1365 LLVM_DEBUG(dbgs() << "Failed to convert dbg.declare to dbg.value: "
1366 << *DII << '\n');
1367 return;
1368 }
1369
Reid Kleckner64818222016-09-27 18:45:31 +00001370 BasicBlock *BB = APN->getParent();
Keith Walkerba159892016-09-22 14:13:25 +00001371 auto InsertionPt = BB->getFirstInsertionPt();
Reid Kleckner64818222016-09-27 18:45:31 +00001372
1373 // The block may be a catchswitch block, which does not have a valid
1374 // insertion point.
1375 // FIXME: Insert dbg.value markers in the successors when appropriate.
1376 if (InsertionPt != BB->end())
Reid Kleckner0fe506b2017-09-21 19:52:03 +00001377 Builder.insertDbgValueIntrinsic(APN, DIVar, DIExpr, DII->getDebugLoc(),
Reid Kleckner64818222016-09-27 18:45:31 +00001378 &*InsertionPt);
Keith Walkerc9412522016-09-19 09:49:30 +00001379}
1380
Adrian Prantl232897f2014-04-25 23:00:25 +00001381/// Determine whether this alloca is either a VLA or an array.
1382static bool isArray(AllocaInst *AI) {
1383 return AI->isArrayAllocation() ||
1384 AI->getType()->getElementType()->isArrayTy();
1385}
1386
Devang Patelaad34d82011-03-17 22:18:16 +00001387/// LowerDbgDeclare - Lowers llvm.dbg.declare intrinsics into appropriate set
1388/// of llvm.dbg.value intrinsics.
1389bool llvm::LowerDbgDeclare(Function &F) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001390 DIBuilder DIB(*F.getParent(), /*AllowUnresolved*/ false);
Devang Patelaad34d82011-03-17 22:18:16 +00001391 SmallVector<DbgDeclareInst *, 4> Dbgs;
Adrian Prantl79c8e8f2014-03-27 23:30:04 +00001392 for (auto &FI : F)
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001393 for (Instruction &BI : FI)
1394 if (auto DDI = dyn_cast<DbgDeclareInst>(&BI))
Devang Patelaad34d82011-03-17 22:18:16 +00001395 Dbgs.push_back(DDI);
Adrian Prantl79c8e8f2014-03-27 23:30:04 +00001396
Devang Patelaad34d82011-03-17 22:18:16 +00001397 if (Dbgs.empty())
1398 return false;
1399
Adrian Prantl79c8e8f2014-03-27 23:30:04 +00001400 for (auto &I : Dbgs) {
1401 DbgDeclareInst *DDI = I;
Adrian Prantl8e10fdb2013-11-18 23:04:38 +00001402 AllocaInst *AI = dyn_cast_or_null<AllocaInst>(DDI->getAddress());
1403 // If this is an alloca for a scalar variable, insert a dbg.value
1404 // at each load and store to the alloca and erase the dbg.declare.
Adrian Prantl32da8892014-04-25 20:49:25 +00001405 // The dbg.values allow tracking a variable even if it is not
1406 // stored on the stack, while the dbg.declare can only describe
1407 // the stack slot (and at a lexical-scope granularity). Later
1408 // passes will attempt to elide the stack slot.
Adrian Prantl5b477be2018-03-09 00:45:04 +00001409 if (!AI || isArray(AI))
1410 continue;
1411
1412 // A volatile load/store means that the alloca can't be elided anyway.
1413 if (llvm::any_of(AI->users(), [](User *U) -> bool {
1414 if (LoadInst *LI = dyn_cast<LoadInst>(U))
1415 return LI->isVolatile();
1416 if (StoreInst *SI = dyn_cast<StoreInst>(U))
1417 return SI->isVolatile();
1418 return false;
1419 }))
1420 continue;
1421
1422 for (auto &AIUse : AI->uses()) {
1423 User *U = AIUse.getUser();
1424 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
1425 if (AIUse.getOperandNo() == 1)
1426 ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
1427 } else if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
1428 ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
1429 } else if (CallInst *CI = dyn_cast<CallInst>(U)) {
Vedant Kumarb572f642018-07-26 20:56:53 +00001430 // This is a call by-value or some other instruction that takes a
1431 // pointer to the variable. Insert a *value* intrinsic that describes
1432 // the variable by dereferencing the alloca.
1433 auto *DerefExpr =
1434 DIExpression::append(DDI->getExpression(), dwarf::DW_OP_deref);
1435 DIB.insertDbgValueIntrinsic(AI, DDI->getVariable(), DerefExpr,
1436 DDI->getDebugLoc(), CI);
Keno Fischer1dd319f2016-01-14 19:12:27 +00001437 }
Devang Patelaad34d82011-03-17 22:18:16 +00001438 }
Adrian Prantl5b477be2018-03-09 00:45:04 +00001439 DDI->eraseFromParent();
Devang Patelaad34d82011-03-17 22:18:16 +00001440 }
1441 return true;
1442}
Cameron Zwarich843bc7d2011-05-24 03:10:43 +00001443
Vedant Kumar6bfc8692018-01-25 21:37:05 +00001444/// Propagate dbg.value intrinsics through the newly inserted PHIs.
1445void llvm::insertDebugValuesForPHIs(BasicBlock *BB,
1446 SmallVectorImpl<PHINode *> &InsertedPHIs) {
1447 assert(BB && "No BasicBlock to clone dbg.value(s) from.");
1448 if (InsertedPHIs.size() == 0)
1449 return;
1450
1451 // Map existing PHI nodes to their dbg.values.
1452 ValueToValueMapTy DbgValueMap;
1453 for (auto &I : *BB) {
Hsiangkai Wangef72e482018-08-06 03:59:47 +00001454 if (auto DbgII = dyn_cast<DbgVariableIntrinsic>(&I)) {
Vedant Kumar6bfc8692018-01-25 21:37:05 +00001455 if (auto *Loc = dyn_cast_or_null<PHINode>(DbgII->getVariableLocation()))
1456 DbgValueMap.insert({Loc, DbgII});
1457 }
1458 }
1459 if (DbgValueMap.size() == 0)
1460 return;
1461
1462 // Then iterate through the new PHIs and look to see if they use one of the
1463 // previously mapped PHIs. If so, insert a new dbg.value intrinsic that will
1464 // propagate the info through the new PHI.
1465 LLVMContext &C = BB->getContext();
1466 for (auto PHI : InsertedPHIs) {
Matt Davis523c6562018-02-23 17:38:27 +00001467 BasicBlock *Parent = PHI->getParent();
1468 // Avoid inserting an intrinsic into an EH block.
1469 if (Parent->getFirstNonPHI()->isEHPad())
1470 continue;
1471 auto PhiMAV = MetadataAsValue::get(C, ValueAsMetadata::get(PHI));
Vedant Kumar6bfc8692018-01-25 21:37:05 +00001472 for (auto VI : PHI->operand_values()) {
1473 auto V = DbgValueMap.find(VI);
1474 if (V != DbgValueMap.end()) {
Hsiangkai Wangef72e482018-08-06 03:59:47 +00001475 auto *DbgII = cast<DbgVariableIntrinsic>(V->second);
Vedant Kumar6bfc8692018-01-25 21:37:05 +00001476 Instruction *NewDbgII = DbgII->clone();
Vedant Kumar6bfc8692018-01-25 21:37:05 +00001477 NewDbgII->setOperand(0, PhiMAV);
Vedant Kumar6394df92018-01-25 23:48:29 +00001478 auto InsertionPt = Parent->getFirstInsertionPt();
1479 assert(InsertionPt != Parent->end() && "Ill-formed basic block");
1480 NewDbgII->insertBefore(&*InsertionPt);
Vedant Kumar6bfc8692018-01-25 21:37:05 +00001481 }
1482 }
1483 }
1484}
1485
Reid Kleckner0fe506b2017-09-21 19:52:03 +00001486/// Finds all intrinsics declaring local variables as living in the memory that
1487/// 'V' points to. This may include a mix of dbg.declare and
1488/// dbg.addr intrinsics.
Hsiangkai Wangef72e482018-08-06 03:59:47 +00001489TinyPtrVector<DbgVariableIntrinsic *> llvm::FindDbgAddrUses(Value *V) {
Vedant Kumarde46f652018-06-26 18:44:52 +00001490 // This function is hot. Check whether the value has any metadata to avoid a
1491 // DenseMap lookup.
1492 if (!V->isUsedByMetadata())
1493 return {};
Reid Kleckner0fe506b2017-09-21 19:52:03 +00001494 auto *L = LocalAsMetadata::getIfExists(V);
1495 if (!L)
1496 return {};
1497 auto *MDV = MetadataAsValue::getIfExists(V->getContext(), L);
1498 if (!MDV)
1499 return {};
Cameron Zwarich843bc7d2011-05-24 03:10:43 +00001500
Hsiangkai Wangef72e482018-08-06 03:59:47 +00001501 TinyPtrVector<DbgVariableIntrinsic *> Declares;
Reid Kleckner0fe506b2017-09-21 19:52:03 +00001502 for (User *U : MDV->users()) {
Hsiangkai Wangef72e482018-08-06 03:59:47 +00001503 if (auto *DII = dyn_cast<DbgVariableIntrinsic>(U))
Reid Kleckner0fe506b2017-09-21 19:52:03 +00001504 if (DII->isAddressOfVariable())
1505 Declares.push_back(DII);
1506 }
1507
1508 return Declares;
Cameron Zwarich843bc7d2011-05-24 03:10:43 +00001509}
Alexey Samsonov3d43b632012-12-12 14:31:53 +00001510
Adrian Prantlfa9e84e2017-03-16 20:11:54 +00001511void llvm::findDbgValues(SmallVectorImpl<DbgValueInst *> &DbgValues, Value *V) {
Vedant Kumarde46f652018-06-26 18:44:52 +00001512 // This function is hot. Check whether the value has any metadata to avoid a
1513 // DenseMap lookup.
1514 if (!V->isUsedByMetadata())
1515 return;
Keith Walkerba159892016-09-22 14:13:25 +00001516 if (auto *L = LocalAsMetadata::getIfExists(V))
1517 if (auto *MDV = MetadataAsValue::getIfExists(V->getContext(), L))
1518 for (User *U : MDV->users())
1519 if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(U))
Adrian Prantlfa9e84e2017-03-16 20:11:54 +00001520 DbgValues.push_back(DVI);
Keith Walkerba159892016-09-22 14:13:25 +00001521}
1522
Hsiangkai Wangef72e482018-08-06 03:59:47 +00001523void llvm::findDbgUsers(SmallVectorImpl<DbgVariableIntrinsic *> &DbgUsers,
Vedant Kumarb2ec02b2018-01-05 23:27:02 +00001524 Value *V) {
Vedant Kumarde46f652018-06-26 18:44:52 +00001525 // This function is hot. Check whether the value has any metadata to avoid a
1526 // DenseMap lookup.
1527 if (!V->isUsedByMetadata())
1528 return;
Reid Kleckner29a5c032017-11-14 21:49:06 +00001529 if (auto *L = LocalAsMetadata::getIfExists(V))
1530 if (auto *MDV = MetadataAsValue::getIfExists(V->getContext(), L))
1531 for (User *U : MDV->users())
Hsiangkai Wangef72e482018-08-06 03:59:47 +00001532 if (DbgVariableIntrinsic *DII = dyn_cast<DbgVariableIntrinsic>(U))
Reid Kleckner29a5c032017-11-14 21:49:06 +00001533 DbgUsers.push_back(DII);
1534}
1535
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +00001536bool llvm::replaceDbgDeclare(Value *Address, Value *NewAddress,
1537 Instruction *InsertBefore, DIBuilder &Builder,
Adrian Prantld1317012017-12-08 21:58:18 +00001538 bool DerefBefore, int Offset, bool DerefAfter) {
Reid Kleckner0fe506b2017-09-21 19:52:03 +00001539 auto DbgAddrs = FindDbgAddrUses(Address);
Hsiangkai Wangef72e482018-08-06 03:59:47 +00001540 for (DbgVariableIntrinsic *DII : DbgAddrs) {
Reid Kleckner0fe506b2017-09-21 19:52:03 +00001541 DebugLoc Loc = DII->getDebugLoc();
1542 auto *DIVar = DII->getVariable();
1543 auto *DIExpr = DII->getExpression();
1544 assert(DIVar && "Missing variable");
Adrian Prantld1317012017-12-08 21:58:18 +00001545 DIExpr = DIExpression::prepend(DIExpr, DerefBefore, Offset, DerefAfter);
Vedant Kumard37e0782018-07-13 22:39:31 +00001546 // Insert llvm.dbg.declare immediately before InsertBefore, and remove old
Reid Kleckner0fe506b2017-09-21 19:52:03 +00001547 // llvm.dbg.declare.
1548 Builder.insertDeclare(NewAddress, DIVar, DIExpr, Loc, InsertBefore);
1549 if (DII == InsertBefore)
Vedant Kumard37e0782018-07-13 22:39:31 +00001550 InsertBefore = InsertBefore->getNextNode();
Reid Kleckner0fe506b2017-09-21 19:52:03 +00001551 DII->eraseFromParent();
1552 }
1553 return !DbgAddrs.empty();
Alexey Samsonov3d43b632012-12-12 14:31:53 +00001554}
Evgeniy Stepanov4fbc0d082012-12-21 11:18:49 +00001555
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +00001556bool llvm::replaceDbgDeclareForAlloca(AllocaInst *AI, Value *NewAllocaAddress,
Adrian Prantld1317012017-12-08 21:58:18 +00001557 DIBuilder &Builder, bool DerefBefore,
1558 int Offset, bool DerefAfter) {
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +00001559 return replaceDbgDeclare(AI, NewAllocaAddress, AI->getNextNode(), Builder,
Adrian Prantld1317012017-12-08 21:58:18 +00001560 DerefBefore, Offset, DerefAfter);
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +00001561}
1562
Evgeniy Stepanov72d961a2016-06-16 22:34:00 +00001563static void replaceOneDbgValueForAlloca(DbgValueInst *DVI, Value *NewAddress,
1564 DIBuilder &Builder, int Offset) {
1565 DebugLoc Loc = DVI->getDebugLoc();
1566 auto *DIVar = DVI->getVariable();
1567 auto *DIExpr = DVI->getExpression();
1568 assert(DIVar && "Missing variable");
1569
1570 // This is an alloca-based llvm.dbg.value. The first thing it should do with
1571 // the alloca pointer is dereference it. Otherwise we don't know how to handle
1572 // it and give up.
1573 if (!DIExpr || DIExpr->getNumElements() < 1 ||
1574 DIExpr->getElement(0) != dwarf::DW_OP_deref)
1575 return;
1576
1577 // Insert the offset immediately after the first deref.
1578 // We could just change the offset argument of dbg.value, but it's unsigned...
1579 if (Offset) {
Adrian Prantl47ea6472017-03-16 21:14:09 +00001580 SmallVector<uint64_t, 4> Ops;
1581 Ops.push_back(dwarf::DW_OP_deref);
Andrew Ng03e35b62017-04-28 08:44:30 +00001582 DIExpression::appendOffset(Ops, Offset);
Adrian Prantl47ea6472017-03-16 21:14:09 +00001583 Ops.append(DIExpr->elements_begin() + 1, DIExpr->elements_end());
1584 DIExpr = Builder.createExpression(Ops);
Evgeniy Stepanov72d961a2016-06-16 22:34:00 +00001585 }
1586
Adrian Prantlabe04752017-07-28 20:21:02 +00001587 Builder.insertDbgValueIntrinsic(NewAddress, DIVar, DIExpr, Loc, DVI);
Evgeniy Stepanov72d961a2016-06-16 22:34:00 +00001588 DVI->eraseFromParent();
1589}
1590
1591void llvm::replaceDbgValueForAlloca(AllocaInst *AI, Value *NewAllocaAddress,
1592 DIBuilder &Builder, int Offset) {
1593 if (auto *L = LocalAsMetadata::getIfExists(AI))
1594 if (auto *MDV = MetadataAsValue::getIfExists(AI->getContext(), L))
1595 for (auto UI = MDV->use_begin(), UE = MDV->use_end(); UI != UE;) {
1596 Use &U = *UI++;
1597 if (auto *DVI = dyn_cast<DbgValueInst>(U.getUser()))
1598 replaceOneDbgValueForAlloca(DVI, NewAllocaAddress, Builder, Offset);
1599 }
1600}
1601
Vedant Kumar6379a622018-07-06 17:32:39 +00001602/// Wrap \p V in a ValueAsMetadata instance.
1603static MetadataAsValue *wrapValueInMetadata(LLVMContext &C, Value *V) {
1604 return MetadataAsValue::get(C, ValueAsMetadata::get(V));
1605}
1606
1607bool llvm::salvageDebugInfo(Instruction &I) {
Hsiangkai Wangef72e482018-08-06 03:59:47 +00001608 SmallVector<DbgVariableIntrinsic *, 1> DbgUsers;
Vedant Kumarb2ec02b2018-01-05 23:27:02 +00001609 findDbgUsers(DbgUsers, &I);
1610 if (DbgUsers.empty())
Vedant Kumar6379a622018-07-06 17:32:39 +00001611 return false;
Vedant Kumarb2ec02b2018-01-05 23:27:02 +00001612
Jeremy Morse84ca7062019-02-05 11:11:28 +00001613 return salvageDebugInfoForDbgValues(I, DbgUsers);
1614}
1615
1616bool llvm::salvageDebugInfoForDbgValues(
1617 Instruction &I, ArrayRef<DbgVariableIntrinsic *> DbgUsers) {
Vedant Kumar6379a622018-07-06 17:32:39 +00001618 auto &Ctx = I.getContext();
1619 auto wrapMD = [&](Value *V) { return wrapValueInMetadata(Ctx, V); };
Adrian Prantl47ea6472017-03-16 21:14:09 +00001620
Jeremy Morse84ca7062019-02-05 11:11:28 +00001621 for (auto *DII : DbgUsers) {
1622 // Do not add DW_OP_stack_value for DbgDeclare and DbgAddr, because they
1623 // are implicitly pointing out the value as a DWARF memory location
1624 // description.
1625 bool StackValue = isa<DbgValueInst>(DII);
1626
1627 DIExpression *DIExpr =
1628 salvageDebugInfoImpl(I, DII->getExpression(), StackValue);
1629
1630 // salvageDebugInfoImpl should fail on examining the first element of
1631 // DbgUsers, or none of them.
1632 if (!DIExpr)
1633 return false;
1634
Vedant Kumarb2ec02b2018-01-05 23:27:02 +00001635 DII->setOperand(0, wrapMD(I.getOperand(0)));
Vedant Kumar6379a622018-07-06 17:32:39 +00001636 DII->setOperand(2, MetadataAsValue::get(Ctx, DIExpr));
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001637 LLVM_DEBUG(dbgs() << "SALVAGE: " << *DII << '\n');
Jeremy Morse84ca7062019-02-05 11:11:28 +00001638 }
1639
1640 return true;
1641}
1642
1643DIExpression *llvm::salvageDebugInfoImpl(Instruction &I,
1644 DIExpression *SrcDIExpr,
1645 bool WithStackValue) {
1646 auto &M = *I.getModule();
1647 auto &DL = M.getDataLayout();
1648
1649 // Apply a vector of opcodes to the source DIExpression.
1650 auto doSalvage = [&](SmallVectorImpl<uint64_t> &Ops) -> DIExpression * {
1651 DIExpression *DIExpr = SrcDIExpr;
1652 if (!Ops.empty()) {
1653 DIExpr = DIExpression::prependOpcodes(DIExpr, Ops, WithStackValue);
1654 }
1655 return DIExpr;
Adrian Prantl182f9fe2017-11-06 22:49:39 +00001656 };
1657
Jeremy Morse84ca7062019-02-05 11:11:28 +00001658 // Apply the given offset to the source DIExpression.
1659 auto applyOffset = [&](uint64_t Offset) -> DIExpression * {
Vedant Kumar04386d82018-02-09 19:19:55 +00001660 SmallVector<uint64_t, 8> Ops;
1661 DIExpression::appendOffset(Ops, Offset);
Jeremy Morse84ca7062019-02-05 11:11:28 +00001662 return doSalvage(Ops);
Vedant Kumar04386d82018-02-09 19:19:55 +00001663 };
1664
Jeremy Morse84ca7062019-02-05 11:11:28 +00001665 // initializer-list helper for applying operators to the source DIExpression.
1666 auto applyOps =
1667 [&](std::initializer_list<uint64_t> Opcodes) -> DIExpression * {
Vedant Kumar04386d82018-02-09 19:19:55 +00001668 SmallVector<uint64_t, 8> Ops(Opcodes);
Jeremy Morse84ca7062019-02-05 11:11:28 +00001669 return doSalvage(Ops);
Vedant Kumar04386d82018-02-09 19:19:55 +00001670 };
1671
Vedant Kumar388fac52018-02-13 03:34:23 +00001672 if (auto *CI = dyn_cast<CastInst>(&I)) {
Wolfgang Pieb4fe42212019-04-15 17:36:29 +00001673 // No-op casts and zexts are irrelevant for debug info.
1674 if (CI->isNoopCast(DL) || isa<ZExtInst>(&I))
1675 return SrcDIExpr;
1676 return nullptr;
Adrian Prantl47ea6472017-03-16 21:14:09 +00001677 } else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
Vedant Kumarb2ec02b2018-01-05 23:27:02 +00001678 unsigned BitWidth =
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00001679 M.getDataLayout().getIndexSizeInBits(GEP->getPointerAddressSpace());
Jeremy Morse84ca7062019-02-05 11:11:28 +00001680 // Rewrite a constant GEP into a DIExpression.
Vedant Kumarb2ec02b2018-01-05 23:27:02 +00001681 APInt Offset(BitWidth, 0);
Jeremy Morse84ca7062019-02-05 11:11:28 +00001682 if (GEP->accumulateConstantOffset(M.getDataLayout(), Offset)) {
1683 return applyOffset(Offset.getSExtValue());
1684 } else {
1685 return nullptr;
1686 }
Adrian Prantl182f9fe2017-11-06 22:49:39 +00001687 } else if (auto *BI = dyn_cast<BinaryOperator>(&I)) {
Vedant Kumar044b5882018-02-15 19:13:03 +00001688 // Rewrite binary operations with constant integer operands.
Vedant Kumar96b7dc02018-02-13 01:09:46 +00001689 auto *ConstInt = dyn_cast<ConstantInt>(I.getOperand(1));
1690 if (!ConstInt || ConstInt->getBitWidth() > 64)
Jeremy Morse84ca7062019-02-05 11:11:28 +00001691 return nullptr;
Vedant Kumar96b7dc02018-02-13 01:09:46 +00001692
1693 uint64_t Val = ConstInt->getSExtValue();
Jeremy Morse84ca7062019-02-05 11:11:28 +00001694 switch (BI->getOpcode()) {
1695 case Instruction::Add:
1696 return applyOffset(Val);
1697 case Instruction::Sub:
1698 return applyOffset(-int64_t(Val));
1699 case Instruction::Mul:
1700 return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_mul});
1701 case Instruction::SDiv:
1702 return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_div});
1703 case Instruction::SRem:
1704 return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_mod});
1705 case Instruction::Or:
1706 return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_or});
1707 case Instruction::And:
1708 return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_and});
1709 case Instruction::Xor:
1710 return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_xor});
1711 case Instruction::Shl:
1712 return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_shl});
1713 case Instruction::LShr:
1714 return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_shr});
1715 case Instruction::AShr:
1716 return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_shra});
1717 default:
1718 // TODO: Salvage constants from each kind of binop we know about.
1719 return nullptr;
Vedant Kumar96b7dc02018-02-13 01:09:46 +00001720 }
Jeremy Morseb33a5c72019-02-12 10:54:30 +00001721 // *Not* to do: we should not attempt to salvage load instructions,
1722 // because the validity and lifetime of a dbg.value containing
1723 // DW_OP_deref becomes difficult to analyze. See PR40628 for examples.
Adrian Prantl47ea6472017-03-16 21:14:09 +00001724 }
Jeremy Morse84ca7062019-02-05 11:11:28 +00001725 return nullptr;
Adrian Prantl47ea6472017-03-16 21:14:09 +00001726}
1727
Vedant Kumar6379a622018-07-06 17:32:39 +00001728/// A replacement for a dbg.value expression.
1729using DbgValReplacement = Optional<DIExpression *>;
1730
1731/// Point debug users of \p From to \p To using exprs given by \p RewriteExpr,
1732/// possibly moving/deleting users to prevent use-before-def. Returns true if
1733/// changes are made.
1734static bool rewriteDebugUsers(
1735 Instruction &From, Value &To, Instruction &DomPoint, DominatorTree &DT,
Hsiangkai Wangef72e482018-08-06 03:59:47 +00001736 function_ref<DbgValReplacement(DbgVariableIntrinsic &DII)> RewriteExpr) {
Vedant Kumar6379a622018-07-06 17:32:39 +00001737 // Find debug users of From.
Hsiangkai Wangef72e482018-08-06 03:59:47 +00001738 SmallVector<DbgVariableIntrinsic *, 1> Users;
Vedant Kumar6fa24b02018-06-20 16:50:25 +00001739 findDbgUsers(Users, &From);
1740 if (Users.empty())
Vedant Kumar6379a622018-07-06 17:32:39 +00001741 return false;
Vedant Kumar6fa24b02018-06-20 16:50:25 +00001742
Vedant Kumar6379a622018-07-06 17:32:39 +00001743 // Prevent use-before-def of To.
1744 bool Changed = false;
Hsiangkai Wangef72e482018-08-06 03:59:47 +00001745 SmallPtrSet<DbgVariableIntrinsic *, 1> DeleteOrSalvage;
Vedant Kumar6379a622018-07-06 17:32:39 +00001746 if (isa<Instruction>(&To)) {
1747 bool DomPointAfterFrom = From.getNextNonDebugInstruction() == &DomPoint;
1748
1749 for (auto *DII : Users) {
1750 // It's common to see a debug user between From and DomPoint. Move it
1751 // after DomPoint to preserve the variable update without any reordering.
1752 if (DomPointAfterFrom && DII->getNextNonDebugInstruction() == &DomPoint) {
1753 LLVM_DEBUG(dbgs() << "MOVE: " << *DII << '\n');
1754 DII->moveAfter(&DomPoint);
1755 Changed = true;
1756
1757 // Users which otherwise aren't dominated by the replacement value must
1758 // be salvaged or deleted.
1759 } else if (!DT.dominates(&DomPoint, DII)) {
1760 DeleteOrSalvage.insert(DII);
1761 }
Vedant Kumarc85ca4c2018-06-26 18:44:53 +00001762 }
Vedant Kumar6379a622018-07-06 17:32:39 +00001763 }
1764
1765 // Update debug users without use-before-def risk.
1766 for (auto *DII : Users) {
1767 if (DeleteOrSalvage.count(DII))
1768 continue;
1769
1770 LLVMContext &Ctx = DII->getContext();
1771 DbgValReplacement DVR = RewriteExpr(*DII);
1772 if (!DVR)
1773 continue;
1774
1775 DII->setOperand(0, wrapValueInMetadata(Ctx, &To));
1776 DII->setOperand(2, MetadataAsValue::get(Ctx, *DVR));
1777 LLVM_DEBUG(dbgs() << "REWRITE: " << *DII << '\n');
1778 Changed = true;
1779 }
1780
1781 if (!DeleteOrSalvage.empty()) {
1782 // Try to salvage the remaining debug users.
1783 Changed |= salvageDebugInfo(From);
1784
1785 // Delete the debug users which weren't salvaged.
1786 for (auto *DII : DeleteOrSalvage) {
1787 if (DII->getVariableLocation() == &From) {
1788 LLVM_DEBUG(dbgs() << "Erased UseBeforeDef: " << *DII << '\n');
1789 DII->eraseFromParent();
1790 Changed = true;
1791 }
1792 }
1793 }
1794
1795 return Changed;
Vedant Kumarc85ca4c2018-06-26 18:44:53 +00001796}
1797
Vedant Kumar6379a622018-07-06 17:32:39 +00001798/// Check if a bitcast between a value of type \p FromTy to type \p ToTy would
1799/// losslessly preserve the bits and semantics of the value. This predicate is
1800/// symmetric, i.e swapping \p FromTy and \p ToTy should give the same result.
1801///
1802/// Note that Type::canLosslesslyBitCastTo is not suitable here because it
1803/// allows semantically unequivalent bitcasts, such as <2 x i64> -> <4 x i32>,
1804/// and also does not allow lossless pointer <-> integer conversions.
1805static bool isBitCastSemanticsPreserving(const DataLayout &DL, Type *FromTy,
1806 Type *ToTy) {
1807 // Trivially compatible types.
1808 if (FromTy == ToTy)
1809 return true;
1810
1811 // Handle compatible pointer <-> integer conversions.
1812 if (FromTy->isIntOrPtrTy() && ToTy->isIntOrPtrTy()) {
1813 bool SameSize = DL.getTypeSizeInBits(FromTy) == DL.getTypeSizeInBits(ToTy);
1814 bool LosslessConversion = !DL.isNonIntegralPointerType(FromTy) &&
1815 !DL.isNonIntegralPointerType(ToTy);
1816 return SameSize && LosslessConversion;
1817 }
1818
1819 // TODO: This is not exhaustive.
1820 return false;
1821}
1822
1823bool llvm::replaceAllDbgUsesWith(Instruction &From, Value &To,
1824 Instruction &DomPoint, DominatorTree &DT) {
1825 // Exit early if From has no debug users.
1826 if (!From.isUsedByMetadata())
1827 return false;
1828
1829 assert(&From != &To && "Can't replace something with itself");
1830
1831 Type *FromTy = From.getType();
1832 Type *ToTy = To.getType();
1833
Hsiangkai Wangef72e482018-08-06 03:59:47 +00001834 auto Identity = [&](DbgVariableIntrinsic &DII) -> DbgValReplacement {
Vedant Kumar6379a622018-07-06 17:32:39 +00001835 return DII.getExpression();
1836 };
1837
1838 // Handle no-op conversions.
1839 Module &M = *From.getModule();
1840 const DataLayout &DL = M.getDataLayout();
1841 if (isBitCastSemanticsPreserving(DL, FromTy, ToTy))
1842 return rewriteDebugUsers(From, To, DomPoint, DT, Identity);
1843
1844 // Handle integer-to-integer widening and narrowing.
1845 // FIXME: Use DW_OP_convert when it's available everywhere.
1846 if (FromTy->isIntegerTy() && ToTy->isIntegerTy()) {
1847 uint64_t FromBits = FromTy->getPrimitiveSizeInBits();
1848 uint64_t ToBits = ToTy->getPrimitiveSizeInBits();
1849 assert(FromBits != ToBits && "Unexpected no-op conversion");
1850
1851 // When the width of the result grows, assume that a debugger will only
1852 // access the low `FromBits` bits when inspecting the source variable.
1853 if (FromBits < ToBits)
1854 return rewriteDebugUsers(From, To, DomPoint, DT, Identity);
1855
1856 // The width of the result has shrunk. Use sign/zero extension to describe
1857 // the source variable's high bits.
Hsiangkai Wangef72e482018-08-06 03:59:47 +00001858 auto SignOrZeroExt = [&](DbgVariableIntrinsic &DII) -> DbgValReplacement {
Vedant Kumar6379a622018-07-06 17:32:39 +00001859 DILocalVariable *Var = DII.getVariable();
1860
1861 // Without knowing signedness, sign/zero extension isn't possible.
1862 auto Signedness = Var->getSignedness();
1863 if (!Signedness)
1864 return None;
1865
1866 bool Signed = *Signedness == DIBasicType::Signedness::Signed;
Markus Lavinb86ce212019-03-19 13:16:28 +00001867 dwarf::TypeKind TK = Signed ? dwarf::DW_ATE_signed : dwarf::DW_ATE_unsigned;
1868 SmallVector<uint64_t, 8> Ops({dwarf::DW_OP_LLVM_convert, ToBits, TK,
1869 dwarf::DW_OP_LLVM_convert, FromBits, TK});
1870 return DIExpression::appendToStack(DII.getExpression(), Ops);
Vedant Kumar6379a622018-07-06 17:32:39 +00001871 };
1872 return rewriteDebugUsers(From, To, DomPoint, DT, SignOrZeroExt);
1873 }
1874
1875 // TODO: Floating-point conversions, vectors.
1876 return false;
Vedant Kumar6fa24b02018-06-20 16:50:25 +00001877}
1878
David Majnemer35c46d32016-01-24 05:26:18 +00001879unsigned llvm::removeAllNonTerminatorAndEHPadInstructions(BasicBlock *BB) {
1880 unsigned NumDeadInst = 0;
1881 // Delete the instructions backwards, as it has a reduced likelihood of
1882 // having to update as many def-use and use-def chains.
1883 Instruction *EndInst = BB->getTerminator(); // Last not to be deleted.
Duncan P. N. Exon Smithe9bc5792016-02-21 20:39:50 +00001884 while (EndInst != &BB->front()) {
David Majnemer35c46d32016-01-24 05:26:18 +00001885 // Delete the next to last instruction.
1886 Instruction *Inst = &*--EndInst->getIterator();
1887 if (!Inst->use_empty() && !Inst->getType()->isTokenTy())
1888 Inst->replaceAllUsesWith(UndefValue::get(Inst->getType()));
1889 if (Inst->isEHPad() || Inst->getType()->isTokenTy()) {
1890 EndInst = Inst;
1891 continue;
1892 }
1893 if (!isa<DbgInfoIntrinsic>(Inst))
1894 ++NumDeadInst;
1895 Inst->eraseFromParent();
1896 }
1897 return NumDeadInst;
1898}
1899
Michael Zolotukhin5020c992016-11-18 21:01:12 +00001900unsigned llvm::changeToUnreachable(Instruction *I, bool UseLLVMTrap,
Alina Sbirleaf31eba62019-05-08 17:05:36 +00001901 bool PreserveLCSSA, DomTreeUpdater *DTU,
1902 MemorySSAUpdater *MSSAU) {
Peter Collingbourne8d642de2013-08-12 22:38:43 +00001903 BasicBlock *BB = I->getParent();
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +00001904 std::vector <DominatorTree::UpdateType> Updates;
1905
Alina Sbirleaf31eba62019-05-08 17:05:36 +00001906 if (MSSAU)
1907 MSSAU->changeToUnreachable(I);
1908
Peter Collingbourne8d642de2013-08-12 22:38:43 +00001909 // Loop over all of the successors, removing BB's entry from any PHI
1910 // nodes.
Chijun Sima21a8b602018-08-03 05:08:17 +00001911 if (DTU)
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +00001912 Updates.reserve(BB->getTerminator()->getNumSuccessors());
1913 for (BasicBlock *Successor : successors(BB)) {
Michael Zolotukhin5020c992016-11-18 21:01:12 +00001914 Successor->removePredecessor(BB, PreserveLCSSA);
Chijun Sima21a8b602018-08-03 05:08:17 +00001915 if (DTU)
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +00001916 Updates.push_back({DominatorTree::Delete, BB, Successor});
1917 }
David Majnemere14e7bc2016-06-25 08:19:55 +00001918 // Insert a call to llvm.trap right before this. This turns the undefined
1919 // behavior into a hard fail instead of falling through into random code.
1920 if (UseLLVMTrap) {
1921 Function *TrapFn =
1922 Intrinsic::getDeclaration(BB->getParent()->getParent(), Intrinsic::trap);
1923 CallInst *CallTrap = CallInst::Create(TrapFn, "", I);
1924 CallTrap->setDebugLoc(I->getDebugLoc());
1925 }
Anastasis Grammenos52d52832018-08-07 20:21:56 +00001926 auto *UI = new UnreachableInst(I->getContext(), I);
1927 UI->setDebugLoc(I->getDebugLoc());
Peter Collingbourne8d642de2013-08-12 22:38:43 +00001928
1929 // All instructions after this are dead.
David Majnemer88542a02016-01-24 06:26:47 +00001930 unsigned NumInstrsRemoved = 0;
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001931 BasicBlock::iterator BBI = I->getIterator(), BBE = BB->end();
Peter Collingbourne8d642de2013-08-12 22:38:43 +00001932 while (BBI != BBE) {
1933 if (!BBI->use_empty())
1934 BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
1935 BB->getInstList().erase(BBI++);
David Majnemer88542a02016-01-24 06:26:47 +00001936 ++NumInstrsRemoved;
Peter Collingbourne8d642de2013-08-12 22:38:43 +00001937 }
Chijun Sima21a8b602018-08-03 05:08:17 +00001938 if (DTU)
Chijun Sima70e97162019-02-22 13:48:38 +00001939 DTU->applyUpdatesPermissive(Updates);
David Majnemer88542a02016-01-24 06:26:47 +00001940 return NumInstrsRemoved;
Peter Collingbourne8d642de2013-08-12 22:38:43 +00001941}
1942
1943/// changeToCall - Convert the specified invoke into a normal call.
Chijun Sima21a8b602018-08-03 05:08:17 +00001944static void changeToCall(InvokeInst *II, DomTreeUpdater *DTU = nullptr) {
Sanjoy Dasccd14562015-12-10 06:39:02 +00001945 SmallVector<Value*, 8> Args(II->arg_begin(), II->arg_end());
Sanjoy Das8a954a02015-12-08 22:26:08 +00001946 SmallVector<OperandBundleDef, 1> OpBundles;
1947 II->getOperandBundlesAsDefs(OpBundles);
James Y Knight7976eb52019-02-01 20:43:25 +00001948 CallInst *NewCall = CallInst::Create(
1949 II->getFunctionType(), II->getCalledValue(), Args, OpBundles, "", II);
Peter Collingbourne8d642de2013-08-12 22:38:43 +00001950 NewCall->takeName(II);
1951 NewCall->setCallingConv(II->getCallingConv());
1952 NewCall->setAttributes(II->getAttributes());
1953 NewCall->setDebugLoc(II->getDebugLoc());
Michael Kruse5948b7f2018-12-14 18:15:11 +00001954 NewCall->copyMetadata(*II);
Peter Collingbourne8d642de2013-08-12 22:38:43 +00001955 II->replaceAllUsesWith(NewCall);
1956
1957 // Follow the call by a branch to the normal destination.
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +00001958 BasicBlock *NormalDestBB = II->getNormalDest();
1959 BranchInst::Create(NormalDestBB, II);
Peter Collingbourne8d642de2013-08-12 22:38:43 +00001960
1961 // Update PHI nodes in the unwind destination
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +00001962 BasicBlock *BB = II->getParent();
1963 BasicBlock *UnwindDestBB = II->getUnwindDest();
1964 UnwindDestBB->removePredecessor(BB);
Peter Collingbourne8d642de2013-08-12 22:38:43 +00001965 II->eraseFromParent();
Chijun Sima21a8b602018-08-03 05:08:17 +00001966 if (DTU)
Chijun Sima70e97162019-02-22 13:48:38 +00001967 DTU->applyUpdatesPermissive({{DominatorTree::Delete, BB, UnwindDestBB}});
Peter Collingbourne8d642de2013-08-12 22:38:43 +00001968}
1969
Kuba Breckaddfdba32016-11-14 21:41:13 +00001970BasicBlock *llvm::changeToInvokeAndSplitBasicBlock(CallInst *CI,
1971 BasicBlock *UnwindEdge) {
1972 BasicBlock *BB = CI->getParent();
1973
1974 // Convert this function call into an invoke instruction. First, split the
1975 // basic block.
1976 BasicBlock *Split =
1977 BB->splitBasicBlock(CI->getIterator(), CI->getName() + ".noexc");
1978
1979 // Delete the unconditional branch inserted by splitBasicBlock
1980 BB->getInstList().pop_back();
1981
1982 // Create the new invoke instruction.
1983 SmallVector<Value *, 8> InvokeArgs(CI->arg_begin(), CI->arg_end());
1984 SmallVector<OperandBundleDef, 1> OpBundles;
1985
1986 CI->getOperandBundlesAsDefs(OpBundles);
1987
1988 // Note: we're round tripping operand bundles through memory here, and that
1989 // can potentially be avoided with a cleverer API design that we do not have
1990 // as of this time.
1991
James Y Knightd9e85a02019-02-01 20:43:34 +00001992 InvokeInst *II =
1993 InvokeInst::Create(CI->getFunctionType(), CI->getCalledValue(), Split,
1994 UnwindEdge, InvokeArgs, OpBundles, CI->getName(), BB);
Kuba Breckaddfdba32016-11-14 21:41:13 +00001995 II->setDebugLoc(CI->getDebugLoc());
1996 II->setCallingConv(CI->getCallingConv());
1997 II->setAttributes(CI->getAttributes());
1998
1999 // Make sure that anything using the call now uses the invoke! This also
Sanjoy Dase6bca0e2017-05-01 17:07:49 +00002000 // updates the CallGraph if present, because it uses a WeakTrackingVH.
Kuba Breckaddfdba32016-11-14 21:41:13 +00002001 CI->replaceAllUsesWith(II);
2002
2003 // Delete the original call
2004 Split->getInstList().pop_front();
2005 return Split;
2006}
2007
David Majnemer7fddecc2015-06-17 20:52:32 +00002008static bool markAliveBlocks(Function &F,
Chijun Sima21a8b602018-08-03 05:08:17 +00002009 SmallPtrSetImpl<BasicBlock *> &Reachable,
2010 DomTreeUpdater *DTU = nullptr) {
Evgeniy Stepanov4fbc0d082012-12-21 11:18:49 +00002011 SmallVector<BasicBlock*, 128> Worklist;
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002012 BasicBlock *BB = &F.front();
Peter Collingbourne8d642de2013-08-12 22:38:43 +00002013 Worklist.push_back(BB);
2014 Reachable.insert(BB);
2015 bool Changed = false;
Evgeniy Stepanov4fbc0d082012-12-21 11:18:49 +00002016 do {
Peter Collingbourne8d642de2013-08-12 22:38:43 +00002017 BB = Worklist.pop_back_val();
2018
2019 // Do a quick scan of the basic block, turning any obviously unreachable
2020 // instructions into LLVM unreachable insts. The instruction combining pass
2021 // canonicalizes unreachable insts into stores to null or undef.
David Majnemer9f506252016-06-25 08:34:38 +00002022 for (Instruction &I : *BB) {
Xin Tong074ccf32018-07-18 18:40:45 +00002023 if (auto *CI = dyn_cast<CallInst>(&I)) {
2024 Value *Callee = CI->getCalledValue();
2025 // Handle intrinsic calls.
2026 if (Function *F = dyn_cast<Function>(Callee)) {
2027 auto IntrinsicID = F->getIntrinsicID();
2028 // Assumptions that are known to be false are equivalent to
2029 // unreachable. Also, if the condition is undefined, then we make the
2030 // choice most beneficial to the optimizer, and choose that to also be
2031 // unreachable.
2032 if (IntrinsicID == Intrinsic::assume) {
2033 if (match(CI->getArgOperand(0), m_CombineOr(m_Zero(), m_Undef()))) {
2034 // Don't insert a call to llvm.trap right before the unreachable.
Chijun Sima21a8b602018-08-03 05:08:17 +00002035 changeToUnreachable(CI, false, false, DTU);
Sanjoy Das54a3a002016-04-21 05:09:12 +00002036 Changed = true;
2037 break;
2038 }
Xin Tong074ccf32018-07-18 18:40:45 +00002039 } else if (IntrinsicID == Intrinsic::experimental_guard) {
2040 // A call to the guard intrinsic bails out of the current
2041 // compilation unit if the predicate passed to it is false. If the
2042 // predicate is a constant false, then we know the guard will bail
2043 // out of the current compile unconditionally, so all code following
2044 // it is dead.
2045 //
2046 // Note: unlike in llvm.assume, it is not "obviously profitable" for
2047 // guards to treat `undef` as `false` since a guard on `undef` can
2048 // still be useful for widening.
2049 if (match(CI->getArgOperand(0), m_Zero()))
2050 if (!isa<UnreachableInst>(CI->getNextNode())) {
2051 changeToUnreachable(CI->getNextNode(), /*UseLLVMTrap=*/false,
Chijun Sima21a8b602018-08-03 05:08:17 +00002052 false, DTU);
Xin Tong074ccf32018-07-18 18:40:45 +00002053 Changed = true;
2054 break;
2055 }
2056 }
2057 } else if ((isa<ConstantPointerNull>(Callee) &&
2058 !NullPointerIsDefined(CI->getFunction())) ||
2059 isa<UndefValue>(Callee)) {
Chijun Sima21a8b602018-08-03 05:08:17 +00002060 changeToUnreachable(CI, /*UseLLVMTrap=*/false, false, DTU);
David Majnemer1fea77c2016-06-25 07:37:27 +00002061 Changed = true;
2062 break;
2063 }
Joseph Tremouletfb4d9f72019-04-02 15:48:58 +00002064 if (CI->doesNotReturn() && !CI->isMustTailCall()) {
Peter Collingbourne8d642de2013-08-12 22:38:43 +00002065 // If we found a call to a no-return function, insert an unreachable
2066 // instruction after it. Make sure there isn't *already* one there
2067 // though.
David Majnemer9f506252016-06-25 08:34:38 +00002068 if (!isa<UnreachableInst>(CI->getNextNode())) {
David Majnemere14e7bc2016-06-25 08:19:55 +00002069 // Don't insert a call to llvm.trap right before the unreachable.
Chijun Sima21a8b602018-08-03 05:08:17 +00002070 changeToUnreachable(CI->getNextNode(), false, false, DTU);
Peter Collingbourne8d642de2013-08-12 22:38:43 +00002071 Changed = true;
2072 }
2073 break;
2074 }
Xin Tong074ccf32018-07-18 18:40:45 +00002075 } else if (auto *SI = dyn_cast<StoreInst>(&I)) {
2076 // Store to undef and store to null are undefined and used to signal
2077 // that they should be changed to unreachable by passes that can't
2078 // modify the CFG.
Peter Collingbourne8d642de2013-08-12 22:38:43 +00002079
Peter Collingbourne8d642de2013-08-12 22:38:43 +00002080 // Don't touch volatile stores.
2081 if (SI->isVolatile()) continue;
2082
2083 Value *Ptr = SI->getOperand(1);
2084
2085 if (isa<UndefValue>(Ptr) ||
2086 (isa<ConstantPointerNull>(Ptr) &&
Manoj Gupta77eeac32018-07-09 22:27:23 +00002087 !NullPointerIsDefined(SI->getFunction(),
2088 SI->getPointerAddressSpace()))) {
Chijun Sima21a8b602018-08-03 05:08:17 +00002089 changeToUnreachable(SI, true, false, DTU);
Peter Collingbourne8d642de2013-08-12 22:38:43 +00002090 Changed = true;
2091 break;
2092 }
2093 }
2094 }
2095
Chandler Carruthedb12a82018-10-15 10:04:59 +00002096 Instruction *Terminator = BB->getTerminator();
David Majnemer2fa86512016-01-05 06:27:50 +00002097 if (auto *II = dyn_cast<InvokeInst>(Terminator)) {
2098 // Turn invokes that call 'nounwind' functions into ordinary calls.
Peter Collingbourne8d642de2013-08-12 22:38:43 +00002099 Value *Callee = II->getCalledValue();
Manoj Gupta77eeac32018-07-09 22:27:23 +00002100 if ((isa<ConstantPointerNull>(Callee) &&
2101 !NullPointerIsDefined(BB->getParent())) ||
2102 isa<UndefValue>(Callee)) {
Chijun Sima21a8b602018-08-03 05:08:17 +00002103 changeToUnreachable(II, true, false, DTU);
Peter Collingbourne8d642de2013-08-12 22:38:43 +00002104 Changed = true;
David Majnemer7fddecc2015-06-17 20:52:32 +00002105 } else if (II->doesNotThrow() && canSimplifyInvokeNoUnwind(&F)) {
Peter Collingbourne8d642de2013-08-12 22:38:43 +00002106 if (II->use_empty() && II->onlyReadsMemory()) {
2107 // jump to the normal destination branch.
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +00002108 BasicBlock *NormalDestBB = II->getNormalDest();
2109 BasicBlock *UnwindDestBB = II->getUnwindDest();
2110 BranchInst::Create(NormalDestBB, II);
2111 UnwindDestBB->removePredecessor(II->getParent());
Peter Collingbourne8d642de2013-08-12 22:38:43 +00002112 II->eraseFromParent();
Chijun Sima21a8b602018-08-03 05:08:17 +00002113 if (DTU)
Chijun Sima70e97162019-02-22 13:48:38 +00002114 DTU->applyUpdatesPermissive(
2115 {{DominatorTree::Delete, BB, UnwindDestBB}});
Peter Collingbourne8d642de2013-08-12 22:38:43 +00002116 } else
Chijun Sima21a8b602018-08-03 05:08:17 +00002117 changeToCall(II, DTU);
Peter Collingbourne8d642de2013-08-12 22:38:43 +00002118 Changed = true;
2119 }
David Majnemer2fa86512016-01-05 06:27:50 +00002120 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Terminator)) {
2121 // Remove catchpads which cannot be reached.
David Majnemer59eb7332016-01-05 07:42:17 +00002122 struct CatchPadDenseMapInfo {
2123 static CatchPadInst *getEmptyKey() {
2124 return DenseMapInfo<CatchPadInst *>::getEmptyKey();
2125 }
Eugene Zelenko6cadde72017-10-17 21:27:42 +00002126
David Majnemer59eb7332016-01-05 07:42:17 +00002127 static CatchPadInst *getTombstoneKey() {
2128 return DenseMapInfo<CatchPadInst *>::getTombstoneKey();
2129 }
Eugene Zelenko6cadde72017-10-17 21:27:42 +00002130
David Majnemer59eb7332016-01-05 07:42:17 +00002131 static unsigned getHashValue(CatchPadInst *CatchPad) {
2132 return static_cast<unsigned>(hash_combine_range(
2133 CatchPad->value_op_begin(), CatchPad->value_op_end()));
2134 }
Eugene Zelenko6cadde72017-10-17 21:27:42 +00002135
David Majnemer59eb7332016-01-05 07:42:17 +00002136 static bool isEqual(CatchPadInst *LHS, CatchPadInst *RHS) {
2137 if (LHS == getEmptyKey() || LHS == getTombstoneKey() ||
2138 RHS == getEmptyKey() || RHS == getTombstoneKey())
2139 return LHS == RHS;
2140 return LHS->isIdenticalTo(RHS);
2141 }
2142 };
2143
2144 // Set of unique CatchPads.
2145 SmallDenseMap<CatchPadInst *, detail::DenseSetEmpty, 4,
2146 CatchPadDenseMapInfo, detail::DenseSetPair<CatchPadInst *>>
2147 HandlerSet;
2148 detail::DenseSetEmpty Empty;
David Majnemer2fa86512016-01-05 06:27:50 +00002149 for (CatchSwitchInst::handler_iterator I = CatchSwitch->handler_begin(),
2150 E = CatchSwitch->handler_end();
2151 I != E; ++I) {
2152 BasicBlock *HandlerBB = *I;
David Majnemer59eb7332016-01-05 07:42:17 +00002153 auto *CatchPad = cast<CatchPadInst>(HandlerBB->getFirstNonPHI());
2154 if (!HandlerSet.insert({CatchPad, Empty}).second) {
David Majnemer2fa86512016-01-05 06:27:50 +00002155 CatchSwitch->removeHandler(I);
2156 --I;
2157 --E;
2158 Changed = true;
2159 }
2160 }
Peter Collingbourne8d642de2013-08-12 22:38:43 +00002161 }
2162
Chijun Sima21a8b602018-08-03 05:08:17 +00002163 Changed |= ConstantFoldTerminator(BB, true, nullptr, DTU);
David Majnemer9f506252016-06-25 08:34:38 +00002164 for (BasicBlock *Successor : successors(BB))
2165 if (Reachable.insert(Successor).second)
2166 Worklist.push_back(Successor);
Evgeniy Stepanov4fbc0d082012-12-21 11:18:49 +00002167 } while (!Worklist.empty());
Peter Collingbourne8d642de2013-08-12 22:38:43 +00002168 return Changed;
2169}
Evgeniy Stepanov4fbc0d082012-12-21 11:18:49 +00002170
Chijun Sima21a8b602018-08-03 05:08:17 +00002171void llvm::removeUnwindEdge(BasicBlock *BB, DomTreeUpdater *DTU) {
Chandler Carruthedb12a82018-10-15 10:04:59 +00002172 Instruction *TI = BB->getTerminator();
Joseph Tremoulet09af67a2015-09-27 01:47:46 +00002173
2174 if (auto *II = dyn_cast<InvokeInst>(TI)) {
Chijun Sima21a8b602018-08-03 05:08:17 +00002175 changeToCall(II, DTU);
Joseph Tremoulet09af67a2015-09-27 01:47:46 +00002176 return;
2177 }
2178
Chandler Carruthc8eaea72018-10-18 00:39:18 +00002179 Instruction *NewTI;
Joseph Tremoulet09af67a2015-09-27 01:47:46 +00002180 BasicBlock *UnwindDest;
2181
2182 if (auto *CRI = dyn_cast<CleanupReturnInst>(TI)) {
2183 NewTI = CleanupReturnInst::Create(CRI->getCleanupPad(), nullptr, CRI);
2184 UnwindDest = CRI->getUnwindDest();
David Majnemer8a1c45d2015-12-12 05:38:55 +00002185 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(TI)) {
2186 auto *NewCatchSwitch = CatchSwitchInst::Create(
2187 CatchSwitch->getParentPad(), nullptr, CatchSwitch->getNumHandlers(),
2188 CatchSwitch->getName(), CatchSwitch);
2189 for (BasicBlock *PadBB : CatchSwitch->handlers())
2190 NewCatchSwitch->addHandler(PadBB);
2191
2192 NewTI = NewCatchSwitch;
2193 UnwindDest = CatchSwitch->getUnwindDest();
Joseph Tremoulet09af67a2015-09-27 01:47:46 +00002194 } else {
2195 llvm_unreachable("Could not find unwind successor");
2196 }
2197
2198 NewTI->takeName(TI);
2199 NewTI->setDebugLoc(TI->getDebugLoc());
2200 UnwindDest->removePredecessor(BB);
David Majnemer8a1c45d2015-12-12 05:38:55 +00002201 TI->replaceAllUsesWith(NewTI);
Joseph Tremoulet09af67a2015-09-27 01:47:46 +00002202 TI->eraseFromParent();
Chijun Sima21a8b602018-08-03 05:08:17 +00002203 if (DTU)
Chijun Sima70e97162019-02-22 13:48:38 +00002204 DTU->applyUpdatesPermissive({{DominatorTree::Delete, BB, UnwindDest}});
Joseph Tremoulet09af67a2015-09-27 01:47:46 +00002205}
2206
Davide Italiano4eb210b2017-07-07 18:54:14 +00002207/// removeUnreachableBlocks - Remove blocks that are not reachable, even
Peter Collingbourne8d642de2013-08-12 22:38:43 +00002208/// if they are in a dead cycle. Return true if a change was made, false
Davide Italiano4eb210b2017-07-07 18:54:14 +00002209/// otherwise. If `LVI` is passed, this function preserves LazyValueInfo
2210/// after modifying the CFG.
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +00002211bool llvm::removeUnreachableBlocks(Function &F, LazyValueInfo *LVI,
Alina Sbirlea2ab544b2018-08-16 21:58:44 +00002212 DomTreeUpdater *DTU,
2213 MemorySSAUpdater *MSSAU) {
Matthias Braunb30f2f512016-01-30 01:24:31 +00002214 SmallPtrSet<BasicBlock*, 16> Reachable;
Chijun Sima21a8b602018-08-03 05:08:17 +00002215 bool Changed = markAliveBlocks(F, Reachable, DTU);
Peter Collingbourne8d642de2013-08-12 22:38:43 +00002216
2217 // If there are unreachable blocks in the CFG...
Evgeniy Stepanov4fbc0d082012-12-21 11:18:49 +00002218 if (Reachable.size() == F.size())
Peter Collingbourne8d642de2013-08-12 22:38:43 +00002219 return Changed;
Evgeniy Stepanov4fbc0d082012-12-21 11:18:49 +00002220
2221 assert(Reachable.size() < F.size());
Peter Collingbourne8d642de2013-08-12 22:38:43 +00002222 NumRemoved += F.size()-Reachable.size();
2223
Alina Sbirlea2ab544b2018-08-16 21:58:44 +00002224 SmallPtrSet<BasicBlock *, 16> DeadBlockSet;
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +00002225 for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ++I) {
2226 auto *BB = &*I;
2227 if (Reachable.count(BB))
Evgeniy Stepanov4fbc0d082012-12-21 11:18:49 +00002228 continue;
Alina Sbirlea2ab544b2018-08-16 21:58:44 +00002229 DeadBlockSet.insert(BB);
2230 }
2231
2232 if (MSSAU)
2233 MSSAU->removeBlocks(DeadBlockSet);
2234
2235 // Loop over all of the basic blocks that are not reachable, dropping all of
2236 // their internal references. Update DTU and LVI if available.
2237 std::vector<DominatorTree::UpdateType> Updates;
2238 for (auto *BB : DeadBlockSet) {
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +00002239 for (BasicBlock *Successor : successors(BB)) {
Alina Sbirlea2ab544b2018-08-16 21:58:44 +00002240 if (!DeadBlockSet.count(Successor))
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +00002241 Successor->removePredecessor(BB);
Chijun Sima21a8b602018-08-03 05:08:17 +00002242 if (DTU)
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +00002243 Updates.push_back({DominatorTree::Delete, BB, Successor});
2244 }
David Majnemerd9833ea2016-01-10 07:13:04 +00002245 if (LVI)
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +00002246 LVI->eraseBlock(BB);
Peter Collingbourne8d642de2013-08-12 22:38:43 +00002247 BB->dropAllReferences();
Evgeniy Stepanov4fbc0d082012-12-21 11:18:49 +00002248 }
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +00002249 for (Function::iterator I = ++F.begin(); I != F.end();) {
2250 auto *BB = &*I;
2251 if (Reachable.count(BB)) {
Reid Klecknercd78ddc2018-01-04 23:23:46 +00002252 ++I;
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +00002253 continue;
2254 }
Chijun Sima21a8b602018-08-03 05:08:17 +00002255 if (DTU) {
Chandler Carruthc8eaea72018-10-18 00:39:18 +00002256 // Remove the terminator of BB to clear the successor list of BB.
Chijun Sima21a8b602018-08-03 05:08:17 +00002257 if (BB->getTerminator())
2258 BB->getInstList().pop_back();
2259 new UnreachableInst(BB->getContext(), BB);
2260 assert(succ_empty(BB) && "The successor list of BB isn't empty before "
2261 "applying corresponding DTU updates.");
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +00002262 ++I;
2263 } else {
2264 I = F.getBasicBlockList().erase(I);
2265 }
2266 }
Evgeniy Stepanov2a066af2013-03-22 08:43:04 +00002267
Chijun Sima21a8b602018-08-03 05:08:17 +00002268 if (DTU) {
Chijun Sima70e97162019-02-22 13:48:38 +00002269 DTU->applyUpdatesPermissive(Updates);
Chijun Sima53048432018-08-03 12:45:29 +00002270 bool Deleted = false;
Alina Sbirlea2ab544b2018-08-16 21:58:44 +00002271 for (auto *BB : DeadBlockSet) {
Chijun Sima53048432018-08-03 12:45:29 +00002272 if (DTU->isBBPendingDeletion(BB))
2273 --NumRemoved;
2274 else
2275 Deleted = true;
Chijun Sima21a8b602018-08-03 05:08:17 +00002276 DTU->deleteBB(BB);
Chijun Sima53048432018-08-03 12:45:29 +00002277 }
2278 if (!Deleted)
2279 return false;
Chijun Sima21a8b602018-08-03 05:08:17 +00002280 }
Evgeniy Stepanov4fbc0d082012-12-21 11:18:49 +00002281 return true;
2282}
Rafael Espindolaea46c322014-08-15 15:46:38 +00002283
Piotr Padlewskidc9b2cf2015-10-02 22:12:22 +00002284void llvm::combineMetadata(Instruction *K, const Instruction *J,
Florian Hahn950576b2018-08-07 15:36:11 +00002285 ArrayRef<unsigned> KnownIDs, bool DoesKMove) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00002286 SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
Adrian Prantlcbdfdb72015-08-20 22:00:30 +00002287 K->dropUnknownNonDebugMetadata(KnownIDs);
Rafael Espindolaea46c322014-08-15 15:46:38 +00002288 K->getAllMetadataOtherThanDebugLoc(Metadata);
David Majnemer6f014d32016-07-25 02:21:19 +00002289 for (const auto &MD : Metadata) {
2290 unsigned Kind = MD.first;
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00002291 MDNode *JMD = J->getMetadata(Kind);
David Majnemer6f014d32016-07-25 02:21:19 +00002292 MDNode *KMD = MD.second;
Rafael Espindolaea46c322014-08-15 15:46:38 +00002293
2294 switch (Kind) {
2295 default:
2296 K->setMetadata(Kind, nullptr); // Remove unknown metadata
2297 break;
2298 case LLVMContext::MD_dbg:
2299 llvm_unreachable("getAllMetadataOtherThanDebugLoc returned a MD_dbg");
2300 case LLVMContext::MD_tbaa:
2301 K->setMetadata(Kind, MDNode::getMostGenericTBAA(JMD, KMD));
2302 break;
2303 case LLVMContext::MD_alias_scope:
Bjorn Steinbrink5ec75222015-02-08 17:07:14 +00002304 K->setMetadata(Kind, MDNode::getMostGenericAliasScope(JMD, KMD));
2305 break;
Rafael Espindolaea46c322014-08-15 15:46:38 +00002306 case LLVMContext::MD_noalias:
Hal Finkele4c0c162016-04-26 02:06:06 +00002307 case LLVMContext::MD_mem_parallel_loop_access:
Rafael Espindolaea46c322014-08-15 15:46:38 +00002308 K->setMetadata(Kind, MDNode::intersect(JMD, KMD));
2309 break;
Michael Kruse978ba612018-12-20 04:58:07 +00002310 case LLVMContext::MD_access_group:
2311 K->setMetadata(LLVMContext::MD_access_group,
2312 intersectAccessGroups(K, J));
2313 break;
Rafael Espindolaea46c322014-08-15 15:46:38 +00002314 case LLVMContext::MD_range:
Florian Hahnfc7654a2018-10-27 16:53:45 +00002315
2316 // If K does move, use most generic range. Otherwise keep the range of
2317 // K.
2318 if (DoesKMove)
2319 // FIXME: If K does move, we should drop the range info and nonnull.
2320 // Currently this function is used with DoesKMove in passes
2321 // doing hoisting/sinking and the current behavior of using the
2322 // most generic range is correct in those cases.
2323 K->setMetadata(Kind, MDNode::getMostGenericRange(JMD, KMD));
Rafael Espindolaea46c322014-08-15 15:46:38 +00002324 break;
2325 case LLVMContext::MD_fpmath:
2326 K->setMetadata(Kind, MDNode::getMostGenericFPMath(JMD, KMD));
2327 break;
2328 case LLVMContext::MD_invariant_load:
2329 // Only set the !invariant.load if it is present in both instructions.
2330 K->setMetadata(Kind, JMD);
2331 break;
Philip Reamesd7c21362014-10-21 21:02:19 +00002332 case LLVMContext::MD_nonnull:
Florian Hahn950576b2018-08-07 15:36:11 +00002333 // If K does move, keep nonull if it is present in both instructions.
2334 if (DoesKMove)
2335 K->setMetadata(Kind, JMD);
Philip Reamesd7c21362014-10-21 21:02:19 +00002336 break;
Piotr Padlewskidc9b2cf2015-10-02 22:12:22 +00002337 case LLVMContext::MD_invariant_group:
2338 // Preserve !invariant.group in K.
2339 break;
Artur Pilipenko5c5011d2015-11-02 17:53:51 +00002340 case LLVMContext::MD_align:
Chandler Carruth2abb65a2017-06-26 03:31:31 +00002341 K->setMetadata(Kind,
Artur Pilipenko5c5011d2015-11-02 17:53:51 +00002342 MDNode::getMostGenericAlignmentOrDereferenceable(JMD, KMD));
2343 break;
2344 case LLVMContext::MD_dereferenceable:
2345 case LLVMContext::MD_dereferenceable_or_null:
Chandler Carruth2abb65a2017-06-26 03:31:31 +00002346 K->setMetadata(Kind,
Artur Pilipenko5c5011d2015-11-02 17:53:51 +00002347 MDNode::getMostGenericAlignmentOrDereferenceable(JMD, KMD));
2348 break;
Rafael Espindolaea46c322014-08-15 15:46:38 +00002349 }
2350 }
Piotr Padlewskidc9b2cf2015-10-02 22:12:22 +00002351 // Set !invariant.group from J if J has it. If both instructions have it
2352 // then we will just pick it from J - even when they are different.
2353 // Also make sure that K is load or store - f.e. combining bitcast with load
2354 // could produce bitcast with invariant.group metadata, which is invalid.
2355 // FIXME: we should try to preserve both invariant.group md if they are
2356 // different, but right now instruction can only have one invariant.group.
2357 if (auto *JMD = J->getMetadata(LLVMContext::MD_invariant_group))
2358 if (isa<LoadInst>(K) || isa<StoreInst>(K))
2359 K->setMetadata(LLVMContext::MD_invariant_group, JMD);
Rafael Espindolaea46c322014-08-15 15:46:38 +00002360}
Philip Reames7c78ef72015-05-22 23:53:24 +00002361
Florian Hahn406f1ff2018-08-24 11:40:04 +00002362void llvm::combineMetadataForCSE(Instruction *K, const Instruction *J,
2363 bool KDominatesJ) {
Eli Friedman02419a92016-08-08 04:10:22 +00002364 unsigned KnownIDs[] = {
2365 LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
2366 LLVMContext::MD_noalias, LLVMContext::MD_range,
2367 LLVMContext::MD_invariant_load, LLVMContext::MD_nonnull,
2368 LLVMContext::MD_invariant_group, LLVMContext::MD_align,
2369 LLVMContext::MD_dereferenceable,
Michael Kruse978ba612018-12-20 04:58:07 +00002370 LLVMContext::MD_dereferenceable_or_null,
2371 LLVMContext::MD_access_group};
Florian Hahn406f1ff2018-08-24 11:40:04 +00002372 combineMetadata(K, J, KnownIDs, KDominatesJ);
Eli Friedman02419a92016-08-08 04:10:22 +00002373}
2374
Florian Hahn39bbe172018-08-07 13:27:33 +00002375void llvm::patchReplacementInstruction(Instruction *I, Value *Repl) {
2376 auto *ReplInst = dyn_cast<Instruction>(Repl);
2377 if (!ReplInst)
2378 return;
2379
2380 // Patch the replacement so that it is not more restrictive than the value
2381 // being replaced.
2382 // Note that if 'I' is a load being replaced by some operation,
2383 // for example, by an arithmetic operation, then andIRFlags()
2384 // would just erase all math flags from the original arithmetic
2385 // operation, which is clearly not wanted and not needed.
2386 if (!isa<LoadInst>(I))
2387 ReplInst->andIRFlags(I);
2388
2389 // FIXME: If both the original and replacement value are part of the
2390 // same control-flow region (meaning that the execution of one
2391 // guarantees the execution of the other), then we can combine the
2392 // noalias scopes here and do better than the general conservative
2393 // answer used in combineMetadata().
2394
2395 // In general, GVN unifies expressions over different control-flow
2396 // regions, and so we need a conservative combination of the noalias
2397 // scopes.
2398 static const unsigned KnownIDs[] = {
2399 LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
2400 LLVMContext::MD_noalias, LLVMContext::MD_range,
2401 LLVMContext::MD_fpmath, LLVMContext::MD_invariant_load,
Michael Kruse978ba612018-12-20 04:58:07 +00002402 LLVMContext::MD_invariant_group, LLVMContext::MD_nonnull,
2403 LLVMContext::MD_access_group};
Florian Hahn950576b2018-08-07 15:36:11 +00002404 combineMetadata(ReplInst, I, KnownIDs, false);
Florian Hahn39bbe172018-08-07 13:27:33 +00002405}
2406
Piotr Padlewskid979c1f2017-05-09 19:39:44 +00002407template <typename RootType, typename DominatesFn>
2408static unsigned replaceDominatedUsesWith(Value *From, Value *To,
2409 const RootType &Root,
2410 const DominatesFn &Dominates) {
Piotr Padlewski28ffcbe2015-09-02 19:59:59 +00002411 assert(From->getType() == To->getType());
2412
2413 unsigned Count = 0;
2414 for (Value::use_iterator UI = From->use_begin(), UE = From->use_end();
2415 UI != UE;) {
2416 Use &U = *UI++;
Piotr Padlewskid979c1f2017-05-09 19:39:44 +00002417 if (!Dominates(Root, U))
2418 continue;
2419 U.set(To);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002420 LLVM_DEBUG(dbgs() << "Replace dominated use of '" << From->getName()
2421 << "' as " << *To << " in " << *U << "\n");
Piotr Padlewskid979c1f2017-05-09 19:39:44 +00002422 ++Count;
Piotr Padlewski28ffcbe2015-09-02 19:59:59 +00002423 }
2424 return Count;
2425}
Sanjoy Dasc21a05a2015-10-08 23:18:30 +00002426
Anna Thomasc07d5542017-05-23 13:36:25 +00002427unsigned llvm::replaceNonLocalUsesWith(Instruction *From, Value *To) {
2428 assert(From->getType() == To->getType());
2429 auto *BB = From->getParent();
2430 unsigned Count = 0;
2431
2432 for (Value::use_iterator UI = From->use_begin(), UE = From->use_end();
2433 UI != UE;) {
2434 Use &U = *UI++;
2435 auto *I = cast<Instruction>(U.getUser());
2436 if (I->getParent() == BB)
2437 continue;
2438 U.set(To);
2439 ++Count;
2440 }
2441 return Count;
2442}
2443
Piotr Padlewskid979c1f2017-05-09 19:39:44 +00002444unsigned llvm::replaceDominatedUsesWith(Value *From, Value *To,
2445 DominatorTree &DT,
2446 const BasicBlockEdge &Root) {
2447 auto Dominates = [&DT](const BasicBlockEdge &Root, const Use &U) {
2448 return DT.dominates(Root, U);
2449 };
2450 return ::replaceDominatedUsesWith(From, To, Root, Dominates);
2451}
2452
2453unsigned llvm::replaceDominatedUsesWith(Value *From, Value *To,
2454 DominatorTree &DT,
2455 const BasicBlock *BB) {
2456 auto ProperlyDominates = [&DT](const BasicBlock *BB, const Use &U) {
2457 auto *I = cast<Instruction>(U.getUser())->getParent();
2458 return DT.properlyDominates(BB, I);
2459 };
2460 return ::replaceDominatedUsesWith(From, To, BB, ProperlyDominates);
2461}
2462
Chandler Carruth31607342019-02-11 07:42:30 +00002463bool llvm::callsGCLeafFunction(const CallBase *Call,
Daniel Neilson2574d7c2017-07-27 16:49:39 +00002464 const TargetLibraryInfo &TLI) {
Sanjoy Dasc21a05a2015-10-08 23:18:30 +00002465 // Check if the function is specifically marked as a gc leaf function.
Chandler Carruth31607342019-02-11 07:42:30 +00002466 if (Call->hasFnAttr("gc-leaf-function"))
Manuel Jacob3eedd112016-01-05 23:59:08 +00002467 return true;
Chandler Carruth31607342019-02-11 07:42:30 +00002468 if (const Function *F = Call->getCalledFunction()) {
Sanjoy Dasd4c78332016-03-25 20:12:13 +00002469 if (F->hasFnAttribute("gc-leaf-function"))
2470 return true;
2471
2472 if (auto IID = F->getIntrinsicID())
2473 // Most LLVM intrinsics do not take safepoints.
2474 return IID != Intrinsic::experimental_gc_statepoint &&
2475 IID != Intrinsic::experimental_deoptimize;
2476 }
Sanjoy Dasc21a05a2015-10-08 23:18:30 +00002477
Daniel Neilson2574d7c2017-07-27 16:49:39 +00002478 // Lib calls can be materialized by some passes, and won't be
2479 // marked as 'gc-leaf-function.' All available Libcalls are
2480 // GC-leaf.
2481 LibFunc LF;
Chandler Carruth31607342019-02-11 07:42:30 +00002482 if (TLI.getLibFunc(ImmutableCallSite(Call), LF)) {
Daniel Neilson2574d7c2017-07-27 16:49:39 +00002483 return TLI.has(LF);
2484 }
2485
Sanjoy Dasc21a05a2015-10-08 23:18:30 +00002486 return false;
2487}
James Molloyf01488e2016-01-15 09:20:19 +00002488
Chandler Carruth2abb65a2017-06-26 03:31:31 +00002489void llvm::copyNonnullMetadata(const LoadInst &OldLI, MDNode *N,
2490 LoadInst &NewLI) {
2491 auto *NewTy = NewLI.getType();
2492
2493 // This only directly applies if the new type is also a pointer.
2494 if (NewTy->isPointerTy()) {
2495 NewLI.setMetadata(LLVMContext::MD_nonnull, N);
2496 return;
2497 }
2498
2499 // The only other translation we can do is to integral loads with !range
2500 // metadata.
2501 if (!NewTy->isIntegerTy())
2502 return;
2503
2504 MDBuilder MDB(NewLI.getContext());
2505 const Value *Ptr = OldLI.getPointerOperand();
2506 auto *ITy = cast<IntegerType>(NewTy);
2507 auto *NullInt = ConstantExpr::getPtrToInt(
2508 ConstantPointerNull::get(cast<PointerType>(Ptr->getType())), ITy);
2509 auto *NonNullInt = ConstantExpr::getAdd(NullInt, ConstantInt::get(ITy, 1));
2510 NewLI.setMetadata(LLVMContext::MD_range,
2511 MDB.createRange(NonNullInt, NullInt));
2512}
2513
2514void llvm::copyRangeMetadata(const DataLayout &DL, const LoadInst &OldLI,
2515 MDNode *N, LoadInst &NewLI) {
2516 auto *NewTy = NewLI.getType();
2517
Rafael Espindolac06f55e2017-11-28 01:25:38 +00002518 // Give up unless it is converted to a pointer where there is a single very
2519 // valuable mapping we can do reliably.
2520 // FIXME: It would be nice to propagate this in more ways, but the type
2521 // conversions make it hard.
2522 if (!NewTy->isPointerTy())
Chandler Carruth2abb65a2017-06-26 03:31:31 +00002523 return;
2524
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00002525 unsigned BitWidth = DL.getIndexTypeSizeInBits(NewTy);
Rafael Espindolac06f55e2017-11-28 01:25:38 +00002526 if (!getConstantRangeFromMetadata(*N).contains(APInt(BitWidth, 0))) {
2527 MDNode *NN = MDNode::get(OldLI.getContext(), None);
2528 NewLI.setMetadata(LLVMContext::MD_nonnull, NN);
Chandler Carruth2abb65a2017-06-26 03:31:31 +00002529 }
2530}
2531
Carlos Alberto Encisoba4e4372018-09-19 08:16:56 +00002532void llvm::dropDebugUsers(Instruction &I) {
2533 SmallVector<DbgVariableIntrinsic *, 1> DbgUsers;
2534 findDbgUsers(DbgUsers, &I);
2535 for (auto *DII : DbgUsers)
2536 DII->eraseFromParent();
2537}
2538
Carlos Alberto Enciso9a24e1a2018-10-25 09:58:59 +00002539void llvm::hoistAllInstructionsInto(BasicBlock *DomBlock, Instruction *InsertPt,
2540 BasicBlock *BB) {
2541 // Since we are moving the instructions out of its basic block, we do not
2542 // retain their original debug locations (DILocations) and debug intrinsic
Carlos Alberto Enciso08dc50f2019-02-08 10:57:26 +00002543 // instructions.
Carlos Alberto Enciso9a24e1a2018-10-25 09:58:59 +00002544 //
2545 // Doing so would degrade the debugging experience and adversely affect the
2546 // accuracy of profiling information.
2547 //
2548 // Currently, when hoisting the instructions, we take the following actions:
Carlos Alberto Enciso08dc50f2019-02-08 10:57:26 +00002549 // - Remove their debug intrinsic instructions.
Carlos Alberto Enciso9a24e1a2018-10-25 09:58:59 +00002550 // - Set their debug locations to the values from the insertion point.
2551 //
2552 // As per PR39141 (comment #8), the more fundamental reason why the dbg.values
2553 // need to be deleted, is because there will not be any instructions with a
2554 // DILocation in either branch left after performing the transformation. We
2555 // can only insert a dbg.value after the two branches are joined again.
2556 //
2557 // See PR38762, PR39243 for more details.
2558 //
2559 // TODO: Extend llvm.dbg.value to take more than one SSA Value (PR39141) to
2560 // encode predicated DIExpressions that yield different results on different
2561 // code paths.
2562 for (BasicBlock::iterator II = BB->begin(), IE = BB->end(); II != IE;) {
2563 Instruction *I = &*II;
2564 I->dropUnknownNonDebugMetadata();
2565 if (I->isUsedByMetadata())
2566 dropDebugUsers(*I);
Carlos Alberto Enciso08dc50f2019-02-08 10:57:26 +00002567 if (isa<DbgInfoIntrinsic>(I)) {
Carlos Alberto Enciso9a24e1a2018-10-25 09:58:59 +00002568 // Remove DbgInfo Intrinsics.
2569 II = I->eraseFromParent();
2570 continue;
2571 }
2572 I->setDebugLoc(InsertPt->getDebugLoc());
2573 ++II;
2574 }
2575 DomBlock->getInstList().splice(InsertPt->getIterator(), BB->getInstList(),
2576 BB->begin(),
2577 BB->getTerminator()->getIterator());
2578}
2579
Benjamin Kramerb7d33112016-08-06 11:13:10 +00002580namespace {
Eugene Zelenko6cadde72017-10-17 21:27:42 +00002581
James Molloyf01488e2016-01-15 09:20:19 +00002582/// A potential constituent of a bitreverse or bswap expression. See
2583/// collectBitParts for a fuller explanation.
2584struct BitPart {
2585 BitPart(Value *P, unsigned BW) : Provider(P) {
2586 Provenance.resize(BW);
2587 }
2588
2589 /// The Value that this is a bitreverse/bswap of.
2590 Value *Provider;
Eugene Zelenko6cadde72017-10-17 21:27:42 +00002591
James Molloyf01488e2016-01-15 09:20:19 +00002592 /// The "provenance" of each bit. Provenance[A] = B means that bit A
2593 /// in Provider becomes bit B in the result of this expression.
2594 SmallVector<int8_t, 32> Provenance; // int8_t means max size is i128.
2595
2596 enum { Unset = -1 };
2597};
Eugene Zelenko6cadde72017-10-17 21:27:42 +00002598
Benjamin Kramerb7d33112016-08-06 11:13:10 +00002599} // end anonymous namespace
James Molloyf01488e2016-01-15 09:20:19 +00002600
2601/// Analyze the specified subexpression and see if it is capable of providing
2602/// pieces of a bswap or bitreverse. The subexpression provides a potential
2603/// piece of a bswap or bitreverse if it can be proven that each non-zero bit in
2604/// the output of the expression came from a corresponding bit in some other
2605/// value. This function is recursive, and the end result is a mapping of
2606/// bitnumber to bitnumber. It is the caller's responsibility to validate that
2607/// the bitnumber to bitnumber mapping is correct for a bswap or bitreverse.
2608///
2609/// For example, if the current subexpression if "(shl i32 %X, 24)" then we know
2610/// that the expression deposits the low byte of %X into the high byte of the
2611/// result and that all other bits are zero. This expression is accepted and a
2612/// BitPart is returned with Provider set to %X and Provenance[24-31] set to
2613/// [0-7].
2614///
2615/// To avoid revisiting values, the BitPart results are memoized into the
2616/// provided map. To avoid unnecessary copying of BitParts, BitParts are
2617/// constructed in-place in the \c BPS map. Because of this \c BPS needs to
2618/// store BitParts objects, not pointers. As we need the concept of a nullptr
2619/// BitParts (Value has been analyzed and the analysis failed), we an Optional
2620/// type instead to provide the same functionality.
2621///
2622/// Because we pass around references into \c BPS, we must use a container that
2623/// does not invalidate internal references (std::map instead of DenseMap).
James Molloyf01488e2016-01-15 09:20:19 +00002624static const Optional<BitPart> &
2625collectBitParts(Value *V, bool MatchBSwaps, bool MatchBitReversals,
David Stuttard411488b2019-05-09 15:02:10 +00002626 std::map<Value *, Optional<BitPart>> &BPS, int Depth) {
James Molloyf01488e2016-01-15 09:20:19 +00002627 auto I = BPS.find(V);
2628 if (I != BPS.end())
2629 return I->second;
2630
2631 auto &Result = BPS[V] = None;
2632 auto BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
2633
David Stuttard411488b2019-05-09 15:02:10 +00002634 // Prevent stack overflow by limiting the recursion depth
2635 if (Depth == BitPartRecursionMaxDepth) {
2636 LLVM_DEBUG(dbgs() << "collectBitParts max recursion depth reached.\n");
2637 return Result;
2638 }
2639
James Molloyf01488e2016-01-15 09:20:19 +00002640 if (Instruction *I = dyn_cast<Instruction>(V)) {
2641 // If this is an or instruction, it may be an inner node of the bswap.
2642 if (I->getOpcode() == Instruction::Or) {
2643 auto &A = collectBitParts(I->getOperand(0), MatchBSwaps,
David Stuttard411488b2019-05-09 15:02:10 +00002644 MatchBitReversals, BPS, Depth + 1);
James Molloyf01488e2016-01-15 09:20:19 +00002645 auto &B = collectBitParts(I->getOperand(1), MatchBSwaps,
David Stuttard411488b2019-05-09 15:02:10 +00002646 MatchBitReversals, BPS, Depth + 1);
James Molloyf01488e2016-01-15 09:20:19 +00002647 if (!A || !B)
2648 return Result;
2649
2650 // Try and merge the two together.
2651 if (!A->Provider || A->Provider != B->Provider)
2652 return Result;
2653
2654 Result = BitPart(A->Provider, BitWidth);
2655 for (unsigned i = 0; i < A->Provenance.size(); ++i) {
2656 if (A->Provenance[i] != BitPart::Unset &&
2657 B->Provenance[i] != BitPart::Unset &&
2658 A->Provenance[i] != B->Provenance[i])
2659 return Result = None;
2660
2661 if (A->Provenance[i] == BitPart::Unset)
2662 Result->Provenance[i] = B->Provenance[i];
2663 else
2664 Result->Provenance[i] = A->Provenance[i];
2665 }
2666
2667 return Result;
2668 }
2669
2670 // If this is a logical shift by a constant, recurse then shift the result.
2671 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
2672 unsigned BitShift =
2673 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
2674 // Ensure the shift amount is defined.
2675 if (BitShift > BitWidth)
2676 return Result;
2677
2678 auto &Res = collectBitParts(I->getOperand(0), MatchBSwaps,
David Stuttard411488b2019-05-09 15:02:10 +00002679 MatchBitReversals, BPS, Depth + 1);
James Molloyf01488e2016-01-15 09:20:19 +00002680 if (!Res)
2681 return Result;
2682 Result = Res;
2683
2684 // Perform the "shift" on BitProvenance.
2685 auto &P = Result->Provenance;
2686 if (I->getOpcode() == Instruction::Shl) {
2687 P.erase(std::prev(P.end(), BitShift), P.end());
2688 P.insert(P.begin(), BitShift, BitPart::Unset);
2689 } else {
2690 P.erase(P.begin(), std::next(P.begin(), BitShift));
2691 P.insert(P.end(), BitShift, BitPart::Unset);
2692 }
2693
2694 return Result;
2695 }
2696
2697 // If this is a logical 'and' with a mask that clears bits, recurse then
2698 // unset the appropriate bits.
2699 if (I->getOpcode() == Instruction::And &&
2700 isa<ConstantInt>(I->getOperand(1))) {
2701 APInt Bit(I->getType()->getPrimitiveSizeInBits(), 1);
2702 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
2703
2704 // Check that the mask allows a multiple of 8 bits for a bswap, for an
2705 // early exit.
2706 unsigned NumMaskedBits = AndMask.countPopulation();
2707 if (!MatchBitReversals && NumMaskedBits % 8 != 0)
2708 return Result;
Chandler Carruth2abb65a2017-06-26 03:31:31 +00002709
James Molloyf01488e2016-01-15 09:20:19 +00002710 auto &Res = collectBitParts(I->getOperand(0), MatchBSwaps,
David Stuttard411488b2019-05-09 15:02:10 +00002711 MatchBitReversals, BPS, Depth + 1);
James Molloyf01488e2016-01-15 09:20:19 +00002712 if (!Res)
2713 return Result;
2714 Result = Res;
2715
2716 for (unsigned i = 0; i < BitWidth; ++i, Bit <<= 1)
2717 // If the AndMask is zero for this bit, clear the bit.
2718 if ((AndMask & Bit) == 0)
2719 Result->Provenance[i] = BitPart::Unset;
Chad Rosiere5819e22016-05-26 14:58:51 +00002720 return Result;
2721 }
James Molloyf01488e2016-01-15 09:20:19 +00002722
Chad Rosiere5819e22016-05-26 14:58:51 +00002723 // If this is a zext instruction zero extend the result.
2724 if (I->getOpcode() == Instruction::ZExt) {
2725 auto &Res = collectBitParts(I->getOperand(0), MatchBSwaps,
David Stuttard411488b2019-05-09 15:02:10 +00002726 MatchBitReversals, BPS, Depth + 1);
Chad Rosiere5819e22016-05-26 14:58:51 +00002727 if (!Res)
2728 return Result;
2729
2730 Result = BitPart(Res->Provider, BitWidth);
2731 auto NarrowBitWidth =
2732 cast<IntegerType>(cast<ZExtInst>(I)->getSrcTy())->getBitWidth();
2733 for (unsigned i = 0; i < NarrowBitWidth; ++i)
2734 Result->Provenance[i] = Res->Provenance[i];
2735 for (unsigned i = NarrowBitWidth; i < BitWidth; ++i)
2736 Result->Provenance[i] = BitPart::Unset;
James Molloyf01488e2016-01-15 09:20:19 +00002737 return Result;
2738 }
2739 }
2740
2741 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
2742 // the input value to the bswap/bitreverse.
2743 Result = BitPart(V, BitWidth);
2744 for (unsigned i = 0; i < BitWidth; ++i)
2745 Result->Provenance[i] = i;
2746 return Result;
2747}
2748
2749static bool bitTransformIsCorrectForBSwap(unsigned From, unsigned To,
2750 unsigned BitWidth) {
2751 if (From % 8 != To % 8)
2752 return false;
2753 // Convert from bit indices to byte indices and check for a byte reversal.
2754 From >>= 3;
2755 To >>= 3;
2756 BitWidth >>= 3;
2757 return From == BitWidth - To - 1;
2758}
2759
2760static bool bitTransformIsCorrectForBitReverse(unsigned From, unsigned To,
2761 unsigned BitWidth) {
2762 return From == BitWidth - To - 1;
2763}
2764
Chad Rosiera00df492016-05-25 16:22:14 +00002765bool llvm::recognizeBSwapOrBitReverseIdiom(
James Molloyf01488e2016-01-15 09:20:19 +00002766 Instruction *I, bool MatchBSwaps, bool MatchBitReversals,
2767 SmallVectorImpl<Instruction *> &InsertedInsts) {
2768 if (Operator::getOpcode(I) != Instruction::Or)
2769 return false;
2770 if (!MatchBSwaps && !MatchBitReversals)
2771 return false;
2772 IntegerType *ITy = dyn_cast<IntegerType>(I->getType());
2773 if (!ITy || ITy->getBitWidth() > 128)
2774 return false; // Can't do vectors or integers > 128 bits.
2775 unsigned BW = ITy->getBitWidth();
2776
Chad Rosiere5819e22016-05-26 14:58:51 +00002777 unsigned DemandedBW = BW;
2778 IntegerType *DemandedTy = ITy;
2779 if (I->hasOneUse()) {
2780 if (TruncInst *Trunc = dyn_cast<TruncInst>(I->user_back())) {
2781 DemandedTy = cast<IntegerType>(Trunc->getType());
2782 DemandedBW = DemandedTy->getBitWidth();
2783 }
2784 }
2785
James Molloyf01488e2016-01-15 09:20:19 +00002786 // Try to find all the pieces corresponding to the bswap.
2787 std::map<Value *, Optional<BitPart>> BPS;
David Stuttard411488b2019-05-09 15:02:10 +00002788 auto Res = collectBitParts(I, MatchBSwaps, MatchBitReversals, BPS, 0);
James Molloyf01488e2016-01-15 09:20:19 +00002789 if (!Res)
2790 return false;
2791 auto &BitProvenance = Res->Provenance;
2792
2793 // Now, is the bit permutation correct for a bswap or a bitreverse? We can
2794 // only byteswap values with an even number of bytes.
Chad Rosiere5819e22016-05-26 14:58:51 +00002795 bool OKForBSwap = DemandedBW % 16 == 0, OKForBitReverse = true;
2796 for (unsigned i = 0; i < DemandedBW; ++i) {
2797 OKForBSwap &=
2798 bitTransformIsCorrectForBSwap(BitProvenance[i], i, DemandedBW);
James Molloyf01488e2016-01-15 09:20:19 +00002799 OKForBitReverse &=
Chad Rosiere5819e22016-05-26 14:58:51 +00002800 bitTransformIsCorrectForBitReverse(BitProvenance[i], i, DemandedBW);
James Molloyf01488e2016-01-15 09:20:19 +00002801 }
2802
2803 Intrinsic::ID Intrin;
2804 if (OKForBSwap && MatchBSwaps)
2805 Intrin = Intrinsic::bswap;
2806 else if (OKForBitReverse && MatchBitReversals)
2807 Intrin = Intrinsic::bitreverse;
2808 else
2809 return false;
2810
Chad Rosiere5819e22016-05-26 14:58:51 +00002811 if (ITy != DemandedTy) {
2812 Function *F = Intrinsic::getDeclaration(I->getModule(), Intrin, DemandedTy);
2813 Value *Provider = Res->Provider;
2814 IntegerType *ProviderTy = cast<IntegerType>(Provider->getType());
2815 // We may need to truncate the provider.
2816 if (DemandedTy != ProviderTy) {
2817 auto *Trunc = CastInst::Create(Instruction::Trunc, Provider, DemandedTy,
2818 "trunc", I);
2819 InsertedInsts.push_back(Trunc);
2820 Provider = Trunc;
2821 }
2822 auto *CI = CallInst::Create(F, Provider, "rev", I);
2823 InsertedInsts.push_back(CI);
2824 auto *ExtInst = CastInst::Create(Instruction::ZExt, CI, ITy, "zext", I);
2825 InsertedInsts.push_back(ExtInst);
2826 return true;
2827 }
2828
James Molloyf01488e2016-01-15 09:20:19 +00002829 Function *F = Intrinsic::getDeclaration(I->getModule(), Intrin, ITy);
2830 InsertedInsts.push_back(CallInst::Create(F, Res->Provider, "rev", I));
2831 return true;
2832}
Marcin Koscielnicki3feda222016-06-18 10:10:37 +00002833
2834// CodeGen has special handling for some string functions that may replace
2835// them with target-specific intrinsics. Since that'd skip our interceptors
2836// in ASan/MSan/TSan/DFSan, and thus make us miss some memory accesses,
2837// we mark affected calls as NoBuiltin, which will disable optimization
2838// in CodeGen.
Evgeniy Stepanovd240a882016-07-28 23:45:15 +00002839void llvm::maybeMarkSanitizerLibraryCallNoBuiltin(
2840 CallInst *CI, const TargetLibraryInfo *TLI) {
Marcin Koscielnicki3feda222016-06-18 10:10:37 +00002841 Function *F = CI->getCalledFunction();
David L. Jonesd21529f2017-01-23 23:16:46 +00002842 LibFunc Func;
Evgeniy Stepanovd240a882016-07-28 23:45:15 +00002843 if (F && !F->hasLocalLinkage() && F->hasName() &&
2844 TLI->getLibFunc(F->getName(), Func) && TLI->hasOptimizedCodeGen(Func) &&
2845 !F->doesNotAccessMemory())
Reid Klecknerb5180542017-03-21 16:57:19 +00002846 CI->addAttribute(AttributeList::FunctionIndex, Attribute::NoBuiltin);
Marcin Koscielnicki3feda222016-06-18 10:10:37 +00002847}
James Molloya9290632017-05-25 12:51:11 +00002848
2849bool llvm::canReplaceOperandWithVariable(const Instruction *I, unsigned OpIdx) {
2850 // We can't have a PHI with a metadata type.
2851 if (I->getOperand(OpIdx)->getType()->isMetadataTy())
2852 return false;
2853
2854 // Early exit.
2855 if (!isa<Constant>(I->getOperand(OpIdx)))
2856 return true;
2857
2858 switch (I->getOpcode()) {
2859 default:
2860 return true;
2861 case Instruction::Call:
2862 case Instruction::Invoke:
Leo Li93abd7d2017-07-10 20:45:34 +00002863 // Can't handle inline asm. Skip it.
2864 if (isa<InlineAsm>(ImmutableCallSite(I).getCalledValue()))
2865 return false;
James Molloya9290632017-05-25 12:51:11 +00002866 // Many arithmetic intrinsics have no issue taking a
2867 // variable, however it's hard to distingish these from
2868 // specials such as @llvm.frameaddress that require a constant.
2869 if (isa<IntrinsicInst>(I))
2870 return false;
2871
2872 // Constant bundle operands may need to retain their constant-ness for
2873 // correctness.
2874 if (ImmutableCallSite(I).isBundleOperand(OpIdx))
2875 return false;
2876 return true;
2877 case Instruction::ShuffleVector:
2878 // Shufflevector masks are constant.
2879 return OpIdx != 2;
Leo Li5499b1b2017-07-06 18:47:05 +00002880 case Instruction::Switch:
James Molloya9290632017-05-25 12:51:11 +00002881 case Instruction::ExtractValue:
James Molloya9290632017-05-25 12:51:11 +00002882 // All operands apart from the first are constant.
2883 return OpIdx == 0;
Leo Li5499b1b2017-07-06 18:47:05 +00002884 case Instruction::InsertValue:
2885 // All operands apart from the first and the second are constant.
2886 return OpIdx < 2;
James Molloya9290632017-05-25 12:51:11 +00002887 case Instruction::Alloca:
Leo Li5499b1b2017-07-06 18:47:05 +00002888 // Static allocas (constant size in the entry block) are handled by
2889 // prologue/epilogue insertion so they're free anyway. We definitely don't
2890 // want to make them non-constant.
Craig Topper781aa182018-05-05 01:57:00 +00002891 return !cast<AllocaInst>(I)->isStaticAlloca();
James Molloya9290632017-05-25 12:51:11 +00002892 case Instruction::GetElementPtr:
2893 if (OpIdx == 0)
2894 return true;
2895 gep_type_iterator It = gep_type_begin(I);
2896 for (auto E = std::next(It, OpIdx); It != E; ++It)
2897 if (It.isStruct())
2898 return false;
2899 return true;
2900 }
2901}
Alexander Potapenko6a63e5a2019-04-15 08:59:56 +00002902
2903using AllocaForValueMapTy = DenseMap<Value *, AllocaInst *>;
2904AllocaInst *llvm::findAllocaForValue(Value *V,
2905 AllocaForValueMapTy &AllocaForValue) {
2906 if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
2907 return AI;
2908 // See if we've already calculated (or started to calculate) alloca for a
2909 // given value.
2910 AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
2911 if (I != AllocaForValue.end())
2912 return I->second;
2913 // Store 0 while we're calculating alloca for value V to avoid
2914 // infinite recursion if the value references itself.
2915 AllocaForValue[V] = nullptr;
2916 AllocaInst *Res = nullptr;
2917 if (CastInst *CI = dyn_cast<CastInst>(V))
2918 Res = findAllocaForValue(CI->getOperand(0), AllocaForValue);
2919 else if (PHINode *PN = dyn_cast<PHINode>(V)) {
2920 for (Value *IncValue : PN->incoming_values()) {
2921 // Allow self-referencing phi-nodes.
2922 if (IncValue == PN)
2923 continue;
2924 AllocaInst *IncValueAI = findAllocaForValue(IncValue, AllocaForValue);
2925 // AI for incoming values should exist and should all be equal.
2926 if (IncValueAI == nullptr || (Res != nullptr && IncValueAI != Res))
2927 return nullptr;
2928 Res = IncValueAI;
2929 }
2930 } else if (GetElementPtrInst *EP = dyn_cast<GetElementPtrInst>(V)) {
2931 Res = findAllocaForValue(EP->getPointerOperand(), AllocaForValue);
2932 } else {
2933 LLVM_DEBUG(dbgs() << "Alloca search cancelled on unknown instruction: "
2934 << *V << "\n");
2935 }
2936 if (Res)
2937 AllocaForValue[V] = Res;
2938 return Res;
2939}