blob: 725bc70c9efb04343ff5baa24417073531d6cd88 [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)
Florian Hahn0a7faa42019-07-20 12:25:47 +0000327 // Delete pointer cast instructions.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000328 RecursivelyDeleteTriviallyDeadInstructions(Address, TLI);
Jakub Staszak8e1a6e72013-07-22 23:16:36 +0000329
Florian Hahn0a7faa42019-07-20 12:25:47 +0000330 // Also zap the blockaddress constant if there are no users remaining,
331 // otherwise the destination is still marked as having its address taken.
332 if (BA->use_empty())
333 BA->destroyConstant();
334
Chris Lattner54a4b842009-11-01 03:40:38 +0000335 // If we didn't find our destination in the IBI successor list, then we
336 // have undefined behavior. Replace the unconditional branch with an
337 // 'unreachable' instruction.
338 if (TheOnlyDest) {
339 BB->getTerminator()->eraseFromParent();
340 new UnreachableInst(BB->getContext(), BB);
341 }
Jakub Staszak8e1a6e72013-07-22 23:16:36 +0000342
Chijun Sima21a8b602018-08-03 05:08:17 +0000343 if (DTU)
Chijun Sima70e97162019-02-22 13:48:38 +0000344 DTU->applyUpdatesPermissive(Updates);
Chris Lattner54a4b842009-11-01 03:40:38 +0000345 return true;
346 }
347 }
Jakub Staszak8e1a6e72013-07-22 23:16:36 +0000348
Chris Lattner28537df2002-05-07 18:07:59 +0000349 return false;
350}
351
Chris Lattner28537df2002-05-07 18:07:59 +0000352//===----------------------------------------------------------------------===//
Chris Lattner852d6d62009-11-10 22:26:15 +0000353// Local dead code elimination.
Chris Lattner28537df2002-05-07 18:07:59 +0000354//
355
Chris Lattnerc6c481c2008-11-27 22:57:53 +0000356/// isInstructionTriviallyDead - Return true if the result produced by the
357/// instruction is not used, and the instruction has no side effects.
358///
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000359bool llvm::isInstructionTriviallyDead(Instruction *I,
360 const TargetLibraryInfo *TLI) {
Daniel Berline3e69e12017-03-10 00:32:33 +0000361 if (!I->use_empty())
362 return false;
363 return wouldInstructionBeTriviallyDead(I, TLI);
364}
365
366bool llvm::wouldInstructionBeTriviallyDead(Instruction *I,
367 const TargetLibraryInfo *TLI) {
Chandler Carruth9ae926b2018-08-26 09:51:22 +0000368 if (I->isTerminator())
Daniel Berline3e69e12017-03-10 00:32:33 +0000369 return false;
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000370
David Majnemer654e1302015-07-31 17:58:14 +0000371 // We don't want the landingpad-like instructions removed by anything this
372 // general.
373 if (I->isEHPad())
Bill Wendlingd9fb4702011-08-15 20:10:51 +0000374 return false;
375
Devang Patelc1431e62011-03-18 23:28:02 +0000376 // We don't want debug info removed by anything this general, unless
377 // debug info is empty.
378 if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(I)) {
Nick Lewycky99890a22011-08-02 21:19:27 +0000379 if (DDI->getAddress())
Devang Patelc1431e62011-03-18 23:28:02 +0000380 return false;
Devang Patel17bbd7f2011-03-21 22:04:45 +0000381 return true;
Nick Lewycky99890a22011-08-02 21:19:27 +0000382 }
Devang Patel17bbd7f2011-03-21 22:04:45 +0000383 if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(I)) {
Devang Patelc1431e62011-03-18 23:28:02 +0000384 if (DVI->getValue())
385 return false;
Devang Patel17bbd7f2011-03-21 22:04:45 +0000386 return true;
Devang Patelc1431e62011-03-18 23:28:02 +0000387 }
Shiva Chen2c864552018-05-09 02:40:45 +0000388 if (DbgLabelInst *DLI = dyn_cast<DbgLabelInst>(I)) {
389 if (DLI->getLabel())
390 return false;
391 return true;
392 }
Devang Patelc1431e62011-03-18 23:28:02 +0000393
Daniel Berline3e69e12017-03-10 00:32:33 +0000394 if (!I->mayHaveSideEffects())
395 return true;
Duncan Sands1efabaa2009-05-06 06:49:50 +0000396
397 // Special case intrinsics that "may have side effects" but can be deleted
398 // when dead.
Nick Lewycky99890a22011-08-02 21:19:27 +0000399 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
Piotr Padlewskia26a08c2018-05-18 23:52:57 +0000400 // Safe to delete llvm.stacksave and launder.invariant.group if dead.
401 if (II->getIntrinsicID() == Intrinsic::stacksave ||
402 II->getIntrinsicID() == Intrinsic::launder_invariant_group)
Chris Lattnere9665832007-12-29 00:59:12 +0000403 return true;
Nick Lewycky99890a22011-08-02 21:19:27 +0000404
405 // Lifetime intrinsics are dead when their right-hand is undef.
Vedant Kumarb264d692018-12-21 21:49:40 +0000406 if (II->isLifetimeStartOrEnd())
Nick Lewycky99890a22011-08-02 21:19:27 +0000407 return isa<UndefValue>(II->getArgOperand(1));
Hal Finkel93046912014-07-25 21:13:35 +0000408
Sanjoy Das107aefc2016-04-29 22:23:16 +0000409 // Assumptions are dead if their condition is trivially true. Guards on
410 // true are operationally no-ops. In the future we can consider more
411 // sophisticated tradeoffs for guards considering potential for check
412 // widening, but for now we keep things simple.
413 if (II->getIntrinsicID() == Intrinsic::assume ||
414 II->getIntrinsicID() == Intrinsic::experimental_guard) {
Hal Finkel93046912014-07-25 21:13:35 +0000415 if (ConstantInt *Cond = dyn_cast<ConstantInt>(II->getArgOperand(0)))
416 return !Cond->isZero();
417
418 return false;
419 }
Nick Lewycky99890a22011-08-02 21:19:27 +0000420 }
Nick Lewyckydd1d3df2011-10-24 04:35:36 +0000421
Daniel Berline3e69e12017-03-10 00:32:33 +0000422 if (isAllocLikeFn(I, TLI))
423 return true;
Nick Lewyckydd1d3df2011-10-24 04:35:36 +0000424
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000425 if (CallInst *CI = isFreeCall(I, TLI))
Nick Lewyckydd1d3df2011-10-24 04:35:36 +0000426 if (Constant *C = dyn_cast<Constant>(CI->getArgOperand(0)))
427 return C->isNullValue() || isa<UndefValue>(C);
428
Chandler Carruth751d95f2019-02-11 07:51:44 +0000429 if (auto *Call = dyn_cast<CallBase>(I))
430 if (isMathLibCallNoop(Call, TLI))
Eli Friedmanb6befc32016-11-02 20:48:11 +0000431 return true;
432
Chris Lattnera36d5252005-05-06 05:27:34 +0000433 return false;
Chris Lattner28537df2002-05-07 18:07:59 +0000434}
435
Chris Lattnerc6c481c2008-11-27 22:57:53 +0000436/// RecursivelyDeleteTriviallyDeadInstructions - If the specified value is a
437/// trivially dead instruction, delete it. If that makes any of its operands
Dan Gohmancb99fe92010-01-05 15:45:31 +0000438/// trivially dead, delete them too, recursively. Return true if any
439/// instructions were deleted.
Alina Sbirlea2ab544b2018-08-16 21:58:44 +0000440bool llvm::RecursivelyDeleteTriviallyDeadInstructions(
441 Value *V, const TargetLibraryInfo *TLI, MemorySSAUpdater *MSSAU) {
Chris Lattnerc6c481c2008-11-27 22:57:53 +0000442 Instruction *I = dyn_cast<Instruction>(V);
Fangrui Song709a3e72019-02-10 09:25:56 +0000443 if (!I || !isInstructionTriviallyDead(I, TLI))
Dan Gohmancb99fe92010-01-05 15:45:31 +0000444 return false;
Jakub Staszak8e1a6e72013-07-22 23:16:36 +0000445
Chris Lattnere9f6c352008-11-28 01:20:46 +0000446 SmallVector<Instruction*, 16> DeadInsts;
447 DeadInsts.push_back(I);
Alina Sbirlea2ab544b2018-08-16 21:58:44 +0000448 RecursivelyDeleteTriviallyDeadInstructions(DeadInsts, TLI, MSSAU);
Jakub Staszak8e1a6e72013-07-22 23:16:36 +0000449
Chandler Carruth4cbcbb02018-05-29 20:15:38 +0000450 return true;
451}
452
453void llvm::RecursivelyDeleteTriviallyDeadInstructions(
Alina Sbirlea2ab544b2018-08-16 21:58:44 +0000454 SmallVectorImpl<Instruction *> &DeadInsts, const TargetLibraryInfo *TLI,
455 MemorySSAUpdater *MSSAU) {
Chandler Carruth4cbcbb02018-05-29 20:15:38 +0000456 // Process the dead instruction list until empty.
457 while (!DeadInsts.empty()) {
458 Instruction &I = *DeadInsts.pop_back_val();
459 assert(I.use_empty() && "Instructions with uses are not dead.");
460 assert(isInstructionTriviallyDead(&I, TLI) &&
461 "Live instruction found in dead worklist!");
462
463 // Don't lose the debug info while deleting the instructions.
464 salvageDebugInfo(I);
Chris Lattnerd4b5ba62008-11-28 00:58:15 +0000465
Chris Lattnere9f6c352008-11-28 01:20:46 +0000466 // Null out all of the instruction's operands to see if any operand becomes
467 // dead as we go.
Chandler Carruth4cbcbb02018-05-29 20:15:38 +0000468 for (Use &OpU : I.operands()) {
469 Value *OpV = OpU.get();
470 OpU.set(nullptr);
Jakub Staszak8e1a6e72013-07-22 23:16:36 +0000471
Chandler Carruth4cbcbb02018-05-29 20:15:38 +0000472 if (!OpV->use_empty())
473 continue;
Jakub Staszak8e1a6e72013-07-22 23:16:36 +0000474
Chris Lattnere9f6c352008-11-28 01:20:46 +0000475 // If the operand is an instruction that became dead as we nulled out the
476 // operand, and if it is 'trivially' dead, delete it in a future loop
477 // iteration.
478 if (Instruction *OpI = dyn_cast<Instruction>(OpV))
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000479 if (isInstructionTriviallyDead(OpI, TLI))
Chris Lattnere9f6c352008-11-28 01:20:46 +0000480 DeadInsts.push_back(OpI);
481 }
Alina Sbirlea2ab544b2018-08-16 21:58:44 +0000482 if (MSSAU)
483 MSSAU->removeMemoryAccess(&I);
Jakub Staszak8e1a6e72013-07-22 23:16:36 +0000484
Chandler Carruth4cbcbb02018-05-29 20:15:38 +0000485 I.eraseFromParent();
486 }
Chris Lattner28537df2002-05-07 18:07:59 +0000487}
Chris Lattner99d68092008-11-27 07:43:12 +0000488
Davide Italiano8ec77092018-12-10 22:17:04 +0000489bool llvm::replaceDbgUsesWithUndef(Instruction *I) {
490 SmallVector<DbgVariableIntrinsic *, 1> DbgUsers;
491 findDbgUsers(DbgUsers, I);
492 for (auto *DII : DbgUsers) {
493 Value *Undef = UndefValue::get(I->getType());
494 DII->setOperand(0, MetadataAsValue::get(DII->getContext(),
495 ValueAsMetadata::get(Undef)));
496 }
497 return !DbgUsers.empty();
498}
499
Nick Lewyckyc8a15692011-02-20 08:38:20 +0000500/// areAllUsesEqual - Check whether the uses of a value are all the same.
501/// This is similar to Instruction::hasOneUse() except this will also return
Duncan Sands6dcd49b2011-02-21 16:27:36 +0000502/// true when there are no uses or multiple uses that all refer to the same
503/// value.
Nick Lewyckyc8a15692011-02-20 08:38:20 +0000504static bool areAllUsesEqual(Instruction *I) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000505 Value::user_iterator UI = I->user_begin();
506 Value::user_iterator UE = I->user_end();
Nick Lewyckyc8a15692011-02-20 08:38:20 +0000507 if (UI == UE)
Duncan Sands6dcd49b2011-02-21 16:27:36 +0000508 return true;
Nick Lewyckyc8a15692011-02-20 08:38:20 +0000509
510 User *TheUse = *UI;
511 for (++UI; UI != UE; ++UI) {
512 if (*UI != TheUse)
513 return false;
514 }
515 return true;
516}
517
Dan Gohmanff089952009-05-02 18:29:22 +0000518/// RecursivelyDeleteDeadPHINode - If the specified value is an effectively
519/// dead PHI node, due to being a def-use chain of single-use nodes that
520/// either forms a cycle or is terminated by a trivially dead instruction,
521/// delete it. If that makes any of its operands trivially dead, delete them
Duncan Sandsecbbf082011-02-21 17:32:05 +0000522/// too, recursively. Return true if a change was made.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000523bool llvm::RecursivelyDeleteDeadPHINode(PHINode *PN,
524 const TargetLibraryInfo *TLI) {
Duncan Sands6dcd49b2011-02-21 16:27:36 +0000525 SmallPtrSet<Instruction*, 4> Visited;
526 for (Instruction *I = PN; areAllUsesEqual(I) && !I->mayHaveSideEffects();
Chandler Carruthcdf47882014-03-09 03:16:01 +0000527 I = cast<Instruction>(*I->user_begin())) {
Duncan Sands6dcd49b2011-02-21 16:27:36 +0000528 if (I->use_empty())
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000529 return RecursivelyDeleteTriviallyDeadInstructions(I, TLI);
Nick Lewycky183c24c2011-02-20 18:05:56 +0000530
Duncan Sands6dcd49b2011-02-21 16:27:36 +0000531 // If we find an instruction more than once, we're on a cycle that
Dan Gohmanff089952009-05-02 18:29:22 +0000532 // won't prove fruitful.
David Blaikie70573dc2014-11-19 07:49:26 +0000533 if (!Visited.insert(I).second) {
Duncan Sands6dcd49b2011-02-21 16:27:36 +0000534 // Break the cycle and delete the instruction and its operands.
535 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000536 (void)RecursivelyDeleteTriviallyDeadInstructions(I, TLI);
Duncan Sandsecbbf082011-02-21 17:32:05 +0000537 return true;
Duncan Sands6dcd49b2011-02-21 16:27:36 +0000538 }
539 }
540 return false;
Dan Gohmanff089952009-05-02 18:29:22 +0000541}
Chris Lattnerc6c481c2008-11-27 22:57:53 +0000542
Fiona Glaserf74cc402015-09-28 18:56:07 +0000543static bool
544simplifyAndDCEInstruction(Instruction *I,
545 SmallSetVector<Instruction *, 16> &WorkList,
546 const DataLayout &DL,
547 const TargetLibraryInfo *TLI) {
548 if (isInstructionTriviallyDead(I, TLI)) {
Vedant Kumarf69baf62018-03-02 22:46:48 +0000549 salvageDebugInfo(*I);
550
Fiona Glaserf74cc402015-09-28 18:56:07 +0000551 // Null out all of the instruction's operands to see if any operand becomes
552 // dead as we go.
553 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
554 Value *OpV = I->getOperand(i);
555 I->setOperand(i, nullptr);
556
557 if (!OpV->use_empty() || I == OpV)
558 continue;
559
560 // If the operand is an instruction that became dead as we nulled out the
561 // operand, and if it is 'trivially' dead, delete it in a future loop
562 // iteration.
563 if (Instruction *OpI = dyn_cast<Instruction>(OpV))
564 if (isInstructionTriviallyDead(OpI, TLI))
565 WorkList.insert(OpI);
566 }
567
568 I->eraseFromParent();
569
570 return true;
571 }
572
573 if (Value *SimpleV = SimplifyInstruction(I, DL)) {
574 // Add the users to the worklist. CAREFUL: an instruction can use itself,
575 // in the case of a phi node.
David Majnemerb8da3a22016-06-25 00:04:10 +0000576 for (User *U : I->users()) {
577 if (U != I) {
Fiona Glaserf74cc402015-09-28 18:56:07 +0000578 WorkList.insert(cast<Instruction>(U));
David Majnemerb8da3a22016-06-25 00:04:10 +0000579 }
580 }
Fiona Glaserf74cc402015-09-28 18:56:07 +0000581
582 // Replace the instruction with its simplified value.
David Majnemerb8da3a22016-06-25 00:04:10 +0000583 bool Changed = false;
584 if (!I->use_empty()) {
585 I->replaceAllUsesWith(SimpleV);
586 Changed = true;
587 }
588 if (isInstructionTriviallyDead(I, TLI)) {
589 I->eraseFromParent();
590 Changed = true;
591 }
592 return Changed;
Fiona Glaserf74cc402015-09-28 18:56:07 +0000593 }
594 return false;
595}
596
Chris Lattner7c743f22010-01-12 19:40:54 +0000597/// SimplifyInstructionsInBlock - Scan the specified basic block and try to
598/// simplify any instructions in it and recursively delete dead instructions.
599///
600/// This returns true if it changed the code, note that it can delete
601/// instructions in other blocks as well in this block.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000602bool llvm::SimplifyInstructionsInBlock(BasicBlock *BB,
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000603 const TargetLibraryInfo *TLI) {
Chris Lattner7c743f22010-01-12 19:40:54 +0000604 bool MadeChange = false;
Fiona Glaserf74cc402015-09-28 18:56:07 +0000605 const DataLayout &DL = BB->getModule()->getDataLayout();
Chandler Carruth0c72e3f2012-03-25 03:29:25 +0000606
607#ifndef NDEBUG
608 // In debug builds, ensure that the terminator of the block is never replaced
609 // or deleted by these simplifications. The idea of simplification is that it
610 // cannot introduce new instructions, and there is no way to replace the
611 // terminator of a block without introducing a new instruction.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000612 AssertingVH<Instruction> TerminatorVH(&BB->back());
Chandler Carruth0c72e3f2012-03-25 03:29:25 +0000613#endif
614
Fiona Glaserf74cc402015-09-28 18:56:07 +0000615 SmallSetVector<Instruction *, 16> WorkList;
616 // Iterate over the original function, only adding insts to the worklist
617 // if they actually need to be revisited. This avoids having to pre-init
618 // the worklist with the entire function's worth of instructions.
Chad Rosier56def252016-05-21 21:12:06 +0000619 for (BasicBlock::iterator BI = BB->begin(), E = std::prev(BB->end());
620 BI != E;) {
Chandler Carruth17fc6ef2012-03-24 23:03:27 +0000621 assert(!BI->isTerminator());
Fiona Glaserf74cc402015-09-28 18:56:07 +0000622 Instruction *I = &*BI;
623 ++BI;
Chandler Carruthcf1b5852012-03-24 21:11:24 +0000624
Fiona Glaserf74cc402015-09-28 18:56:07 +0000625 // We're visiting this instruction now, so make sure it's not in the
626 // worklist from an earlier visit.
627 if (!WorkList.count(I))
628 MadeChange |= simplifyAndDCEInstruction(I, WorkList, DL, TLI);
629 }
Eli Friedman17bf4922011-04-02 22:45:17 +0000630
Fiona Glaserf74cc402015-09-28 18:56:07 +0000631 while (!WorkList.empty()) {
632 Instruction *I = WorkList.pop_back_val();
633 MadeChange |= simplifyAndDCEInstruction(I, WorkList, DL, TLI);
Chris Lattner7c743f22010-01-12 19:40:54 +0000634 }
635 return MadeChange;
636}
637
Chris Lattner99d68092008-11-27 07:43:12 +0000638//===----------------------------------------------------------------------===//
Chris Lattner852d6d62009-11-10 22:26:15 +0000639// Control Flow Graph Restructuring.
Chris Lattner99d68092008-11-27 07:43:12 +0000640//
641
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +0000642void llvm::RemovePredecessorAndSimplify(BasicBlock *BB, BasicBlock *Pred,
Chijun Sima21a8b602018-08-03 05:08:17 +0000643 DomTreeUpdater *DTU) {
Chris Lattner852d6d62009-11-10 22:26:15 +0000644 // This only adjusts blocks with PHI nodes.
645 if (!isa<PHINode>(BB->begin()))
646 return;
Jakub Staszak8e1a6e72013-07-22 23:16:36 +0000647
Chris Lattner852d6d62009-11-10 22:26:15 +0000648 // Remove the entries for Pred from the PHI nodes in BB, but do not simplify
649 // them down. This will leave us with single entry phi nodes and other phis
650 // that can be removed.
651 BB->removePredecessor(Pred, true);
Jakub Staszak8e1a6e72013-07-22 23:16:36 +0000652
Sanjoy Dase6bca0e2017-05-01 17:07:49 +0000653 WeakTrackingVH PhiIt = &BB->front();
Chris Lattner852d6d62009-11-10 22:26:15 +0000654 while (PHINode *PN = dyn_cast<PHINode>(PhiIt)) {
655 PhiIt = &*++BasicBlock::iterator(cast<Instruction>(PhiIt));
Chris Lattnere41ab072010-07-15 06:06:04 +0000656 Value *OldPhiIt = PhiIt;
Chandler Carruthcf1b5852012-03-24 21:11:24 +0000657
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000658 if (!recursivelySimplifyInstruction(PN))
Chandler Carruthcf1b5852012-03-24 21:11:24 +0000659 continue;
660
Chris Lattner852d6d62009-11-10 22:26:15 +0000661 // If recursive simplification ended up deleting the next PHI node we would
662 // iterate to, then our iterator is invalid, restart scanning from the top
663 // of the block.
Chris Lattnere41ab072010-07-15 06:06:04 +0000664 if (PhiIt != OldPhiIt) PhiIt = &BB->front();
Chris Lattner852d6d62009-11-10 22:26:15 +0000665 }
Chijun Sima21a8b602018-08-03 05:08:17 +0000666 if (DTU)
Chijun Sima70e97162019-02-22 13:48:38 +0000667 DTU->applyUpdatesPermissive({{DominatorTree::Delete, Pred, BB}});
Chris Lattner852d6d62009-11-10 22:26:15 +0000668}
669
Chijun Sima21a8b602018-08-03 05:08:17 +0000670void llvm::MergeBasicBlockIntoOnlyPred(BasicBlock *DestBB,
671 DomTreeUpdater *DTU) {
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +0000672
Chris Lattner99d68092008-11-27 07:43:12 +0000673 // If BB has single-entry PHI nodes, fold them.
674 while (PHINode *PN = dyn_cast<PHINode>(DestBB->begin())) {
675 Value *NewVal = PN->getIncomingValue(0);
676 // Replace self referencing PHI with undef, it must be dead.
Owen Andersonb292b8c2009-07-30 23:03:37 +0000677 if (NewVal == PN) NewVal = UndefValue::get(PN->getType());
Chris Lattner99d68092008-11-27 07:43:12 +0000678 PN->replaceAllUsesWith(NewVal);
679 PN->eraseFromParent();
680 }
Jakub Staszak8e1a6e72013-07-22 23:16:36 +0000681
Chris Lattner99d68092008-11-27 07:43:12 +0000682 BasicBlock *PredBB = DestBB->getSinglePredecessor();
683 assert(PredBB && "Block doesn't have a single predecessor!");
Jakub Staszak8e1a6e72013-07-22 23:16:36 +0000684
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +0000685 bool ReplaceEntryBB = false;
686 if (PredBB == &DestBB->getParent()->getEntryBlock())
687 ReplaceEntryBB = true;
688
Chijun Sima21a8b602018-08-03 05:08:17 +0000689 // DTU updates: Collect all the edges that enter
690 // PredBB. These dominator edges will be redirected to DestBB.
Vedant Kumar4de31bb2018-11-19 19:54:27 +0000691 SmallVector<DominatorTree::UpdateType, 32> Updates;
Chijun Sima21a8b602018-08-03 05:08:17 +0000692
693 if (DTU) {
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +0000694 Updates.push_back({DominatorTree::Delete, PredBB, DestBB});
695 for (auto I = pred_begin(PredBB), E = pred_end(PredBB); I != E; ++I) {
696 Updates.push_back({DominatorTree::Delete, *I, PredBB});
697 // This predecessor of PredBB may already have DestBB as a successor.
698 if (llvm::find(successors(*I), DestBB) == succ_end(*I))
699 Updates.push_back({DominatorTree::Insert, *I, DestBB});
700 }
701 }
702
Chris Lattner6fbfe582010-02-15 20:47:49 +0000703 // Zap anything that took the address of DestBB. Not doing this will give the
704 // address an invalid value.
705 if (DestBB->hasAddressTaken()) {
706 BlockAddress *BA = BlockAddress::get(DestBB);
707 Constant *Replacement =
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000708 ConstantInt::get(Type::getInt32Ty(BA->getContext()), 1);
Chris Lattner6fbfe582010-02-15 20:47:49 +0000709 BA->replaceAllUsesWith(ConstantExpr::getIntToPtr(Replacement,
710 BA->getType()));
711 BA->destroyConstant();
712 }
Jakub Staszak8e1a6e72013-07-22 23:16:36 +0000713
Chris Lattner99d68092008-11-27 07:43:12 +0000714 // Anything that branched to PredBB now branches to DestBB.
715 PredBB->replaceAllUsesWith(DestBB);
Jakub Staszak8e1a6e72013-07-22 23:16:36 +0000716
Jay Foad61ea0e42011-06-23 09:09:15 +0000717 // Splice all the instructions from PredBB to DestBB.
718 PredBB->getTerminator()->eraseFromParent();
Bill Wendling90dd90a2013-10-21 04:09:17 +0000719 DestBB->getInstList().splice(DestBB->begin(), PredBB->getInstList());
Chijun Sima21a8b602018-08-03 05:08:17 +0000720 new UnreachableInst(PredBB->getContext(), PredBB);
Jay Foad61ea0e42011-06-23 09:09:15 +0000721
Owen Andersona8d1c3e2014-07-12 07:12:47 +0000722 // If the PredBB is the entry block of the function, move DestBB up to
723 // become the entry block after we erase PredBB.
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +0000724 if (ReplaceEntryBB)
Owen Andersona8d1c3e2014-07-12 07:12:47 +0000725 DestBB->moveAfter(PredBB);
Evandro Menezes3701df52017-09-28 17:24:40 +0000726
Chijun Sima21a8b602018-08-03 05:08:17 +0000727 if (DTU) {
728 assert(PredBB->getInstList().size() == 1 &&
729 isa<UnreachableInst>(PredBB->getTerminator()) &&
730 "The successor list of PredBB isn't empty before "
731 "applying corresponding DTU updates.");
Chijun Sima70e97162019-02-22 13:48:38 +0000732 DTU->applyUpdatesPermissive(Updates);
Chijun Sima21a8b602018-08-03 05:08:17 +0000733 DTU->deleteBB(PredBB);
734 // Recalculation of DomTree is needed when updating a forward DomTree and
735 // the Entry BB is replaced.
736 if (ReplaceEntryBB && DTU->hasDomTree()) {
737 // The entry block was removed and there is no external interface for
738 // the dominator tree to be notified of this change. In this corner-case
739 // we recalculate the entire tree.
740 DTU->recalculate(*(DestBB->getParent()));
Balaram Makam9ee942f2017-10-26 15:04:53 +0000741 }
Evandro Menezes3701df52017-09-28 17:24:40 +0000742 }
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +0000743
Chijun Sima21a8b602018-08-03 05:08:17 +0000744 else {
745 PredBB->eraseFromParent(); // Nuke BB if DTU is nullptr.
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +0000746 }
Chris Lattner99d68092008-11-27 07:43:12 +0000747}
Devang Patelcaf44852009-02-10 07:00:59 +0000748
Sanjay Patel38a02002019-07-25 13:11:21 +0000749/// Return true if we can choose one of these values to use in place of the
750/// other. Note that we will always choose the non-undef value to keep.
Duncan Sandse773c082013-07-11 08:28:20 +0000751static bool CanMergeValues(Value *First, Value *Second) {
752 return First == Second || isa<UndefValue>(First) || isa<UndefValue>(Second);
753}
754
Sanjay Patel38a02002019-07-25 13:11:21 +0000755/// Return true if we can fold BB, an almost-empty BB ending in an unconditional
756/// branch to Succ, into Succ.
Chris Lattnercbd18fc2009-11-10 05:59:26 +0000757///
758/// Assumption: Succ is the single successor for BB.
Chris Lattnercbd18fc2009-11-10 05:59:26 +0000759static bool CanPropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
760 assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");
761
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000762 LLVM_DEBUG(dbgs() << "Looking to fold " << BB->getName() << " into "
763 << Succ->getName() << "\n");
Chris Lattnercbd18fc2009-11-10 05:59:26 +0000764 // Shortcut, if there is only a single predecessor it must be BB and merging
765 // is always safe
766 if (Succ->getSinglePredecessor()) return true;
767
768 // Make a list of the predecessors of BB
Benjamin Kramerb5188f12011-12-06 16:14:29 +0000769 SmallPtrSet<BasicBlock*, 16> BBPreds(pred_begin(BB), pred_end(BB));
Chris Lattnercbd18fc2009-11-10 05:59:26 +0000770
Chris Lattnercbd18fc2009-11-10 05:59:26 +0000771 // Look at all the phi nodes in Succ, to see if they present a conflict when
772 // merging these blocks
773 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
774 PHINode *PN = cast<PHINode>(I);
775
776 // If the incoming value from BB is again a PHINode in
777 // BB which has the same incoming value for *PI as PN does, we can
778 // merge the phi nodes and then the blocks can still be merged
779 PHINode *BBPN = dyn_cast<PHINode>(PN->getIncomingValueForBlock(BB));
780 if (BBPN && BBPN->getParent() == BB) {
Benjamin Kramerb5188f12011-12-06 16:14:29 +0000781 for (unsigned PI = 0, PE = PN->getNumIncomingValues(); PI != PE; ++PI) {
782 BasicBlock *IBB = PN->getIncomingBlock(PI);
783 if (BBPreds.count(IBB) &&
Duncan Sandse773c082013-07-11 08:28:20 +0000784 !CanMergeValues(BBPN->getIncomingValueForBlock(IBB),
785 PN->getIncomingValue(PI))) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000786 LLVM_DEBUG(dbgs()
787 << "Can't fold, phi node " << PN->getName() << " in "
788 << Succ->getName() << " is conflicting with "
789 << BBPN->getName() << " with regard to common predecessor "
790 << IBB->getName() << "\n");
Chris Lattnercbd18fc2009-11-10 05:59:26 +0000791 return false;
792 }
793 }
794 } else {
795 Value* Val = PN->getIncomingValueForBlock(BB);
Benjamin Kramerb5188f12011-12-06 16:14:29 +0000796 for (unsigned PI = 0, PE = PN->getNumIncomingValues(); PI != PE; ++PI) {
Chris Lattnercbd18fc2009-11-10 05:59:26 +0000797 // See if the incoming value for the common predecessor is equal to the
798 // one for BB, in which case this phi node will not prevent the merging
799 // of the block.
Benjamin Kramerb5188f12011-12-06 16:14:29 +0000800 BasicBlock *IBB = PN->getIncomingBlock(PI);
Duncan Sandse773c082013-07-11 08:28:20 +0000801 if (BBPreds.count(IBB) &&
802 !CanMergeValues(Val, PN->getIncomingValue(PI))) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000803 LLVM_DEBUG(dbgs() << "Can't fold, phi node " << PN->getName()
804 << " in " << Succ->getName()
805 << " is conflicting with regard to common "
806 << "predecessor " << IBB->getName() << "\n");
Chris Lattnercbd18fc2009-11-10 05:59:26 +0000807 return false;
808 }
809 }
810 }
811 }
812
813 return true;
814}
815
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000816using PredBlockVector = SmallVector<BasicBlock *, 16>;
817using IncomingValueMap = DenseMap<BasicBlock *, Value *>;
Duncan Sandse773c082013-07-11 08:28:20 +0000818
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000819/// Determines the value to use as the phi node input for a block.
Duncan Sandse773c082013-07-11 08:28:20 +0000820///
821/// Select between \p OldVal any value that we know flows from \p BB
822/// to a particular phi on the basis of which one (if either) is not
823/// undef. Update IncomingValues based on the selected value.
824///
825/// \param OldVal The value we are considering selecting.
826/// \param BB The block that the value flows in from.
827/// \param IncomingValues A map from block-to-value for other phi inputs
828/// that we have examined.
829///
830/// \returns the selected value.
831static Value *selectIncomingValueForBlock(Value *OldVal, BasicBlock *BB,
832 IncomingValueMap &IncomingValues) {
833 if (!isa<UndefValue>(OldVal)) {
834 assert((!IncomingValues.count(BB) ||
835 IncomingValues.find(BB)->second == OldVal) &&
836 "Expected OldVal to match incoming value from BB!");
837
838 IncomingValues.insert(std::make_pair(BB, OldVal));
839 return OldVal;
840 }
841
842 IncomingValueMap::const_iterator It = IncomingValues.find(BB);
843 if (It != IncomingValues.end()) return It->second;
844
845 return OldVal;
846}
847
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000848/// Create a map from block to value for the operands of a
Duncan Sandse773c082013-07-11 08:28:20 +0000849/// given phi.
850///
851/// Create a map from block to value for each non-undef value flowing
852/// into \p PN.
853///
854/// \param PN The phi we are collecting the map for.
855/// \param IncomingValues [out] The map from block to value for this phi.
856static void gatherIncomingValuesToPhi(PHINode *PN,
857 IncomingValueMap &IncomingValues) {
858 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
859 BasicBlock *BB = PN->getIncomingBlock(i);
860 Value *V = PN->getIncomingValue(i);
861
862 if (!isa<UndefValue>(V))
863 IncomingValues.insert(std::make_pair(BB, V));
864 }
865}
866
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000867/// Replace the incoming undef values to a phi with the values
Duncan Sandse773c082013-07-11 08:28:20 +0000868/// from a block-to-value map.
869///
870/// \param PN The phi we are replacing the undefs in.
871/// \param IncomingValues A map from block to value.
872static void replaceUndefValuesInPhi(PHINode *PN,
873 const IncomingValueMap &IncomingValues) {
874 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
875 Value *V = PN->getIncomingValue(i);
876
877 if (!isa<UndefValue>(V)) continue;
878
879 BasicBlock *BB = PN->getIncomingBlock(i);
880 IncomingValueMap::const_iterator It = IncomingValues.find(BB);
881 if (It == IncomingValues.end()) continue;
882
883 PN->setIncomingValue(i, It->second);
884 }
885}
886
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000887/// Replace a value flowing from a block to a phi with
Duncan Sandse773c082013-07-11 08:28:20 +0000888/// potentially multiple instances of that value flowing from the
889/// block's predecessors to the phi.
890///
891/// \param BB The block with the value flowing into the phi.
892/// \param BBPreds The predecessors of BB.
893/// \param PN The phi that we are updating.
894static void redirectValuesFromPredecessorsToPhi(BasicBlock *BB,
895 const PredBlockVector &BBPreds,
896 PHINode *PN) {
897 Value *OldVal = PN->removeIncomingValue(BB, false);
898 assert(OldVal && "No entry in PHI for Pred BB!");
899
900 IncomingValueMap IncomingValues;
901
902 // We are merging two blocks - BB, and the block containing PN - and
903 // as a result we need to redirect edges from the predecessors of BB
904 // to go to the block containing PN, and update PN
905 // accordingly. Since we allow merging blocks in the case where the
906 // predecessor and successor blocks both share some predecessors,
907 // and where some of those common predecessors might have undef
908 // values flowing into PN, we want to rewrite those values to be
909 // consistent with the non-undef values.
910
911 gatherIncomingValuesToPhi(PN, IncomingValues);
912
913 // If this incoming value is one of the PHI nodes in BB, the new entries
914 // in the PHI node are the entries from the old PHI.
915 if (isa<PHINode>(OldVal) && cast<PHINode>(OldVal)->getParent() == BB) {
916 PHINode *OldValPN = cast<PHINode>(OldVal);
917 for (unsigned i = 0, e = OldValPN->getNumIncomingValues(); i != e; ++i) {
918 // Note that, since we are merging phi nodes and BB and Succ might
919 // have common predecessors, we could end up with a phi node with
920 // identical incoming branches. This will be cleaned up later (and
921 // will trigger asserts if we try to clean it up now, without also
922 // simplifying the corresponding conditional branch).
923 BasicBlock *PredBB = OldValPN->getIncomingBlock(i);
924 Value *PredVal = OldValPN->getIncomingValue(i);
925 Value *Selected = selectIncomingValueForBlock(PredVal, PredBB,
926 IncomingValues);
927
928 // And add a new incoming value for this predecessor for the
929 // newly retargeted branch.
930 PN->addIncoming(Selected, PredBB);
931 }
932 } else {
933 for (unsigned i = 0, e = BBPreds.size(); i != e; ++i) {
934 // Update existing incoming values in PN for this
935 // predecessor of BB.
936 BasicBlock *PredBB = BBPreds[i];
937 Value *Selected = selectIncomingValueForBlock(OldVal, PredBB,
938 IncomingValues);
939
940 // And add a new incoming value for this predecessor for the
941 // newly retargeted branch.
942 PN->addIncoming(Selected, PredBB);
943 }
944 }
945
946 replaceUndefValuesInPhi(PN, IncomingValues);
947}
948
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +0000949bool llvm::TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB,
Chijun Sima21a8b602018-08-03 05:08:17 +0000950 DomTreeUpdater *DTU) {
Dan Gohman4a63fad2010-08-14 00:29:42 +0000951 assert(BB != &BB->getParent()->getEntryBlock() &&
952 "TryToSimplifyUncondBranchFromEmptyBlock called on entry block!");
953
Chris Lattnercbd18fc2009-11-10 05:59:26 +0000954 // We can't eliminate infinite loops.
955 BasicBlock *Succ = cast<BranchInst>(BB->getTerminator())->getSuccessor(0);
956 if (BB == Succ) return false;
Jakub Staszak8e1a6e72013-07-22 23:16:36 +0000957
Reid Klecknerbca59d22016-05-02 19:43:22 +0000958 // Check to see if merging these blocks would cause conflicts for any of the
959 // phi nodes in BB or Succ. If not, we can safely merge.
960 if (!CanPropagatePredecessorsForPHIs(BB, Succ)) return false;
Chris Lattnercbd18fc2009-11-10 05:59:26 +0000961
Reid Klecknerbca59d22016-05-02 19:43:22 +0000962 // Check for cases where Succ has multiple predecessors and a PHI node in BB
963 // has uses which will not disappear when the PHI nodes are merged. It is
964 // possible to handle such cases, but difficult: it requires checking whether
965 // BB dominates Succ, which is non-trivial to calculate in the case where
966 // Succ has multiple predecessors. Also, it requires checking whether
967 // constructing the necessary self-referential PHI node doesn't introduce any
968 // conflicts; this isn't too difficult, but the previous code for doing this
969 // was incorrect.
970 //
971 // Note that if this check finds a live use, BB dominates Succ, so BB is
972 // something like a loop pre-header (or rarely, a part of an irreducible CFG);
973 // folding the branch isn't profitable in that case anyway.
974 if (!Succ->getSinglePredecessor()) {
975 BasicBlock::iterator BBI = BB->begin();
976 while (isa<PHINode>(*BBI)) {
977 for (Use &U : BBI->uses()) {
978 if (PHINode* PN = dyn_cast<PHINode>(U.getUser())) {
979 if (PN->getIncomingBlock(U) != BB)
Hans Wennborgb7599322016-05-02 17:22:54 +0000980 return false;
Reid Klecknerbca59d22016-05-02 19:43:22 +0000981 } else {
982 return false;
Hans Wennborgb7599322016-05-02 17:22:54 +0000983 }
Hans Wennborgb7599322016-05-02 17:22:54 +0000984 }
Reid Klecknerbca59d22016-05-02 19:43:22 +0000985 ++BBI;
Hans Wennborgb7599322016-05-02 17:22:54 +0000986 }
Hans Wennborgb7599322016-05-02 17:22:54 +0000987 }
Reid Klecknerbca59d22016-05-02 19:43:22 +0000988
Craig Topper784929d2019-02-08 20:48:56 +0000989 // We cannot fold the block if it's a branch to an already present callbr
990 // successor because that creates duplicate successors.
991 for (auto I = pred_begin(BB), E = pred_end(BB); I != E; ++I) {
992 if (auto *CBI = dyn_cast<CallBrInst>((*I)->getTerminator())) {
993 if (Succ == CBI->getDefaultDest())
994 return false;
995 for (unsigned i = 0, e = CBI->getNumIndirectDests(); i != e; ++i)
996 if (Succ == CBI->getIndirectDest(i))
997 return false;
998 }
999 }
1000
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001001 LLVM_DEBUG(dbgs() << "Killing Trivial BB: \n" << *BB);
Reid Klecknerbca59d22016-05-02 19:43:22 +00001002
Vedant Kumar4de31bb2018-11-19 19:54:27 +00001003 SmallVector<DominatorTree::UpdateType, 32> Updates;
Chijun Sima21a8b602018-08-03 05:08:17 +00001004 if (DTU) {
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +00001005 Updates.push_back({DominatorTree::Delete, BB, Succ});
1006 // All predecessors of BB will be moved to Succ.
1007 for (auto I = pred_begin(BB), E = pred_end(BB); I != E; ++I) {
1008 Updates.push_back({DominatorTree::Delete, *I, BB});
1009 // This predecessor of BB may already have Succ as a successor.
1010 if (llvm::find(successors(*I), Succ) == succ_end(*I))
1011 Updates.push_back({DominatorTree::Insert, *I, Succ});
1012 }
1013 }
1014
Reid Klecknerbca59d22016-05-02 19:43:22 +00001015 if (isa<PHINode>(Succ->begin())) {
1016 // If there is more than one pred of succ, and there are PHI nodes in
1017 // the successor, then we need to add incoming edges for the PHI nodes
1018 //
1019 const PredBlockVector BBPreds(pred_begin(BB), pred_end(BB));
1020
1021 // Loop over all of the PHI nodes in the successor of BB.
1022 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
1023 PHINode *PN = cast<PHINode>(I);
1024
1025 redirectValuesFromPredecessorsToPhi(BB, BBPreds, PN);
1026 }
1027 }
1028
1029 if (Succ->getSinglePredecessor()) {
1030 // BB is the only predecessor of Succ, so Succ will end up with exactly
1031 // the same predecessors BB had.
1032
1033 // Copy over any phi, debug or lifetime instruction.
1034 BB->getTerminator()->eraseFromParent();
1035 Succ->getInstList().splice(Succ->getFirstNonPHI()->getIterator(),
1036 BB->getInstList());
1037 } else {
1038 while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
1039 // We explicitly check for such uses in CanPropagatePredecessorsForPHIs.
1040 assert(PN->use_empty() && "There shouldn't be any uses here!");
1041 PN->eraseFromParent();
1042 }
1043 }
1044
Florian Hahn77382be2016-11-18 13:12:07 +00001045 // If the unconditional branch we replaced contains llvm.loop metadata, we
1046 // add the metadata to the branch instructions in the predecessors.
1047 unsigned LoopMDKind = BB->getContext().getMDKindID("llvm.loop");
1048 Instruction *TI = BB->getTerminator();
Daniel Jasper0a51ec22017-09-30 11:57:19 +00001049 if (TI)
Florian Hahn77382be2016-11-18 13:12:07 +00001050 if (MDNode *LoopMD = TI->getMetadata(LoopMDKind))
1051 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
1052 BasicBlock *Pred = *PI;
1053 Pred->getTerminator()->setMetadata(LoopMDKind, LoopMD);
1054 }
1055
Reid Klecknerbca59d22016-05-02 19:43:22 +00001056 // Everything that jumped to BB now goes to Succ.
1057 BB->replaceAllUsesWith(Succ);
1058 if (!Succ->hasName()) Succ->takeName(BB);
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +00001059
Chijun Sima21a8b602018-08-03 05:08:17 +00001060 // Clear the successor list of BB to match updates applying to DTU later.
1061 if (BB->getTerminator())
1062 BB->getInstList().pop_back();
1063 new UnreachableInst(BB->getContext(), BB);
1064 assert(succ_empty(BB) && "The successor list of BB isn't empty before "
1065 "applying corresponding DTU updates.");
1066
1067 if (DTU) {
Chijun Sima70e97162019-02-22 13:48:38 +00001068 DTU->applyUpdatesPermissive(Updates);
Chijun Sima21a8b602018-08-03 05:08:17 +00001069 DTU->deleteBB(BB);
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +00001070 } else {
1071 BB->eraseFromParent(); // Delete the old basic block.
1072 }
Reid Klecknerbca59d22016-05-02 19:43:22 +00001073 return true;
Chris Lattnercbd18fc2009-11-10 05:59:26 +00001074}
1075
Jim Grosbachd831ef42009-12-02 17:06:45 +00001076bool llvm::EliminateDuplicatePHINodes(BasicBlock *BB) {
Jim Grosbachd831ef42009-12-02 17:06:45 +00001077 // This implementation doesn't currently consider undef operands
Nick Lewyckyfa44dc62011-06-28 03:57:31 +00001078 // specially. Theoretically, two phis which are identical except for
Jim Grosbachd831ef42009-12-02 17:06:45 +00001079 // one having an undef where the other doesn't could be collapsed.
1080
Benjamin Kramer2b2cdd72015-06-18 16:01:00 +00001081 struct PHIDenseMapInfo {
1082 static PHINode *getEmptyKey() {
1083 return DenseMapInfo<PHINode *>::getEmptyKey();
1084 }
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001085
Benjamin Kramer2b2cdd72015-06-18 16:01:00 +00001086 static PHINode *getTombstoneKey() {
1087 return DenseMapInfo<PHINode *>::getTombstoneKey();
1088 }
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001089
Benjamin Kramer2b2cdd72015-06-18 16:01:00 +00001090 static unsigned getHashValue(PHINode *PN) {
1091 // Compute a hash value on the operands. Instcombine will likely have
1092 // sorted them, which helps expose duplicates, but we have to check all
1093 // the operands to be safe in case instcombine hasn't run.
1094 return static_cast<unsigned>(hash_combine(
1095 hash_combine_range(PN->value_op_begin(), PN->value_op_end()),
1096 hash_combine_range(PN->block_begin(), PN->block_end())));
1097 }
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001098
Benjamin Kramer2b2cdd72015-06-18 16:01:00 +00001099 static bool isEqual(PHINode *LHS, PHINode *RHS) {
1100 if (LHS == getEmptyKey() || LHS == getTombstoneKey() ||
1101 RHS == getEmptyKey() || RHS == getTombstoneKey())
1102 return LHS == RHS;
1103 return LHS->isIdenticalTo(RHS);
1104 }
1105 };
Jim Grosbachd831ef42009-12-02 17:06:45 +00001106
Benjamin Kramer2b2cdd72015-06-18 16:01:00 +00001107 // Set of unique PHINodes.
1108 DenseSet<PHINode *, PHIDenseMapInfo> PHISet;
Jim Grosbachd831ef42009-12-02 17:06:45 +00001109
1110 // Examine each PHI.
Benjamin Kramer2b2cdd72015-06-18 16:01:00 +00001111 bool Changed = false;
1112 for (auto I = BB->begin(); PHINode *PN = dyn_cast<PHINode>(I++);) {
1113 auto Inserted = PHISet.insert(PN);
1114 if (!Inserted.second) {
1115 // A duplicate. Replace this PHI with its duplicate.
1116 PN->replaceAllUsesWith(*Inserted.first);
1117 PN->eraseFromParent();
1118 Changed = true;
Benjamin Kramerf175e042015-09-02 19:52:23 +00001119
1120 // The RAUW can change PHIs that we already visited. Start over from the
1121 // beginning.
1122 PHISet.clear();
1123 I = BB->begin();
Jim Grosbachd831ef42009-12-02 17:06:45 +00001124 }
1125 }
1126
1127 return Changed;
1128}
Chris Lattner6fcd32e2010-12-25 20:37:57 +00001129
1130/// enforceKnownAlignment - If the specified pointer points to an object that
1131/// we control, modify the object's alignment to PrefAlign. This isn't
1132/// often possible though. If alignment is important, a more reliable approach
1133/// is to simply align all global variables and allocation instructions to
1134/// their preferred alignment from the beginning.
Benjamin Kramer570dd782010-12-30 22:34:44 +00001135static unsigned enforceKnownAlignment(Value *V, unsigned Align,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001136 unsigned PrefAlign,
1137 const DataLayout &DL) {
James Y Knightac03dca2016-01-15 16:33:06 +00001138 assert(PrefAlign > Align);
1139
Eli Friedman19ace4c2011-06-15 21:08:25 +00001140 V = V->stripPointerCasts();
Chris Lattner6fcd32e2010-12-25 20:37:57 +00001141
Eli Friedman19ace4c2011-06-15 21:08:25 +00001142 if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
James Y Knightac03dca2016-01-15 16:33:06 +00001143 // TODO: ideally, computeKnownBits ought to have used
1144 // AllocaInst::getAlignment() in its computation already, making
1145 // the below max redundant. But, as it turns out,
1146 // stripPointerCasts recurses through infinite layers of bitcasts,
1147 // while computeKnownBits is not allowed to traverse more than 6
1148 // levels.
1149 Align = std::max(AI->getAlignment(), Align);
1150 if (PrefAlign <= Align)
1151 return Align;
1152
Lang Hamesde7ab802011-10-10 23:42:08 +00001153 // If the preferred alignment is greater than the natural stack alignment
1154 // then don't round up. This avoids dynamic stack realignment.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001155 if (DL.exceedsNaturalStackAlignment(PrefAlign))
Lang Hamesde7ab802011-10-10 23:42:08 +00001156 return Align;
Chris Lattner6fcd32e2010-12-25 20:37:57 +00001157 AI->setAlignment(PrefAlign);
1158 return PrefAlign;
1159 }
Chris Lattner6fcd32e2010-12-25 20:37:57 +00001160
Rafael Espindola99e05cf2014-05-13 18:45:48 +00001161 if (auto *GO = dyn_cast<GlobalObject>(V)) {
James Y Knightac03dca2016-01-15 16:33:06 +00001162 // TODO: as above, this shouldn't be necessary.
1163 Align = std::max(GO->getAlignment(), Align);
1164 if (PrefAlign <= Align)
1165 return Align;
1166
Chris Lattner6fcd32e2010-12-25 20:37:57 +00001167 // If there is a large requested alignment and we can, bump up the alignment
Reid Kleckner486fa392015-07-14 00:11:08 +00001168 // of the global. If the memory we set aside for the global may not be the
1169 // memory used by the final program then it is impossible for us to reliably
1170 // enforce the preferred alignment.
James Y Knightac03dca2016-01-15 16:33:06 +00001171 if (!GO->canIncreaseAlignment())
Rafael Espindolafc13db42014-05-09 16:01:06 +00001172 return Align;
Jakub Staszak8e1a6e72013-07-22 23:16:36 +00001173
James Y Knightac03dca2016-01-15 16:33:06 +00001174 GO->setAlignment(PrefAlign);
1175 return PrefAlign;
Chris Lattner6fcd32e2010-12-25 20:37:57 +00001176 }
1177
1178 return Align;
1179}
1180
Chris Lattner6fcd32e2010-12-25 20:37:57 +00001181unsigned llvm::getOrEnforceKnownAlignment(Value *V, unsigned PrefAlign,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001182 const DataLayout &DL,
Hal Finkel60db0582014-09-07 18:57:58 +00001183 const Instruction *CxtI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001184 AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001185 const DominatorTree *DT) {
Chris Lattner6fcd32e2010-12-25 20:37:57 +00001186 assert(V->getType()->isPointerTy() &&
1187 "getOrEnforceKnownAlignment expects a pointer!");
Matt Arsenault87dc6072013-08-01 22:42:18 +00001188
Craig Topper8205a1a2017-05-24 16:53:07 +00001189 KnownBits Known = computeKnownBits(V, DL, 0, AC, CxtI, DT);
Craig Topper8df66c62017-05-12 17:20:30 +00001190 unsigned TrailZ = Known.countMinTrailingZeros();
Jakub Staszak8e1a6e72013-07-22 23:16:36 +00001191
Matt Arsenaultf64212b2013-07-23 22:20:57 +00001192 // Avoid trouble with ridiculously large TrailZ values, such as
Chris Lattner6fcd32e2010-12-25 20:37:57 +00001193 // those computed from a null pointer.
1194 TrailZ = std::min(TrailZ, unsigned(sizeof(unsigned) * CHAR_BIT - 1));
Jakub Staszak8e1a6e72013-07-22 23:16:36 +00001195
Craig Topper8205a1a2017-05-24 16:53:07 +00001196 unsigned Align = 1u << std::min(Known.getBitWidth() - 1, TrailZ);
Jakub Staszak8e1a6e72013-07-22 23:16:36 +00001197
Chris Lattner6fcd32e2010-12-25 20:37:57 +00001198 // LLVM doesn't support alignments larger than this currently.
1199 Align = std::min(Align, +Value::MaximumAlignment);
Jakub Staszak8e1a6e72013-07-22 23:16:36 +00001200
Chris Lattner6fcd32e2010-12-25 20:37:57 +00001201 if (PrefAlign > Align)
Matt Arsenault87dc6072013-08-01 22:42:18 +00001202 Align = enforceKnownAlignment(V, Align, PrefAlign, DL);
Jakub Staszak8e1a6e72013-07-22 23:16:36 +00001203
Chris Lattner6fcd32e2010-12-25 20:37:57 +00001204 // We don't need to make any adjustment.
1205 return Align;
1206}
1207
Devang Patel8c0b16b2011-03-17 21:58:19 +00001208///===---------------------------------------------------------------------===//
1209/// Dbg Intrinsic utilities
1210///
1211
Adrian Prantl29b9de72013-04-26 17:48:33 +00001212/// See if there is a dbg.value intrinsic for DIVar before I.
Adrian Prantla5b2a642016-02-17 20:02:25 +00001213static bool LdStHasDebugValue(DILocalVariable *DIVar, DIExpression *DIExpr,
1214 Instruction *I) {
Adrian Prantl29b9de72013-04-26 17:48:33 +00001215 // Since we can't guarantee that the original dbg.declare instrinsic
1216 // is removed by LowerDbgDeclare(), we need to make sure that we are
1217 // not inserting the same dbg.value intrinsic over and over.
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001218 BasicBlock::InstListType::iterator PrevI(I);
Adrian Prantl29b9de72013-04-26 17:48:33 +00001219 if (PrevI != I->getParent()->getInstList().begin()) {
1220 --PrevI;
1221 if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(PrevI))
1222 if (DVI->getValue() == I->getOperand(0) &&
Adrian Prantla5b2a642016-02-17 20:02:25 +00001223 DVI->getVariable() == DIVar &&
1224 DVI->getExpression() == DIExpr)
Adrian Prantl29b9de72013-04-26 17:48:33 +00001225 return true;
1226 }
1227 return false;
1228}
1229
Keith Walkerba159892016-09-22 14:13:25 +00001230/// See if there is a dbg.value intrinsic for DIVar for the PHI node.
Chandler Carruth2abb65a2017-06-26 03:31:31 +00001231static bool PhiHasDebugValue(DILocalVariable *DIVar,
Keith Walkerba159892016-09-22 14:13:25 +00001232 DIExpression *DIExpr,
1233 PHINode *APN) {
1234 // 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.
Adrian Prantlfa9e84e2017-03-16 20:11:54 +00001237 SmallVector<DbgValueInst *, 1> DbgValues;
1238 findDbgValues(DbgValues, APN);
1239 for (auto *DVI : DbgValues) {
1240 assert(DVI->getValue() == APN);
Adrian Prantlfa9e84e2017-03-16 20:11:54 +00001241 if ((DVI->getVariable() == DIVar) && (DVI->getExpression() == DIExpr))
1242 return true;
1243 }
1244 return false;
Keith Walkerba159892016-09-22 14:13:25 +00001245}
1246
Bjorn Pettersson428caf92018-06-15 13:48:55 +00001247/// Check if the alloc size of \p ValTy is large enough to cover the variable
1248/// (or fragment of the variable) described by \p DII.
1249///
1250/// This is primarily intended as a helper for the different
1251/// ConvertDebugDeclareToDebugValue functions. The dbg.declare/dbg.addr that is
1252/// converted describes an alloca'd variable, so we need to use the
1253/// alloc size of the value when doing the comparison. E.g. an i1 value will be
1254/// identified as covering an n-bit fragment, if the store size of i1 is at
1255/// least n bits.
Hsiangkai Wangef72e482018-08-06 03:59:47 +00001256static bool valueCoversEntireFragment(Type *ValTy, DbgVariableIntrinsic *DII) {
Bjorn Pettersson428caf92018-06-15 13:48:55 +00001257 const DataLayout &DL = DII->getModule()->getDataLayout();
1258 uint64_t ValueSize = DL.getTypeAllocSizeInBits(ValTy);
1259 if (auto FragmentSize = DII->getFragmentSizeInBits())
1260 return ValueSize >= *FragmentSize;
Bjorn Pettersson550517b2018-06-26 06:17:00 +00001261 // We can't always calculate the size of the DI variable (e.g. if it is a
1262 // VLA). Try to use the size of the alloca that the dbg intrinsic describes
1263 // intead.
1264 if (DII->isAddressOfVariable())
1265 if (auto *AI = dyn_cast_or_null<AllocaInst>(DII->getVariableLocation()))
1266 if (auto FragmentSize = AI->getAllocationSizeInBits(DL))
1267 return ValueSize >= *FragmentSize;
1268 // Could not determine size of variable. Conservatively return false.
Bjorn Pettersson428caf92018-06-15 13:48:55 +00001269 return false;
1270}
1271
Jeremy Morsea2b780b2019-05-10 10:03:41 +00001272/// Produce a DebugLoc to use for each dbg.declare/inst pair that are promoted
1273/// to a dbg.value. Because no machine insts can come from debug intrinsics,
1274/// only the scope and inlinedAt is significant. Zero line numbers are used in
1275/// case this DebugLoc leaks into any adjacent instructions.
1276static DebugLoc getDebugValueLoc(DbgVariableIntrinsic *DII, Instruction *Src) {
1277 // Original dbg.declare must have a location.
1278 DebugLoc DeclareLoc = DII->getDebugLoc();
1279 MDNode *Scope = DeclareLoc.getScope();
1280 DILocation *InlinedAt = DeclareLoc.getInlinedAt();
1281 // Produce an unknown location with the correct scope / inlinedAt fields.
1282 return DebugLoc::get(0, 0, Scope, InlinedAt);
1283}
1284
Adrian Prantld00333a2013-04-26 18:10:50 +00001285/// Inserts a llvm.dbg.value intrinsic before a store to an alloca'd value
Reid Kleckner0fe506b2017-09-21 19:52:03 +00001286/// that has an associated llvm.dbg.declare or llvm.dbg.addr intrinsic.
Hsiangkai Wangef72e482018-08-06 03:59:47 +00001287void llvm::ConvertDebugDeclareToDebugValue(DbgVariableIntrinsic *DII,
Devang Patel8c0b16b2011-03-17 21:58:19 +00001288 StoreInst *SI, DIBuilder &Builder) {
Reid Kleckner0fe506b2017-09-21 19:52:03 +00001289 assert(DII->isAddressOfVariable());
1290 auto *DIVar = DII->getVariable();
Duncan P. N. Exon Smithd4a19a32015-04-21 18:24:23 +00001291 assert(DIVar && "Missing variable");
Reid Kleckner0fe506b2017-09-21 19:52:03 +00001292 auto *DIExpr = DII->getExpression();
Brian Gesiak1c44ed82019-04-02 14:57:56 +00001293 Value *DV = SI->getValueOperand();
Devang Patel8c0b16b2011-03-17 21:58:19 +00001294
Jeremy Morsea2b780b2019-05-10 10:03:41 +00001295 DebugLoc NewLoc = getDebugValueLoc(DII, SI);
1296
Brian Gesiak1c44ed82019-04-02 14:57:56 +00001297 if (!valueCoversEntireFragment(DV->getType(), DII)) {
Bjorn Pettersson428caf92018-06-15 13:48:55 +00001298 // FIXME: If storing to a part of the variable described by the dbg.declare,
1299 // then we want to insert a dbg.value for the corresponding fragment.
1300 LLVM_DEBUG(dbgs() << "Failed to convert dbg.declare to dbg.value: "
1301 << *DII << '\n');
1302 // For now, when there is a store to parts of the variable (but we do not
1303 // know which part) we insert an dbg.value instrinsic to indicate that we
1304 // know nothing about the variable's content.
1305 DV = UndefValue::get(DV->getType());
1306 if (!LdStHasDebugValue(DIVar, DIExpr, SI))
Jeremy Morsea2b780b2019-05-10 10:03:41 +00001307 Builder.insertDbgValueIntrinsic(DV, DIVar, DIExpr, NewLoc, SI);
Bjorn Pettersson428caf92018-06-15 13:48:55 +00001308 return;
1309 }
1310
David Blaikie441cfee2017-05-15 21:34:01 +00001311 if (!LdStHasDebugValue(DIVar, DIExpr, SI))
Jeremy Morsea2b780b2019-05-10 10:03:41 +00001312 Builder.insertDbgValueIntrinsic(DV, DIVar, DIExpr, NewLoc, SI);
Devang Patel8c0b16b2011-03-17 21:58:19 +00001313}
1314
Adrian Prantld00333a2013-04-26 18:10:50 +00001315/// Inserts a llvm.dbg.value intrinsic before a load of an alloca'd value
Reid Kleckner0fe506b2017-09-21 19:52:03 +00001316/// that has an associated llvm.dbg.declare or llvm.dbg.addr intrinsic.
Hsiangkai Wangef72e482018-08-06 03:59:47 +00001317void llvm::ConvertDebugDeclareToDebugValue(DbgVariableIntrinsic *DII,
Devang Patel2c7ee272011-03-18 23:45:43 +00001318 LoadInst *LI, DIBuilder &Builder) {
Reid Kleckner0fe506b2017-09-21 19:52:03 +00001319 auto *DIVar = DII->getVariable();
1320 auto *DIExpr = DII->getExpression();
Duncan P. N. Exon Smithd4a19a32015-04-21 18:24:23 +00001321 assert(DIVar && "Missing variable");
Devang Patel2c7ee272011-03-18 23:45:43 +00001322
Adrian Prantla5b2a642016-02-17 20:02:25 +00001323 if (LdStHasDebugValue(DIVar, DIExpr, LI))
Keith Walkerba159892016-09-22 14:13:25 +00001324 return;
Adrian Prantl29b9de72013-04-26 17:48:33 +00001325
Bjorn Pettersson550517b2018-06-26 06:17:00 +00001326 if (!valueCoversEntireFragment(LI->getType(), DII)) {
1327 // FIXME: If only referring to a part of the variable described by the
1328 // dbg.declare, then we want to insert a dbg.value for the corresponding
1329 // fragment.
1330 LLVM_DEBUG(dbgs() << "Failed to convert dbg.declare to dbg.value: "
1331 << *DII << '\n');
1332 return;
1333 }
1334
Jeremy Morsea2b780b2019-05-10 10:03:41 +00001335 DebugLoc NewLoc = getDebugValueLoc(DII, nullptr);
1336
Keno Fischer00cbf9a2015-12-19 02:02:44 +00001337 // We are now tracking the loaded value instead of the address. In the
1338 // future if multi-location support is added to the IR, it might be
1339 // preferable to keep tracking both the loaded value and the original
1340 // address in case the alloca can not be elided.
1341 Instruction *DbgValue = Builder.insertDbgValueIntrinsic(
Jeremy Morsea2b780b2019-05-10 10:03:41 +00001342 LI, DIVar, DIExpr, NewLoc, (Instruction *)nullptr);
Keno Fischer00cbf9a2015-12-19 02:02:44 +00001343 DbgValue->insertAfter(LI);
Keith Walkerba159892016-09-22 14:13:25 +00001344}
1345
Reid Kleckner0fe506b2017-09-21 19:52:03 +00001346/// Inserts a llvm.dbg.value intrinsic after a phi that has an associated
1347/// llvm.dbg.declare or llvm.dbg.addr intrinsic.
Hsiangkai Wangef72e482018-08-06 03:59:47 +00001348void llvm::ConvertDebugDeclareToDebugValue(DbgVariableIntrinsic *DII,
Keith Walkerba159892016-09-22 14:13:25 +00001349 PHINode *APN, DIBuilder &Builder) {
Reid Kleckner0fe506b2017-09-21 19:52:03 +00001350 auto *DIVar = DII->getVariable();
1351 auto *DIExpr = DII->getExpression();
Keith Walkerba159892016-09-22 14:13:25 +00001352 assert(DIVar && "Missing variable");
1353
1354 if (PhiHasDebugValue(DIVar, DIExpr, APN))
1355 return;
1356
Bjorn Pettersson550517b2018-06-26 06:17:00 +00001357 if (!valueCoversEntireFragment(APN->getType(), DII)) {
1358 // FIXME: If only referring to a part of the variable described by the
1359 // dbg.declare, then we want to insert a dbg.value for the corresponding
1360 // fragment.
1361 LLVM_DEBUG(dbgs() << "Failed to convert dbg.declare to dbg.value: "
1362 << *DII << '\n');
1363 return;
1364 }
1365
Reid Kleckner64818222016-09-27 18:45:31 +00001366 BasicBlock *BB = APN->getParent();
Keith Walkerba159892016-09-22 14:13:25 +00001367 auto InsertionPt = BB->getFirstInsertionPt();
Reid Kleckner64818222016-09-27 18:45:31 +00001368
Jeremy Morsea2b780b2019-05-10 10:03:41 +00001369 DebugLoc NewLoc = getDebugValueLoc(DII, nullptr);
1370
Reid Kleckner64818222016-09-27 18:45:31 +00001371 // The block may be a catchswitch block, which does not have a valid
1372 // insertion point.
1373 // FIXME: Insert dbg.value markers in the successors when appropriate.
1374 if (InsertionPt != BB->end())
Jeremy Morsea2b780b2019-05-10 10:03:41 +00001375 Builder.insertDbgValueIntrinsic(APN, DIVar, DIExpr, NewLoc, &*InsertionPt);
Keith Walkerc9412522016-09-19 09:49:30 +00001376}
1377
Adrian Prantl232897f2014-04-25 23:00:25 +00001378/// Determine whether this alloca is either a VLA or an array.
1379static bool isArray(AllocaInst *AI) {
1380 return AI->isArrayAllocation() ||
1381 AI->getType()->getElementType()->isArrayTy();
1382}
1383
Devang Patelaad34d82011-03-17 22:18:16 +00001384/// LowerDbgDeclare - Lowers llvm.dbg.declare intrinsics into appropriate set
1385/// of llvm.dbg.value intrinsics.
1386bool llvm::LowerDbgDeclare(Function &F) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001387 DIBuilder DIB(*F.getParent(), /*AllowUnresolved*/ false);
Devang Patelaad34d82011-03-17 22:18:16 +00001388 SmallVector<DbgDeclareInst *, 4> Dbgs;
Adrian Prantl79c8e8f2014-03-27 23:30:04 +00001389 for (auto &FI : F)
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001390 for (Instruction &BI : FI)
1391 if (auto DDI = dyn_cast<DbgDeclareInst>(&BI))
Devang Patelaad34d82011-03-17 22:18:16 +00001392 Dbgs.push_back(DDI);
Adrian Prantl79c8e8f2014-03-27 23:30:04 +00001393
Devang Patelaad34d82011-03-17 22:18:16 +00001394 if (Dbgs.empty())
1395 return false;
1396
Adrian Prantl79c8e8f2014-03-27 23:30:04 +00001397 for (auto &I : Dbgs) {
1398 DbgDeclareInst *DDI = I;
Adrian Prantl8e10fdb2013-11-18 23:04:38 +00001399 AllocaInst *AI = dyn_cast_or_null<AllocaInst>(DDI->getAddress());
1400 // If this is an alloca for a scalar variable, insert a dbg.value
1401 // at each load and store to the alloca and erase the dbg.declare.
Adrian Prantl32da8892014-04-25 20:49:25 +00001402 // The dbg.values allow tracking a variable even if it is not
1403 // stored on the stack, while the dbg.declare can only describe
1404 // the stack slot (and at a lexical-scope granularity). Later
1405 // passes will attempt to elide the stack slot.
Adrian Prantl5b477be2018-03-09 00:45:04 +00001406 if (!AI || isArray(AI))
1407 continue;
1408
1409 // A volatile load/store means that the alloca can't be elided anyway.
1410 if (llvm::any_of(AI->users(), [](User *U) -> bool {
1411 if (LoadInst *LI = dyn_cast<LoadInst>(U))
1412 return LI->isVolatile();
1413 if (StoreInst *SI = dyn_cast<StoreInst>(U))
1414 return SI->isVolatile();
1415 return false;
1416 }))
1417 continue;
1418
1419 for (auto &AIUse : AI->uses()) {
1420 User *U = AIUse.getUser();
1421 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
1422 if (AIUse.getOperandNo() == 1)
1423 ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
1424 } else if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
1425 ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
1426 } else if (CallInst *CI = dyn_cast<CallInst>(U)) {
Vedant Kumarb572f642018-07-26 20:56:53 +00001427 // This is a call by-value or some other instruction that takes a
1428 // pointer to the variable. Insert a *value* intrinsic that describes
1429 // the variable by dereferencing the alloca.
Jeremy Morsea2b780b2019-05-10 10:03:41 +00001430 DebugLoc NewLoc = getDebugValueLoc(DDI, nullptr);
Vedant Kumarb572f642018-07-26 20:56:53 +00001431 auto *DerefExpr =
1432 DIExpression::append(DDI->getExpression(), dwarf::DW_OP_deref);
Jeremy Morsea2b780b2019-05-10 10:03:41 +00001433 DIB.insertDbgValueIntrinsic(AI, DDI->getVariable(), DerefExpr, NewLoc,
1434 CI);
Keno Fischer1dd319f2016-01-14 19:12:27 +00001435 }
Devang Patelaad34d82011-03-17 22:18:16 +00001436 }
Adrian Prantl5b477be2018-03-09 00:45:04 +00001437 DDI->eraseFromParent();
Devang Patelaad34d82011-03-17 22:18:16 +00001438 }
1439 return true;
1440}
Cameron Zwarich843bc7d2011-05-24 03:10:43 +00001441
Vedant Kumar6bfc8692018-01-25 21:37:05 +00001442/// Propagate dbg.value intrinsics through the newly inserted PHIs.
1443void llvm::insertDebugValuesForPHIs(BasicBlock *BB,
1444 SmallVectorImpl<PHINode *> &InsertedPHIs) {
1445 assert(BB && "No BasicBlock to clone dbg.value(s) from.");
1446 if (InsertedPHIs.size() == 0)
1447 return;
1448
1449 // Map existing PHI nodes to their dbg.values.
1450 ValueToValueMapTy DbgValueMap;
1451 for (auto &I : *BB) {
Hsiangkai Wangef72e482018-08-06 03:59:47 +00001452 if (auto DbgII = dyn_cast<DbgVariableIntrinsic>(&I)) {
Vedant Kumar6bfc8692018-01-25 21:37:05 +00001453 if (auto *Loc = dyn_cast_or_null<PHINode>(DbgII->getVariableLocation()))
1454 DbgValueMap.insert({Loc, DbgII});
1455 }
1456 }
1457 if (DbgValueMap.size() == 0)
1458 return;
1459
1460 // Then iterate through the new PHIs and look to see if they use one of the
1461 // previously mapped PHIs. If so, insert a new dbg.value intrinsic that will
1462 // propagate the info through the new PHI.
1463 LLVMContext &C = BB->getContext();
1464 for (auto PHI : InsertedPHIs) {
Matt Davis523c6562018-02-23 17:38:27 +00001465 BasicBlock *Parent = PHI->getParent();
1466 // Avoid inserting an intrinsic into an EH block.
1467 if (Parent->getFirstNonPHI()->isEHPad())
1468 continue;
1469 auto PhiMAV = MetadataAsValue::get(C, ValueAsMetadata::get(PHI));
Vedant Kumar6bfc8692018-01-25 21:37:05 +00001470 for (auto VI : PHI->operand_values()) {
1471 auto V = DbgValueMap.find(VI);
1472 if (V != DbgValueMap.end()) {
Hsiangkai Wangef72e482018-08-06 03:59:47 +00001473 auto *DbgII = cast<DbgVariableIntrinsic>(V->second);
Vedant Kumar6bfc8692018-01-25 21:37:05 +00001474 Instruction *NewDbgII = DbgII->clone();
Vedant Kumar6bfc8692018-01-25 21:37:05 +00001475 NewDbgII->setOperand(0, PhiMAV);
Vedant Kumar6394df92018-01-25 23:48:29 +00001476 auto InsertionPt = Parent->getFirstInsertionPt();
1477 assert(InsertionPt != Parent->end() && "Ill-formed basic block");
1478 NewDbgII->insertBefore(&*InsertionPt);
Vedant Kumar6bfc8692018-01-25 21:37:05 +00001479 }
1480 }
1481 }
1482}
1483
Reid Kleckner0fe506b2017-09-21 19:52:03 +00001484/// Finds all intrinsics declaring local variables as living in the memory that
1485/// 'V' points to. This may include a mix of dbg.declare and
1486/// dbg.addr intrinsics.
Hsiangkai Wangef72e482018-08-06 03:59:47 +00001487TinyPtrVector<DbgVariableIntrinsic *> llvm::FindDbgAddrUses(Value *V) {
Vedant Kumarde46f652018-06-26 18:44:52 +00001488 // This function is hot. Check whether the value has any metadata to avoid a
1489 // DenseMap lookup.
1490 if (!V->isUsedByMetadata())
1491 return {};
Reid Kleckner0fe506b2017-09-21 19:52:03 +00001492 auto *L = LocalAsMetadata::getIfExists(V);
1493 if (!L)
1494 return {};
1495 auto *MDV = MetadataAsValue::getIfExists(V->getContext(), L);
1496 if (!MDV)
1497 return {};
Cameron Zwarich843bc7d2011-05-24 03:10:43 +00001498
Hsiangkai Wangef72e482018-08-06 03:59:47 +00001499 TinyPtrVector<DbgVariableIntrinsic *> Declares;
Reid Kleckner0fe506b2017-09-21 19:52:03 +00001500 for (User *U : MDV->users()) {
Hsiangkai Wangef72e482018-08-06 03:59:47 +00001501 if (auto *DII = dyn_cast<DbgVariableIntrinsic>(U))
Reid Kleckner0fe506b2017-09-21 19:52:03 +00001502 if (DII->isAddressOfVariable())
1503 Declares.push_back(DII);
1504 }
1505
1506 return Declares;
Cameron Zwarich843bc7d2011-05-24 03:10:43 +00001507}
Alexey Samsonov3d43b632012-12-12 14:31:53 +00001508
Adrian Prantlfa9e84e2017-03-16 20:11:54 +00001509void llvm::findDbgValues(SmallVectorImpl<DbgValueInst *> &DbgValues, Value *V) {
Vedant Kumarde46f652018-06-26 18:44:52 +00001510 // This function is hot. Check whether the value has any metadata to avoid a
1511 // DenseMap lookup.
1512 if (!V->isUsedByMetadata())
1513 return;
Keith Walkerba159892016-09-22 14:13:25 +00001514 if (auto *L = LocalAsMetadata::getIfExists(V))
1515 if (auto *MDV = MetadataAsValue::getIfExists(V->getContext(), L))
1516 for (User *U : MDV->users())
1517 if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(U))
Adrian Prantlfa9e84e2017-03-16 20:11:54 +00001518 DbgValues.push_back(DVI);
Keith Walkerba159892016-09-22 14:13:25 +00001519}
1520
Hsiangkai Wangef72e482018-08-06 03:59:47 +00001521void llvm::findDbgUsers(SmallVectorImpl<DbgVariableIntrinsic *> &DbgUsers,
Vedant Kumarb2ec02b2018-01-05 23:27:02 +00001522 Value *V) {
Vedant Kumarde46f652018-06-26 18:44:52 +00001523 // This function is hot. Check whether the value has any metadata to avoid a
1524 // DenseMap lookup.
1525 if (!V->isUsedByMetadata())
1526 return;
Reid Kleckner29a5c032017-11-14 21:49:06 +00001527 if (auto *L = LocalAsMetadata::getIfExists(V))
1528 if (auto *MDV = MetadataAsValue::getIfExists(V->getContext(), L))
1529 for (User *U : MDV->users())
Hsiangkai Wangef72e482018-08-06 03:59:47 +00001530 if (DbgVariableIntrinsic *DII = dyn_cast<DbgVariableIntrinsic>(U))
Reid Kleckner29a5c032017-11-14 21:49:06 +00001531 DbgUsers.push_back(DII);
1532}
1533
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +00001534bool llvm::replaceDbgDeclare(Value *Address, Value *NewAddress,
1535 Instruction *InsertBefore, DIBuilder &Builder,
Petar Jovanovice85bbf52019-05-20 10:35:57 +00001536 uint8_t DIExprFlags, int Offset) {
Reid Kleckner0fe506b2017-09-21 19:52:03 +00001537 auto DbgAddrs = FindDbgAddrUses(Address);
Hsiangkai Wangef72e482018-08-06 03:59:47 +00001538 for (DbgVariableIntrinsic *DII : DbgAddrs) {
Reid Kleckner0fe506b2017-09-21 19:52:03 +00001539 DebugLoc Loc = DII->getDebugLoc();
1540 auto *DIVar = DII->getVariable();
1541 auto *DIExpr = DII->getExpression();
1542 assert(DIVar && "Missing variable");
Petar Jovanovice85bbf52019-05-20 10:35:57 +00001543 DIExpr = DIExpression::prepend(DIExpr, DIExprFlags, Offset);
Vedant Kumard37e0782018-07-13 22:39:31 +00001544 // Insert llvm.dbg.declare immediately before InsertBefore, and remove old
Reid Kleckner0fe506b2017-09-21 19:52:03 +00001545 // llvm.dbg.declare.
1546 Builder.insertDeclare(NewAddress, DIVar, DIExpr, Loc, InsertBefore);
1547 if (DII == InsertBefore)
Vedant Kumard37e0782018-07-13 22:39:31 +00001548 InsertBefore = InsertBefore->getNextNode();
Reid Kleckner0fe506b2017-09-21 19:52:03 +00001549 DII->eraseFromParent();
1550 }
1551 return !DbgAddrs.empty();
Alexey Samsonov3d43b632012-12-12 14:31:53 +00001552}
Evgeniy Stepanov4fbc0d082012-12-21 11:18:49 +00001553
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +00001554bool llvm::replaceDbgDeclareForAlloca(AllocaInst *AI, Value *NewAllocaAddress,
Petar Jovanovice85bbf52019-05-20 10:35:57 +00001555 DIBuilder &Builder, uint8_t DIExprFlags,
1556 int Offset) {
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +00001557 return replaceDbgDeclare(AI, NewAllocaAddress, AI->getNextNode(), Builder,
Petar Jovanovice85bbf52019-05-20 10:35:57 +00001558 DIExprFlags, Offset);
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +00001559}
1560
Evgeniy Stepanov72d961a2016-06-16 22:34:00 +00001561static void replaceOneDbgValueForAlloca(DbgValueInst *DVI, Value *NewAddress,
1562 DIBuilder &Builder, int Offset) {
1563 DebugLoc Loc = DVI->getDebugLoc();
1564 auto *DIVar = DVI->getVariable();
1565 auto *DIExpr = DVI->getExpression();
1566 assert(DIVar && "Missing variable");
1567
1568 // This is an alloca-based llvm.dbg.value. The first thing it should do with
1569 // the alloca pointer is dereference it. Otherwise we don't know how to handle
1570 // it and give up.
1571 if (!DIExpr || DIExpr->getNumElements() < 1 ||
1572 DIExpr->getElement(0) != dwarf::DW_OP_deref)
1573 return;
1574
Petr Hosekf6cd6ff2019-07-22 18:52:42 +00001575 // Insert the offset before the first deref.
Evgeniy Stepanov72d961a2016-06-16 22:34:00 +00001576 // We could just change the offset argument of dbg.value, but it's unsigned...
Petr Hosek8b161ba2019-07-24 00:16:23 +00001577 if (Offset)
1578 DIExpr = DIExpression::prepend(DIExpr, 0, Offset);
Evgeniy Stepanov72d961a2016-06-16 22:34:00 +00001579
Adrian Prantlabe04752017-07-28 20:21:02 +00001580 Builder.insertDbgValueIntrinsic(NewAddress, DIVar, DIExpr, Loc, DVI);
Evgeniy Stepanov72d961a2016-06-16 22:34:00 +00001581 DVI->eraseFromParent();
1582}
1583
1584void llvm::replaceDbgValueForAlloca(AllocaInst *AI, Value *NewAllocaAddress,
1585 DIBuilder &Builder, int Offset) {
1586 if (auto *L = LocalAsMetadata::getIfExists(AI))
1587 if (auto *MDV = MetadataAsValue::getIfExists(AI->getContext(), L))
1588 for (auto UI = MDV->use_begin(), UE = MDV->use_end(); UI != UE;) {
1589 Use &U = *UI++;
1590 if (auto *DVI = dyn_cast<DbgValueInst>(U.getUser()))
1591 replaceOneDbgValueForAlloca(DVI, NewAllocaAddress, Builder, Offset);
1592 }
1593}
1594
Vedant Kumar6379a622018-07-06 17:32:39 +00001595/// Wrap \p V in a ValueAsMetadata instance.
1596static MetadataAsValue *wrapValueInMetadata(LLVMContext &C, Value *V) {
1597 return MetadataAsValue::get(C, ValueAsMetadata::get(V));
1598}
1599
1600bool llvm::salvageDebugInfo(Instruction &I) {
Hsiangkai Wangef72e482018-08-06 03:59:47 +00001601 SmallVector<DbgVariableIntrinsic *, 1> DbgUsers;
Vedant Kumarb2ec02b2018-01-05 23:27:02 +00001602 findDbgUsers(DbgUsers, &I);
1603 if (DbgUsers.empty())
Vedant Kumar6379a622018-07-06 17:32:39 +00001604 return false;
Vedant Kumarb2ec02b2018-01-05 23:27:02 +00001605
Jeremy Morse84ca7062019-02-05 11:11:28 +00001606 return salvageDebugInfoForDbgValues(I, DbgUsers);
1607}
1608
1609bool llvm::salvageDebugInfoForDbgValues(
1610 Instruction &I, ArrayRef<DbgVariableIntrinsic *> DbgUsers) {
Vedant Kumar6379a622018-07-06 17:32:39 +00001611 auto &Ctx = I.getContext();
1612 auto wrapMD = [&](Value *V) { return wrapValueInMetadata(Ctx, V); };
Adrian Prantl47ea6472017-03-16 21:14:09 +00001613
Jeremy Morse84ca7062019-02-05 11:11:28 +00001614 for (auto *DII : DbgUsers) {
1615 // Do not add DW_OP_stack_value for DbgDeclare and DbgAddr, because they
1616 // are implicitly pointing out the value as a DWARF memory location
1617 // description.
1618 bool StackValue = isa<DbgValueInst>(DII);
1619
1620 DIExpression *DIExpr =
1621 salvageDebugInfoImpl(I, DII->getExpression(), StackValue);
1622
1623 // salvageDebugInfoImpl should fail on examining the first element of
1624 // DbgUsers, or none of them.
1625 if (!DIExpr)
1626 return false;
1627
Vedant Kumarb2ec02b2018-01-05 23:27:02 +00001628 DII->setOperand(0, wrapMD(I.getOperand(0)));
Vedant Kumar6379a622018-07-06 17:32:39 +00001629 DII->setOperand(2, MetadataAsValue::get(Ctx, DIExpr));
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001630 LLVM_DEBUG(dbgs() << "SALVAGE: " << *DII << '\n');
Jeremy Morse84ca7062019-02-05 11:11:28 +00001631 }
1632
1633 return true;
1634}
1635
1636DIExpression *llvm::salvageDebugInfoImpl(Instruction &I,
1637 DIExpression *SrcDIExpr,
1638 bool WithStackValue) {
1639 auto &M = *I.getModule();
1640 auto &DL = M.getDataLayout();
1641
1642 // Apply a vector of opcodes to the source DIExpression.
1643 auto doSalvage = [&](SmallVectorImpl<uint64_t> &Ops) -> DIExpression * {
1644 DIExpression *DIExpr = SrcDIExpr;
1645 if (!Ops.empty()) {
1646 DIExpr = DIExpression::prependOpcodes(DIExpr, Ops, WithStackValue);
1647 }
1648 return DIExpr;
Adrian Prantl182f9fe2017-11-06 22:49:39 +00001649 };
1650
Jeremy Morse84ca7062019-02-05 11:11:28 +00001651 // Apply the given offset to the source DIExpression.
1652 auto applyOffset = [&](uint64_t Offset) -> DIExpression * {
Vedant Kumar04386d82018-02-09 19:19:55 +00001653 SmallVector<uint64_t, 8> Ops;
1654 DIExpression::appendOffset(Ops, Offset);
Jeremy Morse84ca7062019-02-05 11:11:28 +00001655 return doSalvage(Ops);
Vedant Kumar04386d82018-02-09 19:19:55 +00001656 };
1657
Jeremy Morse84ca7062019-02-05 11:11:28 +00001658 // initializer-list helper for applying operators to the source DIExpression.
1659 auto applyOps =
1660 [&](std::initializer_list<uint64_t> Opcodes) -> DIExpression * {
Vedant Kumar04386d82018-02-09 19:19:55 +00001661 SmallVector<uint64_t, 8> Ops(Opcodes);
Jeremy Morse84ca7062019-02-05 11:11:28 +00001662 return doSalvage(Ops);
Vedant Kumar04386d82018-02-09 19:19:55 +00001663 };
1664
Vedant Kumar388fac52018-02-13 03:34:23 +00001665 if (auto *CI = dyn_cast<CastInst>(&I)) {
Wolfgang Pieb4fe42212019-04-15 17:36:29 +00001666 // No-op casts and zexts are irrelevant for debug info.
1667 if (CI->isNoopCast(DL) || isa<ZExtInst>(&I))
1668 return SrcDIExpr;
Bob Haarman032f87b2019-05-21 11:53:41 +00001669 return nullptr;
1670 } else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
Vedant Kumarb2ec02b2018-01-05 23:27:02 +00001671 unsigned BitWidth =
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00001672 M.getDataLayout().getIndexSizeInBits(GEP->getPointerAddressSpace());
Jeremy Morse84ca7062019-02-05 11:11:28 +00001673 // Rewrite a constant GEP into a DIExpression.
Vedant Kumarb2ec02b2018-01-05 23:27:02 +00001674 APInt Offset(BitWidth, 0);
Jeremy Morse84ca7062019-02-05 11:11:28 +00001675 if (GEP->accumulateConstantOffset(M.getDataLayout(), Offset)) {
1676 return applyOffset(Offset.getSExtValue());
1677 } else {
1678 return nullptr;
1679 }
Adrian Prantl182f9fe2017-11-06 22:49:39 +00001680 } else if (auto *BI = dyn_cast<BinaryOperator>(&I)) {
Vedant Kumar044b5882018-02-15 19:13:03 +00001681 // Rewrite binary operations with constant integer operands.
Vedant Kumar96b7dc02018-02-13 01:09:46 +00001682 auto *ConstInt = dyn_cast<ConstantInt>(I.getOperand(1));
1683 if (!ConstInt || ConstInt->getBitWidth() > 64)
Jeremy Morse84ca7062019-02-05 11:11:28 +00001684 return nullptr;
Vedant Kumar96b7dc02018-02-13 01:09:46 +00001685
1686 uint64_t Val = ConstInt->getSExtValue();
Jeremy Morse84ca7062019-02-05 11:11:28 +00001687 switch (BI->getOpcode()) {
1688 case Instruction::Add:
1689 return applyOffset(Val);
1690 case Instruction::Sub:
1691 return applyOffset(-int64_t(Val));
1692 case Instruction::Mul:
1693 return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_mul});
1694 case Instruction::SDiv:
1695 return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_div});
1696 case Instruction::SRem:
1697 return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_mod});
1698 case Instruction::Or:
1699 return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_or});
1700 case Instruction::And:
1701 return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_and});
1702 case Instruction::Xor:
1703 return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_xor});
1704 case Instruction::Shl:
1705 return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_shl});
1706 case Instruction::LShr:
1707 return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_shr});
1708 case Instruction::AShr:
1709 return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_shra});
1710 default:
1711 // TODO: Salvage constants from each kind of binop we know about.
1712 return nullptr;
Vedant Kumar96b7dc02018-02-13 01:09:46 +00001713 }
Jeremy Morseb33a5c72019-02-12 10:54:30 +00001714 // *Not* to do: we should not attempt to salvage load instructions,
1715 // because the validity and lifetime of a dbg.value containing
1716 // DW_OP_deref becomes difficult to analyze. See PR40628 for examples.
Adrian Prantl47ea6472017-03-16 21:14:09 +00001717 }
Jeremy Morse84ca7062019-02-05 11:11:28 +00001718 return nullptr;
Adrian Prantl47ea6472017-03-16 21:14:09 +00001719}
1720
Vedant Kumar6379a622018-07-06 17:32:39 +00001721/// A replacement for a dbg.value expression.
1722using DbgValReplacement = Optional<DIExpression *>;
1723
1724/// Point debug users of \p From to \p To using exprs given by \p RewriteExpr,
1725/// possibly moving/deleting users to prevent use-before-def. Returns true if
1726/// changes are made.
1727static bool rewriteDebugUsers(
1728 Instruction &From, Value &To, Instruction &DomPoint, DominatorTree &DT,
Hsiangkai Wangef72e482018-08-06 03:59:47 +00001729 function_ref<DbgValReplacement(DbgVariableIntrinsic &DII)> RewriteExpr) {
Vedant Kumar6379a622018-07-06 17:32:39 +00001730 // Find debug users of From.
Hsiangkai Wangef72e482018-08-06 03:59:47 +00001731 SmallVector<DbgVariableIntrinsic *, 1> Users;
Vedant Kumar6fa24b02018-06-20 16:50:25 +00001732 findDbgUsers(Users, &From);
1733 if (Users.empty())
Vedant Kumar6379a622018-07-06 17:32:39 +00001734 return false;
Vedant Kumar6fa24b02018-06-20 16:50:25 +00001735
Vedant Kumar6379a622018-07-06 17:32:39 +00001736 // Prevent use-before-def of To.
1737 bool Changed = false;
Hsiangkai Wangef72e482018-08-06 03:59:47 +00001738 SmallPtrSet<DbgVariableIntrinsic *, 1> DeleteOrSalvage;
Vedant Kumar6379a622018-07-06 17:32:39 +00001739 if (isa<Instruction>(&To)) {
1740 bool DomPointAfterFrom = From.getNextNonDebugInstruction() == &DomPoint;
1741
1742 for (auto *DII : Users) {
1743 // It's common to see a debug user between From and DomPoint. Move it
1744 // after DomPoint to preserve the variable update without any reordering.
1745 if (DomPointAfterFrom && DII->getNextNonDebugInstruction() == &DomPoint) {
1746 LLVM_DEBUG(dbgs() << "MOVE: " << *DII << '\n');
1747 DII->moveAfter(&DomPoint);
1748 Changed = true;
1749
1750 // Users which otherwise aren't dominated by the replacement value must
1751 // be salvaged or deleted.
1752 } else if (!DT.dominates(&DomPoint, DII)) {
1753 DeleteOrSalvage.insert(DII);
1754 }
Vedant Kumarc85ca4c2018-06-26 18:44:53 +00001755 }
Vedant Kumar6379a622018-07-06 17:32:39 +00001756 }
1757
1758 // Update debug users without use-before-def risk.
1759 for (auto *DII : Users) {
1760 if (DeleteOrSalvage.count(DII))
1761 continue;
1762
1763 LLVMContext &Ctx = DII->getContext();
1764 DbgValReplacement DVR = RewriteExpr(*DII);
1765 if (!DVR)
1766 continue;
1767
1768 DII->setOperand(0, wrapValueInMetadata(Ctx, &To));
1769 DII->setOperand(2, MetadataAsValue::get(Ctx, *DVR));
1770 LLVM_DEBUG(dbgs() << "REWRITE: " << *DII << '\n');
1771 Changed = true;
1772 }
1773
1774 if (!DeleteOrSalvage.empty()) {
1775 // Try to salvage the remaining debug users.
1776 Changed |= salvageDebugInfo(From);
1777
1778 // Delete the debug users which weren't salvaged.
1779 for (auto *DII : DeleteOrSalvage) {
1780 if (DII->getVariableLocation() == &From) {
1781 LLVM_DEBUG(dbgs() << "Erased UseBeforeDef: " << *DII << '\n');
1782 DII->eraseFromParent();
1783 Changed = true;
1784 }
1785 }
1786 }
1787
1788 return Changed;
Vedant Kumarc85ca4c2018-06-26 18:44:53 +00001789}
1790
Vedant Kumar6379a622018-07-06 17:32:39 +00001791/// Check if a bitcast between a value of type \p FromTy to type \p ToTy would
1792/// losslessly preserve the bits and semantics of the value. This predicate is
1793/// symmetric, i.e swapping \p FromTy and \p ToTy should give the same result.
1794///
1795/// Note that Type::canLosslesslyBitCastTo is not suitable here because it
1796/// allows semantically unequivalent bitcasts, such as <2 x i64> -> <4 x i32>,
1797/// and also does not allow lossless pointer <-> integer conversions.
1798static bool isBitCastSemanticsPreserving(const DataLayout &DL, Type *FromTy,
1799 Type *ToTy) {
1800 // Trivially compatible types.
1801 if (FromTy == ToTy)
1802 return true;
1803
1804 // Handle compatible pointer <-> integer conversions.
1805 if (FromTy->isIntOrPtrTy() && ToTy->isIntOrPtrTy()) {
1806 bool SameSize = DL.getTypeSizeInBits(FromTy) == DL.getTypeSizeInBits(ToTy);
1807 bool LosslessConversion = !DL.isNonIntegralPointerType(FromTy) &&
1808 !DL.isNonIntegralPointerType(ToTy);
1809 return SameSize && LosslessConversion;
1810 }
1811
1812 // TODO: This is not exhaustive.
1813 return false;
1814}
1815
1816bool llvm::replaceAllDbgUsesWith(Instruction &From, Value &To,
1817 Instruction &DomPoint, DominatorTree &DT) {
1818 // Exit early if From has no debug users.
1819 if (!From.isUsedByMetadata())
1820 return false;
1821
1822 assert(&From != &To && "Can't replace something with itself");
1823
1824 Type *FromTy = From.getType();
1825 Type *ToTy = To.getType();
1826
Hsiangkai Wangef72e482018-08-06 03:59:47 +00001827 auto Identity = [&](DbgVariableIntrinsic &DII) -> DbgValReplacement {
Vedant Kumar6379a622018-07-06 17:32:39 +00001828 return DII.getExpression();
1829 };
1830
1831 // Handle no-op conversions.
1832 Module &M = *From.getModule();
1833 const DataLayout &DL = M.getDataLayout();
1834 if (isBitCastSemanticsPreserving(DL, FromTy, ToTy))
1835 return rewriteDebugUsers(From, To, DomPoint, DT, Identity);
1836
1837 // Handle integer-to-integer widening and narrowing.
1838 // FIXME: Use DW_OP_convert when it's available everywhere.
1839 if (FromTy->isIntegerTy() && ToTy->isIntegerTy()) {
1840 uint64_t FromBits = FromTy->getPrimitiveSizeInBits();
1841 uint64_t ToBits = ToTy->getPrimitiveSizeInBits();
1842 assert(FromBits != ToBits && "Unexpected no-op conversion");
1843
1844 // When the width of the result grows, assume that a debugger will only
1845 // access the low `FromBits` bits when inspecting the source variable.
1846 if (FromBits < ToBits)
1847 return rewriteDebugUsers(From, To, DomPoint, DT, Identity);
1848
1849 // The width of the result has shrunk. Use sign/zero extension to describe
1850 // the source variable's high bits.
Hsiangkai Wangef72e482018-08-06 03:59:47 +00001851 auto SignOrZeroExt = [&](DbgVariableIntrinsic &DII) -> DbgValReplacement {
Vedant Kumar6379a622018-07-06 17:32:39 +00001852 DILocalVariable *Var = DII.getVariable();
1853
1854 // Without knowing signedness, sign/zero extension isn't possible.
1855 auto Signedness = Var->getSignedness();
1856 if (!Signedness)
1857 return None;
1858
1859 bool Signed = *Signedness == DIBasicType::Signedness::Signed;
Markus Lavinb86ce212019-03-19 13:16:28 +00001860 dwarf::TypeKind TK = Signed ? dwarf::DW_ATE_signed : dwarf::DW_ATE_unsigned;
1861 SmallVector<uint64_t, 8> Ops({dwarf::DW_OP_LLVM_convert, ToBits, TK,
1862 dwarf::DW_OP_LLVM_convert, FromBits, TK});
1863 return DIExpression::appendToStack(DII.getExpression(), Ops);
Vedant Kumar6379a622018-07-06 17:32:39 +00001864 };
1865 return rewriteDebugUsers(From, To, DomPoint, DT, SignOrZeroExt);
1866 }
1867
1868 // TODO: Floating-point conversions, vectors.
1869 return false;
Vedant Kumar6fa24b02018-06-20 16:50:25 +00001870}
1871
David Majnemer35c46d32016-01-24 05:26:18 +00001872unsigned llvm::removeAllNonTerminatorAndEHPadInstructions(BasicBlock *BB) {
1873 unsigned NumDeadInst = 0;
1874 // Delete the instructions backwards, as it has a reduced likelihood of
1875 // having to update as many def-use and use-def chains.
1876 Instruction *EndInst = BB->getTerminator(); // Last not to be deleted.
Duncan P. N. Exon Smithe9bc5792016-02-21 20:39:50 +00001877 while (EndInst != &BB->front()) {
David Majnemer35c46d32016-01-24 05:26:18 +00001878 // Delete the next to last instruction.
1879 Instruction *Inst = &*--EndInst->getIterator();
1880 if (!Inst->use_empty() && !Inst->getType()->isTokenTy())
1881 Inst->replaceAllUsesWith(UndefValue::get(Inst->getType()));
1882 if (Inst->isEHPad() || Inst->getType()->isTokenTy()) {
1883 EndInst = Inst;
1884 continue;
1885 }
1886 if (!isa<DbgInfoIntrinsic>(Inst))
1887 ++NumDeadInst;
1888 Inst->eraseFromParent();
1889 }
1890 return NumDeadInst;
1891}
1892
Michael Zolotukhin5020c992016-11-18 21:01:12 +00001893unsigned llvm::changeToUnreachable(Instruction *I, bool UseLLVMTrap,
Alina Sbirleaf31eba62019-05-08 17:05:36 +00001894 bool PreserveLCSSA, DomTreeUpdater *DTU,
1895 MemorySSAUpdater *MSSAU) {
Peter Collingbourne8d642de2013-08-12 22:38:43 +00001896 BasicBlock *BB = I->getParent();
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +00001897 std::vector <DominatorTree::UpdateType> Updates;
1898
Alina Sbirleaf31eba62019-05-08 17:05:36 +00001899 if (MSSAU)
1900 MSSAU->changeToUnreachable(I);
1901
Peter Collingbourne8d642de2013-08-12 22:38:43 +00001902 // Loop over all of the successors, removing BB's entry from any PHI
1903 // nodes.
Chijun Sima21a8b602018-08-03 05:08:17 +00001904 if (DTU)
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +00001905 Updates.reserve(BB->getTerminator()->getNumSuccessors());
1906 for (BasicBlock *Successor : successors(BB)) {
Michael Zolotukhin5020c992016-11-18 21:01:12 +00001907 Successor->removePredecessor(BB, PreserveLCSSA);
Chijun Sima21a8b602018-08-03 05:08:17 +00001908 if (DTU)
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +00001909 Updates.push_back({DominatorTree::Delete, BB, Successor});
1910 }
David Majnemere14e7bc2016-06-25 08:19:55 +00001911 // Insert a call to llvm.trap right before this. This turns the undefined
1912 // behavior into a hard fail instead of falling through into random code.
1913 if (UseLLVMTrap) {
1914 Function *TrapFn =
1915 Intrinsic::getDeclaration(BB->getParent()->getParent(), Intrinsic::trap);
1916 CallInst *CallTrap = CallInst::Create(TrapFn, "", I);
1917 CallTrap->setDebugLoc(I->getDebugLoc());
1918 }
Anastasis Grammenos52d52832018-08-07 20:21:56 +00001919 auto *UI = new UnreachableInst(I->getContext(), I);
1920 UI->setDebugLoc(I->getDebugLoc());
Peter Collingbourne8d642de2013-08-12 22:38:43 +00001921
1922 // All instructions after this are dead.
David Majnemer88542a02016-01-24 06:26:47 +00001923 unsigned NumInstrsRemoved = 0;
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001924 BasicBlock::iterator BBI = I->getIterator(), BBE = BB->end();
Peter Collingbourne8d642de2013-08-12 22:38:43 +00001925 while (BBI != BBE) {
1926 if (!BBI->use_empty())
1927 BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
1928 BB->getInstList().erase(BBI++);
David Majnemer88542a02016-01-24 06:26:47 +00001929 ++NumInstrsRemoved;
Peter Collingbourne8d642de2013-08-12 22:38:43 +00001930 }
Chijun Sima21a8b602018-08-03 05:08:17 +00001931 if (DTU)
Chijun Sima70e97162019-02-22 13:48:38 +00001932 DTU->applyUpdatesPermissive(Updates);
David Majnemer88542a02016-01-24 06:26:47 +00001933 return NumInstrsRemoved;
Peter Collingbourne8d642de2013-08-12 22:38:43 +00001934}
1935
1936/// changeToCall - Convert the specified invoke into a normal call.
Stefan Stipanovic6058b862019-07-22 23:58:23 +00001937void llvm::changeToCall(InvokeInst *II, DomTreeUpdater *DTU) {
Sanjoy Dasccd14562015-12-10 06:39:02 +00001938 SmallVector<Value*, 8> Args(II->arg_begin(), II->arg_end());
Sanjoy Das8a954a02015-12-08 22:26:08 +00001939 SmallVector<OperandBundleDef, 1> OpBundles;
1940 II->getOperandBundlesAsDefs(OpBundles);
James Y Knight7976eb52019-02-01 20:43:25 +00001941 CallInst *NewCall = CallInst::Create(
1942 II->getFunctionType(), II->getCalledValue(), Args, OpBundles, "", II);
Peter Collingbourne8d642de2013-08-12 22:38:43 +00001943 NewCall->takeName(II);
1944 NewCall->setCallingConv(II->getCallingConv());
1945 NewCall->setAttributes(II->getAttributes());
1946 NewCall->setDebugLoc(II->getDebugLoc());
Michael Kruse5948b7f2018-12-14 18:15:11 +00001947 NewCall->copyMetadata(*II);
Peter Collingbourne8d642de2013-08-12 22:38:43 +00001948 II->replaceAllUsesWith(NewCall);
1949
1950 // Follow the call by a branch to the normal destination.
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +00001951 BasicBlock *NormalDestBB = II->getNormalDest();
1952 BranchInst::Create(NormalDestBB, II);
Peter Collingbourne8d642de2013-08-12 22:38:43 +00001953
1954 // Update PHI nodes in the unwind destination
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +00001955 BasicBlock *BB = II->getParent();
1956 BasicBlock *UnwindDestBB = II->getUnwindDest();
1957 UnwindDestBB->removePredecessor(BB);
Peter Collingbourne8d642de2013-08-12 22:38:43 +00001958 II->eraseFromParent();
Chijun Sima21a8b602018-08-03 05:08:17 +00001959 if (DTU)
Chijun Sima70e97162019-02-22 13:48:38 +00001960 DTU->applyUpdatesPermissive({{DominatorTree::Delete, BB, UnwindDestBB}});
Peter Collingbourne8d642de2013-08-12 22:38:43 +00001961}
1962
Kuba Breckaddfdba32016-11-14 21:41:13 +00001963BasicBlock *llvm::changeToInvokeAndSplitBasicBlock(CallInst *CI,
1964 BasicBlock *UnwindEdge) {
1965 BasicBlock *BB = CI->getParent();
1966
1967 // Convert this function call into an invoke instruction. First, split the
1968 // basic block.
1969 BasicBlock *Split =
1970 BB->splitBasicBlock(CI->getIterator(), CI->getName() + ".noexc");
1971
1972 // Delete the unconditional branch inserted by splitBasicBlock
1973 BB->getInstList().pop_back();
1974
1975 // Create the new invoke instruction.
1976 SmallVector<Value *, 8> InvokeArgs(CI->arg_begin(), CI->arg_end());
1977 SmallVector<OperandBundleDef, 1> OpBundles;
1978
1979 CI->getOperandBundlesAsDefs(OpBundles);
1980
1981 // Note: we're round tripping operand bundles through memory here, and that
1982 // can potentially be avoided with a cleverer API design that we do not have
1983 // as of this time.
1984
James Y Knightd9e85a02019-02-01 20:43:34 +00001985 InvokeInst *II =
1986 InvokeInst::Create(CI->getFunctionType(), CI->getCalledValue(), Split,
1987 UnwindEdge, InvokeArgs, OpBundles, CI->getName(), BB);
Kuba Breckaddfdba32016-11-14 21:41:13 +00001988 II->setDebugLoc(CI->getDebugLoc());
1989 II->setCallingConv(CI->getCallingConv());
1990 II->setAttributes(CI->getAttributes());
1991
1992 // Make sure that anything using the call now uses the invoke! This also
Sanjoy Dase6bca0e2017-05-01 17:07:49 +00001993 // updates the CallGraph if present, because it uses a WeakTrackingVH.
Kuba Breckaddfdba32016-11-14 21:41:13 +00001994 CI->replaceAllUsesWith(II);
1995
1996 // Delete the original call
1997 Split->getInstList().pop_front();
1998 return Split;
1999}
2000
David Majnemer7fddecc2015-06-17 20:52:32 +00002001static bool markAliveBlocks(Function &F,
Chijun Sima21a8b602018-08-03 05:08:17 +00002002 SmallPtrSetImpl<BasicBlock *> &Reachable,
2003 DomTreeUpdater *DTU = nullptr) {
Evgeniy Stepanov4fbc0d082012-12-21 11:18:49 +00002004 SmallVector<BasicBlock*, 128> Worklist;
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002005 BasicBlock *BB = &F.front();
Peter Collingbourne8d642de2013-08-12 22:38:43 +00002006 Worklist.push_back(BB);
2007 Reachable.insert(BB);
2008 bool Changed = false;
Evgeniy Stepanov4fbc0d082012-12-21 11:18:49 +00002009 do {
Peter Collingbourne8d642de2013-08-12 22:38:43 +00002010 BB = Worklist.pop_back_val();
2011
2012 // Do a quick scan of the basic block, turning any obviously unreachable
2013 // instructions into LLVM unreachable insts. The instruction combining pass
2014 // canonicalizes unreachable insts into stores to null or undef.
David Majnemer9f506252016-06-25 08:34:38 +00002015 for (Instruction &I : *BB) {
Xin Tong074ccf32018-07-18 18:40:45 +00002016 if (auto *CI = dyn_cast<CallInst>(&I)) {
2017 Value *Callee = CI->getCalledValue();
2018 // Handle intrinsic calls.
2019 if (Function *F = dyn_cast<Function>(Callee)) {
2020 auto IntrinsicID = F->getIntrinsicID();
2021 // Assumptions that are known to be false are equivalent to
2022 // unreachable. Also, if the condition is undefined, then we make the
2023 // choice most beneficial to the optimizer, and choose that to also be
2024 // unreachable.
2025 if (IntrinsicID == Intrinsic::assume) {
2026 if (match(CI->getArgOperand(0), m_CombineOr(m_Zero(), m_Undef()))) {
2027 // Don't insert a call to llvm.trap right before the unreachable.
Chijun Sima21a8b602018-08-03 05:08:17 +00002028 changeToUnreachable(CI, false, false, DTU);
Sanjoy Das54a3a002016-04-21 05:09:12 +00002029 Changed = true;
2030 break;
2031 }
Xin Tong074ccf32018-07-18 18:40:45 +00002032 } else if (IntrinsicID == Intrinsic::experimental_guard) {
2033 // A call to the guard intrinsic bails out of the current
2034 // compilation unit if the predicate passed to it is false. If the
2035 // predicate is a constant false, then we know the guard will bail
2036 // out of the current compile unconditionally, so all code following
2037 // it is dead.
2038 //
2039 // Note: unlike in llvm.assume, it is not "obviously profitable" for
2040 // guards to treat `undef` as `false` since a guard on `undef` can
2041 // still be useful for widening.
2042 if (match(CI->getArgOperand(0), m_Zero()))
2043 if (!isa<UnreachableInst>(CI->getNextNode())) {
2044 changeToUnreachable(CI->getNextNode(), /*UseLLVMTrap=*/false,
Chijun Sima21a8b602018-08-03 05:08:17 +00002045 false, DTU);
Xin Tong074ccf32018-07-18 18:40:45 +00002046 Changed = true;
2047 break;
2048 }
2049 }
2050 } else if ((isa<ConstantPointerNull>(Callee) &&
2051 !NullPointerIsDefined(CI->getFunction())) ||
2052 isa<UndefValue>(Callee)) {
Chijun Sima21a8b602018-08-03 05:08:17 +00002053 changeToUnreachable(CI, /*UseLLVMTrap=*/false, false, DTU);
David Majnemer1fea77c2016-06-25 07:37:27 +00002054 Changed = true;
2055 break;
2056 }
Joseph Tremouletfb4d9f72019-04-02 15:48:58 +00002057 if (CI->doesNotReturn() && !CI->isMustTailCall()) {
Peter Collingbourne8d642de2013-08-12 22:38:43 +00002058 // If we found a call to a no-return function, insert an unreachable
2059 // instruction after it. Make sure there isn't *already* one there
2060 // though.
David Majnemer9f506252016-06-25 08:34:38 +00002061 if (!isa<UnreachableInst>(CI->getNextNode())) {
David Majnemere14e7bc2016-06-25 08:19:55 +00002062 // Don't insert a call to llvm.trap right before the unreachable.
Chijun Sima21a8b602018-08-03 05:08:17 +00002063 changeToUnreachable(CI->getNextNode(), false, false, DTU);
Peter Collingbourne8d642de2013-08-12 22:38:43 +00002064 Changed = true;
2065 }
2066 break;
2067 }
Xin Tong074ccf32018-07-18 18:40:45 +00002068 } else if (auto *SI = dyn_cast<StoreInst>(&I)) {
2069 // Store to undef and store to null are undefined and used to signal
2070 // that they should be changed to unreachable by passes that can't
2071 // modify the CFG.
Peter Collingbourne8d642de2013-08-12 22:38:43 +00002072
Peter Collingbourne8d642de2013-08-12 22:38:43 +00002073 // Don't touch volatile stores.
2074 if (SI->isVolatile()) continue;
2075
2076 Value *Ptr = SI->getOperand(1);
2077
2078 if (isa<UndefValue>(Ptr) ||
2079 (isa<ConstantPointerNull>(Ptr) &&
Manoj Gupta77eeac32018-07-09 22:27:23 +00002080 !NullPointerIsDefined(SI->getFunction(),
2081 SI->getPointerAddressSpace()))) {
Chijun Sima21a8b602018-08-03 05:08:17 +00002082 changeToUnreachable(SI, true, false, DTU);
Peter Collingbourne8d642de2013-08-12 22:38:43 +00002083 Changed = true;
2084 break;
2085 }
2086 }
2087 }
2088
Chandler Carruthedb12a82018-10-15 10:04:59 +00002089 Instruction *Terminator = BB->getTerminator();
David Majnemer2fa86512016-01-05 06:27:50 +00002090 if (auto *II = dyn_cast<InvokeInst>(Terminator)) {
2091 // Turn invokes that call 'nounwind' functions into ordinary calls.
Peter Collingbourne8d642de2013-08-12 22:38:43 +00002092 Value *Callee = II->getCalledValue();
Manoj Gupta77eeac32018-07-09 22:27:23 +00002093 if ((isa<ConstantPointerNull>(Callee) &&
2094 !NullPointerIsDefined(BB->getParent())) ||
2095 isa<UndefValue>(Callee)) {
Chijun Sima21a8b602018-08-03 05:08:17 +00002096 changeToUnreachable(II, true, false, DTU);
Peter Collingbourne8d642de2013-08-12 22:38:43 +00002097 Changed = true;
David Majnemer7fddecc2015-06-17 20:52:32 +00002098 } else if (II->doesNotThrow() && canSimplifyInvokeNoUnwind(&F)) {
Peter Collingbourne8d642de2013-08-12 22:38:43 +00002099 if (II->use_empty() && II->onlyReadsMemory()) {
2100 // jump to the normal destination branch.
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +00002101 BasicBlock *NormalDestBB = II->getNormalDest();
2102 BasicBlock *UnwindDestBB = II->getUnwindDest();
2103 BranchInst::Create(NormalDestBB, II);
2104 UnwindDestBB->removePredecessor(II->getParent());
Peter Collingbourne8d642de2013-08-12 22:38:43 +00002105 II->eraseFromParent();
Chijun Sima21a8b602018-08-03 05:08:17 +00002106 if (DTU)
Chijun Sima70e97162019-02-22 13:48:38 +00002107 DTU->applyUpdatesPermissive(
2108 {{DominatorTree::Delete, BB, UnwindDestBB}});
Peter Collingbourne8d642de2013-08-12 22:38:43 +00002109 } else
Chijun Sima21a8b602018-08-03 05:08:17 +00002110 changeToCall(II, DTU);
Peter Collingbourne8d642de2013-08-12 22:38:43 +00002111 Changed = true;
2112 }
David Majnemer2fa86512016-01-05 06:27:50 +00002113 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Terminator)) {
2114 // Remove catchpads which cannot be reached.
David Majnemer59eb7332016-01-05 07:42:17 +00002115 struct CatchPadDenseMapInfo {
2116 static CatchPadInst *getEmptyKey() {
2117 return DenseMapInfo<CatchPadInst *>::getEmptyKey();
2118 }
Eugene Zelenko6cadde72017-10-17 21:27:42 +00002119
David Majnemer59eb7332016-01-05 07:42:17 +00002120 static CatchPadInst *getTombstoneKey() {
2121 return DenseMapInfo<CatchPadInst *>::getTombstoneKey();
2122 }
Eugene Zelenko6cadde72017-10-17 21:27:42 +00002123
David Majnemer59eb7332016-01-05 07:42:17 +00002124 static unsigned getHashValue(CatchPadInst *CatchPad) {
2125 return static_cast<unsigned>(hash_combine_range(
2126 CatchPad->value_op_begin(), CatchPad->value_op_end()));
2127 }
Eugene Zelenko6cadde72017-10-17 21:27:42 +00002128
David Majnemer59eb7332016-01-05 07:42:17 +00002129 static bool isEqual(CatchPadInst *LHS, CatchPadInst *RHS) {
2130 if (LHS == getEmptyKey() || LHS == getTombstoneKey() ||
2131 RHS == getEmptyKey() || RHS == getTombstoneKey())
2132 return LHS == RHS;
2133 return LHS->isIdenticalTo(RHS);
2134 }
2135 };
2136
2137 // Set of unique CatchPads.
2138 SmallDenseMap<CatchPadInst *, detail::DenseSetEmpty, 4,
2139 CatchPadDenseMapInfo, detail::DenseSetPair<CatchPadInst *>>
2140 HandlerSet;
2141 detail::DenseSetEmpty Empty;
David Majnemer2fa86512016-01-05 06:27:50 +00002142 for (CatchSwitchInst::handler_iterator I = CatchSwitch->handler_begin(),
2143 E = CatchSwitch->handler_end();
2144 I != E; ++I) {
2145 BasicBlock *HandlerBB = *I;
David Majnemer59eb7332016-01-05 07:42:17 +00002146 auto *CatchPad = cast<CatchPadInst>(HandlerBB->getFirstNonPHI());
2147 if (!HandlerSet.insert({CatchPad, Empty}).second) {
David Majnemer2fa86512016-01-05 06:27:50 +00002148 CatchSwitch->removeHandler(I);
2149 --I;
2150 --E;
2151 Changed = true;
2152 }
2153 }
Peter Collingbourne8d642de2013-08-12 22:38:43 +00002154 }
2155
Chijun Sima21a8b602018-08-03 05:08:17 +00002156 Changed |= ConstantFoldTerminator(BB, true, nullptr, DTU);
David Majnemer9f506252016-06-25 08:34:38 +00002157 for (BasicBlock *Successor : successors(BB))
2158 if (Reachable.insert(Successor).second)
2159 Worklist.push_back(Successor);
Evgeniy Stepanov4fbc0d082012-12-21 11:18:49 +00002160 } while (!Worklist.empty());
Peter Collingbourne8d642de2013-08-12 22:38:43 +00002161 return Changed;
2162}
Evgeniy Stepanov4fbc0d082012-12-21 11:18:49 +00002163
Chijun Sima21a8b602018-08-03 05:08:17 +00002164void llvm::removeUnwindEdge(BasicBlock *BB, DomTreeUpdater *DTU) {
Chandler Carruthedb12a82018-10-15 10:04:59 +00002165 Instruction *TI = BB->getTerminator();
Joseph Tremoulet09af67a2015-09-27 01:47:46 +00002166
2167 if (auto *II = dyn_cast<InvokeInst>(TI)) {
Chijun Sima21a8b602018-08-03 05:08:17 +00002168 changeToCall(II, DTU);
Joseph Tremoulet09af67a2015-09-27 01:47:46 +00002169 return;
2170 }
2171
Chandler Carruthc8eaea72018-10-18 00:39:18 +00002172 Instruction *NewTI;
Joseph Tremoulet09af67a2015-09-27 01:47:46 +00002173 BasicBlock *UnwindDest;
2174
2175 if (auto *CRI = dyn_cast<CleanupReturnInst>(TI)) {
2176 NewTI = CleanupReturnInst::Create(CRI->getCleanupPad(), nullptr, CRI);
2177 UnwindDest = CRI->getUnwindDest();
David Majnemer8a1c45d2015-12-12 05:38:55 +00002178 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(TI)) {
2179 auto *NewCatchSwitch = CatchSwitchInst::Create(
2180 CatchSwitch->getParentPad(), nullptr, CatchSwitch->getNumHandlers(),
2181 CatchSwitch->getName(), CatchSwitch);
2182 for (BasicBlock *PadBB : CatchSwitch->handlers())
2183 NewCatchSwitch->addHandler(PadBB);
2184
2185 NewTI = NewCatchSwitch;
2186 UnwindDest = CatchSwitch->getUnwindDest();
Joseph Tremoulet09af67a2015-09-27 01:47:46 +00002187 } else {
2188 llvm_unreachable("Could not find unwind successor");
2189 }
2190
2191 NewTI->takeName(TI);
2192 NewTI->setDebugLoc(TI->getDebugLoc());
2193 UnwindDest->removePredecessor(BB);
David Majnemer8a1c45d2015-12-12 05:38:55 +00002194 TI->replaceAllUsesWith(NewTI);
Joseph Tremoulet09af67a2015-09-27 01:47:46 +00002195 TI->eraseFromParent();
Chijun Sima21a8b602018-08-03 05:08:17 +00002196 if (DTU)
Chijun Sima70e97162019-02-22 13:48:38 +00002197 DTU->applyUpdatesPermissive({{DominatorTree::Delete, BB, UnwindDest}});
Joseph Tremoulet09af67a2015-09-27 01:47:46 +00002198}
2199
Davide Italiano4eb210b2017-07-07 18:54:14 +00002200/// removeUnreachableBlocks - Remove blocks that are not reachable, even
Peter Collingbourne8d642de2013-08-12 22:38:43 +00002201/// if they are in a dead cycle. Return true if a change was made, false
Davide Italiano4eb210b2017-07-07 18:54:14 +00002202/// otherwise. If `LVI` is passed, this function preserves LazyValueInfo
2203/// after modifying the CFG.
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +00002204bool llvm::removeUnreachableBlocks(Function &F, LazyValueInfo *LVI,
Alina Sbirlea2ab544b2018-08-16 21:58:44 +00002205 DomTreeUpdater *DTU,
2206 MemorySSAUpdater *MSSAU) {
Matthias Braunb30f2f512016-01-30 01:24:31 +00002207 SmallPtrSet<BasicBlock*, 16> Reachable;
Chijun Sima21a8b602018-08-03 05:08:17 +00002208 bool Changed = markAliveBlocks(F, Reachable, DTU);
Peter Collingbourne8d642de2013-08-12 22:38:43 +00002209
2210 // If there are unreachable blocks in the CFG...
Evgeniy Stepanov4fbc0d082012-12-21 11:18:49 +00002211 if (Reachable.size() == F.size())
Peter Collingbourne8d642de2013-08-12 22:38:43 +00002212 return Changed;
Evgeniy Stepanov4fbc0d082012-12-21 11:18:49 +00002213
2214 assert(Reachable.size() < F.size());
Peter Collingbourne8d642de2013-08-12 22:38:43 +00002215 NumRemoved += F.size()-Reachable.size();
2216
Alina Sbirleadb101862019-07-12 22:30:30 +00002217 SmallSetVector<BasicBlock *, 8> DeadBlockSet;
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +00002218 for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ++I) {
2219 auto *BB = &*I;
2220 if (Reachable.count(BB))
Evgeniy Stepanov4fbc0d082012-12-21 11:18:49 +00002221 continue;
Alina Sbirlea2ab544b2018-08-16 21:58:44 +00002222 DeadBlockSet.insert(BB);
2223 }
2224
2225 if (MSSAU)
2226 MSSAU->removeBlocks(DeadBlockSet);
2227
2228 // Loop over all of the basic blocks that are not reachable, dropping all of
2229 // their internal references. Update DTU and LVI if available.
2230 std::vector<DominatorTree::UpdateType> Updates;
2231 for (auto *BB : DeadBlockSet) {
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +00002232 for (BasicBlock *Successor : successors(BB)) {
Alina Sbirlea2ab544b2018-08-16 21:58:44 +00002233 if (!DeadBlockSet.count(Successor))
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +00002234 Successor->removePredecessor(BB);
Chijun Sima21a8b602018-08-03 05:08:17 +00002235 if (DTU)
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +00002236 Updates.push_back({DominatorTree::Delete, BB, Successor});
2237 }
David Majnemerd9833ea2016-01-10 07:13:04 +00002238 if (LVI)
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +00002239 LVI->eraseBlock(BB);
Peter Collingbourne8d642de2013-08-12 22:38:43 +00002240 BB->dropAllReferences();
Evgeniy Stepanov4fbc0d082012-12-21 11:18:49 +00002241 }
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +00002242 for (Function::iterator I = ++F.begin(); I != F.end();) {
2243 auto *BB = &*I;
2244 if (Reachable.count(BB)) {
Reid Klecknercd78ddc2018-01-04 23:23:46 +00002245 ++I;
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +00002246 continue;
2247 }
Chijun Sima21a8b602018-08-03 05:08:17 +00002248 if (DTU) {
Chandler Carruthc8eaea72018-10-18 00:39:18 +00002249 // Remove the terminator of BB to clear the successor list of BB.
Chijun Sima21a8b602018-08-03 05:08:17 +00002250 if (BB->getTerminator())
2251 BB->getInstList().pop_back();
2252 new UnreachableInst(BB->getContext(), BB);
2253 assert(succ_empty(BB) && "The successor list of BB isn't empty before "
2254 "applying corresponding DTU updates.");
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +00002255 ++I;
2256 } else {
2257 I = F.getBasicBlockList().erase(I);
2258 }
2259 }
Evgeniy Stepanov2a066af2013-03-22 08:43:04 +00002260
Chijun Sima21a8b602018-08-03 05:08:17 +00002261 if (DTU) {
Chijun Sima70e97162019-02-22 13:48:38 +00002262 DTU->applyUpdatesPermissive(Updates);
Chijun Sima53048432018-08-03 12:45:29 +00002263 bool Deleted = false;
Alina Sbirlea2ab544b2018-08-16 21:58:44 +00002264 for (auto *BB : DeadBlockSet) {
Chijun Sima53048432018-08-03 12:45:29 +00002265 if (DTU->isBBPendingDeletion(BB))
2266 --NumRemoved;
2267 else
2268 Deleted = true;
Chijun Sima21a8b602018-08-03 05:08:17 +00002269 DTU->deleteBB(BB);
Chijun Sima53048432018-08-03 12:45:29 +00002270 }
2271 if (!Deleted)
2272 return false;
Chijun Sima21a8b602018-08-03 05:08:17 +00002273 }
Evgeniy Stepanov4fbc0d082012-12-21 11:18:49 +00002274 return true;
2275}
Rafael Espindolaea46c322014-08-15 15:46:38 +00002276
Piotr Padlewskidc9b2cf2015-10-02 22:12:22 +00002277void llvm::combineMetadata(Instruction *K, const Instruction *J,
Florian Hahn950576b2018-08-07 15:36:11 +00002278 ArrayRef<unsigned> KnownIDs, bool DoesKMove) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00002279 SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
Adrian Prantlcbdfdb72015-08-20 22:00:30 +00002280 K->dropUnknownNonDebugMetadata(KnownIDs);
Rafael Espindolaea46c322014-08-15 15:46:38 +00002281 K->getAllMetadataOtherThanDebugLoc(Metadata);
David Majnemer6f014d32016-07-25 02:21:19 +00002282 for (const auto &MD : Metadata) {
2283 unsigned Kind = MD.first;
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00002284 MDNode *JMD = J->getMetadata(Kind);
David Majnemer6f014d32016-07-25 02:21:19 +00002285 MDNode *KMD = MD.second;
Rafael Espindolaea46c322014-08-15 15:46:38 +00002286
2287 switch (Kind) {
2288 default:
2289 K->setMetadata(Kind, nullptr); // Remove unknown metadata
2290 break;
2291 case LLVMContext::MD_dbg:
2292 llvm_unreachable("getAllMetadataOtherThanDebugLoc returned a MD_dbg");
2293 case LLVMContext::MD_tbaa:
2294 K->setMetadata(Kind, MDNode::getMostGenericTBAA(JMD, KMD));
2295 break;
2296 case LLVMContext::MD_alias_scope:
Bjorn Steinbrink5ec75222015-02-08 17:07:14 +00002297 K->setMetadata(Kind, MDNode::getMostGenericAliasScope(JMD, KMD));
2298 break;
Rafael Espindolaea46c322014-08-15 15:46:38 +00002299 case LLVMContext::MD_noalias:
Hal Finkele4c0c162016-04-26 02:06:06 +00002300 case LLVMContext::MD_mem_parallel_loop_access:
Rafael Espindolaea46c322014-08-15 15:46:38 +00002301 K->setMetadata(Kind, MDNode::intersect(JMD, KMD));
2302 break;
Michael Kruse978ba612018-12-20 04:58:07 +00002303 case LLVMContext::MD_access_group:
2304 K->setMetadata(LLVMContext::MD_access_group,
2305 intersectAccessGroups(K, J));
2306 break;
Rafael Espindolaea46c322014-08-15 15:46:38 +00002307 case LLVMContext::MD_range:
Florian Hahnfc7654a2018-10-27 16:53:45 +00002308
2309 // If K does move, use most generic range. Otherwise keep the range of
2310 // K.
2311 if (DoesKMove)
2312 // FIXME: If K does move, we should drop the range info and nonnull.
2313 // Currently this function is used with DoesKMove in passes
2314 // doing hoisting/sinking and the current behavior of using the
2315 // most generic range is correct in those cases.
2316 K->setMetadata(Kind, MDNode::getMostGenericRange(JMD, KMD));
Rafael Espindolaea46c322014-08-15 15:46:38 +00002317 break;
2318 case LLVMContext::MD_fpmath:
2319 K->setMetadata(Kind, MDNode::getMostGenericFPMath(JMD, KMD));
2320 break;
2321 case LLVMContext::MD_invariant_load:
2322 // Only set the !invariant.load if it is present in both instructions.
2323 K->setMetadata(Kind, JMD);
2324 break;
Philip Reamesd7c21362014-10-21 21:02:19 +00002325 case LLVMContext::MD_nonnull:
Florian Hahn950576b2018-08-07 15:36:11 +00002326 // If K does move, keep nonull if it is present in both instructions.
2327 if (DoesKMove)
2328 K->setMetadata(Kind, JMD);
Philip Reamesd7c21362014-10-21 21:02:19 +00002329 break;
Piotr Padlewskidc9b2cf2015-10-02 22:12:22 +00002330 case LLVMContext::MD_invariant_group:
2331 // Preserve !invariant.group in K.
2332 break;
Artur Pilipenko5c5011d2015-11-02 17:53:51 +00002333 case LLVMContext::MD_align:
Chandler Carruth2abb65a2017-06-26 03:31:31 +00002334 K->setMetadata(Kind,
Artur Pilipenko5c5011d2015-11-02 17:53:51 +00002335 MDNode::getMostGenericAlignmentOrDereferenceable(JMD, KMD));
2336 break;
2337 case LLVMContext::MD_dereferenceable:
2338 case LLVMContext::MD_dereferenceable_or_null:
Chandler Carruth2abb65a2017-06-26 03:31:31 +00002339 K->setMetadata(Kind,
Artur Pilipenko5c5011d2015-11-02 17:53:51 +00002340 MDNode::getMostGenericAlignmentOrDereferenceable(JMD, KMD));
2341 break;
Yonghong Song44b16bd2019-08-03 23:41:26 +00002342 case LLVMContext::MD_preserve_access_index:
2343 // Preserve !preserve.access.index in K.
2344 break;
Rafael Espindolaea46c322014-08-15 15:46:38 +00002345 }
2346 }
Piotr Padlewskidc9b2cf2015-10-02 22:12:22 +00002347 // Set !invariant.group from J if J has it. If both instructions have it
2348 // then we will just pick it from J - even when they are different.
2349 // Also make sure that K is load or store - f.e. combining bitcast with load
2350 // could produce bitcast with invariant.group metadata, which is invalid.
2351 // FIXME: we should try to preserve both invariant.group md if they are
2352 // different, but right now instruction can only have one invariant.group.
2353 if (auto *JMD = J->getMetadata(LLVMContext::MD_invariant_group))
2354 if (isa<LoadInst>(K) || isa<StoreInst>(K))
2355 K->setMetadata(LLVMContext::MD_invariant_group, JMD);
Rafael Espindolaea46c322014-08-15 15:46:38 +00002356}
Philip Reames7c78ef72015-05-22 23:53:24 +00002357
Florian Hahn406f1ff2018-08-24 11:40:04 +00002358void llvm::combineMetadataForCSE(Instruction *K, const Instruction *J,
2359 bool KDominatesJ) {
Eli Friedman02419a92016-08-08 04:10:22 +00002360 unsigned KnownIDs[] = {
2361 LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
2362 LLVMContext::MD_noalias, LLVMContext::MD_range,
2363 LLVMContext::MD_invariant_load, LLVMContext::MD_nonnull,
2364 LLVMContext::MD_invariant_group, LLVMContext::MD_align,
2365 LLVMContext::MD_dereferenceable,
Michael Kruse978ba612018-12-20 04:58:07 +00002366 LLVMContext::MD_dereferenceable_or_null,
Yonghong Song44b16bd2019-08-03 23:41:26 +00002367 LLVMContext::MD_access_group, LLVMContext::MD_preserve_access_index};
Florian Hahn406f1ff2018-08-24 11:40:04 +00002368 combineMetadata(K, J, KnownIDs, KDominatesJ);
Eli Friedman02419a92016-08-08 04:10:22 +00002369}
2370
Sanjay Patel86e9f9d2019-07-24 22:11:11 +00002371void llvm::copyMetadataForLoad(LoadInst &Dest, const LoadInst &Source) {
2372 SmallVector<std::pair<unsigned, MDNode *>, 8> MD;
2373 Source.getAllMetadata(MD);
2374 MDBuilder MDB(Dest.getContext());
2375 Type *NewType = Dest.getType();
2376 const DataLayout &DL = Source.getModule()->getDataLayout();
2377 for (const auto &MDPair : MD) {
2378 unsigned ID = MDPair.first;
2379 MDNode *N = MDPair.second;
2380 // Note, essentially every kind of metadata should be preserved here! This
2381 // routine is supposed to clone a load instruction changing *only its type*.
2382 // The only metadata it makes sense to drop is metadata which is invalidated
2383 // when the pointer type changes. This should essentially never be the case
2384 // in LLVM, but we explicitly switch over only known metadata to be
2385 // conservatively correct. If you are adding metadata to LLVM which pertains
2386 // to loads, you almost certainly want to add it here.
2387 switch (ID) {
2388 case LLVMContext::MD_dbg:
2389 case LLVMContext::MD_tbaa:
2390 case LLVMContext::MD_prof:
2391 case LLVMContext::MD_fpmath:
2392 case LLVMContext::MD_tbaa_struct:
2393 case LLVMContext::MD_invariant_load:
2394 case LLVMContext::MD_alias_scope:
2395 case LLVMContext::MD_noalias:
2396 case LLVMContext::MD_nontemporal:
2397 case LLVMContext::MD_mem_parallel_loop_access:
2398 case LLVMContext::MD_access_group:
2399 // All of these directly apply.
2400 Dest.setMetadata(ID, N);
2401 break;
2402
2403 case LLVMContext::MD_nonnull:
2404 copyNonnullMetadata(Source, N, Dest);
2405 break;
2406
2407 case LLVMContext::MD_align:
2408 case LLVMContext::MD_dereferenceable:
2409 case LLVMContext::MD_dereferenceable_or_null:
2410 // These only directly apply if the new type is also a pointer.
2411 if (NewType->isPointerTy())
2412 Dest.setMetadata(ID, N);
2413 break;
2414
2415 case LLVMContext::MD_range:
2416 copyRangeMetadata(DL, Source, N, Dest);
2417 break;
2418 }
2419 }
2420}
2421
Florian Hahn39bbe172018-08-07 13:27:33 +00002422void llvm::patchReplacementInstruction(Instruction *I, Value *Repl) {
2423 auto *ReplInst = dyn_cast<Instruction>(Repl);
2424 if (!ReplInst)
2425 return;
2426
2427 // Patch the replacement so that it is not more restrictive than the value
2428 // being replaced.
2429 // Note that if 'I' is a load being replaced by some operation,
2430 // for example, by an arithmetic operation, then andIRFlags()
2431 // would just erase all math flags from the original arithmetic
2432 // operation, which is clearly not wanted and not needed.
2433 if (!isa<LoadInst>(I))
2434 ReplInst->andIRFlags(I);
2435
2436 // FIXME: If both the original and replacement value are part of the
2437 // same control-flow region (meaning that the execution of one
2438 // guarantees the execution of the other), then we can combine the
2439 // noalias scopes here and do better than the general conservative
2440 // answer used in combineMetadata().
2441
2442 // In general, GVN unifies expressions over different control-flow
2443 // regions, and so we need a conservative combination of the noalias
2444 // scopes.
2445 static const unsigned KnownIDs[] = {
2446 LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
2447 LLVMContext::MD_noalias, LLVMContext::MD_range,
2448 LLVMContext::MD_fpmath, LLVMContext::MD_invariant_load,
Michael Kruse978ba612018-12-20 04:58:07 +00002449 LLVMContext::MD_invariant_group, LLVMContext::MD_nonnull,
Yonghong Song44b16bd2019-08-03 23:41:26 +00002450 LLVMContext::MD_access_group, LLVMContext::MD_preserve_access_index};
Florian Hahn950576b2018-08-07 15:36:11 +00002451 combineMetadata(ReplInst, I, KnownIDs, false);
Florian Hahn39bbe172018-08-07 13:27:33 +00002452}
2453
Piotr Padlewskid979c1f2017-05-09 19:39:44 +00002454template <typename RootType, typename DominatesFn>
2455static unsigned replaceDominatedUsesWith(Value *From, Value *To,
2456 const RootType &Root,
2457 const DominatesFn &Dominates) {
Piotr Padlewski28ffcbe2015-09-02 19:59:59 +00002458 assert(From->getType() == To->getType());
2459
2460 unsigned Count = 0;
2461 for (Value::use_iterator UI = From->use_begin(), UE = From->use_end();
2462 UI != UE;) {
2463 Use &U = *UI++;
Piotr Padlewskid979c1f2017-05-09 19:39:44 +00002464 if (!Dominates(Root, U))
2465 continue;
2466 U.set(To);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002467 LLVM_DEBUG(dbgs() << "Replace dominated use of '" << From->getName()
2468 << "' as " << *To << " in " << *U << "\n");
Piotr Padlewskid979c1f2017-05-09 19:39:44 +00002469 ++Count;
Piotr Padlewski28ffcbe2015-09-02 19:59:59 +00002470 }
2471 return Count;
2472}
Sanjoy Dasc21a05a2015-10-08 23:18:30 +00002473
Anna Thomasc07d5542017-05-23 13:36:25 +00002474unsigned llvm::replaceNonLocalUsesWith(Instruction *From, Value *To) {
2475 assert(From->getType() == To->getType());
2476 auto *BB = From->getParent();
2477 unsigned Count = 0;
2478
2479 for (Value::use_iterator UI = From->use_begin(), UE = From->use_end();
2480 UI != UE;) {
2481 Use &U = *UI++;
2482 auto *I = cast<Instruction>(U.getUser());
2483 if (I->getParent() == BB)
2484 continue;
2485 U.set(To);
2486 ++Count;
2487 }
2488 return Count;
2489}
2490
Piotr Padlewskid979c1f2017-05-09 19:39:44 +00002491unsigned llvm::replaceDominatedUsesWith(Value *From, Value *To,
2492 DominatorTree &DT,
2493 const BasicBlockEdge &Root) {
2494 auto Dominates = [&DT](const BasicBlockEdge &Root, const Use &U) {
2495 return DT.dominates(Root, U);
2496 };
2497 return ::replaceDominatedUsesWith(From, To, Root, Dominates);
2498}
2499
2500unsigned llvm::replaceDominatedUsesWith(Value *From, Value *To,
2501 DominatorTree &DT,
2502 const BasicBlock *BB) {
2503 auto ProperlyDominates = [&DT](const BasicBlock *BB, const Use &U) {
2504 auto *I = cast<Instruction>(U.getUser())->getParent();
2505 return DT.properlyDominates(BB, I);
2506 };
2507 return ::replaceDominatedUsesWith(From, To, BB, ProperlyDominates);
2508}
2509
Chandler Carruth31607342019-02-11 07:42:30 +00002510bool llvm::callsGCLeafFunction(const CallBase *Call,
Daniel Neilson2574d7c2017-07-27 16:49:39 +00002511 const TargetLibraryInfo &TLI) {
Sanjoy Dasc21a05a2015-10-08 23:18:30 +00002512 // Check if the function is specifically marked as a gc leaf function.
Chandler Carruth31607342019-02-11 07:42:30 +00002513 if (Call->hasFnAttr("gc-leaf-function"))
Manuel Jacob3eedd112016-01-05 23:59:08 +00002514 return true;
Chandler Carruth31607342019-02-11 07:42:30 +00002515 if (const Function *F = Call->getCalledFunction()) {
Sanjoy Dasd4c78332016-03-25 20:12:13 +00002516 if (F->hasFnAttribute("gc-leaf-function"))
2517 return true;
2518
2519 if (auto IID = F->getIntrinsicID())
2520 // Most LLVM intrinsics do not take safepoints.
2521 return IID != Intrinsic::experimental_gc_statepoint &&
2522 IID != Intrinsic::experimental_deoptimize;
2523 }
Sanjoy Dasc21a05a2015-10-08 23:18:30 +00002524
Daniel Neilson2574d7c2017-07-27 16:49:39 +00002525 // Lib calls can be materialized by some passes, and won't be
2526 // marked as 'gc-leaf-function.' All available Libcalls are
2527 // GC-leaf.
2528 LibFunc LF;
Chandler Carruth31607342019-02-11 07:42:30 +00002529 if (TLI.getLibFunc(ImmutableCallSite(Call), LF)) {
Daniel Neilson2574d7c2017-07-27 16:49:39 +00002530 return TLI.has(LF);
2531 }
2532
Sanjoy Dasc21a05a2015-10-08 23:18:30 +00002533 return false;
2534}
James Molloyf01488e2016-01-15 09:20:19 +00002535
Chandler Carruth2abb65a2017-06-26 03:31:31 +00002536void llvm::copyNonnullMetadata(const LoadInst &OldLI, MDNode *N,
2537 LoadInst &NewLI) {
2538 auto *NewTy = NewLI.getType();
2539
2540 // This only directly applies if the new type is also a pointer.
2541 if (NewTy->isPointerTy()) {
2542 NewLI.setMetadata(LLVMContext::MD_nonnull, N);
2543 return;
2544 }
2545
2546 // The only other translation we can do is to integral loads with !range
2547 // metadata.
2548 if (!NewTy->isIntegerTy())
2549 return;
2550
2551 MDBuilder MDB(NewLI.getContext());
2552 const Value *Ptr = OldLI.getPointerOperand();
2553 auto *ITy = cast<IntegerType>(NewTy);
2554 auto *NullInt = ConstantExpr::getPtrToInt(
2555 ConstantPointerNull::get(cast<PointerType>(Ptr->getType())), ITy);
2556 auto *NonNullInt = ConstantExpr::getAdd(NullInt, ConstantInt::get(ITy, 1));
2557 NewLI.setMetadata(LLVMContext::MD_range,
2558 MDB.createRange(NonNullInt, NullInt));
2559}
2560
2561void llvm::copyRangeMetadata(const DataLayout &DL, const LoadInst &OldLI,
2562 MDNode *N, LoadInst &NewLI) {
2563 auto *NewTy = NewLI.getType();
2564
Rafael Espindolac06f55e2017-11-28 01:25:38 +00002565 // Give up unless it is converted to a pointer where there is a single very
2566 // valuable mapping we can do reliably.
2567 // FIXME: It would be nice to propagate this in more ways, but the type
2568 // conversions make it hard.
2569 if (!NewTy->isPointerTy())
Chandler Carruth2abb65a2017-06-26 03:31:31 +00002570 return;
2571
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00002572 unsigned BitWidth = DL.getIndexTypeSizeInBits(NewTy);
Rafael Espindolac06f55e2017-11-28 01:25:38 +00002573 if (!getConstantRangeFromMetadata(*N).contains(APInt(BitWidth, 0))) {
2574 MDNode *NN = MDNode::get(OldLI.getContext(), None);
2575 NewLI.setMetadata(LLVMContext::MD_nonnull, NN);
Chandler Carruth2abb65a2017-06-26 03:31:31 +00002576 }
2577}
2578
Carlos Alberto Encisoba4e4372018-09-19 08:16:56 +00002579void llvm::dropDebugUsers(Instruction &I) {
2580 SmallVector<DbgVariableIntrinsic *, 1> DbgUsers;
2581 findDbgUsers(DbgUsers, &I);
2582 for (auto *DII : DbgUsers)
2583 DII->eraseFromParent();
2584}
2585
Carlos Alberto Enciso9a24e1a2018-10-25 09:58:59 +00002586void llvm::hoistAllInstructionsInto(BasicBlock *DomBlock, Instruction *InsertPt,
2587 BasicBlock *BB) {
2588 // Since we are moving the instructions out of its basic block, we do not
2589 // retain their original debug locations (DILocations) and debug intrinsic
Carlos Alberto Enciso08dc50f2019-02-08 10:57:26 +00002590 // instructions.
Carlos Alberto Enciso9a24e1a2018-10-25 09:58:59 +00002591 //
2592 // Doing so would degrade the debugging experience and adversely affect the
2593 // accuracy of profiling information.
2594 //
2595 // Currently, when hoisting the instructions, we take the following actions:
Carlos Alberto Enciso08dc50f2019-02-08 10:57:26 +00002596 // - Remove their debug intrinsic instructions.
Carlos Alberto Enciso9a24e1a2018-10-25 09:58:59 +00002597 // - Set their debug locations to the values from the insertion point.
2598 //
2599 // As per PR39141 (comment #8), the more fundamental reason why the dbg.values
2600 // need to be deleted, is because there will not be any instructions with a
2601 // DILocation in either branch left after performing the transformation. We
2602 // can only insert a dbg.value after the two branches are joined again.
2603 //
2604 // See PR38762, PR39243 for more details.
2605 //
2606 // TODO: Extend llvm.dbg.value to take more than one SSA Value (PR39141) to
2607 // encode predicated DIExpressions that yield different results on different
2608 // code paths.
2609 for (BasicBlock::iterator II = BB->begin(), IE = BB->end(); II != IE;) {
2610 Instruction *I = &*II;
2611 I->dropUnknownNonDebugMetadata();
2612 if (I->isUsedByMetadata())
2613 dropDebugUsers(*I);
Carlos Alberto Enciso08dc50f2019-02-08 10:57:26 +00002614 if (isa<DbgInfoIntrinsic>(I)) {
Carlos Alberto Enciso9a24e1a2018-10-25 09:58:59 +00002615 // Remove DbgInfo Intrinsics.
2616 II = I->eraseFromParent();
2617 continue;
2618 }
2619 I->setDebugLoc(InsertPt->getDebugLoc());
2620 ++II;
2621 }
2622 DomBlock->getInstList().splice(InsertPt->getIterator(), BB->getInstList(),
2623 BB->begin(),
2624 BB->getTerminator()->getIterator());
2625}
2626
Benjamin Kramerb7d33112016-08-06 11:13:10 +00002627namespace {
Eugene Zelenko6cadde72017-10-17 21:27:42 +00002628
James Molloyf01488e2016-01-15 09:20:19 +00002629/// A potential constituent of a bitreverse or bswap expression. See
2630/// collectBitParts for a fuller explanation.
2631struct BitPart {
2632 BitPart(Value *P, unsigned BW) : Provider(P) {
2633 Provenance.resize(BW);
2634 }
2635
2636 /// The Value that this is a bitreverse/bswap of.
2637 Value *Provider;
Eugene Zelenko6cadde72017-10-17 21:27:42 +00002638
James Molloyf01488e2016-01-15 09:20:19 +00002639 /// The "provenance" of each bit. Provenance[A] = B means that bit A
2640 /// in Provider becomes bit B in the result of this expression.
2641 SmallVector<int8_t, 32> Provenance; // int8_t means max size is i128.
2642
2643 enum { Unset = -1 };
2644};
Eugene Zelenko6cadde72017-10-17 21:27:42 +00002645
Benjamin Kramerb7d33112016-08-06 11:13:10 +00002646} // end anonymous namespace
James Molloyf01488e2016-01-15 09:20:19 +00002647
2648/// Analyze the specified subexpression and see if it is capable of providing
2649/// pieces of a bswap or bitreverse. The subexpression provides a potential
2650/// piece of a bswap or bitreverse if it can be proven that each non-zero bit in
2651/// the output of the expression came from a corresponding bit in some other
2652/// value. This function is recursive, and the end result is a mapping of
2653/// bitnumber to bitnumber. It is the caller's responsibility to validate that
2654/// the bitnumber to bitnumber mapping is correct for a bswap or bitreverse.
2655///
2656/// For example, if the current subexpression if "(shl i32 %X, 24)" then we know
2657/// that the expression deposits the low byte of %X into the high byte of the
2658/// result and that all other bits are zero. This expression is accepted and a
2659/// BitPart is returned with Provider set to %X and Provenance[24-31] set to
2660/// [0-7].
2661///
2662/// To avoid revisiting values, the BitPart results are memoized into the
2663/// provided map. To avoid unnecessary copying of BitParts, BitParts are
2664/// constructed in-place in the \c BPS map. Because of this \c BPS needs to
2665/// store BitParts objects, not pointers. As we need the concept of a nullptr
2666/// BitParts (Value has been analyzed and the analysis failed), we an Optional
2667/// type instead to provide the same functionality.
2668///
2669/// Because we pass around references into \c BPS, we must use a container that
2670/// does not invalidate internal references (std::map instead of DenseMap).
James Molloyf01488e2016-01-15 09:20:19 +00002671static const Optional<BitPart> &
2672collectBitParts(Value *V, bool MatchBSwaps, bool MatchBitReversals,
David Stuttard411488b2019-05-09 15:02:10 +00002673 std::map<Value *, Optional<BitPart>> &BPS, int Depth) {
James Molloyf01488e2016-01-15 09:20:19 +00002674 auto I = BPS.find(V);
2675 if (I != BPS.end())
2676 return I->second;
2677
2678 auto &Result = BPS[V] = None;
2679 auto BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
2680
David Stuttard411488b2019-05-09 15:02:10 +00002681 // Prevent stack overflow by limiting the recursion depth
2682 if (Depth == BitPartRecursionMaxDepth) {
2683 LLVM_DEBUG(dbgs() << "collectBitParts max recursion depth reached.\n");
2684 return Result;
2685 }
2686
James Molloyf01488e2016-01-15 09:20:19 +00002687 if (Instruction *I = dyn_cast<Instruction>(V)) {
2688 // If this is an or instruction, it may be an inner node of the bswap.
2689 if (I->getOpcode() == Instruction::Or) {
2690 auto &A = collectBitParts(I->getOperand(0), MatchBSwaps,
David Stuttard411488b2019-05-09 15:02:10 +00002691 MatchBitReversals, BPS, Depth + 1);
James Molloyf01488e2016-01-15 09:20:19 +00002692 auto &B = collectBitParts(I->getOperand(1), MatchBSwaps,
David Stuttard411488b2019-05-09 15:02:10 +00002693 MatchBitReversals, BPS, Depth + 1);
James Molloyf01488e2016-01-15 09:20:19 +00002694 if (!A || !B)
2695 return Result;
2696
2697 // Try and merge the two together.
2698 if (!A->Provider || A->Provider != B->Provider)
2699 return Result;
2700
2701 Result = BitPart(A->Provider, BitWidth);
2702 for (unsigned i = 0; i < A->Provenance.size(); ++i) {
2703 if (A->Provenance[i] != BitPart::Unset &&
2704 B->Provenance[i] != BitPart::Unset &&
2705 A->Provenance[i] != B->Provenance[i])
2706 return Result = None;
2707
2708 if (A->Provenance[i] == BitPart::Unset)
2709 Result->Provenance[i] = B->Provenance[i];
2710 else
2711 Result->Provenance[i] = A->Provenance[i];
2712 }
2713
2714 return Result;
2715 }
2716
2717 // If this is a logical shift by a constant, recurse then shift the result.
2718 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
2719 unsigned BitShift =
2720 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
2721 // Ensure the shift amount is defined.
2722 if (BitShift > BitWidth)
2723 return Result;
2724
2725 auto &Res = collectBitParts(I->getOperand(0), MatchBSwaps,
David Stuttard411488b2019-05-09 15:02:10 +00002726 MatchBitReversals, BPS, Depth + 1);
James Molloyf01488e2016-01-15 09:20:19 +00002727 if (!Res)
2728 return Result;
2729 Result = Res;
2730
2731 // Perform the "shift" on BitProvenance.
2732 auto &P = Result->Provenance;
2733 if (I->getOpcode() == Instruction::Shl) {
2734 P.erase(std::prev(P.end(), BitShift), P.end());
2735 P.insert(P.begin(), BitShift, BitPart::Unset);
2736 } else {
2737 P.erase(P.begin(), std::next(P.begin(), BitShift));
2738 P.insert(P.end(), BitShift, BitPart::Unset);
2739 }
2740
2741 return Result;
2742 }
2743
2744 // If this is a logical 'and' with a mask that clears bits, recurse then
2745 // unset the appropriate bits.
2746 if (I->getOpcode() == Instruction::And &&
2747 isa<ConstantInt>(I->getOperand(1))) {
2748 APInt Bit(I->getType()->getPrimitiveSizeInBits(), 1);
2749 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
2750
2751 // Check that the mask allows a multiple of 8 bits for a bswap, for an
2752 // early exit.
2753 unsigned NumMaskedBits = AndMask.countPopulation();
2754 if (!MatchBitReversals && NumMaskedBits % 8 != 0)
2755 return Result;
Chandler Carruth2abb65a2017-06-26 03:31:31 +00002756
James Molloyf01488e2016-01-15 09:20:19 +00002757 auto &Res = collectBitParts(I->getOperand(0), MatchBSwaps,
David Stuttard411488b2019-05-09 15:02:10 +00002758 MatchBitReversals, BPS, Depth + 1);
James Molloyf01488e2016-01-15 09:20:19 +00002759 if (!Res)
2760 return Result;
2761 Result = Res;
2762
2763 for (unsigned i = 0; i < BitWidth; ++i, Bit <<= 1)
2764 // If the AndMask is zero for this bit, clear the bit.
2765 if ((AndMask & Bit) == 0)
2766 Result->Provenance[i] = BitPart::Unset;
Chad Rosiere5819e22016-05-26 14:58:51 +00002767 return Result;
2768 }
James Molloyf01488e2016-01-15 09:20:19 +00002769
Chad Rosiere5819e22016-05-26 14:58:51 +00002770 // If this is a zext instruction zero extend the result.
2771 if (I->getOpcode() == Instruction::ZExt) {
2772 auto &Res = collectBitParts(I->getOperand(0), MatchBSwaps,
David Stuttard411488b2019-05-09 15:02:10 +00002773 MatchBitReversals, BPS, Depth + 1);
Chad Rosiere5819e22016-05-26 14:58:51 +00002774 if (!Res)
2775 return Result;
2776
2777 Result = BitPart(Res->Provider, BitWidth);
2778 auto NarrowBitWidth =
2779 cast<IntegerType>(cast<ZExtInst>(I)->getSrcTy())->getBitWidth();
2780 for (unsigned i = 0; i < NarrowBitWidth; ++i)
2781 Result->Provenance[i] = Res->Provenance[i];
2782 for (unsigned i = NarrowBitWidth; i < BitWidth; ++i)
2783 Result->Provenance[i] = BitPart::Unset;
James Molloyf01488e2016-01-15 09:20:19 +00002784 return Result;
2785 }
2786 }
2787
2788 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
2789 // the input value to the bswap/bitreverse.
2790 Result = BitPart(V, BitWidth);
2791 for (unsigned i = 0; i < BitWidth; ++i)
2792 Result->Provenance[i] = i;
2793 return Result;
2794}
2795
2796static bool bitTransformIsCorrectForBSwap(unsigned From, unsigned To,
2797 unsigned BitWidth) {
2798 if (From % 8 != To % 8)
2799 return false;
2800 // Convert from bit indices to byte indices and check for a byte reversal.
2801 From >>= 3;
2802 To >>= 3;
2803 BitWidth >>= 3;
2804 return From == BitWidth - To - 1;
2805}
2806
2807static bool bitTransformIsCorrectForBitReverse(unsigned From, unsigned To,
2808 unsigned BitWidth) {
2809 return From == BitWidth - To - 1;
2810}
2811
Chad Rosiera00df492016-05-25 16:22:14 +00002812bool llvm::recognizeBSwapOrBitReverseIdiom(
James Molloyf01488e2016-01-15 09:20:19 +00002813 Instruction *I, bool MatchBSwaps, bool MatchBitReversals,
2814 SmallVectorImpl<Instruction *> &InsertedInsts) {
2815 if (Operator::getOpcode(I) != Instruction::Or)
2816 return false;
2817 if (!MatchBSwaps && !MatchBitReversals)
2818 return false;
2819 IntegerType *ITy = dyn_cast<IntegerType>(I->getType());
2820 if (!ITy || ITy->getBitWidth() > 128)
2821 return false; // Can't do vectors or integers > 128 bits.
2822 unsigned BW = ITy->getBitWidth();
2823
Chad Rosiere5819e22016-05-26 14:58:51 +00002824 unsigned DemandedBW = BW;
2825 IntegerType *DemandedTy = ITy;
2826 if (I->hasOneUse()) {
2827 if (TruncInst *Trunc = dyn_cast<TruncInst>(I->user_back())) {
2828 DemandedTy = cast<IntegerType>(Trunc->getType());
2829 DemandedBW = DemandedTy->getBitWidth();
2830 }
2831 }
2832
James Molloyf01488e2016-01-15 09:20:19 +00002833 // Try to find all the pieces corresponding to the bswap.
2834 std::map<Value *, Optional<BitPart>> BPS;
David Stuttard411488b2019-05-09 15:02:10 +00002835 auto Res = collectBitParts(I, MatchBSwaps, MatchBitReversals, BPS, 0);
James Molloyf01488e2016-01-15 09:20:19 +00002836 if (!Res)
2837 return false;
2838 auto &BitProvenance = Res->Provenance;
2839
2840 // Now, is the bit permutation correct for a bswap or a bitreverse? We can
2841 // only byteswap values with an even number of bytes.
Chad Rosiere5819e22016-05-26 14:58:51 +00002842 bool OKForBSwap = DemandedBW % 16 == 0, OKForBitReverse = true;
2843 for (unsigned i = 0; i < DemandedBW; ++i) {
2844 OKForBSwap &=
2845 bitTransformIsCorrectForBSwap(BitProvenance[i], i, DemandedBW);
James Molloyf01488e2016-01-15 09:20:19 +00002846 OKForBitReverse &=
Chad Rosiere5819e22016-05-26 14:58:51 +00002847 bitTransformIsCorrectForBitReverse(BitProvenance[i], i, DemandedBW);
James Molloyf01488e2016-01-15 09:20:19 +00002848 }
2849
2850 Intrinsic::ID Intrin;
2851 if (OKForBSwap && MatchBSwaps)
2852 Intrin = Intrinsic::bswap;
2853 else if (OKForBitReverse && MatchBitReversals)
2854 Intrin = Intrinsic::bitreverse;
2855 else
2856 return false;
2857
Chad Rosiere5819e22016-05-26 14:58:51 +00002858 if (ITy != DemandedTy) {
2859 Function *F = Intrinsic::getDeclaration(I->getModule(), Intrin, DemandedTy);
2860 Value *Provider = Res->Provider;
2861 IntegerType *ProviderTy = cast<IntegerType>(Provider->getType());
2862 // We may need to truncate the provider.
2863 if (DemandedTy != ProviderTy) {
2864 auto *Trunc = CastInst::Create(Instruction::Trunc, Provider, DemandedTy,
2865 "trunc", I);
2866 InsertedInsts.push_back(Trunc);
2867 Provider = Trunc;
2868 }
2869 auto *CI = CallInst::Create(F, Provider, "rev", I);
2870 InsertedInsts.push_back(CI);
2871 auto *ExtInst = CastInst::Create(Instruction::ZExt, CI, ITy, "zext", I);
2872 InsertedInsts.push_back(ExtInst);
2873 return true;
2874 }
2875
James Molloyf01488e2016-01-15 09:20:19 +00002876 Function *F = Intrinsic::getDeclaration(I->getModule(), Intrin, ITy);
2877 InsertedInsts.push_back(CallInst::Create(F, Res->Provider, "rev", I));
2878 return true;
2879}
Marcin Koscielnicki3feda222016-06-18 10:10:37 +00002880
2881// CodeGen has special handling for some string functions that may replace
2882// them with target-specific intrinsics. Since that'd skip our interceptors
2883// in ASan/MSan/TSan/DFSan, and thus make us miss some memory accesses,
2884// we mark affected calls as NoBuiltin, which will disable optimization
2885// in CodeGen.
Evgeniy Stepanovd240a882016-07-28 23:45:15 +00002886void llvm::maybeMarkSanitizerLibraryCallNoBuiltin(
2887 CallInst *CI, const TargetLibraryInfo *TLI) {
Marcin Koscielnicki3feda222016-06-18 10:10:37 +00002888 Function *F = CI->getCalledFunction();
David L. Jonesd21529f2017-01-23 23:16:46 +00002889 LibFunc Func;
Evgeniy Stepanovd240a882016-07-28 23:45:15 +00002890 if (F && !F->hasLocalLinkage() && F->hasName() &&
2891 TLI->getLibFunc(F->getName(), Func) && TLI->hasOptimizedCodeGen(Func) &&
2892 !F->doesNotAccessMemory())
Reid Klecknerb5180542017-03-21 16:57:19 +00002893 CI->addAttribute(AttributeList::FunctionIndex, Attribute::NoBuiltin);
Marcin Koscielnicki3feda222016-06-18 10:10:37 +00002894}
James Molloya9290632017-05-25 12:51:11 +00002895
2896bool llvm::canReplaceOperandWithVariable(const Instruction *I, unsigned OpIdx) {
2897 // We can't have a PHI with a metadata type.
2898 if (I->getOperand(OpIdx)->getType()->isMetadataTy())
2899 return false;
2900
2901 // Early exit.
2902 if (!isa<Constant>(I->getOperand(OpIdx)))
2903 return true;
2904
2905 switch (I->getOpcode()) {
2906 default:
2907 return true;
2908 case Instruction::Call:
2909 case Instruction::Invoke:
Leo Li93abd7d2017-07-10 20:45:34 +00002910 // Can't handle inline asm. Skip it.
2911 if (isa<InlineAsm>(ImmutableCallSite(I).getCalledValue()))
2912 return false;
James Molloya9290632017-05-25 12:51:11 +00002913 // Many arithmetic intrinsics have no issue taking a
2914 // variable, however it's hard to distingish these from
2915 // specials such as @llvm.frameaddress that require a constant.
2916 if (isa<IntrinsicInst>(I))
2917 return false;
2918
2919 // Constant bundle operands may need to retain their constant-ness for
2920 // correctness.
2921 if (ImmutableCallSite(I).isBundleOperand(OpIdx))
2922 return false;
2923 return true;
2924 case Instruction::ShuffleVector:
2925 // Shufflevector masks are constant.
2926 return OpIdx != 2;
Leo Li5499b1b2017-07-06 18:47:05 +00002927 case Instruction::Switch:
James Molloya9290632017-05-25 12:51:11 +00002928 case Instruction::ExtractValue:
James Molloya9290632017-05-25 12:51:11 +00002929 // All operands apart from the first are constant.
2930 return OpIdx == 0;
Leo Li5499b1b2017-07-06 18:47:05 +00002931 case Instruction::InsertValue:
2932 // All operands apart from the first and the second are constant.
2933 return OpIdx < 2;
James Molloya9290632017-05-25 12:51:11 +00002934 case Instruction::Alloca:
Leo Li5499b1b2017-07-06 18:47:05 +00002935 // Static allocas (constant size in the entry block) are handled by
2936 // prologue/epilogue insertion so they're free anyway. We definitely don't
2937 // want to make them non-constant.
Craig Topper781aa182018-05-05 01:57:00 +00002938 return !cast<AllocaInst>(I)->isStaticAlloca();
James Molloya9290632017-05-25 12:51:11 +00002939 case Instruction::GetElementPtr:
2940 if (OpIdx == 0)
2941 return true;
2942 gep_type_iterator It = gep_type_begin(I);
2943 for (auto E = std::next(It, OpIdx); It != E; ++It)
2944 if (It.isStruct())
2945 return false;
2946 return true;
2947 }
2948}
Alexander Potapenko6a63e5a2019-04-15 08:59:56 +00002949
2950using AllocaForValueMapTy = DenseMap<Value *, AllocaInst *>;
2951AllocaInst *llvm::findAllocaForValue(Value *V,
2952 AllocaForValueMapTy &AllocaForValue) {
2953 if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
2954 return AI;
2955 // See if we've already calculated (or started to calculate) alloca for a
2956 // given value.
2957 AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
2958 if (I != AllocaForValue.end())
2959 return I->second;
2960 // Store 0 while we're calculating alloca for value V to avoid
2961 // infinite recursion if the value references itself.
2962 AllocaForValue[V] = nullptr;
2963 AllocaInst *Res = nullptr;
2964 if (CastInst *CI = dyn_cast<CastInst>(V))
2965 Res = findAllocaForValue(CI->getOperand(0), AllocaForValue);
2966 else if (PHINode *PN = dyn_cast<PHINode>(V)) {
2967 for (Value *IncValue : PN->incoming_values()) {
2968 // Allow self-referencing phi-nodes.
2969 if (IncValue == PN)
2970 continue;
2971 AllocaInst *IncValueAI = findAllocaForValue(IncValue, AllocaForValue);
2972 // AI for incoming values should exist and should all be equal.
2973 if (IncValueAI == nullptr || (Res != nullptr && IncValueAI != Res))
2974 return nullptr;
2975 Res = IncValueAI;
2976 }
2977 } else if (GetElementPtrInst *EP = dyn_cast<GetElementPtrInst>(V)) {
2978 Res = findAllocaForValue(EP->getPointerOperand(), AllocaForValue);
2979 } else {
2980 LLVM_DEBUG(dbgs() << "Alloca search cancelled on unknown instruction: "
2981 << *V << "\n");
2982 }
2983 if (Res)
2984 AllocaForValue[V] = Res;
2985 return Res;
2986}