Bug Summary

File:src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/ADT/APInt.h
Warning:line 403, column 36
The result of the right shift is undefined due to shifting by '64', which is greater or equal to the width of type 'llvm::APInt::WordType'

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple amd64-unknown-openbsd7.0 -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name Local.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -mrelocation-model pic -pic-level 1 -fhalf-no-semantic-interposition -mframe-pointer=all -relaxed-aliasing -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -fcoverage-compilation-dir=/usr/src/gnu/usr.bin/clang/libLLVM/obj -resource-dir /usr/local/lib/clang/13.0.0 -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Target/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Target/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Target/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Target/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Target/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Target/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Analysis -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/ASMParser -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/BinaryFormat -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Bitcode -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Bitcode -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Bitstream -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms -I /include/llvm/CodeGen -I /include/llvm/CodeGen/PBQP -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/IR -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/IR -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms/Coroutines -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/ProfileData/Coverage -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/DebugInfo/CodeView -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/DebugInfo/DWARF -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/DebugInfo -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/DebugInfo/MSF -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/DebugInfo/PDB -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Demangle -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/ExecutionEngine -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/ExecutionEngine/JITLink -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/ExecutionEngine/Orc -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Frontend -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Frontend/OpenACC -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Frontend -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Frontend/OpenMP -I /include/llvm/CodeGen/GlobalISel -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/IRReader -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms/InstCombine -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/Transforms/InstCombine -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/LTO -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Linker -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/MC -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/MC/MCParser -I /include/llvm/CodeGen/MIRParser -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Object -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Option -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Passes -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/ -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/ProfileData -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms/Scalar -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/ADT -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Support -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/DebugInfo/Symbolize -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Target -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms/Utils -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms/Vectorize -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/X86 -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Target/X86 -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/X86 -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Target/X86 -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/X86 -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Target/X86 -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/X86 -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Target/X86 -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/X86 -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Target/X86 -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms/IPO -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include -I /usr/src/gnu/usr.bin/clang/libLLVM/../include -I /usr/src/gnu/usr.bin/clang/libLLVM/obj -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include -D NDEBUG -D __STDC_LIMIT_MACROS -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D LLVM_PREFIX="/usr" -D PIC -internal-isystem /usr/include/c++/v1 -internal-isystem /usr/local/lib/clang/13.0.0/include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/usr/src/gnu/usr.bin/clang/libLLVM/obj -ferror-limit 19 -fvisibility-inlines-hidden -fwrapv -D_RET_PROTECTOR -ret-protector -fno-rtti -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -fno-builtin-malloc -fno-builtin-calloc -fno-builtin-realloc -fno-builtin-valloc -fno-builtin-free -fno-builtin-strdup -fno-builtin-strndup -analyzer-output=html -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /home/ben/Projects/vmm/scan-build/2022-01-12-194120-40624-1 -x c++ /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Transforms/Utils/Local.cpp

/usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Transforms/Utils/Local.cpp

1//===- Local.cpp - Functions to perform local transformations -------------===//
2//
3// 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
6//
7//===----------------------------------------------------------------------===//
8//
9// This family of functions perform various local transformations to the
10// program.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/Transforms/Utils/Local.h"
15#include "llvm/ADT/APInt.h"
16#include "llvm/ADT/DenseMap.h"
17#include "llvm/ADT/DenseMapInfo.h"
18#include "llvm/ADT/DenseSet.h"
19#include "llvm/ADT/Hashing.h"
20#include "llvm/ADT/None.h"
21#include "llvm/ADT/Optional.h"
22#include "llvm/ADT/STLExtras.h"
23#include "llvm/ADT/SetVector.h"
24#include "llvm/ADT/SmallPtrSet.h"
25#include "llvm/ADT/SmallVector.h"
26#include "llvm/ADT/Statistic.h"
27#include "llvm/Analysis/AssumeBundleQueries.h"
28#include "llvm/Analysis/ConstantFolding.h"
29#include "llvm/Analysis/DomTreeUpdater.h"
30#include "llvm/Analysis/EHPersonalities.h"
31#include "llvm/Analysis/InstructionSimplify.h"
32#include "llvm/Analysis/LazyValueInfo.h"
33#include "llvm/Analysis/MemoryBuiltins.h"
34#include "llvm/Analysis/MemorySSAUpdater.h"
35#include "llvm/Analysis/TargetLibraryInfo.h"
36#include "llvm/Analysis/ValueTracking.h"
37#include "llvm/Analysis/VectorUtils.h"
38#include "llvm/BinaryFormat/Dwarf.h"
39#include "llvm/IR/Argument.h"
40#include "llvm/IR/Attributes.h"
41#include "llvm/IR/BasicBlock.h"
42#include "llvm/IR/CFG.h"
43#include "llvm/IR/Constant.h"
44#include "llvm/IR/ConstantRange.h"
45#include "llvm/IR/Constants.h"
46#include "llvm/IR/DIBuilder.h"
47#include "llvm/IR/DataLayout.h"
48#include "llvm/IR/DebugInfoMetadata.h"
49#include "llvm/IR/DebugLoc.h"
50#include "llvm/IR/DerivedTypes.h"
51#include "llvm/IR/Dominators.h"
52#include "llvm/IR/Function.h"
53#include "llvm/IR/GetElementPtrTypeIterator.h"
54#include "llvm/IR/GlobalObject.h"
55#include "llvm/IR/IRBuilder.h"
56#include "llvm/IR/InstrTypes.h"
57#include "llvm/IR/Instruction.h"
58#include "llvm/IR/Instructions.h"
59#include "llvm/IR/IntrinsicInst.h"
60#include "llvm/IR/Intrinsics.h"
61#include "llvm/IR/LLVMContext.h"
62#include "llvm/IR/MDBuilder.h"
63#include "llvm/IR/Metadata.h"
64#include "llvm/IR/Module.h"
65#include "llvm/IR/Operator.h"
66#include "llvm/IR/PatternMatch.h"
67#include "llvm/IR/PseudoProbe.h"
68#include "llvm/IR/Type.h"
69#include "llvm/IR/Use.h"
70#include "llvm/IR/User.h"
71#include "llvm/IR/Value.h"
72#include "llvm/IR/ValueHandle.h"
73#include "llvm/Support/Casting.h"
74#include "llvm/Support/Debug.h"
75#include "llvm/Support/ErrorHandling.h"
76#include "llvm/Support/KnownBits.h"
77#include "llvm/Support/raw_ostream.h"
78#include "llvm/Transforms/Utils/BasicBlockUtils.h"
79#include "llvm/Transforms/Utils/ValueMapper.h"
80#include <algorithm>
81#include <cassert>
82#include <climits>
83#include <cstdint>
84#include <iterator>
85#include <map>
86#include <utility>
87
88using namespace llvm;
89using namespace llvm::PatternMatch;
90
91#define DEBUG_TYPE"local" "local"
92
93STATISTIC(NumRemoved, "Number of unreachable basic blocks removed")static llvm::Statistic NumRemoved = {"local", "NumRemoved", "Number of unreachable basic blocks removed"
}
;
94STATISTIC(NumPHICSEs, "Number of PHI's that got CSE'd")static llvm::Statistic NumPHICSEs = {"local", "NumPHICSEs", "Number of PHI's that got CSE'd"
}
;
95
96static cl::opt<bool> PHICSEDebugHash(
97 "phicse-debug-hash",
98#ifdef EXPENSIVE_CHECKS
99 cl::init(true),
100#else
101 cl::init(false),
102#endif
103 cl::Hidden,
104 cl::desc("Perform extra assertion checking to verify that PHINodes's hash "
105 "function is well-behaved w.r.t. its isEqual predicate"));
106
107static cl::opt<unsigned> PHICSENumPHISmallSize(
108 "phicse-num-phi-smallsize", cl::init(32), cl::Hidden,
109 cl::desc(
110 "When the basic block contains not more than this number of PHI nodes, "
111 "perform a (faster!) exhaustive search instead of set-driven one."));
112
113// Max recursion depth for collectBitParts used when detecting bswap and
114// bitreverse idioms.
115static const unsigned BitPartRecursionMaxDepth = 48;
116
117//===----------------------------------------------------------------------===//
118// Local constant propagation.
119//
120
121/// ConstantFoldTerminator - If a terminator instruction is predicated on a
122/// constant value, convert it into an unconditional branch to the constant
123/// destination. This is a nontrivial operation because the successors of this
124/// basic block must have their PHI nodes updated.
125/// Also calls RecursivelyDeleteTriviallyDeadInstructions() on any branch/switch
126/// conditions and indirectbr addresses this might make dead if
127/// DeleteDeadConditions is true.
128bool llvm::ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions,
129 const TargetLibraryInfo *TLI,
130 DomTreeUpdater *DTU) {
131 Instruction *T = BB->getTerminator();
132 IRBuilder<> Builder(T);
133
134 // Branch - See if we are conditional jumping on constant
135 if (auto *BI = dyn_cast<BranchInst>(T)) {
136 if (BI->isUnconditional()) return false; // Can't optimize uncond branch
137
138 BasicBlock *Dest1 = BI->getSuccessor(0);
139 BasicBlock *Dest2 = BI->getSuccessor(1);
140
141 if (Dest2 == Dest1) { // Conditional branch to same location?
142 // This branch matches something like this:
143 // br bool %cond, label %Dest, label %Dest
144 // and changes it into: br label %Dest
145
146 // Let the basic block know that we are letting go of one copy of it.
147 assert(BI->getParent() && "Terminator not inserted in block!")((void)0);
148 Dest1->removePredecessor(BI->getParent());
149
150 // Replace the conditional branch with an unconditional one.
151 BranchInst *NewBI = Builder.CreateBr(Dest1);
152
153 // Transfer the metadata to the new branch instruction.
154 NewBI->copyMetadata(*BI, {LLVMContext::MD_loop, LLVMContext::MD_dbg,
155 LLVMContext::MD_annotation});
156
157 Value *Cond = BI->getCondition();
158 BI->eraseFromParent();
159 if (DeleteDeadConditions)
160 RecursivelyDeleteTriviallyDeadInstructions(Cond, TLI);
161 return true;
162 }
163
164 if (auto *Cond = dyn_cast<ConstantInt>(BI->getCondition())) {
165 // Are we branching on constant?
166 // YES. Change to unconditional branch...
167 BasicBlock *Destination = Cond->getZExtValue() ? Dest1 : Dest2;
168 BasicBlock *OldDest = Cond->getZExtValue() ? Dest2 : Dest1;
169
170 // Let the basic block know that we are letting go of it. Based on this,
171 // it will adjust it's PHI nodes.
172 OldDest->removePredecessor(BB);
173
174 // Replace the conditional branch with an unconditional one.
175 BranchInst *NewBI = Builder.CreateBr(Destination);
176
177 // Transfer the metadata to the new branch instruction.
178 NewBI->copyMetadata(*BI, {LLVMContext::MD_loop, LLVMContext::MD_dbg,
179 LLVMContext::MD_annotation});
180
181 BI->eraseFromParent();
182 if (DTU)
183 DTU->applyUpdates({{DominatorTree::Delete, BB, OldDest}});
184 return true;
185 }
186
187 return false;
188 }
189
190 if (auto *SI = dyn_cast<SwitchInst>(T)) {
191 // If we are switching on a constant, we can convert the switch to an
192 // unconditional branch.
193 auto *CI = dyn_cast<ConstantInt>(SI->getCondition());
194 BasicBlock *DefaultDest = SI->getDefaultDest();
195 BasicBlock *TheOnlyDest = DefaultDest;
196
197 // If the default is unreachable, ignore it when searching for TheOnlyDest.
198 if (isa<UnreachableInst>(DefaultDest->getFirstNonPHIOrDbg()) &&
199 SI->getNumCases() > 0) {
200 TheOnlyDest = SI->case_begin()->getCaseSuccessor();
201 }
202
203 bool Changed = false;
204
205 // Figure out which case it goes to.
206 for (auto i = SI->case_begin(), e = SI->case_end(); i != e;) {
207 // Found case matching a constant operand?
208 if (i->getCaseValue() == CI) {
209 TheOnlyDest = i->getCaseSuccessor();
210 break;
211 }
212
213 // Check to see if this branch is going to the same place as the default
214 // dest. If so, eliminate it as an explicit compare.
215 if (i->getCaseSuccessor() == DefaultDest) {
216 MDNode *MD = SI->getMetadata(LLVMContext::MD_prof);
217 unsigned NCases = SI->getNumCases();
218 // Fold the case metadata into the default if there will be any branches
219 // left, unless the metadata doesn't match the switch.
220 if (NCases > 1 && MD && MD->getNumOperands() == 2 + NCases) {
221 // Collect branch weights into a vector.
222 SmallVector<uint32_t, 8> Weights;
223 for (unsigned MD_i = 1, MD_e = MD->getNumOperands(); MD_i < MD_e;
224 ++MD_i) {
225 auto *CI = mdconst::extract<ConstantInt>(MD->getOperand(MD_i));
226 Weights.push_back(CI->getValue().getZExtValue());
227 }
228 // Merge weight of this case to the default weight.
229 unsigned idx = i->getCaseIndex();
230 Weights[0] += Weights[idx+1];
231 // Remove weight for this case.
232 std::swap(Weights[idx+1], Weights.back());
233 Weights.pop_back();
234 SI->setMetadata(LLVMContext::MD_prof,
235 MDBuilder(BB->getContext()).
236 createBranchWeights(Weights));
237 }
238 // Remove this entry.
239 BasicBlock *ParentBB = SI->getParent();
240 DefaultDest->removePredecessor(ParentBB);
241 i = SI->removeCase(i);
242 e = SI->case_end();
243 Changed = true;
244 continue;
245 }
246
247 // Otherwise, check to see if the switch only branches to one destination.
248 // We do this by reseting "TheOnlyDest" to null when we find two non-equal
249 // destinations.
250 if (i->getCaseSuccessor() != TheOnlyDest)
251 TheOnlyDest = nullptr;
252
253 // Increment this iterator as we haven't removed the case.
254 ++i;
255 }
256
257 if (CI && !TheOnlyDest) {
258 // Branching on a constant, but not any of the cases, go to the default
259 // successor.
260 TheOnlyDest = SI->getDefaultDest();
261 }
262
263 // If we found a single destination that we can fold the switch into, do so
264 // now.
265 if (TheOnlyDest) {
266 // Insert the new branch.
267 Builder.CreateBr(TheOnlyDest);
268 BasicBlock *BB = SI->getParent();
269
270 SmallSet<BasicBlock *, 8> RemovedSuccessors;
271
272 // Remove entries from PHI nodes which we no longer branch to...
273 BasicBlock *SuccToKeep = TheOnlyDest;
274 for (BasicBlock *Succ : successors(SI)) {
275 if (DTU && Succ != TheOnlyDest)
276 RemovedSuccessors.insert(Succ);
277 // Found case matching a constant operand?
278 if (Succ == SuccToKeep) {
279 SuccToKeep = nullptr; // Don't modify the first branch to TheOnlyDest
280 } else {
281 Succ->removePredecessor(BB);
282 }
283 }
284
285 // Delete the old switch.
286 Value *Cond = SI->getCondition();
287 SI->eraseFromParent();
288 if (DeleteDeadConditions)
289 RecursivelyDeleteTriviallyDeadInstructions(Cond, TLI);
290 if (DTU) {
291 std::vector<DominatorTree::UpdateType> Updates;
292 Updates.reserve(RemovedSuccessors.size());
293 for (auto *RemovedSuccessor : RemovedSuccessors)
294 Updates.push_back({DominatorTree::Delete, BB, RemovedSuccessor});
295 DTU->applyUpdates(Updates);
296 }
297 return true;
298 }
299
300 if (SI->getNumCases() == 1) {
301 // Otherwise, we can fold this switch into a conditional branch
302 // instruction if it has only one non-default destination.
303 auto FirstCase = *SI->case_begin();
304 Value *Cond = Builder.CreateICmpEQ(SI->getCondition(),
305 FirstCase.getCaseValue(), "cond");
306
307 // Insert the new branch.
308 BranchInst *NewBr = Builder.CreateCondBr(Cond,
309 FirstCase.getCaseSuccessor(),
310 SI->getDefaultDest());
311 MDNode *MD = SI->getMetadata(LLVMContext::MD_prof);
312 if (MD && MD->getNumOperands() == 3) {
313 ConstantInt *SICase =
314 mdconst::dyn_extract<ConstantInt>(MD->getOperand(2));
315 ConstantInt *SIDef =
316 mdconst::dyn_extract<ConstantInt>(MD->getOperand(1));
317 assert(SICase && SIDef)((void)0);
318 // The TrueWeight should be the weight for the single case of SI.
319 NewBr->setMetadata(LLVMContext::MD_prof,
320 MDBuilder(BB->getContext()).
321 createBranchWeights(SICase->getValue().getZExtValue(),
322 SIDef->getValue().getZExtValue()));
323 }
324
325 // Update make.implicit metadata to the newly-created conditional branch.
326 MDNode *MakeImplicitMD = SI->getMetadata(LLVMContext::MD_make_implicit);
327 if (MakeImplicitMD)
328 NewBr->setMetadata(LLVMContext::MD_make_implicit, MakeImplicitMD);
329
330 // Delete the old switch.
331 SI->eraseFromParent();
332 return true;
333 }
334 return Changed;
335 }
336
337 if (auto *IBI = dyn_cast<IndirectBrInst>(T)) {
338 // indirectbr blockaddress(@F, @BB) -> br label @BB
339 if (auto *BA =
340 dyn_cast<BlockAddress>(IBI->getAddress()->stripPointerCasts())) {
341 BasicBlock *TheOnlyDest = BA->getBasicBlock();
342 SmallSet<BasicBlock *, 8> RemovedSuccessors;
343
344 // Insert the new branch.
345 Builder.CreateBr(TheOnlyDest);
346
347 BasicBlock *SuccToKeep = TheOnlyDest;
348 for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
349 BasicBlock *DestBB = IBI->getDestination(i);
350 if (DTU && DestBB != TheOnlyDest)
351 RemovedSuccessors.insert(DestBB);
352 if (IBI->getDestination(i) == SuccToKeep) {
353 SuccToKeep = nullptr;
354 } else {
355 DestBB->removePredecessor(BB);
356 }
357 }
358 Value *Address = IBI->getAddress();
359 IBI->eraseFromParent();
360 if (DeleteDeadConditions)
361 // Delete pointer cast instructions.
362 RecursivelyDeleteTriviallyDeadInstructions(Address, TLI);
363
364 // Also zap the blockaddress constant if there are no users remaining,
365 // otherwise the destination is still marked as having its address taken.
366 if (BA->use_empty())
367 BA->destroyConstant();
368
369 // If we didn't find our destination in the IBI successor list, then we
370 // have undefined behavior. Replace the unconditional branch with an
371 // 'unreachable' instruction.
372 if (SuccToKeep) {
373 BB->getTerminator()->eraseFromParent();
374 new UnreachableInst(BB->getContext(), BB);
375 }
376
377 if (DTU) {
378 std::vector<DominatorTree::UpdateType> Updates;
379 Updates.reserve(RemovedSuccessors.size());
380 for (auto *RemovedSuccessor : RemovedSuccessors)
381 Updates.push_back({DominatorTree::Delete, BB, RemovedSuccessor});
382 DTU->applyUpdates(Updates);
383 }
384 return true;
385 }
386 }
387
388 return false;
389}
390
391//===----------------------------------------------------------------------===//
392// Local dead code elimination.
393//
394
395/// isInstructionTriviallyDead - Return true if the result produced by the
396/// instruction is not used, and the instruction has no side effects.
397///
398bool llvm::isInstructionTriviallyDead(Instruction *I,
399 const TargetLibraryInfo *TLI) {
400 if (!I->use_empty())
401 return false;
402 return wouldInstructionBeTriviallyDead(I, TLI);
403}
404
405bool llvm::wouldInstructionBeTriviallyDead(Instruction *I,
406 const TargetLibraryInfo *TLI) {
407 if (I->isTerminator())
408 return false;
409
410 // We don't want the landingpad-like instructions removed by anything this
411 // general.
412 if (I->isEHPad())
413 return false;
414
415 // We don't want debug info removed by anything this general, unless
416 // debug info is empty.
417 if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(I)) {
418 if (DDI->getAddress())
419 return false;
420 return true;
421 }
422 if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(I)) {
423 if (DVI->hasArgList() || DVI->getValue(0))
424 return false;
425 return true;
426 }
427 if (DbgLabelInst *DLI = dyn_cast<DbgLabelInst>(I)) {
428 if (DLI->getLabel())
429 return false;
430 return true;
431 }
432
433 if (!I->willReturn())
434 return false;
435
436 if (!I->mayHaveSideEffects())
437 return true;
438
439 // Special case intrinsics that "may have side effects" but can be deleted
440 // when dead.
441 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
442 // Safe to delete llvm.stacksave and launder.invariant.group if dead.
443 if (II->getIntrinsicID() == Intrinsic::stacksave ||
444 II->getIntrinsicID() == Intrinsic::launder_invariant_group)
445 return true;
446
447 if (II->isLifetimeStartOrEnd()) {
448 auto *Arg = II->getArgOperand(1);
449 // Lifetime intrinsics are dead when their right-hand is undef.
450 if (isa<UndefValue>(Arg))
451 return true;
452 // If the right-hand is an alloc, global, or argument and the only uses
453 // are lifetime intrinsics then the intrinsics are dead.
454 if (isa<AllocaInst>(Arg) || isa<GlobalValue>(Arg) || isa<Argument>(Arg))
455 return llvm::all_of(Arg->uses(), [](Use &Use) {
456 if (IntrinsicInst *IntrinsicUse =
457 dyn_cast<IntrinsicInst>(Use.getUser()))
458 return IntrinsicUse->isLifetimeStartOrEnd();
459 return false;
460 });
461 return false;
462 }
463
464 // Assumptions are dead if their condition is trivially true. Guards on
465 // true are operationally no-ops. In the future we can consider more
466 // sophisticated tradeoffs for guards considering potential for check
467 // widening, but for now we keep things simple.
468 if ((II->getIntrinsicID() == Intrinsic::assume &&
469 isAssumeWithEmptyBundle(cast<AssumeInst>(*II))) ||
470 II->getIntrinsicID() == Intrinsic::experimental_guard) {
471 if (ConstantInt *Cond = dyn_cast<ConstantInt>(II->getArgOperand(0)))
472 return !Cond->isZero();
473
474 return false;
475 }
476
477 if (auto *FPI = dyn_cast<ConstrainedFPIntrinsic>(I)) {
478 Optional<fp::ExceptionBehavior> ExBehavior = FPI->getExceptionBehavior();
479 return ExBehavior.getValue() != fp::ebStrict;
480 }
481 }
482
483 if (isAllocLikeFn(I, TLI))
484 return true;
485
486 if (CallInst *CI = isFreeCall(I, TLI))
487 if (Constant *C = dyn_cast<Constant>(CI->getArgOperand(0)))
488 return C->isNullValue() || isa<UndefValue>(C);
489
490 if (auto *Call = dyn_cast<CallBase>(I))
491 if (isMathLibCallNoop(Call, TLI))
492 return true;
493
494 // To express possible interaction with floating point environment constrained
495 // intrinsics are described as if they access memory. So they look like having
496 // side effect but actually do not have it unless they raise floating point
497 // exception. If FP exceptions are ignored, the intrinsic may be deleted.
498 if (auto *CI = dyn_cast<ConstrainedFPIntrinsic>(I)) {
499 Optional<fp::ExceptionBehavior> EB = CI->getExceptionBehavior();
500 if (!EB || *EB == fp::ExceptionBehavior::ebIgnore)
501 return true;
502 }
503
504 return false;
505}
506
507/// RecursivelyDeleteTriviallyDeadInstructions - If the specified value is a
508/// trivially dead instruction, delete it. If that makes any of its operands
509/// trivially dead, delete them too, recursively. Return true if any
510/// instructions were deleted.
511bool llvm::RecursivelyDeleteTriviallyDeadInstructions(
512 Value *V, const TargetLibraryInfo *TLI, MemorySSAUpdater *MSSAU,
513 std::function<void(Value *)> AboutToDeleteCallback) {
514 Instruction *I = dyn_cast<Instruction>(V);
515 if (!I || !isInstructionTriviallyDead(I, TLI))
516 return false;
517
518 SmallVector<WeakTrackingVH, 16> DeadInsts;
519 DeadInsts.push_back(I);
520 RecursivelyDeleteTriviallyDeadInstructions(DeadInsts, TLI, MSSAU,
521 AboutToDeleteCallback);
522
523 return true;
524}
525
526bool llvm::RecursivelyDeleteTriviallyDeadInstructionsPermissive(
527 SmallVectorImpl<WeakTrackingVH> &DeadInsts, const TargetLibraryInfo *TLI,
528 MemorySSAUpdater *MSSAU,
529 std::function<void(Value *)> AboutToDeleteCallback) {
530 unsigned S = 0, E = DeadInsts.size(), Alive = 0;
531 for (; S != E; ++S) {
532 auto *I = cast<Instruction>(DeadInsts[S]);
533 if (!isInstructionTriviallyDead(I)) {
534 DeadInsts[S] = nullptr;
535 ++Alive;
536 }
537 }
538 if (Alive == E)
539 return false;
540 RecursivelyDeleteTriviallyDeadInstructions(DeadInsts, TLI, MSSAU,
541 AboutToDeleteCallback);
542 return true;
543}
544
545void llvm::RecursivelyDeleteTriviallyDeadInstructions(
546 SmallVectorImpl<WeakTrackingVH> &DeadInsts, const TargetLibraryInfo *TLI,
547 MemorySSAUpdater *MSSAU,
548 std::function<void(Value *)> AboutToDeleteCallback) {
549 // Process the dead instruction list until empty.
550 while (!DeadInsts.empty()) {
551 Value *V = DeadInsts.pop_back_val();
552 Instruction *I = cast_or_null<Instruction>(V);
553 if (!I)
554 continue;
555 assert(isInstructionTriviallyDead(I, TLI) &&((void)0)
556 "Live instruction found in dead worklist!")((void)0);
557 assert(I->use_empty() && "Instructions with uses are not dead.")((void)0);
558
559 // Don't lose the debug info while deleting the instructions.
560 salvageDebugInfo(*I);
561
562 if (AboutToDeleteCallback)
563 AboutToDeleteCallback(I);
564
565 // Null out all of the instruction's operands to see if any operand becomes
566 // dead as we go.
567 for (Use &OpU : I->operands()) {
568 Value *OpV = OpU.get();
569 OpU.set(nullptr);
570
571 if (!OpV->use_empty())
572 continue;
573
574 // If the operand is an instruction that became dead as we nulled out the
575 // operand, and if it is 'trivially' dead, delete it in a future loop
576 // iteration.
577 if (Instruction *OpI = dyn_cast<Instruction>(OpV))
578 if (isInstructionTriviallyDead(OpI, TLI))
579 DeadInsts.push_back(OpI);
580 }
581 if (MSSAU)
582 MSSAU->removeMemoryAccess(I);
583
584 I->eraseFromParent();
585 }
586}
587
588bool llvm::replaceDbgUsesWithUndef(Instruction *I) {
589 SmallVector<DbgVariableIntrinsic *, 1> DbgUsers;
590 findDbgUsers(DbgUsers, I);
591 for (auto *DII : DbgUsers) {
592 Value *Undef = UndefValue::get(I->getType());
593 DII->replaceVariableLocationOp(I, Undef);
594 }
595 return !DbgUsers.empty();
596}
597
598/// areAllUsesEqual - Check whether the uses of a value are all the same.
599/// This is similar to Instruction::hasOneUse() except this will also return
600/// true when there are no uses or multiple uses that all refer to the same
601/// value.
602static bool areAllUsesEqual(Instruction *I) {
603 Value::user_iterator UI = I->user_begin();
604 Value::user_iterator UE = I->user_end();
605 if (UI == UE)
606 return true;
607
608 User *TheUse = *UI;
609 for (++UI; UI != UE; ++UI) {
610 if (*UI != TheUse)
611 return false;
612 }
613 return true;
614}
615
616/// RecursivelyDeleteDeadPHINode - If the specified value is an effectively
617/// dead PHI node, due to being a def-use chain of single-use nodes that
618/// either forms a cycle or is terminated by a trivially dead instruction,
619/// delete it. If that makes any of its operands trivially dead, delete them
620/// too, recursively. Return true if a change was made.
621bool llvm::RecursivelyDeleteDeadPHINode(PHINode *PN,
622 const TargetLibraryInfo *TLI,
623 llvm::MemorySSAUpdater *MSSAU) {
624 SmallPtrSet<Instruction*, 4> Visited;
625 for (Instruction *I = PN; areAllUsesEqual(I) && !I->mayHaveSideEffects();
626 I = cast<Instruction>(*I->user_begin())) {
627 if (I->use_empty())
628 return RecursivelyDeleteTriviallyDeadInstructions(I, TLI, MSSAU);
629
630 // If we find an instruction more than once, we're on a cycle that
631 // won't prove fruitful.
632 if (!Visited.insert(I).second) {
633 // Break the cycle and delete the instruction and its operands.
634 I->replaceAllUsesWith(UndefValue::get(I->getType()));
635 (void)RecursivelyDeleteTriviallyDeadInstructions(I, TLI, MSSAU);
636 return true;
637 }
638 }
639 return false;
640}
641
642static bool
643simplifyAndDCEInstruction(Instruction *I,
644 SmallSetVector<Instruction *, 16> &WorkList,
645 const DataLayout &DL,
646 const TargetLibraryInfo *TLI) {
647 if (isInstructionTriviallyDead(I, TLI)) {
648 salvageDebugInfo(*I);
649
650 // Null out all of the instruction's operands to see if any operand becomes
651 // dead as we go.
652 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
653 Value *OpV = I->getOperand(i);
654 I->setOperand(i, nullptr);
655
656 if (!OpV->use_empty() || I == OpV)
657 continue;
658
659 // If the operand is an instruction that became dead as we nulled out the
660 // operand, and if it is 'trivially' dead, delete it in a future loop
661 // iteration.
662 if (Instruction *OpI = dyn_cast<Instruction>(OpV))
663 if (isInstructionTriviallyDead(OpI, TLI))
664 WorkList.insert(OpI);
665 }
666
667 I->eraseFromParent();
668
669 return true;
670 }
671
672 if (Value *SimpleV = SimplifyInstruction(I, DL)) {
673 // Add the users to the worklist. CAREFUL: an instruction can use itself,
674 // in the case of a phi node.
675 for (User *U : I->users()) {
676 if (U != I) {
677 WorkList.insert(cast<Instruction>(U));
678 }
679 }
680
681 // Replace the instruction with its simplified value.
682 bool Changed = false;
683 if (!I->use_empty()) {
684 I->replaceAllUsesWith(SimpleV);
685 Changed = true;
686 }
687 if (isInstructionTriviallyDead(I, TLI)) {
688 I->eraseFromParent();
689 Changed = true;
690 }
691 return Changed;
692 }
693 return false;
694}
695
696/// SimplifyInstructionsInBlock - Scan the specified basic block and try to
697/// simplify any instructions in it and recursively delete dead instructions.
698///
699/// This returns true if it changed the code, note that it can delete
700/// instructions in other blocks as well in this block.
701bool llvm::SimplifyInstructionsInBlock(BasicBlock *BB,
702 const TargetLibraryInfo *TLI) {
703 bool MadeChange = false;
704 const DataLayout &DL = BB->getModule()->getDataLayout();
705
706#ifndef NDEBUG1
707 // In debug builds, ensure that the terminator of the block is never replaced
708 // or deleted by these simplifications. The idea of simplification is that it
709 // cannot introduce new instructions, and there is no way to replace the
710 // terminator of a block without introducing a new instruction.
711 AssertingVH<Instruction> TerminatorVH(&BB->back());
712#endif
713
714 SmallSetVector<Instruction *, 16> WorkList;
715 // Iterate over the original function, only adding insts to the worklist
716 // if they actually need to be revisited. This avoids having to pre-init
717 // the worklist with the entire function's worth of instructions.
718 for (BasicBlock::iterator BI = BB->begin(), E = std::prev(BB->end());
719 BI != E;) {
720 assert(!BI->isTerminator())((void)0);
721 Instruction *I = &*BI;
722 ++BI;
723
724 // We're visiting this instruction now, so make sure it's not in the
725 // worklist from an earlier visit.
726 if (!WorkList.count(I))
727 MadeChange |= simplifyAndDCEInstruction(I, WorkList, DL, TLI);
728 }
729
730 while (!WorkList.empty()) {
731 Instruction *I = WorkList.pop_back_val();
732 MadeChange |= simplifyAndDCEInstruction(I, WorkList, DL, TLI);
733 }
734 return MadeChange;
735}
736
737//===----------------------------------------------------------------------===//
738// Control Flow Graph Restructuring.
739//
740
741void llvm::MergeBasicBlockIntoOnlyPred(BasicBlock *DestBB,
742 DomTreeUpdater *DTU) {
743
744 // If BB has single-entry PHI nodes, fold them.
745 while (PHINode *PN = dyn_cast<PHINode>(DestBB->begin())) {
746 Value *NewVal = PN->getIncomingValue(0);
747 // Replace self referencing PHI with undef, it must be dead.
748 if (NewVal == PN) NewVal = UndefValue::get(PN->getType());
749 PN->replaceAllUsesWith(NewVal);
750 PN->eraseFromParent();
751 }
752
753 BasicBlock *PredBB = DestBB->getSinglePredecessor();
754 assert(PredBB && "Block doesn't have a single predecessor!")((void)0);
755
756 bool ReplaceEntryBB = PredBB->isEntryBlock();
757
758 // DTU updates: Collect all the edges that enter
759 // PredBB. These dominator edges will be redirected to DestBB.
760 SmallVector<DominatorTree::UpdateType, 32> Updates;
761
762 if (DTU) {
763 SmallPtrSet<BasicBlock *, 2> PredsOfPredBB(pred_begin(PredBB),
764 pred_end(PredBB));
765 Updates.reserve(Updates.size() + 2 * PredsOfPredBB.size() + 1);
766 for (BasicBlock *PredOfPredBB : PredsOfPredBB)
767 // This predecessor of PredBB may already have DestBB as a successor.
768 if (PredOfPredBB != PredBB)
769 Updates.push_back({DominatorTree::Insert, PredOfPredBB, DestBB});
770 for (BasicBlock *PredOfPredBB : PredsOfPredBB)
771 Updates.push_back({DominatorTree::Delete, PredOfPredBB, PredBB});
772 Updates.push_back({DominatorTree::Delete, PredBB, DestBB});
773 }
774
775 // Zap anything that took the address of DestBB. Not doing this will give the
776 // address an invalid value.
777 if (DestBB->hasAddressTaken()) {
778 BlockAddress *BA = BlockAddress::get(DestBB);
779 Constant *Replacement =
780 ConstantInt::get(Type::getInt32Ty(BA->getContext()), 1);
781 BA->replaceAllUsesWith(ConstantExpr::getIntToPtr(Replacement,
782 BA->getType()));
783 BA->destroyConstant();
784 }
785
786 // Anything that branched to PredBB now branches to DestBB.
787 PredBB->replaceAllUsesWith(DestBB);
788
789 // Splice all the instructions from PredBB to DestBB.
790 PredBB->getTerminator()->eraseFromParent();
791 DestBB->getInstList().splice(DestBB->begin(), PredBB->getInstList());
792 new UnreachableInst(PredBB->getContext(), PredBB);
793
794 // If the PredBB is the entry block of the function, move DestBB up to
795 // become the entry block after we erase PredBB.
796 if (ReplaceEntryBB)
797 DestBB->moveAfter(PredBB);
798
799 if (DTU) {
800 assert(PredBB->getInstList().size() == 1 &&((void)0)
801 isa<UnreachableInst>(PredBB->getTerminator()) &&((void)0)
802 "The successor list of PredBB isn't empty before "((void)0)
803 "applying corresponding DTU updates.")((void)0);
804 DTU->applyUpdatesPermissive(Updates);
805 DTU->deleteBB(PredBB);
806 // Recalculation of DomTree is needed when updating a forward DomTree and
807 // the Entry BB is replaced.
808 if (ReplaceEntryBB && DTU->hasDomTree()) {
809 // The entry block was removed and there is no external interface for
810 // the dominator tree to be notified of this change. In this corner-case
811 // we recalculate the entire tree.
812 DTU->recalculate(*(DestBB->getParent()));
813 }
814 }
815
816 else {
817 PredBB->eraseFromParent(); // Nuke BB if DTU is nullptr.
818 }
819}
820
821/// Return true if we can choose one of these values to use in place of the
822/// other. Note that we will always choose the non-undef value to keep.
823static bool CanMergeValues(Value *First, Value *Second) {
824 return First == Second || isa<UndefValue>(First) || isa<UndefValue>(Second);
825}
826
827/// Return true if we can fold BB, an almost-empty BB ending in an unconditional
828/// branch to Succ, into Succ.
829///
830/// Assumption: Succ is the single successor for BB.
831static bool CanPropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
832 assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!")((void)0);
833
834 LLVM_DEBUG(dbgs() << "Looking to fold " << BB->getName() << " into "do { } while (false)
835 << Succ->getName() << "\n")do { } while (false);
836 // Shortcut, if there is only a single predecessor it must be BB and merging
837 // is always safe
838 if (Succ->getSinglePredecessor()) return true;
839
840 // Make a list of the predecessors of BB
841 SmallPtrSet<BasicBlock*, 16> BBPreds(pred_begin(BB), pred_end(BB));
842
843 // Look at all the phi nodes in Succ, to see if they present a conflict when
844 // merging these blocks
845 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
846 PHINode *PN = cast<PHINode>(I);
847
848 // If the incoming value from BB is again a PHINode in
849 // BB which has the same incoming value for *PI as PN does, we can
850 // merge the phi nodes and then the blocks can still be merged
851 PHINode *BBPN = dyn_cast<PHINode>(PN->getIncomingValueForBlock(BB));
852 if (BBPN && BBPN->getParent() == BB) {
853 for (unsigned PI = 0, PE = PN->getNumIncomingValues(); PI != PE; ++PI) {
854 BasicBlock *IBB = PN->getIncomingBlock(PI);
855 if (BBPreds.count(IBB) &&
856 !CanMergeValues(BBPN->getIncomingValueForBlock(IBB),
857 PN->getIncomingValue(PI))) {
858 LLVM_DEBUG(dbgs()do { } while (false)
859 << "Can't fold, phi node " << PN->getName() << " in "do { } while (false)
860 << Succ->getName() << " is conflicting with "do { } while (false)
861 << BBPN->getName() << " with regard to common predecessor "do { } while (false)
862 << IBB->getName() << "\n")do { } while (false);
863 return false;
864 }
865 }
866 } else {
867 Value* Val = PN->getIncomingValueForBlock(BB);
868 for (unsigned PI = 0, PE = PN->getNumIncomingValues(); PI != PE; ++PI) {
869 // See if the incoming value for the common predecessor is equal to the
870 // one for BB, in which case this phi node will not prevent the merging
871 // of the block.
872 BasicBlock *IBB = PN->getIncomingBlock(PI);
873 if (BBPreds.count(IBB) &&
874 !CanMergeValues(Val, PN->getIncomingValue(PI))) {
875 LLVM_DEBUG(dbgs() << "Can't fold, phi node " << PN->getName()do { } while (false)
876 << " in " << Succ->getName()do { } while (false)
877 << " is conflicting with regard to common "do { } while (false)
878 << "predecessor " << IBB->getName() << "\n")do { } while (false);
879 return false;
880 }
881 }
882 }
883 }
884
885 return true;
886}
887
888using PredBlockVector = SmallVector<BasicBlock *, 16>;
889using IncomingValueMap = DenseMap<BasicBlock *, Value *>;
890
891/// Determines the value to use as the phi node input for a block.
892///
893/// Select between \p OldVal any value that we know flows from \p BB
894/// to a particular phi on the basis of which one (if either) is not
895/// undef. Update IncomingValues based on the selected value.
896///
897/// \param OldVal The value we are considering selecting.
898/// \param BB The block that the value flows in from.
899/// \param IncomingValues A map from block-to-value for other phi inputs
900/// that we have examined.
901///
902/// \returns the selected value.
903static Value *selectIncomingValueForBlock(Value *OldVal, BasicBlock *BB,
904 IncomingValueMap &IncomingValues) {
905 if (!isa<UndefValue>(OldVal)) {
906 assert((!IncomingValues.count(BB) ||((void)0)
907 IncomingValues.find(BB)->second == OldVal) &&((void)0)
908 "Expected OldVal to match incoming value from BB!")((void)0);
909
910 IncomingValues.insert(std::make_pair(BB, OldVal));
911 return OldVal;
912 }
913
914 IncomingValueMap::const_iterator It = IncomingValues.find(BB);
915 if (It != IncomingValues.end()) return It->second;
916
917 return OldVal;
918}
919
920/// Create a map from block to value for the operands of a
921/// given phi.
922///
923/// Create a map from block to value for each non-undef value flowing
924/// into \p PN.
925///
926/// \param PN The phi we are collecting the map for.
927/// \param IncomingValues [out] The map from block to value for this phi.
928static void gatherIncomingValuesToPhi(PHINode *PN,
929 IncomingValueMap &IncomingValues) {
930 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
931 BasicBlock *BB = PN->getIncomingBlock(i);
932 Value *V = PN->getIncomingValue(i);
933
934 if (!isa<UndefValue>(V))
935 IncomingValues.insert(std::make_pair(BB, V));
936 }
937}
938
939/// Replace the incoming undef values to a phi with the values
940/// from a block-to-value map.
941///
942/// \param PN The phi we are replacing the undefs in.
943/// \param IncomingValues A map from block to value.
944static void replaceUndefValuesInPhi(PHINode *PN,
945 const IncomingValueMap &IncomingValues) {
946 SmallVector<unsigned> TrueUndefOps;
947 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
948 Value *V = PN->getIncomingValue(i);
949
950 if (!isa<UndefValue>(V)) continue;
951
952 BasicBlock *BB = PN->getIncomingBlock(i);
953 IncomingValueMap::const_iterator It = IncomingValues.find(BB);
954
955 // Keep track of undef/poison incoming values. Those must match, so we fix
956 // them up below if needed.
957 // Note: this is conservatively correct, but we could try harder and group
958 // the undef values per incoming basic block.
959 if (It == IncomingValues.end()) {
960 TrueUndefOps.push_back(i);
961 continue;
962 }
963
964 // There is a defined value for this incoming block, so map this undef
965 // incoming value to the defined value.
966 PN->setIncomingValue(i, It->second);
967 }
968
969 // If there are both undef and poison values incoming, then convert those
970 // values to undef. It is invalid to have different values for the same
971 // incoming block.
972 unsigned PoisonCount = count_if(TrueUndefOps, [&](unsigned i) {
973 return isa<PoisonValue>(PN->getIncomingValue(i));
974 });
975 if (PoisonCount != 0 && PoisonCount != TrueUndefOps.size()) {
976 for (unsigned i : TrueUndefOps)
977 PN->setIncomingValue(i, UndefValue::get(PN->getType()));
978 }
979}
980
981/// Replace a value flowing from a block to a phi with
982/// potentially multiple instances of that value flowing from the
983/// block's predecessors to the phi.
984///
985/// \param BB The block with the value flowing into the phi.
986/// \param BBPreds The predecessors of BB.
987/// \param PN The phi that we are updating.
988static void redirectValuesFromPredecessorsToPhi(BasicBlock *BB,
989 const PredBlockVector &BBPreds,
990 PHINode *PN) {
991 Value *OldVal = PN->removeIncomingValue(BB, false);
992 assert(OldVal && "No entry in PHI for Pred BB!")((void)0);
993
994 IncomingValueMap IncomingValues;
995
996 // We are merging two blocks - BB, and the block containing PN - and
997 // as a result we need to redirect edges from the predecessors of BB
998 // to go to the block containing PN, and update PN
999 // accordingly. Since we allow merging blocks in the case where the
1000 // predecessor and successor blocks both share some predecessors,
1001 // and where some of those common predecessors might have undef
1002 // values flowing into PN, we want to rewrite those values to be
1003 // consistent with the non-undef values.
1004
1005 gatherIncomingValuesToPhi(PN, IncomingValues);
1006
1007 // If this incoming value is one of the PHI nodes in BB, the new entries
1008 // in the PHI node are the entries from the old PHI.
1009 if (isa<PHINode>(OldVal) && cast<PHINode>(OldVal)->getParent() == BB) {
1010 PHINode *OldValPN = cast<PHINode>(OldVal);
1011 for (unsigned i = 0, e = OldValPN->getNumIncomingValues(); i != e; ++i) {
1012 // Note that, since we are merging phi nodes and BB and Succ might
1013 // have common predecessors, we could end up with a phi node with
1014 // identical incoming branches. This will be cleaned up later (and
1015 // will trigger asserts if we try to clean it up now, without also
1016 // simplifying the corresponding conditional branch).
1017 BasicBlock *PredBB = OldValPN->getIncomingBlock(i);
1018 Value *PredVal = OldValPN->getIncomingValue(i);
1019 Value *Selected = selectIncomingValueForBlock(PredVal, PredBB,
1020 IncomingValues);
1021
1022 // And add a new incoming value for this predecessor for the
1023 // newly retargeted branch.
1024 PN->addIncoming(Selected, PredBB);
1025 }
1026 } else {
1027 for (unsigned i = 0, e = BBPreds.size(); i != e; ++i) {
1028 // Update existing incoming values in PN for this
1029 // predecessor of BB.
1030 BasicBlock *PredBB = BBPreds[i];
1031 Value *Selected = selectIncomingValueForBlock(OldVal, PredBB,
1032 IncomingValues);
1033
1034 // And add a new incoming value for this predecessor for the
1035 // newly retargeted branch.
1036 PN->addIncoming(Selected, PredBB);
1037 }
1038 }
1039
1040 replaceUndefValuesInPhi(PN, IncomingValues);
1041}
1042
1043bool llvm::TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB,
1044 DomTreeUpdater *DTU) {
1045 assert(BB != &BB->getParent()->getEntryBlock() &&((void)0)
1046 "TryToSimplifyUncondBranchFromEmptyBlock called on entry block!")((void)0);
1047
1048 // We can't eliminate infinite loops.
1049 BasicBlock *Succ = cast<BranchInst>(BB->getTerminator())->getSuccessor(0);
1050 if (BB == Succ) return false;
1051
1052 // Check to see if merging these blocks would cause conflicts for any of the
1053 // phi nodes in BB or Succ. If not, we can safely merge.
1054 if (!CanPropagatePredecessorsForPHIs(BB, Succ)) return false;
1055
1056 // Check for cases where Succ has multiple predecessors and a PHI node in BB
1057 // has uses which will not disappear when the PHI nodes are merged. It is
1058 // possible to handle such cases, but difficult: it requires checking whether
1059 // BB dominates Succ, which is non-trivial to calculate in the case where
1060 // Succ has multiple predecessors. Also, it requires checking whether
1061 // constructing the necessary self-referential PHI node doesn't introduce any
1062 // conflicts; this isn't too difficult, but the previous code for doing this
1063 // was incorrect.
1064 //
1065 // Note that if this check finds a live use, BB dominates Succ, so BB is
1066 // something like a loop pre-header (or rarely, a part of an irreducible CFG);
1067 // folding the branch isn't profitable in that case anyway.
1068 if (!Succ->getSinglePredecessor()) {
1069 BasicBlock::iterator BBI = BB->begin();
1070 while (isa<PHINode>(*BBI)) {
1071 for (Use &U : BBI->uses()) {
1072 if (PHINode* PN = dyn_cast<PHINode>(U.getUser())) {
1073 if (PN->getIncomingBlock(U) != BB)
1074 return false;
1075 } else {
1076 return false;
1077 }
1078 }
1079 ++BBI;
1080 }
1081 }
1082
1083 // We cannot fold the block if it's a branch to an already present callbr
1084 // successor because that creates duplicate successors.
1085 for (BasicBlock *PredBB : predecessors(BB)) {
1086 if (auto *CBI = dyn_cast<CallBrInst>(PredBB->getTerminator())) {
1087 if (Succ == CBI->getDefaultDest())
1088 return false;
1089 for (unsigned i = 0, e = CBI->getNumIndirectDests(); i != e; ++i)
1090 if (Succ == CBI->getIndirectDest(i))
1091 return false;
1092 }
1093 }
1094
1095 LLVM_DEBUG(dbgs() << "Killing Trivial BB: \n" << *BB)do { } while (false);
1096
1097 SmallVector<DominatorTree::UpdateType, 32> Updates;
1098 if (DTU) {
1099 // All predecessors of BB will be moved to Succ.
1100 SmallPtrSet<BasicBlock *, 8> PredsOfBB(pred_begin(BB), pred_end(BB));
1101 SmallPtrSet<BasicBlock *, 8> PredsOfSucc(pred_begin(Succ), pred_end(Succ));
1102 Updates.reserve(Updates.size() + 2 * PredsOfBB.size() + 1);
1103 for (auto *PredOfBB : PredsOfBB)
1104 // This predecessor of BB may already have Succ as a successor.
1105 if (!PredsOfSucc.contains(PredOfBB))
1106 Updates.push_back({DominatorTree::Insert, PredOfBB, Succ});
1107 for (auto *PredOfBB : PredsOfBB)
1108 Updates.push_back({DominatorTree::Delete, PredOfBB, BB});
1109 Updates.push_back({DominatorTree::Delete, BB, Succ});
1110 }
1111
1112 if (isa<PHINode>(Succ->begin())) {
1113 // If there is more than one pred of succ, and there are PHI nodes in
1114 // the successor, then we need to add incoming edges for the PHI nodes
1115 //
1116 const PredBlockVector BBPreds(pred_begin(BB), pred_end(BB));
1117
1118 // Loop over all of the PHI nodes in the successor of BB.
1119 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
1120 PHINode *PN = cast<PHINode>(I);
1121
1122 redirectValuesFromPredecessorsToPhi(BB, BBPreds, PN);
1123 }
1124 }
1125
1126 if (Succ->getSinglePredecessor()) {
1127 // BB is the only predecessor of Succ, so Succ will end up with exactly
1128 // the same predecessors BB had.
1129
1130 // Copy over any phi, debug or lifetime instruction.
1131 BB->getTerminator()->eraseFromParent();
1132 Succ->getInstList().splice(Succ->getFirstNonPHI()->getIterator(),
1133 BB->getInstList());
1134 } else {
1135 while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
1136 // We explicitly check for such uses in CanPropagatePredecessorsForPHIs.
1137 assert(PN->use_empty() && "There shouldn't be any uses here!")((void)0);
1138 PN->eraseFromParent();
1139 }
1140 }
1141
1142 // If the unconditional branch we replaced contains llvm.loop metadata, we
1143 // add the metadata to the branch instructions in the predecessors.
1144 unsigned LoopMDKind = BB->getContext().getMDKindID("llvm.loop");
1145 Instruction *TI = BB->getTerminator();
1146 if (TI)
1147 if (MDNode *LoopMD = TI->getMetadata(LoopMDKind))
1148 for (BasicBlock *Pred : predecessors(BB))
1149 Pred->getTerminator()->setMetadata(LoopMDKind, LoopMD);
1150
1151 // Everything that jumped to BB now goes to Succ.
1152 BB->replaceAllUsesWith(Succ);
1153 if (!Succ->hasName()) Succ->takeName(BB);
1154
1155 // Clear the successor list of BB to match updates applying to DTU later.
1156 if (BB->getTerminator())
1157 BB->getInstList().pop_back();
1158 new UnreachableInst(BB->getContext(), BB);
1159 assert(succ_empty(BB) && "The successor list of BB isn't empty before "((void)0)
1160 "applying corresponding DTU updates.")((void)0);
1161
1162 if (DTU)
1163 DTU->applyUpdates(Updates);
1164
1165 DeleteDeadBlock(BB, DTU);
1166
1167 return true;
1168}
1169
1170static bool EliminateDuplicatePHINodesNaiveImpl(BasicBlock *BB) {
1171 // This implementation doesn't currently consider undef operands
1172 // specially. Theoretically, two phis which are identical except for
1173 // one having an undef where the other doesn't could be collapsed.
1174
1175 bool Changed = false;
1176
1177 // Examine each PHI.
1178 // Note that increment of I must *NOT* be in the iteration_expression, since
1179 // we don't want to immediately advance when we restart from the beginning.
1180 for (auto I = BB->begin(); PHINode *PN = dyn_cast<PHINode>(I);) {
1181 ++I;
1182 // Is there an identical PHI node in this basic block?
1183 // Note that we only look in the upper square's triangle,
1184 // we already checked that the lower triangle PHI's aren't identical.
1185 for (auto J = I; PHINode *DuplicatePN = dyn_cast<PHINode>(J); ++J) {
1186 if (!DuplicatePN->isIdenticalToWhenDefined(PN))
1187 continue;
1188 // A duplicate. Replace this PHI with the base PHI.
1189 ++NumPHICSEs;
1190 DuplicatePN->replaceAllUsesWith(PN);
1191 DuplicatePN->eraseFromParent();
1192 Changed = true;
1193
1194 // The RAUW can change PHIs that we already visited.
1195 I = BB->begin();
1196 break; // Start over from the beginning.
1197 }
1198 }
1199 return Changed;
1200}
1201
1202static bool EliminateDuplicatePHINodesSetBasedImpl(BasicBlock *BB) {
1203 // This implementation doesn't currently consider undef operands
1204 // specially. Theoretically, two phis which are identical except for
1205 // one having an undef where the other doesn't could be collapsed.
1206
1207 struct PHIDenseMapInfo {
1208 static PHINode *getEmptyKey() {
1209 return DenseMapInfo<PHINode *>::getEmptyKey();
1210 }
1211
1212 static PHINode *getTombstoneKey() {
1213 return DenseMapInfo<PHINode *>::getTombstoneKey();
1214 }
1215
1216 static bool isSentinel(PHINode *PN) {
1217 return PN == getEmptyKey() || PN == getTombstoneKey();
1218 }
1219
1220 // WARNING: this logic must be kept in sync with
1221 // Instruction::isIdenticalToWhenDefined()!
1222 static unsigned getHashValueImpl(PHINode *PN) {
1223 // Compute a hash value on the operands. Instcombine will likely have
1224 // sorted them, which helps expose duplicates, but we have to check all
1225 // the operands to be safe in case instcombine hasn't run.
1226 return static_cast<unsigned>(hash_combine(
1227 hash_combine_range(PN->value_op_begin(), PN->value_op_end()),
1228 hash_combine_range(PN->block_begin(), PN->block_end())));
1229 }
1230
1231 static unsigned getHashValue(PHINode *PN) {
1232#ifndef NDEBUG1
1233 // If -phicse-debug-hash was specified, return a constant -- this
1234 // will force all hashing to collide, so we'll exhaustively search
1235 // the table for a match, and the assertion in isEqual will fire if
1236 // there's a bug causing equal keys to hash differently.
1237 if (PHICSEDebugHash)
1238 return 0;
1239#endif
1240 return getHashValueImpl(PN);
1241 }
1242
1243 static bool isEqualImpl(PHINode *LHS, PHINode *RHS) {
1244 if (isSentinel(LHS) || isSentinel(RHS))
1245 return LHS == RHS;
1246 return LHS->isIdenticalTo(RHS);
1247 }
1248
1249 static bool isEqual(PHINode *LHS, PHINode *RHS) {
1250 // These comparisons are nontrivial, so assert that equality implies
1251 // hash equality (DenseMap demands this as an invariant).
1252 bool Result = isEqualImpl(LHS, RHS);
1253 assert(!Result || (isSentinel(LHS) && LHS == RHS) ||((void)0)
1254 getHashValueImpl(LHS) == getHashValueImpl(RHS))((void)0);
1255 return Result;
1256 }
1257 };
1258
1259 // Set of unique PHINodes.
1260 DenseSet<PHINode *, PHIDenseMapInfo> PHISet;
1261 PHISet.reserve(4 * PHICSENumPHISmallSize);
1262
1263 // Examine each PHI.
1264 bool Changed = false;
1265 for (auto I = BB->begin(); PHINode *PN = dyn_cast<PHINode>(I++);) {
1266 auto Inserted = PHISet.insert(PN);
1267 if (!Inserted.second) {
1268 // A duplicate. Replace this PHI with its duplicate.
1269 ++NumPHICSEs;
1270 PN->replaceAllUsesWith(*Inserted.first);
1271 PN->eraseFromParent();
1272 Changed = true;
1273
1274 // The RAUW can change PHIs that we already visited. Start over from the
1275 // beginning.
1276 PHISet.clear();
1277 I = BB->begin();
1278 }
1279 }
1280
1281 return Changed;
1282}
1283
1284bool llvm::EliminateDuplicatePHINodes(BasicBlock *BB) {
1285 if (
1286#ifndef NDEBUG1
1287 !PHICSEDebugHash &&
1288#endif
1289 hasNItemsOrLess(BB->phis(), PHICSENumPHISmallSize))
1290 return EliminateDuplicatePHINodesNaiveImpl(BB);
1291 return EliminateDuplicatePHINodesSetBasedImpl(BB);
1292}
1293
1294/// If the specified pointer points to an object that we control, try to modify
1295/// the object's alignment to PrefAlign. Returns a minimum known alignment of
1296/// the value after the operation, which may be lower than PrefAlign.
1297///
1298/// Increating value alignment isn't often possible though. If alignment is
1299/// important, a more reliable approach is to simply align all global variables
1300/// and allocation instructions to their preferred alignment from the beginning.
1301static Align tryEnforceAlignment(Value *V, Align PrefAlign,
1302 const DataLayout &DL) {
1303 V = V->stripPointerCasts();
1304
1305 if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1306 // TODO: Ideally, this function would not be called if PrefAlign is smaller
1307 // than the current alignment, as the known bits calculation should have
1308 // already taken it into account. However, this is not always the case,
1309 // as computeKnownBits() has a depth limit, while stripPointerCasts()
1310 // doesn't.
1311 Align CurrentAlign = AI->getAlign();
1312 if (PrefAlign <= CurrentAlign)
1313 return CurrentAlign;
1314
1315 // If the preferred alignment is greater than the natural stack alignment
1316 // then don't round up. This avoids dynamic stack realignment.
1317 if (DL.exceedsNaturalStackAlignment(PrefAlign))
1318 return CurrentAlign;
1319 AI->setAlignment(PrefAlign);
1320 return PrefAlign;
1321 }
1322
1323 if (auto *GO = dyn_cast<GlobalObject>(V)) {
1324 // TODO: as above, this shouldn't be necessary.
1325 Align CurrentAlign = GO->getPointerAlignment(DL);
1326 if (PrefAlign <= CurrentAlign)
1327 return CurrentAlign;
1328
1329 // If there is a large requested alignment and we can, bump up the alignment
1330 // of the global. If the memory we set aside for the global may not be the
1331 // memory used by the final program then it is impossible for us to reliably
1332 // enforce the preferred alignment.
1333 if (!GO->canIncreaseAlignment())
1334 return CurrentAlign;
1335
1336 GO->setAlignment(PrefAlign);
1337 return PrefAlign;
1338 }
1339
1340 return Align(1);
1341}
1342
1343Align llvm::getOrEnforceKnownAlignment(Value *V, MaybeAlign PrefAlign,
1344 const DataLayout &DL,
1345 const Instruction *CxtI,
1346 AssumptionCache *AC,
1347 const DominatorTree *DT) {
1348 assert(V->getType()->isPointerTy() &&((void)0)
1349 "getOrEnforceKnownAlignment expects a pointer!")((void)0);
1350
1351 KnownBits Known = computeKnownBits(V, DL, 0, AC, CxtI, DT);
1352 unsigned TrailZ = Known.countMinTrailingZeros();
1353
1354 // Avoid trouble with ridiculously large TrailZ values, such as
1355 // those computed from a null pointer.
1356 // LLVM doesn't support alignments larger than (1 << MaxAlignmentExponent).
1357 TrailZ = std::min(TrailZ, +Value::MaxAlignmentExponent);
1358
1359 Align Alignment = Align(1ull << std::min(Known.getBitWidth() - 1, TrailZ));
1360
1361 if (PrefAlign && *PrefAlign > Alignment)
1362 Alignment = std::max(Alignment, tryEnforceAlignment(V, *PrefAlign, DL));
1363
1364 // We don't need to make any adjustment.
1365 return Alignment;
1366}
1367
1368///===---------------------------------------------------------------------===//
1369/// Dbg Intrinsic utilities
1370///
1371
1372/// See if there is a dbg.value intrinsic for DIVar for the PHI node.
1373static bool PhiHasDebugValue(DILocalVariable *DIVar,
1374 DIExpression *DIExpr,
1375 PHINode *APN) {
1376 // Since we can't guarantee that the original dbg.declare instrinsic
1377 // is removed by LowerDbgDeclare(), we need to make sure that we are
1378 // not inserting the same dbg.value intrinsic over and over.
1379 SmallVector<DbgValueInst *, 1> DbgValues;
1380 findDbgValues(DbgValues, APN);
1381 for (auto *DVI : DbgValues) {
1382 assert(is_contained(DVI->getValues(), APN))((void)0);
1383 if ((DVI->getVariable() == DIVar) && (DVI->getExpression() == DIExpr))
1384 return true;
1385 }
1386 return false;
1387}
1388
1389/// Check if the alloc size of \p ValTy is large enough to cover the variable
1390/// (or fragment of the variable) described by \p DII.
1391///
1392/// This is primarily intended as a helper for the different
1393/// ConvertDebugDeclareToDebugValue functions. The dbg.declare/dbg.addr that is
1394/// converted describes an alloca'd variable, so we need to use the
1395/// alloc size of the value when doing the comparison. E.g. an i1 value will be
1396/// identified as covering an n-bit fragment, if the store size of i1 is at
1397/// least n bits.
1398static bool valueCoversEntireFragment(Type *ValTy, DbgVariableIntrinsic *DII) {
1399 const DataLayout &DL = DII->getModule()->getDataLayout();
1400 TypeSize ValueSize = DL.getTypeAllocSizeInBits(ValTy);
1401 if (Optional<uint64_t> FragmentSize = DII->getFragmentSizeInBits()) {
1402 assert(!ValueSize.isScalable() &&((void)0)
1403 "Fragments don't work on scalable types.")((void)0);
1404 return ValueSize.getFixedSize() >= *FragmentSize;
1405 }
1406 // We can't always calculate the size of the DI variable (e.g. if it is a
1407 // VLA). Try to use the size of the alloca that the dbg intrinsic describes
1408 // intead.
1409 if (DII->isAddressOfVariable()) {
1410 // DII should have exactly 1 location when it is an address.
1411 assert(DII->getNumVariableLocationOps() == 1 &&((void)0)
1412 "address of variable must have exactly 1 location operand.")((void)0);
1413 if (auto *AI =
1414 dyn_cast_or_null<AllocaInst>(DII->getVariableLocationOp(0))) {
1415 if (Optional<TypeSize> FragmentSize = AI->getAllocationSizeInBits(DL)) {
1416 assert(ValueSize.isScalable() == FragmentSize->isScalable() &&((void)0)
1417 "Both sizes should agree on the scalable flag.")((void)0);
1418 return TypeSize::isKnownGE(ValueSize, *FragmentSize);
1419 }
1420 }
1421 }
1422 // Could not determine size of variable. Conservatively return false.
1423 return false;
1424}
1425
1426/// Produce a DebugLoc to use for each dbg.declare/inst pair that are promoted
1427/// to a dbg.value. Because no machine insts can come from debug intrinsics,
1428/// only the scope and inlinedAt is significant. Zero line numbers are used in
1429/// case this DebugLoc leaks into any adjacent instructions.
1430static DebugLoc getDebugValueLoc(DbgVariableIntrinsic *DII, Instruction *Src) {
1431 // Original dbg.declare must have a location.
1432 const DebugLoc &DeclareLoc = DII->getDebugLoc();
1433 MDNode *Scope = DeclareLoc.getScope();
1434 DILocation *InlinedAt = DeclareLoc.getInlinedAt();
1435 // Produce an unknown location with the correct scope / inlinedAt fields.
1436 return DILocation::get(DII->getContext(), 0, 0, Scope, InlinedAt);
1437}
1438
1439/// Inserts a llvm.dbg.value intrinsic before a store to an alloca'd value
1440/// that has an associated llvm.dbg.declare or llvm.dbg.addr intrinsic.
1441void llvm::ConvertDebugDeclareToDebugValue(DbgVariableIntrinsic *DII,
1442 StoreInst *SI, DIBuilder &Builder) {
1443 assert(DII->isAddressOfVariable())((void)0);
1444 auto *DIVar = DII->getVariable();
1445 assert(DIVar && "Missing variable")((void)0);
1446 auto *DIExpr = DII->getExpression();
1447 Value *DV = SI->getValueOperand();
1448
1449 DebugLoc NewLoc = getDebugValueLoc(DII, SI);
1450
1451 if (!valueCoversEntireFragment(DV->getType(), DII)) {
1452 // FIXME: If storing to a part of the variable described by the dbg.declare,
1453 // then we want to insert a dbg.value for the corresponding fragment.
1454 LLVM_DEBUG(dbgs() << "Failed to convert dbg.declare to dbg.value: "do { } while (false)
1455 << *DII << '\n')do { } while (false);
1456 // For now, when there is a store to parts of the variable (but we do not
1457 // know which part) we insert an dbg.value instrinsic to indicate that we
1458 // know nothing about the variable's content.
1459 DV = UndefValue::get(DV->getType());
1460 Builder.insertDbgValueIntrinsic(DV, DIVar, DIExpr, NewLoc, SI);
1461 return;
1462 }
1463
1464 Builder.insertDbgValueIntrinsic(DV, DIVar, DIExpr, NewLoc, SI);
1465}
1466
1467/// Inserts a llvm.dbg.value intrinsic before a load of an alloca'd value
1468/// that has an associated llvm.dbg.declare or llvm.dbg.addr intrinsic.
1469void llvm::ConvertDebugDeclareToDebugValue(DbgVariableIntrinsic *DII,
1470 LoadInst *LI, DIBuilder &Builder) {
1471 auto *DIVar = DII->getVariable();
1472 auto *DIExpr = DII->getExpression();
1473 assert(DIVar && "Missing variable")((void)0);
1474
1475 if (!valueCoversEntireFragment(LI->getType(), DII)) {
1476 // FIXME: If only referring to a part of the variable described by the
1477 // dbg.declare, then we want to insert a dbg.value for the corresponding
1478 // fragment.
1479 LLVM_DEBUG(dbgs() << "Failed to convert dbg.declare to dbg.value: "do { } while (false)
1480 << *DII << '\n')do { } while (false);
1481 return;
1482 }
1483
1484 DebugLoc NewLoc = getDebugValueLoc(DII, nullptr);
1485
1486 // We are now tracking the loaded value instead of the address. In the
1487 // future if multi-location support is added to the IR, it might be
1488 // preferable to keep tracking both the loaded value and the original
1489 // address in case the alloca can not be elided.
1490 Instruction *DbgValue = Builder.insertDbgValueIntrinsic(
1491 LI, DIVar, DIExpr, NewLoc, (Instruction *)nullptr);
1492 DbgValue->insertAfter(LI);
1493}
1494
1495/// Inserts a llvm.dbg.value intrinsic after a phi that has an associated
1496/// llvm.dbg.declare or llvm.dbg.addr intrinsic.
1497void llvm::ConvertDebugDeclareToDebugValue(DbgVariableIntrinsic *DII,
1498 PHINode *APN, DIBuilder &Builder) {
1499 auto *DIVar = DII->getVariable();
1500 auto *DIExpr = DII->getExpression();
1501 assert(DIVar && "Missing variable")((void)0);
1502
1503 if (PhiHasDebugValue(DIVar, DIExpr, APN))
1504 return;
1505
1506 if (!valueCoversEntireFragment(APN->getType(), DII)) {
1507 // FIXME: If only referring to a part of the variable described by the
1508 // dbg.declare, then we want to insert a dbg.value for the corresponding
1509 // fragment.
1510 LLVM_DEBUG(dbgs() << "Failed to convert dbg.declare to dbg.value: "do { } while (false)
1511 << *DII << '\n')do { } while (false);
1512 return;
1513 }
1514
1515 BasicBlock *BB = APN->getParent();
1516 auto InsertionPt = BB->getFirstInsertionPt();
1517
1518 DebugLoc NewLoc = getDebugValueLoc(DII, nullptr);
1519
1520 // The block may be a catchswitch block, which does not have a valid
1521 // insertion point.
1522 // FIXME: Insert dbg.value markers in the successors when appropriate.
1523 if (InsertionPt != BB->end())
1524 Builder.insertDbgValueIntrinsic(APN, DIVar, DIExpr, NewLoc, &*InsertionPt);
1525}
1526
1527/// Determine whether this alloca is either a VLA or an array.
1528static bool isArray(AllocaInst *AI) {
1529 return AI->isArrayAllocation() ||
1530 (AI->getAllocatedType() && AI->getAllocatedType()->isArrayTy());
1531}
1532
1533/// Determine whether this alloca is a structure.
1534static bool isStructure(AllocaInst *AI) {
1535 return AI->getAllocatedType() && AI->getAllocatedType()->isStructTy();
1536}
1537
1538/// LowerDbgDeclare - Lowers llvm.dbg.declare intrinsics into appropriate set
1539/// of llvm.dbg.value intrinsics.
1540bool llvm::LowerDbgDeclare(Function &F) {
1541 bool Changed = false;
1542 DIBuilder DIB(*F.getParent(), /*AllowUnresolved*/ false);
1543 SmallVector<DbgDeclareInst *, 4> Dbgs;
1544 for (auto &FI : F)
1545 for (Instruction &BI : FI)
1546 if (auto DDI = dyn_cast<DbgDeclareInst>(&BI))
1547 Dbgs.push_back(DDI);
1548
1549 if (Dbgs.empty())
1550 return Changed;
1551
1552 for (auto &I : Dbgs) {
1553 DbgDeclareInst *DDI = I;
1554 AllocaInst *AI = dyn_cast_or_null<AllocaInst>(DDI->getAddress());
1555 // If this is an alloca for a scalar variable, insert a dbg.value
1556 // at each load and store to the alloca and erase the dbg.declare.
1557 // The dbg.values allow tracking a variable even if it is not
1558 // stored on the stack, while the dbg.declare can only describe
1559 // the stack slot (and at a lexical-scope granularity). Later
1560 // passes will attempt to elide the stack slot.
1561 if (!AI || isArray(AI) || isStructure(AI))
1562 continue;
1563
1564 // A volatile load/store means that the alloca can't be elided anyway.
1565 if (llvm::any_of(AI->users(), [](User *U) -> bool {
1566 if (LoadInst *LI = dyn_cast<LoadInst>(U))
1567 return LI->isVolatile();
1568 if (StoreInst *SI = dyn_cast<StoreInst>(U))
1569 return SI->isVolatile();
1570 return false;
1571 }))
1572 continue;
1573
1574 SmallVector<const Value *, 8> WorkList;
1575 WorkList.push_back(AI);
1576 while (!WorkList.empty()) {
1577 const Value *V = WorkList.pop_back_val();
1578 for (auto &AIUse : V->uses()) {
1579 User *U = AIUse.getUser();
1580 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
1581 if (AIUse.getOperandNo() == 1)
1582 ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
1583 } else if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
1584 ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
1585 } else if (CallInst *CI = dyn_cast<CallInst>(U)) {
1586 // This is a call by-value or some other instruction that takes a
1587 // pointer to the variable. Insert a *value* intrinsic that describes
1588 // the variable by dereferencing the alloca.
1589 if (!CI->isLifetimeStartOrEnd()) {
1590 DebugLoc NewLoc = getDebugValueLoc(DDI, nullptr);
1591 auto *DerefExpr =
1592 DIExpression::append(DDI->getExpression(), dwarf::DW_OP_deref);
1593 DIB.insertDbgValueIntrinsic(AI, DDI->getVariable(), DerefExpr,
1594 NewLoc, CI);
1595 }
1596 } else if (BitCastInst *BI = dyn_cast<BitCastInst>(U)) {
1597 if (BI->getType()->isPointerTy())
1598 WorkList.push_back(BI);
1599 }
1600 }
1601 }
1602 DDI->eraseFromParent();
1603 Changed = true;
1604 }
1605
1606 if (Changed)
1607 for (BasicBlock &BB : F)
1608 RemoveRedundantDbgInstrs(&BB);
1609
1610 return Changed;
1611}
1612
1613/// Propagate dbg.value intrinsics through the newly inserted PHIs.
1614void llvm::insertDebugValuesForPHIs(BasicBlock *BB,
1615 SmallVectorImpl<PHINode *> &InsertedPHIs) {
1616 assert(BB && "No BasicBlock to clone dbg.value(s) from.")((void)0);
1617 if (InsertedPHIs.size() == 0)
1618 return;
1619
1620 // Map existing PHI nodes to their dbg.values.
1621 ValueToValueMapTy DbgValueMap;
1622 for (auto &I : *BB) {
1623 if (auto DbgII = dyn_cast<DbgVariableIntrinsic>(&I)) {
1624 for (Value *V : DbgII->location_ops())
1625 if (auto *Loc = dyn_cast_or_null<PHINode>(V))
1626 DbgValueMap.insert({Loc, DbgII});
1627 }
1628 }
1629 if (DbgValueMap.size() == 0)
1630 return;
1631
1632 // Map a pair of the destination BB and old dbg.value to the new dbg.value,
1633 // so that if a dbg.value is being rewritten to use more than one of the
1634 // inserted PHIs in the same destination BB, we can update the same dbg.value
1635 // with all the new PHIs instead of creating one copy for each.
1636 MapVector<std::pair<BasicBlock *, DbgVariableIntrinsic *>,
1637 DbgVariableIntrinsic *>
1638 NewDbgValueMap;
1639 // Then iterate through the new PHIs and look to see if they use one of the
1640 // previously mapped PHIs. If so, create a new dbg.value intrinsic that will
1641 // propagate the info through the new PHI. If we use more than one new PHI in
1642 // a single destination BB with the same old dbg.value, merge the updates so
1643 // that we get a single new dbg.value with all the new PHIs.
1644 for (auto PHI : InsertedPHIs) {
1645 BasicBlock *Parent = PHI->getParent();
1646 // Avoid inserting an intrinsic into an EH block.
1647 if (Parent->getFirstNonPHI()->isEHPad())
1648 continue;
1649 for (auto VI : PHI->operand_values()) {
1650 auto V = DbgValueMap.find(VI);
1651 if (V != DbgValueMap.end()) {
1652 auto *DbgII = cast<DbgVariableIntrinsic>(V->second);
1653 auto NewDI = NewDbgValueMap.find({Parent, DbgII});
1654 if (NewDI == NewDbgValueMap.end()) {
1655 auto *NewDbgII = cast<DbgVariableIntrinsic>(DbgII->clone());
1656 NewDI = NewDbgValueMap.insert({{Parent, DbgII}, NewDbgII}).first;
1657 }
1658 DbgVariableIntrinsic *NewDbgII = NewDI->second;
1659 // If PHI contains VI as an operand more than once, we may
1660 // replaced it in NewDbgII; confirm that it is present.
1661 if (is_contained(NewDbgII->location_ops(), VI))
1662 NewDbgII->replaceVariableLocationOp(VI, PHI);
1663 }
1664 }
1665 }
1666 // Insert thew new dbg.values into their destination blocks.
1667 for (auto DI : NewDbgValueMap) {
1668 BasicBlock *Parent = DI.first.first;
1669 auto *NewDbgII = DI.second;
1670 auto InsertionPt = Parent->getFirstInsertionPt();
1671 assert(InsertionPt != Parent->end() && "Ill-formed basic block")((void)0);
1672 NewDbgII->insertBefore(&*InsertionPt);
1673 }
1674}
1675
1676bool llvm::replaceDbgDeclare(Value *Address, Value *NewAddress,
1677 DIBuilder &Builder, uint8_t DIExprFlags,
1678 int Offset) {
1679 auto DbgAddrs = FindDbgAddrUses(Address);
1680 for (DbgVariableIntrinsic *DII : DbgAddrs) {
1681 const DebugLoc &Loc = DII->getDebugLoc();
1682 auto *DIVar = DII->getVariable();
1683 auto *DIExpr = DII->getExpression();
1684 assert(DIVar && "Missing variable")((void)0);
1685 DIExpr = DIExpression::prepend(DIExpr, DIExprFlags, Offset);
1686 // Insert llvm.dbg.declare immediately before DII, and remove old
1687 // llvm.dbg.declare.
1688 Builder.insertDeclare(NewAddress, DIVar, DIExpr, Loc, DII);
1689 DII->eraseFromParent();
1690 }
1691 return !DbgAddrs.empty();
1692}
1693
1694static void replaceOneDbgValueForAlloca(DbgValueInst *DVI, Value *NewAddress,
1695 DIBuilder &Builder, int Offset) {
1696 const DebugLoc &Loc = DVI->getDebugLoc();
1697 auto *DIVar = DVI->getVariable();
1698 auto *DIExpr = DVI->getExpression();
1699 assert(DIVar && "Missing variable")((void)0);
1700
1701 // This is an alloca-based llvm.dbg.value. The first thing it should do with
1702 // the alloca pointer is dereference it. Otherwise we don't know how to handle
1703 // it and give up.
1704 if (!DIExpr || DIExpr->getNumElements() < 1 ||
1705 DIExpr->getElement(0) != dwarf::DW_OP_deref)
1706 return;
1707
1708 // Insert the offset before the first deref.
1709 // We could just change the offset argument of dbg.value, but it's unsigned...
1710 if (Offset)
1711 DIExpr = DIExpression::prepend(DIExpr, 0, Offset);
1712
1713 Builder.insertDbgValueIntrinsic(NewAddress, DIVar, DIExpr, Loc, DVI);
1714 DVI->eraseFromParent();
1715}
1716
1717void llvm::replaceDbgValueForAlloca(AllocaInst *AI, Value *NewAllocaAddress,
1718 DIBuilder &Builder, int Offset) {
1719 if (auto *L = LocalAsMetadata::getIfExists(AI))
1720 if (auto *MDV = MetadataAsValue::getIfExists(AI->getContext(), L))
1721 for (Use &U : llvm::make_early_inc_range(MDV->uses()))
1722 if (auto *DVI = dyn_cast<DbgValueInst>(U.getUser()))
1723 replaceOneDbgValueForAlloca(DVI, NewAllocaAddress, Builder, Offset);
1724}
1725
1726/// Where possible to salvage debug information for \p I do so
1727/// and return True. If not possible mark undef and return False.
1728void llvm::salvageDebugInfo(Instruction &I) {
1729 SmallVector<DbgVariableIntrinsic *, 1> DbgUsers;
1730 findDbgUsers(DbgUsers, &I);
1731 salvageDebugInfoForDbgValues(I, DbgUsers);
1732}
1733
1734void llvm::salvageDebugInfoForDbgValues(
1735 Instruction &I, ArrayRef<DbgVariableIntrinsic *> DbgUsers) {
1736 // This is an arbitrary chosen limit on the maximum number of values we can
1737 // salvage up to in a DIArgList, used for performance reasons.
1738 const unsigned MaxDebugArgs = 16;
1739 bool Salvaged = false;
1740
1741 for (auto *DII : DbgUsers) {
1742 // Do not add DW_OP_stack_value for DbgDeclare and DbgAddr, because they
1743 // are implicitly pointing out the value as a DWARF memory location
1744 // description.
1745 bool StackValue = isa<DbgValueInst>(DII);
1746 auto DIILocation = DII->location_ops();
1747 assert(((void)0)
1748 is_contained(DIILocation, &I) &&((void)0)
1749 "DbgVariableIntrinsic must use salvaged instruction as its location")((void)0);
1750 SmallVector<Value *, 4> AdditionalValues;
1751 // `I` may appear more than once in DII's location ops, and each use of `I`
1752 // must be updated in the DIExpression and potentially have additional
1753 // values added; thus we call salvageDebugInfoImpl for each `I` instance in
1754 // DIILocation.
1755 DIExpression *SalvagedExpr = DII->getExpression();
1756 auto LocItr = find(DIILocation, &I);
1757 while (SalvagedExpr && LocItr != DIILocation.end()) {
1758 unsigned LocNo = std::distance(DIILocation.begin(), LocItr);
1759 SalvagedExpr = salvageDebugInfoImpl(I, SalvagedExpr, StackValue, LocNo,
1760 AdditionalValues);
1761 LocItr = std::find(++LocItr, DIILocation.end(), &I);
1762 }
1763 // salvageDebugInfoImpl should fail on examining the first element of
1764 // DbgUsers, or none of them.
1765 if (!SalvagedExpr)
1766 break;
1767
1768 DII->replaceVariableLocationOp(&I, I.getOperand(0));
1769 if (AdditionalValues.empty()) {
1770 DII->setExpression(SalvagedExpr);
1771 } else if (isa<DbgValueInst>(DII) &&
1772 DII->getNumVariableLocationOps() + AdditionalValues.size() <=
1773 MaxDebugArgs) {
1774 DII->addVariableLocationOps(AdditionalValues, SalvagedExpr);
1775 } else {
1776 // Do not salvage using DIArgList for dbg.addr/dbg.declare, as it is
1777 // currently only valid for stack value expressions.
1778 // Also do not salvage if the resulting DIArgList would contain an
1779 // unreasonably large number of values.
1780 Value *Undef = UndefValue::get(I.getOperand(0)->getType());
1781 DII->replaceVariableLocationOp(I.getOperand(0), Undef);
1782 }
1783 LLVM_DEBUG(dbgs() << "SALVAGE: " << *DII << '\n')do { } while (false);
1784 Salvaged = true;
1785 }
1786
1787 if (Salvaged)
1788 return;
1789
1790 for (auto *DII : DbgUsers) {
1791 Value *Undef = UndefValue::get(I.getType());
1792 DII->replaceVariableLocationOp(&I, Undef);
1793 }
1794}
1795
1796bool getSalvageOpsForGEP(GetElementPtrInst *GEP, const DataLayout &DL,
1797 uint64_t CurrentLocOps,
1798 SmallVectorImpl<uint64_t> &Opcodes,
1799 SmallVectorImpl<Value *> &AdditionalValues) {
1800 unsigned BitWidth = DL.getIndexSizeInBits(GEP->getPointerAddressSpace());
1801 // Rewrite a GEP into a DIExpression.
1802 MapVector<Value *, APInt> VariableOffsets;
1803 APInt ConstantOffset(BitWidth, 0);
1804 if (!GEP->collectOffset(DL, BitWidth, VariableOffsets, ConstantOffset))
1805 return false;
1806 if (!VariableOffsets.empty() && !CurrentLocOps) {
1807 Opcodes.insert(Opcodes.begin(), {dwarf::DW_OP_LLVM_arg, 0});
1808 CurrentLocOps = 1;
1809 }
1810 for (auto Offset : VariableOffsets) {
1811 AdditionalValues.push_back(Offset.first);
1812 assert(Offset.second.isStrictlyPositive() &&((void)0)
1813 "Expected strictly positive multiplier for offset.")((void)0);
1814 Opcodes.append({dwarf::DW_OP_LLVM_arg, CurrentLocOps++, dwarf::DW_OP_constu,
1815 Offset.second.getZExtValue(), dwarf::DW_OP_mul,
1816 dwarf::DW_OP_plus});
1817 }
1818 DIExpression::appendOffset(Opcodes, ConstantOffset.getSExtValue());
1819 return true;
1820}
1821
1822uint64_t getDwarfOpForBinOp(Instruction::BinaryOps Opcode) {
1823 switch (Opcode) {
1824 case Instruction::Add:
1825 return dwarf::DW_OP_plus;
1826 case Instruction::Sub:
1827 return dwarf::DW_OP_minus;
1828 case Instruction::Mul:
1829 return dwarf::DW_OP_mul;
1830 case Instruction::SDiv:
1831 return dwarf::DW_OP_div;
1832 case Instruction::SRem:
1833 return dwarf::DW_OP_mod;
1834 case Instruction::Or:
1835 return dwarf::DW_OP_or;
1836 case Instruction::And:
1837 return dwarf::DW_OP_and;
1838 case Instruction::Xor:
1839 return dwarf::DW_OP_xor;
1840 case Instruction::Shl:
1841 return dwarf::DW_OP_shl;
1842 case Instruction::LShr:
1843 return dwarf::DW_OP_shr;
1844 case Instruction::AShr:
1845 return dwarf::DW_OP_shra;
1846 default:
1847 // TODO: Salvage from each kind of binop we know about.
1848 return 0;
1849 }
1850}
1851
1852bool getSalvageOpsForBinOp(BinaryOperator *BI, uint64_t CurrentLocOps,
1853 SmallVectorImpl<uint64_t> &Opcodes,
1854 SmallVectorImpl<Value *> &AdditionalValues) {
1855 // Handle binary operations with constant integer operands as a special case.
1856 auto *ConstInt = dyn_cast<ConstantInt>(BI->getOperand(1));
1857 // Values wider than 64 bits cannot be represented within a DIExpression.
1858 if (ConstInt && ConstInt->getBitWidth() > 64)
1859 return false;
1860
1861 Instruction::BinaryOps BinOpcode = BI->getOpcode();
1862 // Push any Constant Int operand onto the expression stack.
1863 if (ConstInt) {
1864 uint64_t Val = ConstInt->getSExtValue();
1865 // Add or Sub Instructions with a constant operand can potentially be
1866 // simplified.
1867 if (BinOpcode == Instruction::Add || BinOpcode == Instruction::Sub) {
1868 uint64_t Offset = BinOpcode == Instruction::Add ? Val : -int64_t(Val);
1869 DIExpression::appendOffset(Opcodes, Offset);
1870 return true;
1871 }
1872 Opcodes.append({dwarf::DW_OP_constu, Val});
1873 } else {
1874 if (!CurrentLocOps) {
1875 Opcodes.append({dwarf::DW_OP_LLVM_arg, 0});
1876 CurrentLocOps = 1;
1877 }
1878 Opcodes.append({dwarf::DW_OP_LLVM_arg, CurrentLocOps});
1879 AdditionalValues.push_back(BI->getOperand(1));
1880 }
1881
1882 // Add salvaged binary operator to expression stack, if it has a valid
1883 // representation in a DIExpression.
1884 uint64_t DwarfBinOp = getDwarfOpForBinOp(BinOpcode);
1885 if (!DwarfBinOp)
1886 return false;
1887 Opcodes.push_back(DwarfBinOp);
1888
1889 return true;
1890}
1891
1892DIExpression *
1893llvm::salvageDebugInfoImpl(Instruction &I, DIExpression *SrcDIExpr,
1894 bool WithStackValue, unsigned LocNo,
1895 SmallVectorImpl<Value *> &AdditionalValues) {
1896 uint64_t CurrentLocOps = SrcDIExpr->getNumLocationOperands();
1897 auto &M = *I.getModule();
1898 auto &DL = M.getDataLayout();
1899
1900 // Apply a vector of opcodes to the source DIExpression.
1901 auto doSalvage = [&](SmallVectorImpl<uint64_t> &Ops) -> DIExpression * {
1902 DIExpression *DIExpr = SrcDIExpr;
1903 if (!Ops.empty()) {
1904 DIExpr = DIExpression::appendOpsToArg(DIExpr, Ops, LocNo, WithStackValue);
1905 }
1906 return DIExpr;
1907 };
1908
1909 // initializer-list helper for applying operators to the source DIExpression.
1910 auto applyOps = [&](ArrayRef<uint64_t> Opcodes) {
1911 SmallVector<uint64_t, 8> Ops(Opcodes.begin(), Opcodes.end());
1912 return doSalvage(Ops);
1913 };
1914
1915 if (auto *CI = dyn_cast<CastInst>(&I)) {
1916 // No-op casts are irrelevant for debug info.
1917 if (CI->isNoopCast(DL))
1918 return SrcDIExpr;
1919
1920 Type *Type = CI->getType();
1921 // Casts other than Trunc, SExt, or ZExt to scalar types cannot be salvaged.
1922 if (Type->isVectorTy() ||
1923 !(isa<TruncInst>(&I) || isa<SExtInst>(&I) || isa<ZExtInst>(&I)))
1924 return nullptr;
1925
1926 Value *FromValue = CI->getOperand(0);
1927 unsigned FromTypeBitSize = FromValue->getType()->getScalarSizeInBits();
1928 unsigned ToTypeBitSize = Type->getScalarSizeInBits();
1929
1930 return applyOps(DIExpression::getExtOps(FromTypeBitSize, ToTypeBitSize,
1931 isa<SExtInst>(&I)));
1932 }
1933
1934 SmallVector<uint64_t, 8> Ops;
1935 if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
1936 if (getSalvageOpsForGEP(GEP, DL, CurrentLocOps, Ops, AdditionalValues))
1937 return doSalvage(Ops);
1938 } else if (auto *BI = dyn_cast<BinaryOperator>(&I)) {
1939 if (getSalvageOpsForBinOp(BI, CurrentLocOps, Ops, AdditionalValues))
1940 return doSalvage(Ops);
1941 }
1942 // *Not* to do: we should not attempt to salvage load instructions,
1943 // because the validity and lifetime of a dbg.value containing
1944 // DW_OP_deref becomes difficult to analyze. See PR40628 for examples.
1945 return nullptr;
1946}
1947
1948/// A replacement for a dbg.value expression.
1949using DbgValReplacement = Optional<DIExpression *>;
1950
1951/// Point debug users of \p From to \p To using exprs given by \p RewriteExpr,
1952/// possibly moving/undefing users to prevent use-before-def. Returns true if
1953/// changes are made.
1954static bool rewriteDebugUsers(
1955 Instruction &From, Value &To, Instruction &DomPoint, DominatorTree &DT,
1956 function_ref<DbgValReplacement(DbgVariableIntrinsic &DII)> RewriteExpr) {
1957 // Find debug users of From.
1958 SmallVector<DbgVariableIntrinsic *, 1> Users;
1959 findDbgUsers(Users, &From);
1960 if (Users.empty())
1961 return false;
1962
1963 // Prevent use-before-def of To.
1964 bool Changed = false;
1965 SmallPtrSet<DbgVariableIntrinsic *, 1> UndefOrSalvage;
1966 if (isa<Instruction>(&To)) {
1967 bool DomPointAfterFrom = From.getNextNonDebugInstruction() == &DomPoint;
1968
1969 for (auto *DII : Users) {
1970 // It's common to see a debug user between From and DomPoint. Move it
1971 // after DomPoint to preserve the variable update without any reordering.
1972 if (DomPointAfterFrom && DII->getNextNonDebugInstruction() == &DomPoint) {
1973 LLVM_DEBUG(dbgs() << "MOVE: " << *DII << '\n')do { } while (false);
1974 DII->moveAfter(&DomPoint);
1975 Changed = true;
1976
1977 // Users which otherwise aren't dominated by the replacement value must
1978 // be salvaged or deleted.
1979 } else if (!DT.dominates(&DomPoint, DII)) {
1980 UndefOrSalvage.insert(DII);
1981 }
1982 }
1983 }
1984
1985 // Update debug users without use-before-def risk.
1986 for (auto *DII : Users) {
1987 if (UndefOrSalvage.count(DII))
1988 continue;
1989
1990 DbgValReplacement DVR = RewriteExpr(*DII);
1991 if (!DVR)
1992 continue;
1993
1994 DII->replaceVariableLocationOp(&From, &To);
1995 DII->setExpression(*DVR);
1996 LLVM_DEBUG(dbgs() << "REWRITE: " << *DII << '\n')do { } while (false);
1997 Changed = true;
1998 }
1999
2000 if (!UndefOrSalvage.empty()) {
2001 // Try to salvage the remaining debug users.
2002 salvageDebugInfo(From);
2003 Changed = true;
2004 }
2005
2006 return Changed;
2007}
2008
2009/// Check if a bitcast between a value of type \p FromTy to type \p ToTy would
2010/// losslessly preserve the bits and semantics of the value. This predicate is
2011/// symmetric, i.e swapping \p FromTy and \p ToTy should give the same result.
2012///
2013/// Note that Type::canLosslesslyBitCastTo is not suitable here because it
2014/// allows semantically unequivalent bitcasts, such as <2 x i64> -> <4 x i32>,
2015/// and also does not allow lossless pointer <-> integer conversions.
2016static bool isBitCastSemanticsPreserving(const DataLayout &DL, Type *FromTy,
2017 Type *ToTy) {
2018 // Trivially compatible types.
2019 if (FromTy == ToTy)
2020 return true;
2021
2022 // Handle compatible pointer <-> integer conversions.
2023 if (FromTy->isIntOrPtrTy() && ToTy->isIntOrPtrTy()) {
2024 bool SameSize = DL.getTypeSizeInBits(FromTy) == DL.getTypeSizeInBits(ToTy);
2025 bool LosslessConversion = !DL.isNonIntegralPointerType(FromTy) &&
2026 !DL.isNonIntegralPointerType(ToTy);
2027 return SameSize && LosslessConversion;
2028 }
2029
2030 // TODO: This is not exhaustive.
2031 return false;
2032}
2033
2034bool llvm::replaceAllDbgUsesWith(Instruction &From, Value &To,
2035 Instruction &DomPoint, DominatorTree &DT) {
2036 // Exit early if From has no debug users.
2037 if (!From.isUsedByMetadata())
2038 return false;
2039
2040 assert(&From != &To && "Can't replace something with itself")((void)0);
2041
2042 Type *FromTy = From.getType();
2043 Type *ToTy = To.getType();
2044
2045 auto Identity = [&](DbgVariableIntrinsic &DII) -> DbgValReplacement {
2046 return DII.getExpression();
2047 };
2048
2049 // Handle no-op conversions.
2050 Module &M = *From.getModule();
2051 const DataLayout &DL = M.getDataLayout();
2052 if (isBitCastSemanticsPreserving(DL, FromTy, ToTy))
2053 return rewriteDebugUsers(From, To, DomPoint, DT, Identity);
2054
2055 // Handle integer-to-integer widening and narrowing.
2056 // FIXME: Use DW_OP_convert when it's available everywhere.
2057 if (FromTy->isIntegerTy() && ToTy->isIntegerTy()) {
2058 uint64_t FromBits = FromTy->getPrimitiveSizeInBits();
2059 uint64_t ToBits = ToTy->getPrimitiveSizeInBits();
2060 assert(FromBits != ToBits && "Unexpected no-op conversion")((void)0);
2061
2062 // When the width of the result grows, assume that a debugger will only
2063 // access the low `FromBits` bits when inspecting the source variable.
2064 if (FromBits < ToBits)
2065 return rewriteDebugUsers(From, To, DomPoint, DT, Identity);
2066
2067 // The width of the result has shrunk. Use sign/zero extension to describe
2068 // the source variable's high bits.
2069 auto SignOrZeroExt = [&](DbgVariableIntrinsic &DII) -> DbgValReplacement {
2070 DILocalVariable *Var = DII.getVariable();
2071
2072 // Without knowing signedness, sign/zero extension isn't possible.
2073 auto Signedness = Var->getSignedness();
2074 if (!Signedness)
2075 return None;
2076
2077 bool Signed = *Signedness == DIBasicType::Signedness::Signed;
2078 return DIExpression::appendExt(DII.getExpression(), ToBits, FromBits,
2079 Signed);
2080 };
2081 return rewriteDebugUsers(From, To, DomPoint, DT, SignOrZeroExt);
2082 }
2083
2084 // TODO: Floating-point conversions, vectors.
2085 return false;
2086}
2087
2088std::pair<unsigned, unsigned>
2089llvm::removeAllNonTerminatorAndEHPadInstructions(BasicBlock *BB) {
2090 unsigned NumDeadInst = 0;
2091 unsigned NumDeadDbgInst = 0;
2092 // Delete the instructions backwards, as it has a reduced likelihood of
2093 // having to update as many def-use and use-def chains.
2094 Instruction *EndInst = BB->getTerminator(); // Last not to be deleted.
2095 while (EndInst != &BB->front()) {
2096 // Delete the next to last instruction.
2097 Instruction *Inst = &*--EndInst->getIterator();
2098 if (!Inst->use_empty() && !Inst->getType()->isTokenTy())
2099 Inst->replaceAllUsesWith(UndefValue::get(Inst->getType()));
2100 if (Inst->isEHPad() || Inst->getType()->isTokenTy()) {
2101 EndInst = Inst;
2102 continue;
2103 }
2104 if (isa<DbgInfoIntrinsic>(Inst))
2105 ++NumDeadDbgInst;
2106 else
2107 ++NumDeadInst;
2108 Inst->eraseFromParent();
2109 }
2110 return {NumDeadInst, NumDeadDbgInst};
2111}
2112
2113unsigned llvm::changeToUnreachable(Instruction *I, bool PreserveLCSSA,
2114 DomTreeUpdater *DTU,
2115 MemorySSAUpdater *MSSAU) {
2116 BasicBlock *BB = I->getParent();
2117
2118 if (MSSAU)
2119 MSSAU->changeToUnreachable(I);
2120
2121 SmallSet<BasicBlock *, 8> UniqueSuccessors;
2122
2123 // Loop over all of the successors, removing BB's entry from any PHI
2124 // nodes.
2125 for (BasicBlock *Successor : successors(BB)) {
2126 Successor->removePredecessor(BB, PreserveLCSSA);
2127 if (DTU)
2128 UniqueSuccessors.insert(Successor);
2129 }
2130 auto *UI = new UnreachableInst(I->getContext(), I);
2131 UI->setDebugLoc(I->getDebugLoc());
2132
2133 // All instructions after this are dead.
2134 unsigned NumInstrsRemoved = 0;
2135 BasicBlock::iterator BBI = I->getIterator(), BBE = BB->end();
2136 while (BBI != BBE) {
2137 if (!BBI->use_empty())
2138 BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
2139 BB->getInstList().erase(BBI++);
2140 ++NumInstrsRemoved;
2141 }
2142 if (DTU) {
2143 SmallVector<DominatorTree::UpdateType, 8> Updates;
2144 Updates.reserve(UniqueSuccessors.size());
2145 for (BasicBlock *UniqueSuccessor : UniqueSuccessors)
2146 Updates.push_back({DominatorTree::Delete, BB, UniqueSuccessor});
2147 DTU->applyUpdates(Updates);
2148 }
2149 return NumInstrsRemoved;
2150}
2151
2152CallInst *llvm::createCallMatchingInvoke(InvokeInst *II) {
2153 SmallVector<Value *, 8> Args(II->args());
2154 SmallVector<OperandBundleDef, 1> OpBundles;
2155 II->getOperandBundlesAsDefs(OpBundles);
2156 CallInst *NewCall = CallInst::Create(II->getFunctionType(),
2157 II->getCalledOperand(), Args, OpBundles);
2158 NewCall->setCallingConv(II->getCallingConv());
2159 NewCall->setAttributes(II->getAttributes());
2160 NewCall->setDebugLoc(II->getDebugLoc());
2161 NewCall->copyMetadata(*II);
2162
2163 // If the invoke had profile metadata, try converting them for CallInst.
2164 uint64_t TotalWeight;
2165 if (NewCall->extractProfTotalWeight(TotalWeight)) {
2166 // Set the total weight if it fits into i32, otherwise reset.
2167 MDBuilder MDB(NewCall->getContext());
2168 auto NewWeights = uint32_t(TotalWeight) != TotalWeight
2169 ? nullptr
2170 : MDB.createBranchWeights({uint32_t(TotalWeight)});
2171 NewCall->setMetadata(LLVMContext::MD_prof, NewWeights);
2172 }
2173
2174 return NewCall;
2175}
2176
2177/// changeToCall - Convert the specified invoke into a normal call.
2178void llvm::changeToCall(InvokeInst *II, DomTreeUpdater *DTU) {
2179 CallInst *NewCall = createCallMatchingInvoke(II);
2180 NewCall->takeName(II);
2181 NewCall->insertBefore(II);
2182 II->replaceAllUsesWith(NewCall);
2183
2184 // Follow the call by a branch to the normal destination.
2185 BasicBlock *NormalDestBB = II->getNormalDest();
2186 BranchInst::Create(NormalDestBB, II);
2187
2188 // Update PHI nodes in the unwind destination
2189 BasicBlock *BB = II->getParent();
2190 BasicBlock *UnwindDestBB = II->getUnwindDest();
2191 UnwindDestBB->removePredecessor(BB);
2192 II->eraseFromParent();
2193 if (DTU)
2194 DTU->applyUpdates({{DominatorTree::Delete, BB, UnwindDestBB}});
2195}
2196
2197BasicBlock *llvm::changeToInvokeAndSplitBasicBlock(CallInst *CI,
2198 BasicBlock *UnwindEdge,
2199 DomTreeUpdater *DTU) {
2200 BasicBlock *BB = CI->getParent();
2201
2202 // Convert this function call into an invoke instruction. First, split the
2203 // basic block.
2204 BasicBlock *Split = SplitBlock(BB, CI, DTU, /*LI=*/nullptr, /*MSSAU*/ nullptr,
2205 CI->getName() + ".noexc");
2206
2207 // Delete the unconditional branch inserted by SplitBlock
2208 BB->getInstList().pop_back();
2209
2210 // Create the new invoke instruction.
2211 SmallVector<Value *, 8> InvokeArgs(CI->args());
2212 SmallVector<OperandBundleDef, 1> OpBundles;
2213
2214 CI->getOperandBundlesAsDefs(OpBundles);
2215
2216 // Note: we're round tripping operand bundles through memory here, and that
2217 // can potentially be avoided with a cleverer API design that we do not have
2218 // as of this time.
2219
2220 InvokeInst *II =
2221 InvokeInst::Create(CI->getFunctionType(), CI->getCalledOperand(), Split,
2222 UnwindEdge, InvokeArgs, OpBundles, CI->getName(), BB);
2223 II->setDebugLoc(CI->getDebugLoc());
2224 II->setCallingConv(CI->getCallingConv());
2225 II->setAttributes(CI->getAttributes());
2226
2227 if (DTU)
2228 DTU->applyUpdates({{DominatorTree::Insert, BB, UnwindEdge}});
2229
2230 // Make sure that anything using the call now uses the invoke! This also
2231 // updates the CallGraph if present, because it uses a WeakTrackingVH.
2232 CI->replaceAllUsesWith(II);
2233
2234 // Delete the original call
2235 Split->getInstList().pop_front();
2236 return Split;
2237}
2238
2239static bool markAliveBlocks(Function &F,
2240 SmallPtrSetImpl<BasicBlock *> &Reachable,
2241 DomTreeUpdater *DTU = nullptr) {
2242 SmallVector<BasicBlock*, 128> Worklist;
2243 BasicBlock *BB = &F.front();
2244 Worklist.push_back(BB);
2245 Reachable.insert(BB);
2246 bool Changed = false;
2247 do {
2248 BB = Worklist.pop_back_val();
2249
2250 // Do a quick scan of the basic block, turning any obviously unreachable
2251 // instructions into LLVM unreachable insts. The instruction combining pass
2252 // canonicalizes unreachable insts into stores to null or undef.
2253 for (Instruction &I : *BB) {
2254 if (auto *CI = dyn_cast<CallInst>(&I)) {
2255 Value *Callee = CI->getCalledOperand();
2256 // Handle intrinsic calls.
2257 if (Function *F = dyn_cast<Function>(Callee)) {
2258 auto IntrinsicID = F->getIntrinsicID();
2259 // Assumptions that are known to be false are equivalent to
2260 // unreachable. Also, if the condition is undefined, then we make the
2261 // choice most beneficial to the optimizer, and choose that to also be
2262 // unreachable.
2263 if (IntrinsicID == Intrinsic::assume) {
2264 if (match(CI->getArgOperand(0), m_CombineOr(m_Zero(), m_Undef()))) {
2265 // Don't insert a call to llvm.trap right before the unreachable.
2266 changeToUnreachable(CI, false, DTU);
2267 Changed = true;
2268 break;
2269 }
2270 } else if (IntrinsicID == Intrinsic::experimental_guard) {
2271 // A call to the guard intrinsic bails out of the current
2272 // compilation unit if the predicate passed to it is false. If the
2273 // predicate is a constant false, then we know the guard will bail
2274 // out of the current compile unconditionally, so all code following
2275 // it is dead.
2276 //
2277 // Note: unlike in llvm.assume, it is not "obviously profitable" for
2278 // guards to treat `undef` as `false` since a guard on `undef` can
2279 // still be useful for widening.
2280 if (match(CI->getArgOperand(0), m_Zero()))
2281 if (!isa<UnreachableInst>(CI->getNextNode())) {
2282 changeToUnreachable(CI->getNextNode(), false, DTU);
2283 Changed = true;
2284 break;
2285 }
2286 }
2287 } else if ((isa<ConstantPointerNull>(Callee) &&
2288 !NullPointerIsDefined(CI->getFunction())) ||
2289 isa<UndefValue>(Callee)) {
2290 changeToUnreachable(CI, false, DTU);
2291 Changed = true;
2292 break;
2293 }
2294 if (CI->doesNotReturn() && !CI->isMustTailCall()) {
2295 // If we found a call to a no-return function, insert an unreachable
2296 // instruction after it. Make sure there isn't *already* one there
2297 // though.
2298 if (!isa<UnreachableInst>(CI->getNextNode())) {
2299 // Don't insert a call to llvm.trap right before the unreachable.
2300 changeToUnreachable(CI->getNextNode(), false, DTU);
2301 Changed = true;
2302 }
2303 break;
2304 }
2305 } else if (auto *SI = dyn_cast<StoreInst>(&I)) {
2306 // Store to undef and store to null are undefined and used to signal
2307 // that they should be changed to unreachable by passes that can't
2308 // modify the CFG.
2309
2310 // Don't touch volatile stores.
2311 if (SI->isVolatile()) continue;
2312
2313 Value *Ptr = SI->getOperand(1);
2314
2315 if (isa<UndefValue>(Ptr) ||
2316 (isa<ConstantPointerNull>(Ptr) &&
2317 !NullPointerIsDefined(SI->getFunction(),
2318 SI->getPointerAddressSpace()))) {
2319 changeToUnreachable(SI, false, DTU);
2320 Changed = true;
2321 break;
2322 }
2323 }
2324 }
2325
2326 Instruction *Terminator = BB->getTerminator();
2327 if (auto *II = dyn_cast<InvokeInst>(Terminator)) {
2328 // Turn invokes that call 'nounwind' functions into ordinary calls.
2329 Value *Callee = II->getCalledOperand();
2330 if ((isa<ConstantPointerNull>(Callee) &&
2331 !NullPointerIsDefined(BB->getParent())) ||
2332 isa<UndefValue>(Callee)) {
2333 changeToUnreachable(II, false, DTU);
2334 Changed = true;
2335 } else if (II->doesNotThrow() && canSimplifyInvokeNoUnwind(&F)) {
2336 if (II->use_empty() && II->onlyReadsMemory()) {
2337 // jump to the normal destination branch.
2338 BasicBlock *NormalDestBB = II->getNormalDest();
2339 BasicBlock *UnwindDestBB = II->getUnwindDest();
2340 BranchInst::Create(NormalDestBB, II);
2341 UnwindDestBB->removePredecessor(II->getParent());
2342 II->eraseFromParent();
2343 if (DTU)
2344 DTU->applyUpdates({{DominatorTree::Delete, BB, UnwindDestBB}});
2345 } else
2346 changeToCall(II, DTU);
2347 Changed = true;
2348 }
2349 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Terminator)) {
2350 // Remove catchpads which cannot be reached.
2351 struct CatchPadDenseMapInfo {
2352 static CatchPadInst *getEmptyKey() {
2353 return DenseMapInfo<CatchPadInst *>::getEmptyKey();
2354 }
2355
2356 static CatchPadInst *getTombstoneKey() {
2357 return DenseMapInfo<CatchPadInst *>::getTombstoneKey();
2358 }
2359
2360 static unsigned getHashValue(CatchPadInst *CatchPad) {
2361 return static_cast<unsigned>(hash_combine_range(
2362 CatchPad->value_op_begin(), CatchPad->value_op_end()));
2363 }
2364
2365 static bool isEqual(CatchPadInst *LHS, CatchPadInst *RHS) {
2366 if (LHS == getEmptyKey() || LHS == getTombstoneKey() ||
2367 RHS == getEmptyKey() || RHS == getTombstoneKey())
2368 return LHS == RHS;
2369 return LHS->isIdenticalTo(RHS);
2370 }
2371 };
2372
2373 SmallDenseMap<BasicBlock *, int, 8> NumPerSuccessorCases;
2374 // Set of unique CatchPads.
2375 SmallDenseMap<CatchPadInst *, detail::DenseSetEmpty, 4,
2376 CatchPadDenseMapInfo, detail::DenseSetPair<CatchPadInst *>>
2377 HandlerSet;
2378 detail::DenseSetEmpty Empty;
2379 for (CatchSwitchInst::handler_iterator I = CatchSwitch->handler_begin(),
2380 E = CatchSwitch->handler_end();
2381 I != E; ++I) {
2382 BasicBlock *HandlerBB = *I;
2383 if (DTU)
2384 ++NumPerSuccessorCases[HandlerBB];
2385 auto *CatchPad = cast<CatchPadInst>(HandlerBB->getFirstNonPHI());
2386 if (!HandlerSet.insert({CatchPad, Empty}).second) {
2387 if (DTU)
2388 --NumPerSuccessorCases[HandlerBB];
2389 CatchSwitch->removeHandler(I);
2390 --I;
2391 --E;
2392 Changed = true;
2393 }
2394 }
2395 if (DTU) {
2396 std::vector<DominatorTree::UpdateType> Updates;
2397 for (const std::pair<BasicBlock *, int> &I : NumPerSuccessorCases)
2398 if (I.second == 0)
2399 Updates.push_back({DominatorTree::Delete, BB, I.first});
2400 DTU->applyUpdates(Updates);
2401 }
2402 }
2403
2404 Changed |= ConstantFoldTerminator(BB, true, nullptr, DTU);
2405 for (BasicBlock *Successor : successors(BB))
2406 if (Reachable.insert(Successor).second)
2407 Worklist.push_back(Successor);
2408 } while (!Worklist.empty());
2409 return Changed;
2410}
2411
2412void llvm::removeUnwindEdge(BasicBlock *BB, DomTreeUpdater *DTU) {
2413 Instruction *TI = BB->getTerminator();
2414
2415 if (auto *II = dyn_cast<InvokeInst>(TI)) {
2416 changeToCall(II, DTU);
2417 return;
2418 }
2419
2420 Instruction *NewTI;
2421 BasicBlock *UnwindDest;
2422
2423 if (auto *CRI = dyn_cast<CleanupReturnInst>(TI)) {
2424 NewTI = CleanupReturnInst::Create(CRI->getCleanupPad(), nullptr, CRI);
2425 UnwindDest = CRI->getUnwindDest();
2426 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(TI)) {
2427 auto *NewCatchSwitch = CatchSwitchInst::Create(
2428 CatchSwitch->getParentPad(), nullptr, CatchSwitch->getNumHandlers(),
2429 CatchSwitch->getName(), CatchSwitch);
2430 for (BasicBlock *PadBB : CatchSwitch->handlers())
2431 NewCatchSwitch->addHandler(PadBB);
2432
2433 NewTI = NewCatchSwitch;
2434 UnwindDest = CatchSwitch->getUnwindDest();
2435 } else {
2436 llvm_unreachable("Could not find unwind successor")__builtin_unreachable();
2437 }
2438
2439 NewTI->takeName(TI);
2440 NewTI->setDebugLoc(TI->getDebugLoc());
2441 UnwindDest->removePredecessor(BB);
2442 TI->replaceAllUsesWith(NewTI);
2443 TI->eraseFromParent();
2444 if (DTU)
2445 DTU->applyUpdates({{DominatorTree::Delete, BB, UnwindDest}});
2446}
2447
2448/// removeUnreachableBlocks - Remove blocks that are not reachable, even
2449/// if they are in a dead cycle. Return true if a change was made, false
2450/// otherwise.
2451bool llvm::removeUnreachableBlocks(Function &F, DomTreeUpdater *DTU,
2452 MemorySSAUpdater *MSSAU) {
2453 SmallPtrSet<BasicBlock *, 16> Reachable;
2454 bool Changed = markAliveBlocks(F, Reachable, DTU);
2455
2456 // If there are unreachable blocks in the CFG...
2457 if (Reachable.size() == F.size())
2458 return Changed;
2459
2460 assert(Reachable.size() < F.size())((void)0);
2461
2462 // Are there any blocks left to actually delete?
2463 SmallSetVector<BasicBlock *, 8> BlocksToRemove;
2464 for (BasicBlock &BB : F) {
2465 // Skip reachable basic blocks
2466 if (Reachable.count(&BB))
2467 continue;
2468 // Skip already-deleted blocks
2469 if (DTU && DTU->isBBPendingDeletion(&BB))
2470 continue;
2471 BlocksToRemove.insert(&BB);
2472 }
2473
2474 if (BlocksToRemove.empty())
2475 return Changed;
2476
2477 Changed = true;
2478 NumRemoved += BlocksToRemove.size();
2479
2480 if (MSSAU)
2481 MSSAU->removeBlocks(BlocksToRemove);
2482
2483 DeleteDeadBlocks(BlocksToRemove.takeVector(), DTU);
2484
2485 return Changed;
2486}
2487
2488void llvm::combineMetadata(Instruction *K, const Instruction *J,
2489 ArrayRef<unsigned> KnownIDs, bool DoesKMove) {
2490 SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
2491 K->dropUnknownNonDebugMetadata(KnownIDs);
2492 K->getAllMetadataOtherThanDebugLoc(Metadata);
2493 for (const auto &MD : Metadata) {
2494 unsigned Kind = MD.first;
2495 MDNode *JMD = J->getMetadata(Kind);
2496 MDNode *KMD = MD.second;
2497
2498 switch (Kind) {
2499 default:
2500 K->setMetadata(Kind, nullptr); // Remove unknown metadata
2501 break;
2502 case LLVMContext::MD_dbg:
2503 llvm_unreachable("getAllMetadataOtherThanDebugLoc returned a MD_dbg")__builtin_unreachable();
2504 case LLVMContext::MD_tbaa:
2505 K->setMetadata(Kind, MDNode::getMostGenericTBAA(JMD, KMD));
2506 break;
2507 case LLVMContext::MD_alias_scope:
2508 K->setMetadata(Kind, MDNode::getMostGenericAliasScope(JMD, KMD));
2509 break;
2510 case LLVMContext::MD_noalias:
2511 case LLVMContext::MD_mem_parallel_loop_access:
2512 K->setMetadata(Kind, MDNode::intersect(JMD, KMD));
2513 break;
2514 case LLVMContext::MD_access_group:
2515 K->setMetadata(LLVMContext::MD_access_group,
2516 intersectAccessGroups(K, J));
2517 break;
2518 case LLVMContext::MD_range:
2519
2520 // If K does move, use most generic range. Otherwise keep the range of
2521 // K.
2522 if (DoesKMove)
2523 // FIXME: If K does move, we should drop the range info and nonnull.
2524 // Currently this function is used with DoesKMove in passes
2525 // doing hoisting/sinking and the current behavior of using the
2526 // most generic range is correct in those cases.
2527 K->setMetadata(Kind, MDNode::getMostGenericRange(JMD, KMD));
2528 break;
2529 case LLVMContext::MD_fpmath:
2530 K->setMetadata(Kind, MDNode::getMostGenericFPMath(JMD, KMD));
2531 break;
2532 case LLVMContext::MD_invariant_load:
2533 // Only set the !invariant.load if it is present in both instructions.
2534 K->setMetadata(Kind, JMD);
2535 break;
2536 case LLVMContext::MD_nonnull:
2537 // If K does move, keep nonull if it is present in both instructions.
2538 if (DoesKMove)
2539 K->setMetadata(Kind, JMD);
2540 break;
2541 case LLVMContext::MD_invariant_group:
2542 // Preserve !invariant.group in K.
2543 break;
2544 case LLVMContext::MD_align:
2545 K->setMetadata(Kind,
2546 MDNode::getMostGenericAlignmentOrDereferenceable(JMD, KMD));
2547 break;
2548 case LLVMContext::MD_dereferenceable:
2549 case LLVMContext::MD_dereferenceable_or_null:
2550 K->setMetadata(Kind,
2551 MDNode::getMostGenericAlignmentOrDereferenceable(JMD, KMD));
2552 break;
2553 case LLVMContext::MD_preserve_access_index:
2554 // Preserve !preserve.access.index in K.
2555 break;
2556 }
2557 }
2558 // Set !invariant.group from J if J has it. If both instructions have it
2559 // then we will just pick it from J - even when they are different.
2560 // Also make sure that K is load or store - f.e. combining bitcast with load
2561 // could produce bitcast with invariant.group metadata, which is invalid.
2562 // FIXME: we should try to preserve both invariant.group md if they are
2563 // different, but right now instruction can only have one invariant.group.
2564 if (auto *JMD = J->getMetadata(LLVMContext::MD_invariant_group))
2565 if (isa<LoadInst>(K) || isa<StoreInst>(K))
2566 K->setMetadata(LLVMContext::MD_invariant_group, JMD);
2567}
2568
2569void llvm::combineMetadataForCSE(Instruction *K, const Instruction *J,
2570 bool KDominatesJ) {
2571 unsigned KnownIDs[] = {
2572 LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
2573 LLVMContext::MD_noalias, LLVMContext::MD_range,
2574 LLVMContext::MD_invariant_load, LLVMContext::MD_nonnull,
2575 LLVMContext::MD_invariant_group, LLVMContext::MD_align,
2576 LLVMContext::MD_dereferenceable,
2577 LLVMContext::MD_dereferenceable_or_null,
2578 LLVMContext::MD_access_group, LLVMContext::MD_preserve_access_index};
2579 combineMetadata(K, J, KnownIDs, KDominatesJ);
2580}
2581
2582void llvm::copyMetadataForLoad(LoadInst &Dest, const LoadInst &Source) {
2583 SmallVector<std::pair<unsigned, MDNode *>, 8> MD;
2584 Source.getAllMetadata(MD);
2585 MDBuilder MDB(Dest.getContext());
2586 Type *NewType = Dest.getType();
2587 const DataLayout &DL = Source.getModule()->getDataLayout();
2588 for (const auto &MDPair : MD) {
2589 unsigned ID = MDPair.first;
2590 MDNode *N = MDPair.second;
2591 // Note, essentially every kind of metadata should be preserved here! This
2592 // routine is supposed to clone a load instruction changing *only its type*.
2593 // The only metadata it makes sense to drop is metadata which is invalidated
2594 // when the pointer type changes. This should essentially never be the case
2595 // in LLVM, but we explicitly switch over only known metadata to be
2596 // conservatively correct. If you are adding metadata to LLVM which pertains
2597 // to loads, you almost certainly want to add it here.
2598 switch (ID) {
2599 case LLVMContext::MD_dbg:
2600 case LLVMContext::MD_tbaa:
2601 case LLVMContext::MD_prof:
2602 case LLVMContext::MD_fpmath:
2603 case LLVMContext::MD_tbaa_struct:
2604 case LLVMContext::MD_invariant_load:
2605 case LLVMContext::MD_alias_scope:
2606 case LLVMContext::MD_noalias:
2607 case LLVMContext::MD_nontemporal:
2608 case LLVMContext::MD_mem_parallel_loop_access:
2609 case LLVMContext::MD_access_group:
2610 // All of these directly apply.
2611 Dest.setMetadata(ID, N);
2612 break;
2613
2614 case LLVMContext::MD_nonnull:
2615 copyNonnullMetadata(Source, N, Dest);
2616 break;
2617
2618 case LLVMContext::MD_align:
2619 case LLVMContext::MD_dereferenceable:
2620 case LLVMContext::MD_dereferenceable_or_null:
2621 // These only directly apply if the new type is also a pointer.
2622 if (NewType->isPointerTy())
2623 Dest.setMetadata(ID, N);
2624 break;
2625
2626 case LLVMContext::MD_range:
2627 copyRangeMetadata(DL, Source, N, Dest);
2628 break;
2629 }
2630 }
2631}
2632
2633void llvm::patchReplacementInstruction(Instruction *I, Value *Repl) {
2634 auto *ReplInst = dyn_cast<Instruction>(Repl);
2635 if (!ReplInst)
2636 return;
2637
2638 // Patch the replacement so that it is not more restrictive than the value
2639 // being replaced.
2640 // Note that if 'I' is a load being replaced by some operation,
2641 // for example, by an arithmetic operation, then andIRFlags()
2642 // would just erase all math flags from the original arithmetic
2643 // operation, which is clearly not wanted and not needed.
2644 if (!isa<LoadInst>(I))
2645 ReplInst->andIRFlags(I);
2646
2647 // FIXME: If both the original and replacement value are part of the
2648 // same control-flow region (meaning that the execution of one
2649 // guarantees the execution of the other), then we can combine the
2650 // noalias scopes here and do better than the general conservative
2651 // answer used in combineMetadata().
2652
2653 // In general, GVN unifies expressions over different control-flow
2654 // regions, and so we need a conservative combination of the noalias
2655 // scopes.
2656 static const unsigned KnownIDs[] = {
2657 LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
2658 LLVMContext::MD_noalias, LLVMContext::MD_range,
2659 LLVMContext::MD_fpmath, LLVMContext::MD_invariant_load,
2660 LLVMContext::MD_invariant_group, LLVMContext::MD_nonnull,
2661 LLVMContext::MD_access_group, LLVMContext::MD_preserve_access_index};
2662 combineMetadata(ReplInst, I, KnownIDs, false);
2663}
2664
2665template <typename RootType, typename DominatesFn>
2666static unsigned replaceDominatedUsesWith(Value *From, Value *To,
2667 const RootType &Root,
2668 const DominatesFn &Dominates) {
2669 assert(From->getType() == To->getType())((void)0);
2670
2671 unsigned Count = 0;
2672 for (Value::use_iterator UI = From->use_begin(), UE = From->use_end();
2673 UI != UE;) {
2674 Use &U = *UI++;
2675 if (!Dominates(Root, U))
2676 continue;
2677 U.set(To);
2678 LLVM_DEBUG(dbgs() << "Replace dominated use of '" << From->getName()do { } while (false)
2679 << "' as " << *To << " in " << *U << "\n")do { } while (false);
2680 ++Count;
2681 }
2682 return Count;
2683}
2684
2685unsigned llvm::replaceNonLocalUsesWith(Instruction *From, Value *To) {
2686 assert(From->getType() == To->getType())((void)0);
2687 auto *BB = From->getParent();
2688 unsigned Count = 0;
2689
2690 for (Value::use_iterator UI = From->use_begin(), UE = From->use_end();
2691 UI != UE;) {
2692 Use &U = *UI++;
2693 auto *I = cast<Instruction>(U.getUser());
2694 if (I->getParent() == BB)
2695 continue;
2696 U.set(To);
2697 ++Count;
2698 }
2699 return Count;
2700}
2701
2702unsigned llvm::replaceDominatedUsesWith(Value *From, Value *To,
2703 DominatorTree &DT,
2704 const BasicBlockEdge &Root) {
2705 auto Dominates = [&DT](const BasicBlockEdge &Root, const Use &U) {
2706 return DT.dominates(Root, U);
2707 };
2708 return ::replaceDominatedUsesWith(From, To, Root, Dominates);
2709}
2710
2711unsigned llvm::replaceDominatedUsesWith(Value *From, Value *To,
2712 DominatorTree &DT,
2713 const BasicBlock *BB) {
2714 auto Dominates = [&DT](const BasicBlock *BB, const Use &U) {
2715 return DT.dominates(BB, U);
2716 };
2717 return ::replaceDominatedUsesWith(From, To, BB, Dominates);
2718}
2719
2720bool llvm::callsGCLeafFunction(const CallBase *Call,
2721 const TargetLibraryInfo &TLI) {
2722 // Check if the function is specifically marked as a gc leaf function.
2723 if (Call->hasFnAttr("gc-leaf-function"))
2724 return true;
2725 if (const Function *F = Call->getCalledFunction()) {
2726 if (F->hasFnAttribute("gc-leaf-function"))
2727 return true;
2728
2729 if (auto IID = F->getIntrinsicID()) {
2730 // Most LLVM intrinsics do not take safepoints.
2731 return IID != Intrinsic::experimental_gc_statepoint &&
2732 IID != Intrinsic::experimental_deoptimize &&
2733 IID != Intrinsic::memcpy_element_unordered_atomic &&
2734 IID != Intrinsic::memmove_element_unordered_atomic;
2735 }
2736 }
2737
2738 // Lib calls can be materialized by some passes, and won't be
2739 // marked as 'gc-leaf-function.' All available Libcalls are
2740 // GC-leaf.
2741 LibFunc LF;
2742 if (TLI.getLibFunc(*Call, LF)) {
2743 return TLI.has(LF);
2744 }
2745
2746 return false;
2747}
2748
2749void llvm::copyNonnullMetadata(const LoadInst &OldLI, MDNode *N,
2750 LoadInst &NewLI) {
2751 auto *NewTy = NewLI.getType();
2752
2753 // This only directly applies if the new type is also a pointer.
2754 if (NewTy->isPointerTy()) {
2755 NewLI.setMetadata(LLVMContext::MD_nonnull, N);
2756 return;
2757 }
2758
2759 // The only other translation we can do is to integral loads with !range
2760 // metadata.
2761 if (!NewTy->isIntegerTy())
2762 return;
2763
2764 MDBuilder MDB(NewLI.getContext());
2765 const Value *Ptr = OldLI.getPointerOperand();
2766 auto *ITy = cast<IntegerType>(NewTy);
2767 auto *NullInt = ConstantExpr::getPtrToInt(
2768 ConstantPointerNull::get(cast<PointerType>(Ptr->getType())), ITy);
2769 auto *NonNullInt = ConstantExpr::getAdd(NullInt, ConstantInt::get(ITy, 1));
2770 NewLI.setMetadata(LLVMContext::MD_range,
2771 MDB.createRange(NonNullInt, NullInt));
2772}
2773
2774void llvm::copyRangeMetadata(const DataLayout &DL, const LoadInst &OldLI,
2775 MDNode *N, LoadInst &NewLI) {
2776 auto *NewTy = NewLI.getType();
2777
2778 // Give up unless it is converted to a pointer where there is a single very
2779 // valuable mapping we can do reliably.
2780 // FIXME: It would be nice to propagate this in more ways, but the type
2781 // conversions make it hard.
2782 if (!NewTy->isPointerTy())
2783 return;
2784
2785 unsigned BitWidth = DL.getPointerTypeSizeInBits(NewTy);
2786 if (!getConstantRangeFromMetadata(*N).contains(APInt(BitWidth, 0))) {
2787 MDNode *NN = MDNode::get(OldLI.getContext(), None);
2788 NewLI.setMetadata(LLVMContext::MD_nonnull, NN);
2789 }
2790}
2791
2792void llvm::dropDebugUsers(Instruction &I) {
2793 SmallVector<DbgVariableIntrinsic *, 1> DbgUsers;
2794 findDbgUsers(DbgUsers, &I);
2795 for (auto *DII : DbgUsers)
2796 DII->eraseFromParent();
2797}
2798
2799void llvm::hoistAllInstructionsInto(BasicBlock *DomBlock, Instruction *InsertPt,
2800 BasicBlock *BB) {
2801 // Since we are moving the instructions out of its basic block, we do not
2802 // retain their original debug locations (DILocations) and debug intrinsic
2803 // instructions.
2804 //
2805 // Doing so would degrade the debugging experience and adversely affect the
2806 // accuracy of profiling information.
2807 //
2808 // Currently, when hoisting the instructions, we take the following actions:
2809 // - Remove their debug intrinsic instructions.
2810 // - Set their debug locations to the values from the insertion point.
2811 //
2812 // As per PR39141 (comment #8), the more fundamental reason why the dbg.values
2813 // need to be deleted, is because there will not be any instructions with a
2814 // DILocation in either branch left after performing the transformation. We
2815 // can only insert a dbg.value after the two branches are joined again.
2816 //
2817 // See PR38762, PR39243 for more details.
2818 //
2819 // TODO: Extend llvm.dbg.value to take more than one SSA Value (PR39141) to
2820 // encode predicated DIExpressions that yield different results on different
2821 // code paths.
2822
2823 for (BasicBlock::iterator II = BB->begin(), IE = BB->end(); II != IE;) {
2824 Instruction *I = &*II;
2825 I->dropUndefImplyingAttrsAndUnknownMetadata();
2826 if (I->isUsedByMetadata())
2827 dropDebugUsers(*I);
2828 if (I->isDebugOrPseudoInst()) {
2829 // Remove DbgInfo and pseudo probe Intrinsics.
2830 II = I->eraseFromParent();
2831 continue;
2832 }
2833 I->setDebugLoc(InsertPt->getDebugLoc());
2834 ++II;
2835 }
2836 DomBlock->getInstList().splice(InsertPt->getIterator(), BB->getInstList(),
2837 BB->begin(),
2838 BB->getTerminator()->getIterator());
2839}
2840
2841namespace {
2842
2843/// A potential constituent of a bitreverse or bswap expression. See
2844/// collectBitParts for a fuller explanation.
2845struct BitPart {
2846 BitPart(Value *P, unsigned BW) : Provider(P) {
2847 Provenance.resize(BW);
2848 }
2849
2850 /// The Value that this is a bitreverse/bswap of.
2851 Value *Provider;
2852
2853 /// The "provenance" of each bit. Provenance[A] = B means that bit A
2854 /// in Provider becomes bit B in the result of this expression.
2855 SmallVector<int8_t, 32> Provenance; // int8_t means max size is i128.
2856
2857 enum { Unset = -1 };
2858};
2859
2860} // end anonymous namespace
2861
2862/// Analyze the specified subexpression and see if it is capable of providing
2863/// pieces of a bswap or bitreverse. The subexpression provides a potential
2864/// piece of a bswap or bitreverse if it can be proved that each non-zero bit in
2865/// the output of the expression came from a corresponding bit in some other
2866/// value. This function is recursive, and the end result is a mapping of
2867/// bitnumber to bitnumber. It is the caller's responsibility to validate that
2868/// the bitnumber to bitnumber mapping is correct for a bswap or bitreverse.
2869///
2870/// For example, if the current subexpression if "(shl i32 %X, 24)" then we know
2871/// that the expression deposits the low byte of %X into the high byte of the
2872/// result and that all other bits are zero. This expression is accepted and a
2873/// BitPart is returned with Provider set to %X and Provenance[24-31] set to
2874/// [0-7].
2875///
2876/// For vector types, all analysis is performed at the per-element level. No
2877/// cross-element analysis is supported (shuffle/insertion/reduction), and all
2878/// constant masks must be splatted across all elements.
2879///
2880/// To avoid revisiting values, the BitPart results are memoized into the
2881/// provided map. To avoid unnecessary copying of BitParts, BitParts are
2882/// constructed in-place in the \c BPS map. Because of this \c BPS needs to
2883/// store BitParts objects, not pointers. As we need the concept of a nullptr
2884/// BitParts (Value has been analyzed and the analysis failed), we an Optional
2885/// type instead to provide the same functionality.
2886///
2887/// Because we pass around references into \c BPS, we must use a container that
2888/// does not invalidate internal references (std::map instead of DenseMap).
2889static const Optional<BitPart> &
2890collectBitParts(Value *V, bool MatchBSwaps, bool MatchBitReversals,
2891 std::map<Value *, Optional<BitPart>> &BPS, int Depth,
2892 bool &FoundRoot) {
2893 auto I = BPS.find(V);
2894 if (I != BPS.end())
2895 return I->second;
2896
2897 auto &Result = BPS[V] = None;
2898 auto BitWidth = V->getType()->getScalarSizeInBits();
2899
2900 // Can't do integer/elements > 128 bits.
2901 if (BitWidth > 128)
2902 return Result;
2903
2904 // Prevent stack overflow by limiting the recursion depth
2905 if (Depth == BitPartRecursionMaxDepth) {
2906 LLVM_DEBUG(dbgs() << "collectBitParts max recursion depth reached.\n")do { } while (false);
2907 return Result;
2908 }
2909
2910 if (auto *I = dyn_cast<Instruction>(V)) {
2911 Value *X, *Y;
2912 const APInt *C;
2913
2914 // If this is an or instruction, it may be an inner node of the bswap.
2915 if (match(V, m_Or(m_Value(X), m_Value(Y)))) {
2916 // Check we have both sources and they are from the same provider.
2917 const auto &A = collectBitParts(X, MatchBSwaps, MatchBitReversals, BPS,
2918 Depth + 1, FoundRoot);
2919 if (!A || !A->Provider)
2920 return Result;
2921
2922 const auto &B = collectBitParts(Y, MatchBSwaps, MatchBitReversals, BPS,
2923 Depth + 1, FoundRoot);
2924 if (!B || A->Provider != B->Provider)
2925 return Result;
2926
2927 // Try and merge the two together.
2928 Result = BitPart(A->Provider, BitWidth);
2929 for (unsigned BitIdx = 0; BitIdx < BitWidth; ++BitIdx) {
2930 if (A->Provenance[BitIdx] != BitPart::Unset &&
2931 B->Provenance[BitIdx] != BitPart::Unset &&
2932 A->Provenance[BitIdx] != B->Provenance[BitIdx])
2933 return Result = None;
2934
2935 if (A->Provenance[BitIdx] == BitPart::Unset)
2936 Result->Provenance[BitIdx] = B->Provenance[BitIdx];
2937 else
2938 Result->Provenance[BitIdx] = A->Provenance[BitIdx];
2939 }
2940
2941 return Result;
2942 }
2943
2944 // If this is a logical shift by a constant, recurse then shift the result.
2945 if (match(V, m_LogicalShift(m_Value(X), m_APInt(C)))) {
2946 const APInt &BitShift = *C;
2947
2948 // Ensure the shift amount is defined.
2949 if (BitShift.uge(BitWidth))
2950 return Result;
2951
2952 // For bswap-only, limit shift amounts to whole bytes, for an early exit.
2953 if (!MatchBitReversals && (BitShift.getZExtValue() % 8) != 0)
2954 return Result;
2955
2956 const auto &Res = collectBitParts(X, MatchBSwaps, MatchBitReversals, BPS,
2957 Depth + 1, FoundRoot);
2958 if (!Res)
2959 return Result;
2960 Result = Res;
2961
2962 // Perform the "shift" on BitProvenance.
2963 auto &P = Result->Provenance;
2964 if (I->getOpcode() == Instruction::Shl) {
2965 P.erase(std::prev(P.end(), BitShift.getZExtValue()), P.end());
2966 P.insert(P.begin(), BitShift.getZExtValue(), BitPart::Unset);
2967 } else {
2968 P.erase(P.begin(), std::next(P.begin(), BitShift.getZExtValue()));
2969 P.insert(P.end(), BitShift.getZExtValue(), BitPart::Unset);
2970 }
2971
2972 return Result;
2973 }
2974
2975 // If this is a logical 'and' with a mask that clears bits, recurse then
2976 // unset the appropriate bits.
2977 if (match(V, m_And(m_Value(X), m_APInt(C)))) {
2978 const APInt &AndMask = *C;
2979
2980 // Check that the mask allows a multiple of 8 bits for a bswap, for an
2981 // early exit.
2982 unsigned NumMaskedBits = AndMask.countPopulation();
2983 if (!MatchBitReversals && (NumMaskedBits % 8) != 0)
2984 return Result;
2985
2986 const auto &Res = collectBitParts(X, MatchBSwaps, MatchBitReversals, BPS,
2987 Depth + 1, FoundRoot);
2988 if (!Res)
2989 return Result;
2990 Result = Res;
2991
2992 for (unsigned BitIdx = 0; BitIdx < BitWidth; ++BitIdx)
2993 // If the AndMask is zero for this bit, clear the bit.
2994 if (AndMask[BitIdx] == 0)
2995 Result->Provenance[BitIdx] = BitPart::Unset;
2996 return Result;
2997 }
2998
2999 // If this is a zext instruction zero extend the result.
3000 if (match(V, m_ZExt(m_Value(X)))) {
3001 const auto &Res = collectBitParts(X, MatchBSwaps, MatchBitReversals, BPS,
3002 Depth + 1, FoundRoot);
3003 if (!Res)
3004 return Result;
3005
3006 Result = BitPart(Res->Provider, BitWidth);
3007 auto NarrowBitWidth = X->getType()->getScalarSizeInBits();
3008 for (unsigned BitIdx = 0; BitIdx < NarrowBitWidth; ++BitIdx)
3009 Result->Provenance[BitIdx] = Res->Provenance[BitIdx];
3010 for (unsigned BitIdx = NarrowBitWidth; BitIdx < BitWidth; ++BitIdx)
3011 Result->Provenance[BitIdx] = BitPart::Unset;
3012 return Result;
3013 }
3014
3015 // If this is a truncate instruction, extract the lower bits.
3016 if (match(V, m_Trunc(m_Value(X)))) {
3017 const auto &Res = collectBitParts(X, MatchBSwaps, MatchBitReversals, BPS,
3018 Depth + 1, FoundRoot);
3019 if (!Res)
3020 return Result;
3021
3022 Result = BitPart(Res->Provider, BitWidth);
3023 for (unsigned BitIdx = 0; BitIdx < BitWidth; ++BitIdx)
3024 Result->Provenance[BitIdx] = Res->Provenance[BitIdx];
3025 return Result;
3026 }
3027
3028 // BITREVERSE - most likely due to us previous matching a partial
3029 // bitreverse.
3030 if (match(V, m_BitReverse(m_Value(X)))) {
3031 const auto &Res = collectBitParts(X, MatchBSwaps, MatchBitReversals, BPS,
3032 Depth + 1, FoundRoot);
3033 if (!Res)
3034 return Result;
3035
3036 Result = BitPart(Res->Provider, BitWidth);
3037 for (unsigned BitIdx = 0; BitIdx < BitWidth; ++BitIdx)
3038 Result->Provenance[(BitWidth - 1) - BitIdx] = Res->Provenance[BitIdx];
3039 return Result;
3040 }
3041
3042 // BSWAP - most likely due to us previous matching a partial bswap.
3043 if (match(V, m_BSwap(m_Value(X)))) {
3044 const auto &Res = collectBitParts(X, MatchBSwaps, MatchBitReversals, BPS,
3045 Depth + 1, FoundRoot);
3046 if (!Res)
3047 return Result;
3048
3049 unsigned ByteWidth = BitWidth / 8;
3050 Result = BitPart(Res->Provider, BitWidth);
3051 for (unsigned ByteIdx = 0; ByteIdx < ByteWidth; ++ByteIdx) {
3052 unsigned ByteBitOfs = ByteIdx * 8;
3053 for (unsigned BitIdx = 0; BitIdx < 8; ++BitIdx)
3054 Result->Provenance[(BitWidth - 8 - ByteBitOfs) + BitIdx] =
3055 Res->Provenance[ByteBitOfs + BitIdx];
3056 }
3057 return Result;
3058 }
3059
3060 // Funnel 'double' shifts take 3 operands, 2 inputs and the shift
3061 // amount (modulo).
3062 // fshl(X,Y,Z): (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
3063 // fshr(X,Y,Z): (X << (BW - (Z % BW))) | (Y >> (Z % BW))
3064 if (match(V, m_FShl(m_Value(X), m_Value(Y), m_APInt(C))) ||
3065 match(V, m_FShr(m_Value(X), m_Value(Y), m_APInt(C)))) {
3066 // We can treat fshr as a fshl by flipping the modulo amount.
3067 unsigned ModAmt = C->urem(BitWidth);
3068 if (cast<IntrinsicInst>(I)->getIntrinsicID() == Intrinsic::fshr)
3069 ModAmt = BitWidth - ModAmt;
3070
3071 // For bswap-only, limit shift amounts to whole bytes, for an early exit.
3072 if (!MatchBitReversals && (ModAmt % 8) != 0)
3073 return Result;
3074
3075 // Check we have both sources and they are from the same provider.
3076 const auto &LHS = collectBitParts(X, MatchBSwaps, MatchBitReversals, BPS,
3077 Depth + 1, FoundRoot);
3078 if (!LHS || !LHS->Provider)
3079 return Result;
3080
3081 const auto &RHS = collectBitParts(Y, MatchBSwaps, MatchBitReversals, BPS,
3082 Depth + 1, FoundRoot);
3083 if (!RHS || LHS->Provider != RHS->Provider)
3084 return Result;
3085
3086 unsigned StartBitRHS = BitWidth - ModAmt;
3087 Result = BitPart(LHS->Provider, BitWidth);
3088 for (unsigned BitIdx = 0; BitIdx < StartBitRHS; ++BitIdx)
3089 Result->Provenance[BitIdx + ModAmt] = LHS->Provenance[BitIdx];
3090 for (unsigned BitIdx = 0; BitIdx < ModAmt; ++BitIdx)
3091 Result->Provenance[BitIdx] = RHS->Provenance[BitIdx + StartBitRHS];
3092 return Result;
3093 }
3094 }
3095
3096 // If we've already found a root input value then we're never going to merge
3097 // these back together.
3098 if (FoundRoot)
3099 return Result;
3100
3101 // Okay, we got to something that isn't a shift, 'or', 'and', etc. This must
3102 // be the root input value to the bswap/bitreverse.
3103 FoundRoot = true;
3104 Result = BitPart(V, BitWidth);
3105 for (unsigned BitIdx = 0; BitIdx < BitWidth; ++BitIdx)
3106 Result->Provenance[BitIdx] = BitIdx;
3107 return Result;
3108}
3109
3110static bool bitTransformIsCorrectForBSwap(unsigned From, unsigned To,
3111 unsigned BitWidth) {
3112 if (From % 8 != To % 8)
3113 return false;
3114 // Convert from bit indices to byte indices and check for a byte reversal.
3115 From >>= 3;
3116 To >>= 3;
3117 BitWidth >>= 3;
3118 return From == BitWidth - To - 1;
3119}
3120
3121static bool bitTransformIsCorrectForBitReverse(unsigned From, unsigned To,
3122 unsigned BitWidth) {
3123 return From == BitWidth - To - 1;
3124}
3125
3126bool llvm::recognizeBSwapOrBitReverseIdiom(
3127 Instruction *I, bool MatchBSwaps, bool MatchBitReversals,
3128 SmallVectorImpl<Instruction *> &InsertedInsts) {
3129 if (!match(I, m_Or(m_Value(), m_Value())) &&
1
Taking false branch
3130 !match(I, m_FShl(m_Value(), m_Value(), m_Value())) &&
3131 !match(I, m_FShr(m_Value(), m_Value(), m_Value())))
3132 return false;
3133 if (!MatchBSwaps && !MatchBitReversals)
2
Assuming 'MatchBSwaps' is true
3134 return false;
3135 Type *ITy = I->getType();
3136 if (!ITy->isIntOrIntVectorTy() || ITy->getScalarSizeInBits() > 128)
3
Assuming the condition is false
4
Taking false branch
3137 return false; // Can't do integer/elements > 128 bits.
3138
3139 Type *DemandedTy = ITy;
3140 if (I->hasOneUse())
5
Taking false branch
3141 if (auto *Trunc = dyn_cast<TruncInst>(I->user_back()))
3142 DemandedTy = Trunc->getType();
3143
3144 // Try to find all the pieces corresponding to the bswap.
3145 bool FoundRoot = false;
3146 std::map<Value *, Optional<BitPart>> BPS;
3147 const auto &Res =
3148 collectBitParts(I, MatchBSwaps, MatchBitReversals, BPS, 0, FoundRoot);
3149 if (!Res)
6
Assuming the condition is false
7
Taking false branch
3150 return false;
3151 ArrayRef<int8_t> BitProvenance = Res->Provenance;
3152 assert(all_of(BitProvenance,((void)0)
3153 [](int8_t I) { return I == BitPart::Unset || 0 <= I; }) &&((void)0)
3154 "Illegal bit provenance index")((void)0);
3155
3156 // If the upper bits are zero, then attempt to perform as a truncated op.
3157 if (BitProvenance.back() == BitPart::Unset) {
8
Assuming the condition is false
9
Taking false branch
3158 while (!BitProvenance.empty() && BitProvenance.back() == BitPart::Unset)
3159 BitProvenance = BitProvenance.drop_back();
3160 if (BitProvenance.empty())
3161 return false; // TODO - handle null value?
3162 DemandedTy = Type::getIntNTy(I->getContext(), BitProvenance.size());
3163 if (auto *IVecTy = dyn_cast<VectorType>(ITy))
3164 DemandedTy = VectorType::get(DemandedTy, IVecTy);
3165 }
3166
3167 // Check BitProvenance hasn't found a source larger than the result type.
3168 unsigned DemandedBW = DemandedTy->getScalarSizeInBits();
3169 if (DemandedBW > ITy->getScalarSizeInBits())
10
Assuming the condition is false
11
Taking false branch
3170 return false;
3171
3172 // Now, is the bit permutation correct for a bswap or a bitreverse? We can
3173 // only byteswap values with an even number of bytes.
3174 APInt DemandedMask = APInt::getAllOnesValue(DemandedBW);
3175 bool OKForBSwap = MatchBSwaps
11.1
'MatchBSwaps' is true
11.1
'MatchBSwaps' is true
&& (DemandedBW % 16) == 0;
12
Assuming the condition is true
3176 bool OKForBitReverse = MatchBitReversals;
3177 for (unsigned BitIdx = 0;
3178 (BitIdx < DemandedBW) && (OKForBSwap || OKForBitReverse); ++BitIdx) {
13
Assuming 'BitIdx' is >= 'DemandedBW'
3179 if (BitProvenance[BitIdx] == BitPart::Unset) {
3180 DemandedMask.clearBit(BitIdx);
3181 continue;
3182 }
3183 OKForBSwap &= bitTransformIsCorrectForBSwap(BitProvenance[BitIdx], BitIdx,
3184 DemandedBW);
3185 OKForBitReverse &= bitTransformIsCorrectForBitReverse(BitProvenance[BitIdx],
3186 BitIdx, DemandedBW);
3187 }
3188
3189 Intrinsic::ID Intrin;
3190 if (OKForBSwap
13.1
'OKForBSwap' is true
13.1
'OKForBSwap' is true
)
14
Taking true branch
3191 Intrin = Intrinsic::bswap;
3192 else if (OKForBitReverse)
3193 Intrin = Intrinsic::bitreverse;
3194 else
3195 return false;
3196
3197 Function *F = Intrinsic::getDeclaration(I->getModule(), Intrin, DemandedTy);
3198 Value *Provider = Res->Provider;
3199
3200 // We may need to truncate the provider.
3201 if (DemandedTy != Provider->getType()) {
15
Assuming the condition is false
16
Taking false branch
3202 auto *Trunc =
3203 CastInst::CreateIntegerCast(Provider, DemandedTy, false, "trunc", I);
3204 InsertedInsts.push_back(Trunc);
3205 Provider = Trunc;
3206 }
3207
3208 Instruction *Result = CallInst::Create(F, Provider, "rev", I);
3209 InsertedInsts.push_back(Result);
3210
3211 if (!DemandedMask.isAllOnesValue()) {
17
Calling 'APInt::isAllOnesValue'
3212 auto *Mask = ConstantInt::get(DemandedTy, DemandedMask);
3213 Result = BinaryOperator::Create(Instruction::And, Result, Mask, "mask", I);
3214 InsertedInsts.push_back(Result);
3215 }
3216
3217 // We may need to zeroextend back to the result type.
3218 if (ITy != Result->getType()) {
3219 auto *ExtInst = CastInst::CreateIntegerCast(Result, ITy, false, "zext", I);
3220 InsertedInsts.push_back(ExtInst);
3221 }
3222
3223 return true;
3224}
3225
3226// CodeGen has special handling for some string functions that may replace
3227// them with target-specific intrinsics. Since that'd skip our interceptors
3228// in ASan/MSan/TSan/DFSan, and thus make us miss some memory accesses,
3229// we mark affected calls as NoBuiltin, which will disable optimization
3230// in CodeGen.
3231void llvm::maybeMarkSanitizerLibraryCallNoBuiltin(
3232 CallInst *CI, const TargetLibraryInfo *TLI) {
3233 Function *F = CI->getCalledFunction();
3234 LibFunc Func;
3235 if (F && !F->hasLocalLinkage() && F->hasName() &&
3236 TLI->getLibFunc(F->getName(), Func) && TLI->hasOptimizedCodeGen(Func) &&
3237 !F->doesNotAccessMemory())
3238 CI->addAttribute(AttributeList::FunctionIndex, Attribute::NoBuiltin);
3239}
3240
3241bool llvm::canReplaceOperandWithVariable(const Instruction *I, unsigned OpIdx) {
3242 // We can't have a PHI with a metadata type.
3243 if (I->getOperand(OpIdx)->getType()->isMetadataTy())
3244 return false;
3245
3246 // Early exit.
3247 if (!isa<Constant>(I->getOperand(OpIdx)))
3248 return true;
3249
3250 switch (I->getOpcode()) {
3251 default:
3252 return true;
3253 case Instruction::Call:
3254 case Instruction::Invoke: {
3255 const auto &CB = cast<CallBase>(*I);
3256
3257 // Can't handle inline asm. Skip it.
3258 if (CB.isInlineAsm())
3259 return false;
3260
3261 // Constant bundle operands may need to retain their constant-ness for
3262 // correctness.
3263 if (CB.isBundleOperand(OpIdx))
3264 return false;
3265
3266 if (OpIdx < CB.getNumArgOperands()) {
3267 // Some variadic intrinsics require constants in the variadic arguments,
3268 // which currently aren't markable as immarg.
3269 if (isa<IntrinsicInst>(CB) &&
3270 OpIdx >= CB.getFunctionType()->getNumParams()) {
3271 // This is known to be OK for stackmap.
3272 return CB.getIntrinsicID() == Intrinsic::experimental_stackmap;
3273 }
3274
3275 // gcroot is a special case, since it requires a constant argument which
3276 // isn't also required to be a simple ConstantInt.
3277 if (CB.getIntrinsicID() == Intrinsic::gcroot)
3278 return false;
3279
3280 // Some intrinsic operands are required to be immediates.
3281 return !CB.paramHasAttr(OpIdx, Attribute::ImmArg);
3282 }
3283
3284 // It is never allowed to replace the call argument to an intrinsic, but it
3285 // may be possible for a call.
3286 return !isa<IntrinsicInst>(CB);
3287 }
3288 case Instruction::ShuffleVector:
3289 // Shufflevector masks are constant.
3290 return OpIdx != 2;
3291 case Instruction::Switch:
3292 case Instruction::ExtractValue:
3293 // All operands apart from the first are constant.
3294 return OpIdx == 0;
3295 case Instruction::InsertValue:
3296 // All operands apart from the first and the second are constant.
3297 return OpIdx < 2;
3298 case Instruction::Alloca:
3299 // Static allocas (constant size in the entry block) are handled by
3300 // prologue/epilogue insertion so they're free anyway. We definitely don't
3301 // want to make them non-constant.
3302 return !cast<AllocaInst>(I)->isStaticAlloca();
3303 case Instruction::GetElementPtr:
3304 if (OpIdx == 0)
3305 return true;
3306 gep_type_iterator It = gep_type_begin(I);
3307 for (auto E = std::next(It, OpIdx); It != E; ++It)
3308 if (It.isStruct())
3309 return false;
3310 return true;
3311 }
3312}
3313
3314Value *llvm::invertCondition(Value *Condition) {
3315 // First: Check if it's a constant
3316 if (Constant *C = dyn_cast<Constant>(Condition))
3317 return ConstantExpr::getNot(C);
3318
3319 // Second: If the condition is already inverted, return the original value
3320 Value *NotCondition;
3321 if (match(Condition, m_Not(m_Value(NotCondition))))
3322 return NotCondition;
3323
3324 BasicBlock *Parent = nullptr;
3325 Instruction *Inst = dyn_cast<Instruction>(Condition);
3326 if (Inst)
3327 Parent = Inst->getParent();
3328 else if (Argument *Arg = dyn_cast<Argument>(Condition))
3329 Parent = &Arg->getParent()->getEntryBlock();
3330 assert(Parent && "Unsupported condition to invert")((void)0);
3331
3332 // Third: Check all the users for an invert
3333 for (User *U : Condition->users())
3334 if (Instruction *I = dyn_cast<Instruction>(U))
3335 if (I->getParent() == Parent && match(I, m_Not(m_Specific(Condition))))
3336 return I;
3337
3338 // Last option: Create a new instruction
3339 auto *Inverted =
3340 BinaryOperator::CreateNot(Condition, Condition->getName() + ".inv");
3341 if (Inst && !isa<PHINode>(Inst))
3342 Inverted->insertAfter(Inst);
3343 else
3344 Inverted->insertBefore(&*Parent->getFirstInsertionPt());
3345 return Inverted;
3346}
3347
3348bool llvm::inferAttributesFromOthers(Function &F) {
3349 // Note: We explicitly check for attributes rather than using cover functions
3350 // because some of the cover functions include the logic being implemented.
3351
3352 bool Changed = false;
3353 // readnone + not convergent implies nosync
3354 if (!F.hasFnAttribute(Attribute::NoSync) &&
3355 F.doesNotAccessMemory() && !F.isConvergent()) {
3356 F.setNoSync();
3357 Changed = true;
3358 }
3359
3360 // readonly implies nofree
3361 if (!F.hasFnAttribute(Attribute::NoFree) && F.onlyReadsMemory()) {
3362 F.setDoesNotFreeMemory();
3363 Changed = true;
3364 }
3365
3366 // willreturn implies mustprogress
3367 if (!F.hasFnAttribute(Attribute::MustProgress) && F.willReturn()) {
3368 F.setMustProgress();
3369 Changed = true;
3370 }
3371
3372 // TODO: There are a bunch of cases of restrictive memory effects we
3373 // can infer by inspecting arguments of argmemonly-ish functions.
3374
3375 return Changed;
3376}

/usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/ADT/APInt.h

1//===-- llvm/ADT/APInt.h - For Arbitrary Precision Integer -----*- C++ -*--===//
2//
3// 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
6//
7//===----------------------------------------------------------------------===//
8///
9/// \file
10/// This file implements a class to represent arbitrary precision
11/// integral constant values and operations on them.
12///
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_ADT_APINT_H
16#define LLVM_ADT_APINT_H
17
18#include "llvm/Support/Compiler.h"
19#include "llvm/Support/MathExtras.h"
20#include <cassert>
21#include <climits>
22#include <cstring>
23#include <utility>
24
25namespace llvm {
26class FoldingSetNodeID;
27class StringRef;
28class hash_code;
29class raw_ostream;
30
31template <typename T> class SmallVectorImpl;
32template <typename T> class ArrayRef;
33template <typename T> class Optional;
34template <typename T> struct DenseMapInfo;
35
36class APInt;
37
38inline APInt operator-(APInt);
39
40//===----------------------------------------------------------------------===//
41// APInt Class
42//===----------------------------------------------------------------------===//
43
44/// Class for arbitrary precision integers.
45///
46/// APInt is a functional replacement for common case unsigned integer type like
47/// "unsigned", "unsigned long" or "uint64_t", but also allows non-byte-width
48/// integer sizes and large integer value types such as 3-bits, 15-bits, or more
49/// than 64-bits of precision. APInt provides a variety of arithmetic operators
50/// and methods to manipulate integer values of any bit-width. It supports both
51/// the typical integer arithmetic and comparison operations as well as bitwise
52/// manipulation.
53///
54/// The class has several invariants worth noting:
55/// * All bit, byte, and word positions are zero-based.
56/// * Once the bit width is set, it doesn't change except by the Truncate,
57/// SignExtend, or ZeroExtend operations.
58/// * All binary operators must be on APInt instances of the same bit width.
59/// Attempting to use these operators on instances with different bit
60/// widths will yield an assertion.
61/// * The value is stored canonically as an unsigned value. For operations
62/// where it makes a difference, there are both signed and unsigned variants
63/// of the operation. For example, sdiv and udiv. However, because the bit
64/// widths must be the same, operations such as Mul and Add produce the same
65/// results regardless of whether the values are interpreted as signed or
66/// not.
67/// * In general, the class tries to follow the style of computation that LLVM
68/// uses in its IR. This simplifies its use for LLVM.
69///
70class LLVM_NODISCARD[[clang::warn_unused_result]] APInt {
71public:
72 typedef uint64_t WordType;
73
74 /// This enum is used to hold the constants we needed for APInt.
75 enum : unsigned {
76 /// Byte size of a word.
77 APINT_WORD_SIZE = sizeof(WordType),
78 /// Bits in a word.
79 APINT_BITS_PER_WORD = APINT_WORD_SIZE * CHAR_BIT8
80 };
81
82 enum class Rounding {
83 DOWN,
84 TOWARD_ZERO,
85 UP,
86 };
87
88 static constexpr WordType WORDTYPE_MAX = ~WordType(0);
89
90private:
91 /// This union is used to store the integer value. When the
92 /// integer bit-width <= 64, it uses VAL, otherwise it uses pVal.
93 union {
94 uint64_t VAL; ///< Used to store the <= 64 bits integer value.
95 uint64_t *pVal; ///< Used to store the >64 bits integer value.
96 } U;
97
98 unsigned BitWidth; ///< The number of bits in this APInt.
99
100 friend struct DenseMapInfo<APInt>;
101
102 friend class APSInt;
103
104 /// Fast internal constructor
105 ///
106 /// This constructor is used only internally for speed of construction of
107 /// temporaries. It is unsafe for general use so it is not public.
108 APInt(uint64_t *val, unsigned bits) : BitWidth(bits) {
109 U.pVal = val;
110 }
111
112 /// Determine which word a bit is in.
113 ///
114 /// \returns the word position for the specified bit position.
115 static unsigned whichWord(unsigned bitPosition) {
116 return bitPosition / APINT_BITS_PER_WORD;
117 }
118
119 /// Determine which bit in a word a bit is in.
120 ///
121 /// \returns the bit position in a word for the specified bit position
122 /// in the APInt.
123 static unsigned whichBit(unsigned bitPosition) {
124 return bitPosition % APINT_BITS_PER_WORD;
125 }
126
127 /// Get a single bit mask.
128 ///
129 /// \returns a uint64_t with only bit at "whichBit(bitPosition)" set
130 /// This method generates and returns a uint64_t (word) mask for a single
131 /// bit at a specific bit position. This is used to mask the bit in the
132 /// corresponding word.
133 static uint64_t maskBit(unsigned bitPosition) {
134 return 1ULL << whichBit(bitPosition);
135 }
136
137 /// Clear unused high order bits
138 ///
139 /// This method is used internally to clear the top "N" bits in the high order
140 /// word that are not used by the APInt. This is needed after the most
141 /// significant word is assigned a value to ensure that those bits are
142 /// zero'd out.
143 APInt &clearUnusedBits() {
144 // Compute how many bits are used in the final word
145 unsigned WordBits = ((BitWidth-1) % APINT_BITS_PER_WORD) + 1;
146
147 // Mask out the high bits.
148 uint64_t mask = WORDTYPE_MAX >> (APINT_BITS_PER_WORD - WordBits);
149 if (isSingleWord())
150 U.VAL &= mask;
151 else
152 U.pVal[getNumWords() - 1] &= mask;
153 return *this;
154 }
155
156 /// Get the word corresponding to a bit position
157 /// \returns the corresponding word for the specified bit position.
158 uint64_t getWord(unsigned bitPosition) const {
159 return isSingleWord() ? U.VAL : U.pVal[whichWord(bitPosition)];
160 }
161
162 /// Utility method to change the bit width of this APInt to new bit width,
163 /// allocating and/or deallocating as necessary. There is no guarantee on the
164 /// value of any bits upon return. Caller should populate the bits after.
165 void reallocate(unsigned NewBitWidth);
166
167 /// Convert a char array into an APInt
168 ///
169 /// \param radix 2, 8, 10, 16, or 36
170 /// Converts a string into a number. The string must be non-empty
171 /// and well-formed as a number of the given base. The bit-width
172 /// must be sufficient to hold the result.
173 ///
174 /// This is used by the constructors that take string arguments.
175 ///
176 /// StringRef::getAsInteger is superficially similar but (1) does
177 /// not assume that the string is well-formed and (2) grows the
178 /// result to hold the input.
179 void fromString(unsigned numBits, StringRef str, uint8_t radix);
180
181 /// An internal division function for dividing APInts.
182 ///
183 /// This is used by the toString method to divide by the radix. It simply
184 /// provides a more convenient form of divide for internal use since KnuthDiv
185 /// has specific constraints on its inputs. If those constraints are not met
186 /// then it provides a simpler form of divide.
187 static void divide(const WordType *LHS, unsigned lhsWords,
188 const WordType *RHS, unsigned rhsWords, WordType *Quotient,
189 WordType *Remainder);
190
191 /// out-of-line slow case for inline constructor
192 void initSlowCase(uint64_t val, bool isSigned);
193
194 /// shared code between two array constructors
195 void initFromArray(ArrayRef<uint64_t> array);
196
197 /// out-of-line slow case for inline copy constructor
198 void initSlowCase(const APInt &that);
199
200 /// out-of-line slow case for shl
201 void shlSlowCase(unsigned ShiftAmt);
202
203 /// out-of-line slow case for lshr.
204 void lshrSlowCase(unsigned ShiftAmt);
205
206 /// out-of-line slow case for ashr.
207 void ashrSlowCase(unsigned ShiftAmt);
208
209 /// out-of-line slow case for operator=
210 void AssignSlowCase(const APInt &RHS);
211
212 /// out-of-line slow case for operator==
213 bool EqualSlowCase(const APInt &RHS) const LLVM_READONLY__attribute__((__pure__));
214
215 /// out-of-line slow case for countLeadingZeros
216 unsigned countLeadingZerosSlowCase() const LLVM_READONLY__attribute__((__pure__));
217
218 /// out-of-line slow case for countLeadingOnes.
219 unsigned countLeadingOnesSlowCase() const LLVM_READONLY__attribute__((__pure__));
220
221 /// out-of-line slow case for countTrailingZeros.
222 unsigned countTrailingZerosSlowCase() const LLVM_READONLY__attribute__((__pure__));
223
224 /// out-of-line slow case for countTrailingOnes
225 unsigned countTrailingOnesSlowCase() const LLVM_READONLY__attribute__((__pure__));
226
227 /// out-of-line slow case for countPopulation
228 unsigned countPopulationSlowCase() const LLVM_READONLY__attribute__((__pure__));
229
230 /// out-of-line slow case for intersects.
231 bool intersectsSlowCase(const APInt &RHS) const LLVM_READONLY__attribute__((__pure__));
232
233 /// out-of-line slow case for isSubsetOf.
234 bool isSubsetOfSlowCase(const APInt &RHS) const LLVM_READONLY__attribute__((__pure__));
235
236 /// out-of-line slow case for setBits.
237 void setBitsSlowCase(unsigned loBit, unsigned hiBit);
238
239 /// out-of-line slow case for flipAllBits.
240 void flipAllBitsSlowCase();
241
242 /// out-of-line slow case for operator&=.
243 void AndAssignSlowCase(const APInt& RHS);
244
245 /// out-of-line slow case for operator|=.
246 void OrAssignSlowCase(const APInt& RHS);
247
248 /// out-of-line slow case for operator^=.
249 void XorAssignSlowCase(const APInt& RHS);
250
251 /// Unsigned comparison. Returns -1, 0, or 1 if this APInt is less than, equal
252 /// to, or greater than RHS.
253 int compare(const APInt &RHS) const LLVM_READONLY__attribute__((__pure__));
254
255 /// Signed comparison. Returns -1, 0, or 1 if this APInt is less than, equal
256 /// to, or greater than RHS.
257 int compareSigned(const APInt &RHS) const LLVM_READONLY__attribute__((__pure__));
258
259public:
260 /// \name Constructors
261 /// @{
262
263 /// Create a new APInt of numBits width, initialized as val.
264 ///
265 /// If isSigned is true then val is treated as if it were a signed value
266 /// (i.e. as an int64_t) and the appropriate sign extension to the bit width
267 /// will be done. Otherwise, no sign extension occurs (high order bits beyond
268 /// the range of val are zero filled).
269 ///
270 /// \param numBits the bit width of the constructed APInt
271 /// \param val the initial value of the APInt
272 /// \param isSigned how to treat signedness of val
273 APInt(unsigned numBits, uint64_t val, bool isSigned = false)
274 : BitWidth(numBits) {
275 assert(BitWidth && "bitwidth too small")((void)0);
276 if (isSingleWord()) {
277 U.VAL = val;
278 clearUnusedBits();
279 } else {
280 initSlowCase(val, isSigned);
281 }
282 }
283
284 /// Construct an APInt of numBits width, initialized as bigVal[].
285 ///
286 /// Note that bigVal.size() can be smaller or larger than the corresponding
287 /// bit width but any extraneous bits will be dropped.
288 ///
289 /// \param numBits the bit width of the constructed APInt
290 /// \param bigVal a sequence of words to form the initial value of the APInt
291 APInt(unsigned numBits, ArrayRef<uint64_t> bigVal);
292
293 /// Equivalent to APInt(numBits, ArrayRef<uint64_t>(bigVal, numWords)), but
294 /// deprecated because this constructor is prone to ambiguity with the
295 /// APInt(unsigned, uint64_t, bool) constructor.
296 ///
297 /// If this overload is ever deleted, care should be taken to prevent calls
298 /// from being incorrectly captured by the APInt(unsigned, uint64_t, bool)
299 /// constructor.
300 APInt(unsigned numBits, unsigned numWords, const uint64_t bigVal[]);
301
302 /// Construct an APInt from a string representation.
303 ///
304 /// This constructor interprets the string \p str in the given radix. The
305 /// interpretation stops when the first character that is not suitable for the
306 /// radix is encountered, or the end of the string. Acceptable radix values
307 /// are 2, 8, 10, 16, and 36. It is an error for the value implied by the
308 /// string to require more bits than numBits.
309 ///
310 /// \param numBits the bit width of the constructed APInt
311 /// \param str the string to be interpreted
312 /// \param radix the radix to use for the conversion
313 APInt(unsigned numBits, StringRef str, uint8_t radix);
314
315 /// Simply makes *this a copy of that.
316 /// Copy Constructor.
317 APInt(const APInt &that) : BitWidth(that.BitWidth) {
318 if (isSingleWord())
319 U.VAL = that.U.VAL;
320 else
321 initSlowCase(that);
322 }
323
324 /// Move Constructor.
325 APInt(APInt &&that) : BitWidth(that.BitWidth) {
326 memcpy(&U, &that.U, sizeof(U));
327 that.BitWidth = 0;
328 }
329
330 /// Destructor.
331 ~APInt() {
332 if (needsCleanup())
333 delete[] U.pVal;
334 }
335
336 /// Default constructor that creates an uninteresting APInt
337 /// representing a 1-bit zero value.
338 ///
339 /// This is useful for object deserialization (pair this with the static
340 /// method Read).
341 explicit APInt() : BitWidth(1) { U.VAL = 0; }
342
343 /// Returns whether this instance allocated memory.
344 bool needsCleanup() const { return !isSingleWord(); }
345
346 /// Used to insert APInt objects, or objects that contain APInt objects, into
347 /// FoldingSets.
348 void Profile(FoldingSetNodeID &id) const;
349
350 /// @}
351 /// \name Value Tests
352 /// @{
353
354 /// Determine if this APInt just has one word to store value.
355 ///
356 /// \returns true if the number of bits <= 64, false otherwise.
357 bool isSingleWord() const { return BitWidth <= APINT_BITS_PER_WORD; }
19
Returning the value 1, which participates in a condition later
358
359 /// Determine sign of this APInt.
360 ///
361 /// This tests the high bit of this APInt to determine if it is set.
362 ///
363 /// \returns true if this APInt is negative, false otherwise
364 bool isNegative() const { return (*this)[BitWidth - 1]; }
365
366 /// Determine if this APInt Value is non-negative (>= 0)
367 ///
368 /// This tests the high bit of the APInt to determine if it is unset.
369 bool isNonNegative() const { return !isNegative(); }
370
371 /// Determine if sign bit of this APInt is set.
372 ///
373 /// This tests the high bit of this APInt to determine if it is set.
374 ///
375 /// \returns true if this APInt has its sign bit set, false otherwise.
376 bool isSignBitSet() const { return (*this)[BitWidth-1]; }
377
378 /// Determine if sign bit of this APInt is clear.
379 ///
380 /// This tests the high bit of this APInt to determine if it is clear.
381 ///
382 /// \returns true if this APInt has its sign bit clear, false otherwise.
383 bool isSignBitClear() const { return !isSignBitSet(); }
384
385 /// Determine if this APInt Value is positive.
386 ///
387 /// This tests if the value of this APInt is positive (> 0). Note
388 /// that 0 is not a positive value.
389 ///
390 /// \returns true if this APInt is positive.
391 bool isStrictlyPositive() const { return isNonNegative() && !isNullValue(); }
392
393 /// Determine if this APInt Value is non-positive (<= 0).
394 ///
395 /// \returns true if this APInt is non-positive.
396 bool isNonPositive() const { return !isStrictlyPositive(); }
397
398 /// Determine if all bits are set
399 ///
400 /// This checks to see if the value has all bits of the APInt are set or not.
401 bool isAllOnesValue() const {
402 if (isSingleWord())
18
Calling 'APInt::isSingleWord'
20
Returning from 'APInt::isSingleWord'
21
Taking true branch
403 return U.VAL == WORDTYPE_MAX >> (APINT_BITS_PER_WORD - BitWidth);
22
The result of the right shift is undefined due to shifting by '64', which is greater or equal to the width of type 'llvm::APInt::WordType'
404 return countTrailingOnesSlowCase() == BitWidth;
405 }
406
407 /// Determine if all bits are clear
408 ///
409 /// This checks to see if the value has all bits of the APInt are clear or
410 /// not.
411 bool isNullValue() const { return !*this; }
412
413 /// Determine if this is a value of 1.
414 ///
415 /// This checks to see if the value of this APInt is one.
416 bool isOneValue() const {
417 if (isSingleWord())
418 return U.VAL == 1;
419 return countLeadingZerosSlowCase() == BitWidth - 1;
420 }
421
422 /// Determine if this is the largest unsigned value.
423 ///
424 /// This checks to see if the value of this APInt is the maximum unsigned
425 /// value for the APInt's bit width.
426 bool isMaxValue() const { return isAllOnesValue(); }
427
428 /// Determine if this is the largest signed value.
429 ///
430 /// This checks to see if the value of this APInt is the maximum signed
431 /// value for the APInt's bit width.
432 bool isMaxSignedValue() const {
433 if (isSingleWord())
434 return U.VAL == ((WordType(1) << (BitWidth - 1)) - 1);
435 return !isNegative() && countTrailingOnesSlowCase() == BitWidth - 1;
436 }
437
438 /// Determine if this is the smallest unsigned value.
439 ///
440 /// This checks to see if the value of this APInt is the minimum unsigned
441 /// value for the APInt's bit width.
442 bool isMinValue() const { return isNullValue(); }
443
444 /// Determine if this is the smallest signed value.
445 ///
446 /// This checks to see if the value of this APInt is the minimum signed
447 /// value for the APInt's bit width.
448 bool isMinSignedValue() const {
449 if (isSingleWord())
450 return U.VAL == (WordType(1) << (BitWidth - 1));
451 return isNegative() && countTrailingZerosSlowCase() == BitWidth - 1;
452 }
453
454 /// Check if this APInt has an N-bits unsigned integer value.
455 bool isIntN(unsigned N) const {
456 assert(N && "N == 0 ???")((void)0);
457 return getActiveBits() <= N;
458 }
459
460 /// Check if this APInt has an N-bits signed integer value.
461 bool isSignedIntN(unsigned N) const {
462 assert(N && "N == 0 ???")((void)0);
463 return getMinSignedBits() <= N;
464 }
465
466 /// Check if this APInt's value is a power of two greater than zero.
467 ///
468 /// \returns true if the argument APInt value is a power of two > 0.
469 bool isPowerOf2() const {
470 if (isSingleWord())
471 return isPowerOf2_64(U.VAL);
472 return countPopulationSlowCase() == 1;
473 }
474
475 /// Check if the APInt's value is returned by getSignMask.
476 ///
477 /// \returns true if this is the value returned by getSignMask.
478 bool isSignMask() const { return isMinSignedValue(); }
479
480 /// Convert APInt to a boolean value.
481 ///
482 /// This converts the APInt to a boolean value as a test against zero.
483 bool getBoolValue() const { return !!*this; }
484
485 /// If this value is smaller than the specified limit, return it, otherwise
486 /// return the limit value. This causes the value to saturate to the limit.
487 uint64_t getLimitedValue(uint64_t Limit = UINT64_MAX0xffffffffffffffffULL) const {
488 return ugt(Limit) ? Limit : getZExtValue();
489 }
490
491 /// Check if the APInt consists of a repeated bit pattern.
492 ///
493 /// e.g. 0x01010101 satisfies isSplat(8).
494 /// \param SplatSizeInBits The size of the pattern in bits. Must divide bit
495 /// width without remainder.
496 bool isSplat(unsigned SplatSizeInBits) const;
497
498 /// \returns true if this APInt value is a sequence of \param numBits ones
499 /// starting at the least significant bit with the remainder zero.
500 bool isMask(unsigned numBits) const {
501 assert(numBits != 0 && "numBits must be non-zero")((void)0);
502 assert(numBits <= BitWidth && "numBits out of range")((void)0);
503 if (isSingleWord())
504 return U.VAL == (WORDTYPE_MAX >> (APINT_BITS_PER_WORD - numBits));
505 unsigned Ones = countTrailingOnesSlowCase();
506 return (numBits == Ones) &&
507 ((Ones + countLeadingZerosSlowCase()) == BitWidth);
508 }
509
510 /// \returns true if this APInt is a non-empty sequence of ones starting at
511 /// the least significant bit with the remainder zero.
512 /// Ex. isMask(0x0000FFFFU) == true.
513 bool isMask() const {
514 if (isSingleWord())
515 return isMask_64(U.VAL);
516 unsigned Ones = countTrailingOnesSlowCase();
517 return (Ones > 0) && ((Ones + countLeadingZerosSlowCase()) == BitWidth);
518 }
519
520 /// Return true if this APInt value contains a sequence of ones with
521 /// the remainder zero.
522 bool isShiftedMask() const {
523 if (isSingleWord())
524 return isShiftedMask_64(U.VAL);
525 unsigned Ones = countPopulationSlowCase();
526 unsigned LeadZ = countLeadingZerosSlowCase();
527 return (Ones + LeadZ + countTrailingZeros()) == BitWidth;
528 }
529
530 /// @}
531 /// \name Value Generators
532 /// @{
533
534 /// Gets maximum unsigned value of APInt for specific bit width.
535 static APInt getMaxValue(unsigned numBits) {
536 return getAllOnesValue(numBits);
537 }
538
539 /// Gets maximum signed value of APInt for a specific bit width.
540 static APInt getSignedMaxValue(unsigned numBits) {
541 APInt API = getAllOnesValue(numBits);
542 API.clearBit(numBits - 1);
543 return API;
544 }
545
546 /// Gets minimum unsigned value of APInt for a specific bit width.
547 static APInt getMinValue(unsigned numBits) { return APInt(numBits, 0); }
548
549 /// Gets minimum signed value of APInt for a specific bit width.
550 static APInt getSignedMinValue(unsigned numBits) {
551 APInt API(numBits, 0);
552 API.setBit(numBits - 1);
553 return API;
554 }
555
556 /// Get the SignMask for a specific bit width.
557 ///
558 /// This is just a wrapper function of getSignedMinValue(), and it helps code
559 /// readability when we want to get a SignMask.
560 static APInt getSignMask(unsigned BitWidth) {
561 return getSignedMinValue(BitWidth);
562 }
563
564 /// Get the all-ones value.
565 ///
566 /// \returns the all-ones value for an APInt of the specified bit-width.
567 static APInt getAllOnesValue(unsigned numBits) {
568 return APInt(numBits, WORDTYPE_MAX, true);
569 }
570
571 /// Get the '0' value.
572 ///
573 /// \returns the '0' value for an APInt of the specified bit-width.
574 static APInt getNullValue(unsigned numBits) { return APInt(numBits, 0); }
575
576 /// Compute an APInt containing numBits highbits from this APInt.
577 ///
578 /// Get an APInt with the same BitWidth as this APInt, just zero mask
579 /// the low bits and right shift to the least significant bit.
580 ///
581 /// \returns the high "numBits" bits of this APInt.
582 APInt getHiBits(unsigned numBits) const;
583
584 /// Compute an APInt containing numBits lowbits from this APInt.
585 ///
586 /// Get an APInt with the same BitWidth as this APInt, just zero mask
587 /// the high bits.
588 ///
589 /// \returns the low "numBits" bits of this APInt.
590 APInt getLoBits(unsigned numBits) const;
591
592 /// Return an APInt with exactly one bit set in the result.
593 static APInt getOneBitSet(unsigned numBits, unsigned BitNo) {
594 APInt Res(numBits, 0);
595 Res.setBit(BitNo);
596 return Res;
597 }
598
599 /// Get a value with a block of bits set.
600 ///
601 /// Constructs an APInt value that has a contiguous range of bits set. The
602 /// bits from loBit (inclusive) to hiBit (exclusive) will be set. All other
603 /// bits will be zero. For example, with parameters(32, 0, 16) you would get
604 /// 0x0000FFFF. Please call getBitsSetWithWrap if \p loBit may be greater than
605 /// \p hiBit.
606 ///
607 /// \param numBits the intended bit width of the result
608 /// \param loBit the index of the lowest bit set.
609 /// \param hiBit the index of the highest bit set.
610 ///
611 /// \returns An APInt value with the requested bits set.
612 static APInt getBitsSet(unsigned numBits, unsigned loBit, unsigned hiBit) {
613 assert(loBit <= hiBit && "loBit greater than hiBit")((void)0);
614 APInt Res(numBits, 0);
615 Res.setBits(loBit, hiBit);
616 return Res;
617 }
618
619 /// Wrap version of getBitsSet.
620 /// If \p hiBit is bigger than \p loBit, this is same with getBitsSet.
621 /// If \p hiBit is not bigger than \p loBit, the set bits "wrap". For example,
622 /// with parameters (32, 28, 4), you would get 0xF000000F.
623 /// If \p hiBit is equal to \p loBit, you would get a result with all bits
624 /// set.
625 static APInt getBitsSetWithWrap(unsigned numBits, unsigned loBit,
626 unsigned hiBit) {
627 APInt Res(numBits, 0);
628 Res.setBitsWithWrap(loBit, hiBit);
629 return Res;
630 }
631
632 /// Get a value with upper bits starting at loBit set.
633 ///
634 /// Constructs an APInt value that has a contiguous range of bits set. The
635 /// bits from loBit (inclusive) to numBits (exclusive) will be set. All other
636 /// bits will be zero. For example, with parameters(32, 12) you would get
637 /// 0xFFFFF000.
638 ///
639 /// \param numBits the intended bit width of the result
640 /// \param loBit the index of the lowest bit to set.
641 ///
642 /// \returns An APInt value with the requested bits set.
643 static APInt getBitsSetFrom(unsigned numBits, unsigned loBit) {
644 APInt Res(numBits, 0);
645 Res.setBitsFrom(loBit);
646 return Res;
647 }
648
649 /// Get a value with high bits set
650 ///
651 /// Constructs an APInt value that has the top hiBitsSet bits set.
652 ///
653 /// \param numBits the bitwidth of the result
654 /// \param hiBitsSet the number of high-order bits set in the result.
655 static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet) {
656 APInt Res(numBits, 0);
657 Res.setHighBits(hiBitsSet);
658 return Res;
659 }
660
661 /// Get a value with low bits set
662 ///
663 /// Constructs an APInt value that has the bottom loBitsSet bits set.
664 ///
665 /// \param numBits the bitwidth of the result
666 /// \param loBitsSet the number of low-order bits set in the result.
667 static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet) {
668 APInt Res(numBits, 0);
669 Res.setLowBits(loBitsSet);
670 return Res;
671 }
672
673 /// Return a value containing V broadcasted over NewLen bits.
674 static APInt getSplat(unsigned NewLen, const APInt &V);
675
676 /// Determine if two APInts have the same value, after zero-extending
677 /// one of them (if needed!) to ensure that the bit-widths match.
678 static bool isSameValue(const APInt &I1, const APInt &I2) {
679 if (I1.getBitWidth() == I2.getBitWidth())
680 return I1 == I2;
681
682 if (I1.getBitWidth() > I2.getBitWidth())
683 return I1 == I2.zext(I1.getBitWidth());
684
685 return I1.zext(I2.getBitWidth()) == I2;
686 }
687
688 /// Overload to compute a hash_code for an APInt value.
689 friend hash_code hash_value(const APInt &Arg);
690
691 /// This function returns a pointer to the internal storage of the APInt.
692 /// This is useful for writing out the APInt in binary form without any
693 /// conversions.
694 const uint64_t *getRawData() const {
695 if (isSingleWord())
696 return &U.VAL;
697 return &U.pVal[0];
698 }
699
700 /// @}
701 /// \name Unary Operators
702 /// @{
703
704 /// Postfix increment operator.
705 ///
706 /// Increments *this by 1.
707 ///
708 /// \returns a new APInt value representing the original value of *this.
709 const APInt operator++(int) {
710 APInt API(*this);
711 ++(*this);
712 return API;
713 }
714
715 /// Prefix increment operator.
716 ///
717 /// \returns *this incremented by one
718 APInt &operator++();
719
720 /// Postfix decrement operator.
721 ///
722 /// Decrements *this by 1.
723 ///
724 /// \returns a new APInt value representing the original value of *this.
725 const APInt operator--(int) {
726 APInt API(*this);
727 --(*this);
728 return API;
729 }
730
731 /// Prefix decrement operator.
732 ///
733 /// \returns *this decremented by one.
734 APInt &operator--();
735
736 /// Logical negation operator.
737 ///
738 /// Performs logical negation operation on this APInt.
739 ///
740 /// \returns true if *this is zero, false otherwise.
741 bool operator!() const {
742 if (isSingleWord())
743 return U.VAL == 0;
744 return countLeadingZerosSlowCase() == BitWidth;
745 }
746
747 /// @}
748 /// \name Assignment Operators
749 /// @{
750
751 /// Copy assignment operator.
752 ///
753 /// \returns *this after assignment of RHS.
754 APInt &operator=(const APInt &RHS) {
755 // If the bitwidths are the same, we can avoid mucking with memory
756 if (isSingleWord() && RHS.isSingleWord()) {
757 U.VAL = RHS.U.VAL;
758 BitWidth = RHS.BitWidth;
759 return clearUnusedBits();
760 }
761
762 AssignSlowCase(RHS);
763 return *this;
764 }
765
766 /// Move assignment operator.
767 APInt &operator=(APInt &&that) {
768#ifdef EXPENSIVE_CHECKS
769 // Some std::shuffle implementations still do self-assignment.
770 if (this == &that)
771 return *this;
772#endif
773 assert(this != &that && "Self-move not supported")((void)0);
774 if (!isSingleWord())
775 delete[] U.pVal;
776
777 // Use memcpy so that type based alias analysis sees both VAL and pVal
778 // as modified.
779 memcpy(&U, &that.U, sizeof(U));
780
781 BitWidth = that.BitWidth;
782 that.BitWidth = 0;
783
784 return *this;
785 }
786
787 /// Assignment operator.
788 ///
789 /// The RHS value is assigned to *this. If the significant bits in RHS exceed
790 /// the bit width, the excess bits are truncated. If the bit width is larger
791 /// than 64, the value is zero filled in the unspecified high order bits.
792 ///
793 /// \returns *this after assignment of RHS value.
794 APInt &operator=(uint64_t RHS) {
795 if (isSingleWord()) {
796 U.VAL = RHS;
797 return clearUnusedBits();
798 }
799 U.pVal[0] = RHS;
800 memset(U.pVal + 1, 0, (getNumWords() - 1) * APINT_WORD_SIZE);
801 return *this;
802 }
803
804 /// Bitwise AND assignment operator.
805 ///
806 /// Performs a bitwise AND operation on this APInt and RHS. The result is
807 /// assigned to *this.
808 ///
809 /// \returns *this after ANDing with RHS.
810 APInt &operator&=(const APInt &RHS) {
811 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same")((void)0);
812 if (isSingleWord())
813 U.VAL &= RHS.U.VAL;
814 else
815 AndAssignSlowCase(RHS);
816 return *this;
817 }
818
819 /// Bitwise AND assignment operator.
820 ///
821 /// Performs a bitwise AND operation on this APInt and RHS. RHS is
822 /// logically zero-extended or truncated to match the bit-width of
823 /// the LHS.
824 APInt &operator&=(uint64_t RHS) {
825 if (isSingleWord()) {
826 U.VAL &= RHS;
827 return *this;
828 }
829 U.pVal[0] &= RHS;
830 memset(U.pVal+1, 0, (getNumWords() - 1) * APINT_WORD_SIZE);
831 return *this;
832 }
833
834 /// Bitwise OR assignment operator.
835 ///
836 /// Performs a bitwise OR operation on this APInt and RHS. The result is
837 /// assigned *this;
838 ///
839 /// \returns *this after ORing with RHS.
840 APInt &operator|=(const APInt &RHS) {
841 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same")((void)0);
842 if (isSingleWord())
843 U.VAL |= RHS.U.VAL;
844 else
845 OrAssignSlowCase(RHS);
846 return *this;
847 }
848
849 /// Bitwise OR assignment operator.
850 ///
851 /// Performs a bitwise OR operation on this APInt and RHS. RHS is
852 /// logically zero-extended or truncated to match the bit-width of
853 /// the LHS.
854 APInt &operator|=(uint64_t RHS) {
855 if (isSingleWord()) {
856 U.VAL |= RHS;
857 return clearUnusedBits();
858 }
859 U.pVal[0] |= RHS;
860 return *this;
861 }
862
863 /// Bitwise XOR assignment operator.
864 ///
865 /// Performs a bitwise XOR operation on this APInt and RHS. The result is
866 /// assigned to *this.
867 ///
868 /// \returns *this after XORing with RHS.
869 APInt &operator^=(const APInt &RHS) {
870 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same")((void)0);
871 if (isSingleWord())
872 U.VAL ^= RHS.U.VAL;
873 else
874 XorAssignSlowCase(RHS);
875 return *this;
876 }
877
878 /// Bitwise XOR assignment operator.
879 ///
880 /// Performs a bitwise XOR operation on this APInt and RHS. RHS is
881 /// logically zero-extended or truncated to match the bit-width of
882 /// the LHS.
883 APInt &operator^=(uint64_t RHS) {
884 if (isSingleWord()) {
885 U.VAL ^= RHS;
886 return clearUnusedBits();
887 }
888 U.pVal[0] ^= RHS;
889 return *this;
890 }
891
892 /// Multiplication assignment operator.
893 ///
894 /// Multiplies this APInt by RHS and assigns the result to *this.
895 ///
896 /// \returns *this
897 APInt &operator*=(const APInt &RHS);
898 APInt &operator*=(uint64_t RHS);
899
900 /// Addition assignment operator.
901 ///
902 /// Adds RHS to *this and assigns the result to *this.
903 ///
904 /// \returns *this
905 APInt &operator+=(const APInt &RHS);
906 APInt &operator+=(uint64_t RHS);
907
908 /// Subtraction assignment operator.
909 ///
910 /// Subtracts RHS from *this and assigns the result to *this.
911 ///
912 /// \returns *this
913 APInt &operator-=(const APInt &RHS);
914 APInt &operator-=(uint64_t RHS);
915
916 /// Left-shift assignment function.
917 ///
918 /// Shifts *this left by shiftAmt and assigns the result to *this.
919 ///
920 /// \returns *this after shifting left by ShiftAmt
921 APInt &operator<<=(unsigned ShiftAmt) {
922 assert(ShiftAmt <= BitWidth && "Invalid shift amount")((void)0);
923 if (isSingleWord()) {
924 if (ShiftAmt == BitWidth)
925 U.VAL = 0;
926 else
927 U.VAL <<= ShiftAmt;
928 return clearUnusedBits();
929 }
930 shlSlowCase(ShiftAmt);
931 return *this;
932 }
933
934 /// Left-shift assignment function.
935 ///
936 /// Shifts *this left by shiftAmt and assigns the result to *this.
937 ///
938 /// \returns *this after shifting left by ShiftAmt
939 APInt &operator<<=(const APInt &ShiftAmt);
940
941 /// @}
942 /// \name Binary Operators
943 /// @{
944
945 /// Multiplication operator.
946 ///
947 /// Multiplies this APInt by RHS and returns the result.
948 APInt operator*(const APInt &RHS) const;
949
950 /// Left logical shift operator.
951 ///
952 /// Shifts this APInt left by \p Bits and returns the result.
953 APInt operator<<(unsigned Bits) const { return shl(Bits); }
954
955 /// Left logical shift operator.
956 ///
957 /// Shifts this APInt left by \p Bits and returns the result.
958 APInt operator<<(const APInt &Bits) const { return shl(Bits); }
959
960 /// Arithmetic right-shift function.
961 ///
962 /// Arithmetic right-shift this APInt by shiftAmt.
963 APInt ashr(unsigned ShiftAmt) const {
964 APInt R(*this);
965 R.ashrInPlace(ShiftAmt);
966 return R;
967 }
968
969 /// Arithmetic right-shift this APInt by ShiftAmt in place.
970 void ashrInPlace(unsigned ShiftAmt) {
971 assert(ShiftAmt <= BitWidth && "Invalid shift amount")((void)0);
972 if (isSingleWord()) {
973 int64_t SExtVAL = SignExtend64(U.VAL, BitWidth);
974 if (ShiftAmt == BitWidth)
975 U.VAL = SExtVAL >> (APINT_BITS_PER_WORD - 1); // Fill with sign bit.
976 else
977 U.VAL = SExtVAL >> ShiftAmt;
978 clearUnusedBits();
979 return;
980 }
981 ashrSlowCase(ShiftAmt);
982 }
983
984 /// Logical right-shift function.
985 ///
986 /// Logical right-shift this APInt by shiftAmt.
987 APInt lshr(unsigned shiftAmt) const {
988 APInt R(*this);
989 R.lshrInPlace(shiftAmt);
990 return R;
991 }
992
993 /// Logical right-shift this APInt by ShiftAmt in place.
994 void lshrInPlace(unsigned ShiftAmt) {
995 assert(ShiftAmt <= BitWidth && "Invalid shift amount")((void)0);
996 if (isSingleWord()) {
997 if (ShiftAmt == BitWidth)
998 U.VAL = 0;
999 else
1000 U.VAL >>= ShiftAmt;
1001 return;
1002 }
1003 lshrSlowCase(ShiftAmt);
1004 }
1005
1006 /// Left-shift function.
1007 ///
1008 /// Left-shift this APInt by shiftAmt.
1009 APInt shl(unsigned shiftAmt) const {
1010 APInt R(*this);
1011 R <<= shiftAmt;
1012 return R;
1013 }
1014
1015 /// Rotate left by rotateAmt.
1016 APInt rotl(unsigned rotateAmt) const;
1017
1018 /// Rotate right by rotateAmt.
1019 APInt rotr(unsigned rotateAmt) const;
1020
1021 /// Arithmetic right-shift function.
1022 ///
1023 /// Arithmetic right-shift this APInt by shiftAmt.
1024 APInt ashr(const APInt &ShiftAmt) const {
1025 APInt R(*this);
1026 R.ashrInPlace(ShiftAmt);
1027 return R;
1028 }
1029
1030 /// Arithmetic right-shift this APInt by shiftAmt in place.
1031 void ashrInPlace(const APInt &shiftAmt);
1032
1033 /// Logical right-shift function.
1034 ///
1035 /// Logical right-shift this APInt by shiftAmt.
1036 APInt lshr(const APInt &ShiftAmt) const {
1037 APInt R(*this);
1038 R.lshrInPlace(ShiftAmt);
1039 return R;
1040 }
1041
1042 /// Logical right-shift this APInt by ShiftAmt in place.
1043 void lshrInPlace(const APInt &ShiftAmt);
1044
1045 /// Left-shift function.
1046 ///
1047 /// Left-shift this APInt by shiftAmt.
1048 APInt shl(const APInt &ShiftAmt) const {
1049 APInt R(*this);
1050 R <<= ShiftAmt;
1051 return R;
1052 }
1053
1054 /// Rotate left by rotateAmt.
1055 APInt rotl(const APInt &rotateAmt) const;
1056
1057 /// Rotate right by rotateAmt.
1058 APInt rotr(const APInt &rotateAmt) const;
1059
1060 /// Unsigned division operation.
1061 ///
1062 /// Perform an unsigned divide operation on this APInt by RHS. Both this and
1063 /// RHS are treated as unsigned quantities for purposes of this division.
1064 ///
1065 /// \returns a new APInt value containing the division result, rounded towards
1066 /// zero.
1067 APInt udiv(const APInt &RHS) const;
1068 APInt udiv(uint64_t RHS) const;
1069
1070 /// Signed division function for APInt.
1071 ///
1072 /// Signed divide this APInt by APInt RHS.
1073 ///
1074 /// The result is rounded towards zero.
1075 APInt sdiv(const APInt &RHS) const;
1076 APInt sdiv(int64_t RHS) const;
1077
1078 /// Unsigned remainder operation.
1079 ///
1080 /// Perform an unsigned remainder operation on this APInt with RHS being the
1081 /// divisor. Both this and RHS are treated as unsigned quantities for purposes
1082 /// of this operation. Note that this is a true remainder operation and not a
1083 /// modulo operation because the sign follows the sign of the dividend which
1084 /// is *this.
1085 ///
1086 /// \returns a new APInt value containing the remainder result
1087 APInt urem(const APInt &RHS) const;
1088 uint64_t urem(uint64_t RHS) const;
1089
1090 /// Function for signed remainder operation.
1091 ///
1092 /// Signed remainder operation on APInt.
1093 APInt srem(const APInt &RHS) const;
1094 int64_t srem(int64_t RHS) const;
1095
1096 /// Dual division/remainder interface.
1097 ///
1098 /// Sometimes it is convenient to divide two APInt values and obtain both the
1099 /// quotient and remainder. This function does both operations in the same
1100 /// computation making it a little more efficient. The pair of input arguments
1101 /// may overlap with the pair of output arguments. It is safe to call
1102 /// udivrem(X, Y, X, Y), for example.
1103 static void udivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient,
1104 APInt &Remainder);
1105 static void udivrem(const APInt &LHS, uint64_t RHS, APInt &Quotient,
1106 uint64_t &Remainder);
1107
1108 static void sdivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient,
1109 APInt &Remainder);
1110 static void sdivrem(const APInt &LHS, int64_t RHS, APInt &Quotient,
1111 int64_t &Remainder);
1112
1113 // Operations that return overflow indicators.
1114 APInt sadd_ov(const APInt &RHS, bool &Overflow) const;
1115 APInt uadd_ov(const APInt &RHS, bool &Overflow) const;
1116 APInt ssub_ov(const APInt &RHS, bool &Overflow) const;
1117 APInt usub_ov(const APInt &RHS, bool &Overflow) const;
1118 APInt sdiv_ov(const APInt &RHS, bool &Overflow) const;
1119 APInt smul_ov(const APInt &RHS, bool &Overflow) const;
1120 APInt umul_ov(const APInt &RHS, bool &Overflow) const;
1121 APInt sshl_ov(const APInt &Amt, bool &Overflow) const;
1122 APInt ushl_ov(const APInt &Amt, bool &Overflow) const;
1123
1124 // Operations that saturate
1125 APInt sadd_sat(const APInt &RHS) const;
1126 APInt uadd_sat(const APInt &RHS) const;
1127 APInt ssub_sat(const APInt &RHS) const;
1128 APInt usub_sat(const APInt &RHS) const;
1129 APInt smul_sat(const APInt &RHS) const;
1130 APInt umul_sat(const APInt &RHS) const;
1131 APInt sshl_sat(const APInt &RHS) const;
1132 APInt ushl_sat(const APInt &RHS) const;
1133
1134 /// Array-indexing support.
1135 ///
1136 /// \returns the bit value at bitPosition
1137 bool operator[](unsigned bitPosition) const {
1138 assert(bitPosition < getBitWidth() && "Bit position out of bounds!")((void)0);
1139 return (maskBit(bitPosition) & getWord(bitPosition)) != 0;
1140 }
1141
1142 /// @}
1143 /// \name Comparison Operators
1144 /// @{
1145
1146 /// Equality operator.
1147 ///
1148 /// Compares this APInt with RHS for the validity of the equality
1149 /// relationship.
1150 bool operator==(const APInt &RHS) const {
1151 assert(BitWidth == RHS.BitWidth && "Comparison requires equal bit widths")((void)0);
1152 if (isSingleWord())
1153 return U.VAL == RHS.U.VAL;
1154 return EqualSlowCase(RHS);
1155 }
1156
1157 /// Equality operator.
1158 ///
1159 /// Compares this APInt with a uint64_t for the validity of the equality
1160 /// relationship.
1161 ///
1162 /// \returns true if *this == Val
1163 bool operator==(uint64_t Val) const {
1164 return (isSingleWord() || getActiveBits() <= 64) && getZExtValue() == Val;
1165 }
1166
1167 /// Equality comparison.
1168 ///
1169 /// Compares this APInt with RHS for the validity of the equality
1170 /// relationship.
1171 ///
1172 /// \returns true if *this == Val
1173 bool eq(const APInt &RHS) const { return (*this) == RHS; }
1174
1175 /// Inequality operator.
1176 ///
1177 /// Compares this APInt with RHS for the validity of the inequality
1178 /// relationship.
1179 ///
1180 /// \returns true if *this != Val
1181 bool operator!=(const APInt &RHS) const { return !((*this) == RHS); }
1182
1183 /// Inequality operator.
1184 ///
1185 /// Compares this APInt with a uint64_t for the validity of the inequality
1186 /// relationship.
1187 ///
1188 /// \returns true if *this != Val
1189 bool operator!=(uint64_t Val) const { return !((*this) == Val); }
1190
1191 /// Inequality comparison
1192 ///
1193 /// Compares this APInt with RHS for the validity of the inequality
1194 /// relationship.
1195 ///
1196 /// \returns true if *this != Val
1197 bool ne(const APInt &RHS) const { return !((*this) == RHS); }
1198
1199 /// Unsigned less than comparison
1200 ///
1201 /// Regards both *this and RHS as unsigned quantities and compares them for
1202 /// the validity of the less-than relationship.
1203 ///
1204 /// \returns true if *this < RHS when both are considered unsigned.
1205 bool ult(const APInt &RHS) const { return compare(RHS) < 0; }
1206
1207 /// Unsigned less than comparison
1208 ///
1209 /// Regards both *this as an unsigned quantity and compares it with RHS for
1210 /// the validity of the less-than relationship.
1211 ///
1212 /// \returns true if *this < RHS when considered unsigned.
1213 bool ult(uint64_t RHS) const {
1214 // Only need to check active bits if not a single word.
1215 return (isSingleWord() || getActiveBits() <= 64) && getZExtValue() < RHS;
1216 }
1217
1218 /// Signed less than comparison
1219 ///
1220 /// Regards both *this and RHS as signed quantities and compares them for
1221 /// validity of the less-than relationship.
1222 ///
1223 /// \returns true if *this < RHS when both are considered signed.
1224 bool slt(const APInt &RHS) const { return compareSigned(RHS) < 0; }
1225
1226 /// Signed less than comparison
1227 ///
1228 /// Regards both *this as a signed quantity and compares it with RHS for
1229 /// the validity of the less-than relationship.
1230 ///
1231 /// \returns true if *this < RHS when considered signed.
1232 bool slt(int64_t RHS) const {
1233 return (!isSingleWord() && getMinSignedBits() > 64) ? isNegative()
1234 : getSExtValue() < RHS;
1235 }
1236
1237 /// Unsigned less or equal comparison
1238 ///
1239 /// Regards both *this and RHS as unsigned quantities and compares them for
1240 /// validity of the less-or-equal relationship.
1241 ///
1242 /// \returns true if *this <= RHS when both are considered unsigned.
1243 bool ule(const APInt &RHS) const { return compare(RHS) <= 0; }
1244
1245 /// Unsigned less or equal comparison
1246 ///
1247 /// Regards both *this as an unsigned quantity and compares it with RHS for
1248 /// the validity of the less-or-equal relationship.
1249 ///
1250 /// \returns true if *this <= RHS when considered unsigned.
1251 bool ule(uint64_t RHS) const { return !ugt(RHS); }
1252
1253 /// Signed less or equal comparison
1254 ///
1255 /// Regards both *this and RHS as signed quantities and compares them for
1256 /// validity of the less-or-equal relationship.
1257 ///
1258 /// \returns true if *this <= RHS when both are considered signed.
1259 bool sle(const APInt &RHS) const { return compareSigned(RHS) <= 0; }
1260
1261 /// Signed less or equal comparison
1262 ///
1263 /// Regards both *this as a signed quantity and compares it with RHS for the
1264 /// validity of the less-or-equal relationship.
1265 ///
1266 /// \returns true if *this <= RHS when considered signed.
1267 bool sle(uint64_t RHS) const { return !sgt(RHS); }
1268
1269 /// Unsigned greater than comparison
1270 ///
1271 /// Regards both *this and RHS as unsigned quantities and compares them for
1272 /// the validity of the greater-than relationship.
1273 ///
1274 /// \returns true if *this > RHS when both are considered unsigned.
1275 bool ugt(const APInt &RHS) const { return !ule(RHS); }
1276
1277 /// Unsigned greater than comparison
1278 ///
1279 /// Regards both *this as an unsigned quantity and compares it with RHS for
1280 /// the validity of the greater-than relationship.
1281 ///
1282 /// \returns true if *this > RHS when considered unsigned.
1283 bool ugt(uint64_t RHS) const {
1284 // Only need to check active bits if not a single word.
1285 return (!isSingleWord() && getActiveBits() > 64) || getZExtValue() > RHS;
1286 }
1287
1288 /// Signed greater than comparison
1289 ///
1290 /// Regards both *this and RHS as signed quantities and compares them for the
1291 /// validity of the greater-than relationship.
1292 ///
1293 /// \returns true if *this > RHS when both are considered signed.
1294 bool sgt(const APInt &RHS) const { return !sle(RHS); }
1295
1296 /// Signed greater than comparison
1297 ///
1298 /// Regards both *this as a signed quantity and compares it with RHS for
1299 /// the validity of the greater-than relationship.
1300 ///
1301 /// \returns true if *this > RHS when considered signed.
1302 bool sgt(int64_t RHS) const {
1303 return (!isSingleWord() && getMinSignedBits() > 64) ? !isNegative()
1304 : getSExtValue() > RHS;
1305 }
1306
1307 /// Unsigned greater or equal comparison
1308 ///
1309 /// Regards both *this and RHS as unsigned quantities and compares them for
1310 /// validity of the greater-or-equal relationship.
1311 ///
1312 /// \returns true if *this >= RHS when both are considered unsigned.
1313 bool uge(const APInt &RHS) const { return !ult(RHS); }
1314
1315 /// Unsigned greater or equal comparison
1316 ///
1317 /// Regards both *this as an unsigned quantity and compares it with RHS for
1318 /// the validity of the greater-or-equal relationship.
1319 ///
1320 /// \returns true if *this >= RHS when considered unsigned.
1321 bool uge(uint64_t RHS) const { return !ult(RHS); }
1322
1323 /// Signed greater or equal comparison
1324 ///
1325 /// Regards both *this and RHS as signed quantities and compares them for
1326 /// validity of the greater-or-equal relationship.
1327 ///
1328 /// \returns true if *this >= RHS when both are considered signed.
1329 bool sge(const APInt &RHS) const { return !slt(RHS); }
1330
1331 /// Signed greater or equal comparison
1332 ///
1333 /// Regards both *this as a signed quantity and compares it with RHS for
1334 /// the validity of the greater-or-equal relationship.
1335 ///
1336 /// \returns true if *this >= RHS when considered signed.
1337 bool sge(int64_t RHS) const { return !slt(RHS); }
1338
1339 /// This operation tests if there are any pairs of corresponding bits
1340 /// between this APInt and RHS that are both set.
1341 bool intersects(const APInt &RHS) const {
1342 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same")((void)0);
1343 if (isSingleWord())
1344 return (U.VAL & RHS.U.VAL) != 0;
1345 return intersectsSlowCase(RHS);
1346 }
1347
1348 /// This operation checks that all bits set in this APInt are also set in RHS.
1349 bool isSubsetOf(const APInt &RHS) const {
1350 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same")((void)0);
1351 if (isSingleWord())
1352 return (U.VAL & ~RHS.U.VAL) == 0;
1353 return isSubsetOfSlowCase(RHS);
1354 }
1355
1356 /// @}
1357 /// \name Resizing Operators
1358 /// @{
1359
1360 /// Truncate to new width.
1361 ///
1362 /// Truncate the APInt to a specified width. It is an error to specify a width
1363 /// that is greater than or equal to the current width.
1364 APInt trunc(unsigned width) const;
1365
1366 /// Truncate to new width with unsigned saturation.
1367 ///
1368 /// If the APInt, treated as unsigned integer, can be losslessly truncated to
1369 /// the new bitwidth, then return truncated APInt. Else, return max value.
1370 APInt truncUSat(unsigned width) const;
1371
1372 /// Truncate to new width with signed saturation.
1373 ///
1374 /// If this APInt, treated as signed integer, can be losslessly truncated to
1375 /// the new bitwidth, then return truncated APInt. Else, return either
1376 /// signed min value if the APInt was negative, or signed max value.
1377 APInt truncSSat(unsigned width) const;
1378
1379 /// Sign extend to a new width.
1380 ///
1381 /// This operation sign extends the APInt to a new width. If the high order
1382 /// bit is set, the fill on the left will be done with 1 bits, otherwise zero.
1383 /// It is an error to specify a width that is less than or equal to the
1384 /// current width.
1385 APInt sext(unsigned width) const;
1386
1387 /// Zero extend to a new width.
1388 ///
1389 /// This operation zero extends the APInt to a new width. The high order bits
1390 /// are filled with 0 bits. It is an error to specify a width that is less
1391 /// than or equal to the current width.
1392 APInt zext(unsigned width) const;
1393
1394 /// Sign extend or truncate to width
1395 ///
1396 /// Make this APInt have the bit width given by \p width. The value is sign
1397 /// extended, truncated, or left alone to make it that width.
1398 APInt sextOrTrunc(unsigned width) const;
1399
1400 /// Zero extend or truncate to width
1401 ///
1402 /// Make this APInt have the bit width given by \p width. The value is zero
1403 /// extended, truncated, or left alone to make it that width.
1404 APInt zextOrTrunc(unsigned width) const;
1405
1406 /// Truncate to width
1407 ///
1408 /// Make this APInt have the bit width given by \p width. The value is
1409 /// truncated or left alone to make it that width.
1410 APInt truncOrSelf(unsigned width) const;
1411
1412 /// Sign extend or truncate to width
1413 ///
1414 /// Make this APInt have the bit width given by \p width. The value is sign
1415 /// extended, or left alone to make it that width.
1416 APInt sextOrSelf(unsigned width) const;
1417
1418 /// Zero extend or truncate to width
1419 ///
1420 /// Make this APInt have the bit width given by \p width. The value is zero
1421 /// extended, or left alone to make it that width.
1422 APInt zextOrSelf(unsigned width) const;
1423
1424 /// @}
1425 /// \name Bit Manipulation Operators
1426 /// @{
1427
1428 /// Set every bit to 1.
1429 void setAllBits() {
1430 if (isSingleWord())
1431 U.VAL = WORDTYPE_MAX;
1432 else
1433 // Set all the bits in all the words.
1434 memset(U.pVal, -1, getNumWords() * APINT_WORD_SIZE);
1435 // Clear the unused ones
1436 clearUnusedBits();
1437 }
1438
1439 /// Set a given bit to 1.
1440 ///
1441 /// Set the given bit to 1 whose position is given as "bitPosition".
1442 void setBit(unsigned BitPosition) {
1443 assert(BitPosition < BitWidth && "BitPosition out of range")((void)0);
1444 WordType Mask = maskBit(BitPosition);
1445 if (isSingleWord())
1446 U.VAL |= Mask;
1447 else
1448 U.pVal[whichWord(BitPosition)] |= Mask;
1449 }
1450
1451 /// Set the sign bit to 1.
1452 void setSignBit() {
1453 setBit(BitWidth - 1);
1454 }
1455
1456 /// Set a given bit to a given value.
1457 void setBitVal(unsigned BitPosition, bool BitValue) {
1458 if (BitValue)
1459 setBit(BitPosition);
1460 else
1461 clearBit(BitPosition);
1462 }
1463
1464 /// Set the bits from loBit (inclusive) to hiBit (exclusive) to 1.
1465 /// This function handles "wrap" case when \p loBit >= \p hiBit, and calls
1466 /// setBits when \p loBit < \p hiBit.
1467 /// For \p loBit == \p hiBit wrap case, set every bit to 1.
1468 void setBitsWithWrap(unsigned loBit, unsigned hiBit) {
1469 assert(hiBit <= BitWidth && "hiBit out of range")((void)0);
1470 assert(loBit <= BitWidth && "loBit out of range")((void)0);
1471 if (loBit < hiBit) {
1472 setBits(loBit, hiBit);
1473 return;
1474 }
1475 setLowBits(hiBit);
1476 setHighBits(BitWidth - loBit);
1477 }
1478
1479 /// Set the bits from loBit (inclusive) to hiBit (exclusive) to 1.
1480 /// This function handles case when \p loBit <= \p hiBit.
1481 void setBits(unsigned loBit, unsigned hiBit) {
1482 assert(hiBit <= BitWidth && "hiBit out of range")((void)0);
1483 assert(loBit <= BitWidth && "loBit out of range")((void)0);
1484 assert(loBit <= hiBit && "loBit greater than hiBit")((void)0);
1485 if (loBit == hiBit)
1486 return;
1487 if (loBit < APINT_BITS_PER_WORD && hiBit <= APINT_BITS_PER_WORD) {
1488 uint64_t mask = WORDTYPE_MAX >> (APINT_BITS_PER_WORD - (hiBit - loBit));
1489 mask <<= loBit;
1490 if (isSingleWord())
1491 U.VAL |= mask;
1492 else
1493 U.pVal[0] |= mask;
1494 } else {
1495 setBitsSlowCase(loBit, hiBit);
1496 }
1497 }
1498
1499 /// Set the top bits starting from loBit.
1500 void setBitsFrom(unsigned loBit) {
1501 return setBits(loBit, BitWidth);
1502 }
1503
1504 /// Set the bottom loBits bits.
1505 void setLowBits(unsigned loBits) {
1506 return setBits(0, loBits);
1507 }
1508
1509 /// Set the top hiBits bits.
1510 void setHighBits(unsigned hiBits) {
1511 return setBits(BitWidth - hiBits, BitWidth);
1512 }
1513
1514 /// Set every bit to 0.
1515 void clearAllBits() {
1516 if (isSingleWord())
1517 U.VAL = 0;
1518 else
1519 memset(U.pVal, 0, getNumWords() * APINT_WORD_SIZE);
1520 }
1521
1522 /// Set a given bit to 0.
1523 ///
1524 /// Set the given bit to 0 whose position is given as "bitPosition".
1525 void clearBit(unsigned BitPosition) {
1526 assert(BitPosition < BitWidth && "BitPosition out of range")((void)0);
1527 WordType Mask = ~maskBit(BitPosition);
1528 if (isSingleWord())
1529 U.VAL &= Mask;
1530 else
1531 U.pVal[whichWord(BitPosition)] &= Mask;
1532 }
1533
1534 /// Set bottom loBits bits to 0.
1535 void clearLowBits(unsigned loBits) {
1536 assert(loBits <= BitWidth && "More bits than bitwidth")((void)0);
1537 APInt Keep = getHighBitsSet(BitWidth, BitWidth - loBits);
1538 *this &= Keep;
1539 }
1540
1541 /// Set the sign bit to 0.
1542 void clearSignBit() {
1543 clearBit(BitWidth - 1);
1544 }
1545
1546 /// Toggle every bit to its opposite value.
1547 void flipAllBits() {
1548 if (isSingleWord()) {
1549 U.VAL ^= WORDTYPE_MAX;
1550 clearUnusedBits();
1551 } else {
1552 flipAllBitsSlowCase();
1553 }
1554 }
1555
1556 /// Toggles a given bit to its opposite value.
1557 ///
1558 /// Toggle a given bit to its opposite value whose position is given
1559 /// as "bitPosition".
1560 void flipBit(unsigned bitPosition);
1561
1562 /// Negate this APInt in place.
1563 void negate() {
1564 flipAllBits();
1565 ++(*this);
1566 }
1567
1568 /// Insert the bits from a smaller APInt starting at bitPosition.
1569 void insertBits(const APInt &SubBits, unsigned bitPosition);
1570 void insertBits(uint64_t SubBits, unsigned bitPosition, unsigned numBits);
1571
1572 /// Return an APInt with the extracted bits [bitPosition,bitPosition+numBits).
1573 APInt extractBits(unsigned numBits, unsigned bitPosition) const;
1574 uint64_t extractBitsAsZExtValue(unsigned numBits, unsigned bitPosition) const;
1575
1576 /// @}
1577 /// \name Value Characterization Functions
1578 /// @{
1579
1580 /// Return the number of bits in the APInt.
1581 unsigned getBitWidth() const { return BitWidth; }
1582
1583 /// Get the number of words.
1584 ///
1585 /// Here one word's bitwidth equals to that of uint64_t.
1586 ///
1587 /// \returns the number of words to hold the integer value of this APInt.
1588 unsigned getNumWords() const { return getNumWords(BitWidth); }
1589
1590 /// Get the number of words.
1591 ///
1592 /// *NOTE* Here one word's bitwidth equals to that of uint64_t.
1593 ///
1594 /// \returns the number of words to hold the integer value with a given bit
1595 /// width.
1596 static unsigned getNumWords(unsigned BitWidth) {
1597 return ((uint64_t)BitWidth + APINT_BITS_PER_WORD - 1) / APINT_BITS_PER_WORD;
1598 }
1599
1600 /// Compute the number of active bits in the value
1601 ///
1602 /// This function returns the number of active bits which is defined as the
1603 /// bit width minus the number of leading zeros. This is used in several
1604 /// computations to see how "wide" the value is.
1605 unsigned getActiveBits() const { return BitWidth - countLeadingZeros(); }
1606
1607 /// Compute the number of active words in the value of this APInt.
1608 ///
1609 /// This is used in conjunction with getActiveData to extract the raw value of
1610 /// the APInt.
1611 unsigned getActiveWords() const {
1612 unsigned numActiveBits = getActiveBits();
1613 return numActiveBits ? whichWord(numActiveBits - 1) + 1 : 1;
1614 }
1615
1616 /// Get the minimum bit size for this signed APInt
1617 ///
1618 /// Computes the minimum bit width for this APInt while considering it to be a
1619 /// signed (and probably negative) value. If the value is not negative, this
1620 /// function returns the same value as getActiveBits()+1. Otherwise, it
1621 /// returns the smallest bit width that will retain the negative value. For
1622 /// example, -1 can be written as 0b1 or 0xFFFFFFFFFF. 0b1 is shorter and so
1623 /// for -1, this function will always return 1.
1624 unsigned getMinSignedBits() const { return BitWidth - getNumSignBits() + 1; }
1625
1626 /// Get zero extended value
1627 ///
1628 /// This method attempts to return the value of this APInt as a zero extended
1629 /// uint64_t. The bitwidth must be <= 64 or the value must fit within a
1630 /// uint64_t. Otherwise an assertion will result.
1631 uint64_t getZExtValue() const {
1632 if (isSingleWord())
1633 return U.VAL;
1634 assert(getActiveBits() <= 64 && "Too many bits for uint64_t")((void)0);
1635 return U.pVal[0];
1636 }
1637
1638 /// Get sign extended value
1639 ///
1640 /// This method attempts to return the value of this APInt as a sign extended
1641 /// int64_t. The bit width must be <= 64 or the value must fit within an
1642 /// int64_t. Otherwise an assertion will result.
1643 int64_t getSExtValue() const {
1644 if (isSingleWord())
1645 return SignExtend64(U.VAL, BitWidth);
1646 assert(getMinSignedBits() <= 64 && "Too many bits for int64_t")((void)0);
1647 return int64_t(U.pVal[0]);
1648 }
1649
1650 /// Get bits required for string value.
1651 ///
1652 /// This method determines how many bits are required to hold the APInt
1653 /// equivalent of the string given by \p str.
1654 static unsigned getBitsNeeded(StringRef str, uint8_t radix);
1655
1656 /// The APInt version of the countLeadingZeros functions in
1657 /// MathExtras.h.
1658 ///
1659 /// It counts the number of zeros from the most significant bit to the first
1660 /// one bit.
1661 ///
1662 /// \returns BitWidth if the value is zero, otherwise returns the number of
1663 /// zeros from the most significant bit to the first one bits.
1664 unsigned countLeadingZeros() const {
1665 if (isSingleWord()) {
1666 unsigned unusedBits = APINT_BITS_PER_WORD - BitWidth;
1667 return llvm::countLeadingZeros(U.VAL) - unusedBits;
1668 }
1669 return countLeadingZerosSlowCase();
1670 }
1671
1672 /// Count the number of leading one bits.
1673 ///
1674 /// This function is an APInt version of the countLeadingOnes
1675 /// functions in MathExtras.h. It counts the number of ones from the most
1676 /// significant bit to the first zero bit.
1677 ///
1678 /// \returns 0 if the high order bit is not set, otherwise returns the number
1679 /// of 1 bits from the most significant to the least
1680 unsigned countLeadingOnes() const {
1681 if (isSingleWord())
1682 return llvm::countLeadingOnes(U.VAL << (APINT_BITS_PER_WORD - BitWidth));
1683 return countLeadingOnesSlowCase();
1684 }
1685
1686 /// Computes the number of leading bits of this APInt that are equal to its
1687 /// sign bit.
1688 unsigned getNumSignBits() const {
1689 return isNegative() ? countLeadingOnes() : countLeadingZeros();
1690 }
1691
1692 /// Count the number of trailing zero bits.
1693 ///
1694 /// This function is an APInt version of the countTrailingZeros
1695 /// functions in MathExtras.h. It counts the number of zeros from the least
1696 /// significant bit to the first set bit.
1697 ///
1698 /// \returns BitWidth if the value is zero, otherwise returns the number of
1699 /// zeros from the least significant bit to the first one bit.
1700 unsigned countTrailingZeros() const {
1701 if (isSingleWord()) {
1702 unsigned TrailingZeros = llvm::countTrailingZeros(U.VAL);
1703 return (TrailingZeros > BitWidth ? BitWidth : TrailingZeros);
1704 }
1705 return countTrailingZerosSlowCase();
1706 }
1707
1708 /// Count the number of trailing one bits.
1709 ///
1710 /// This function is an APInt version of the countTrailingOnes
1711 /// functions in MathExtras.h. It counts the number of ones from the least
1712 /// significant bit to the first zero bit.
1713 ///
1714 /// \returns BitWidth if the value is all ones, otherwise returns the number
1715 /// of ones from the least significant bit to the first zero bit.
1716 unsigned countTrailingOnes() const {
1717 if (isSingleWord())
1718 return llvm::countTrailingOnes(U.VAL);
1719 return countTrailingOnesSlowCase();
1720 }
1721
1722 /// Count the number of bits set.
1723 ///
1724 /// This function is an APInt version of the countPopulation functions
1725 /// in MathExtras.h. It counts the number of 1 bits in the APInt value.
1726 ///
1727 /// \returns 0 if the value is zero, otherwise returns the number of set bits.
1728 unsigned countPopulation() const {
1729 if (isSingleWord())
1730 return llvm::countPopulation(U.VAL);
1731 return countPopulationSlowCase();
1732 }
1733
1734 /// @}
1735 /// \name Conversion Functions
1736 /// @{
1737 void print(raw_ostream &OS, bool isSigned) const;
1738
1739 /// Converts an APInt to a string and append it to Str. Str is commonly a
1740 /// SmallString.
1741 void toString(SmallVectorImpl<char> &Str, unsigned Radix, bool Signed,
1742 bool formatAsCLiteral = false) const;
1743
1744 /// Considers the APInt to be unsigned and converts it into a string in the
1745 /// radix given. The radix can be 2, 8, 10 16, or 36.
1746 void toStringUnsigned(SmallVectorImpl<char> &Str, unsigned Radix = 10) const {
1747 toString(Str, Radix, false, false);
1748 }
1749
1750 /// Considers the APInt to be signed and converts it into a string in the
1751 /// radix given. The radix can be 2, 8, 10, 16, or 36.
1752 void toStringSigned(SmallVectorImpl<char> &Str, unsigned Radix = 10) const {
1753 toString(Str, Radix, true, false);
1754 }
1755
1756 /// \returns a byte-swapped representation of this APInt Value.
1757 APInt byteSwap() const;
1758
1759 /// \returns the value with the bit representation reversed of this APInt
1760 /// Value.
1761 APInt reverseBits() const;
1762
1763 /// Converts this APInt to a double value.
1764 double roundToDouble(bool isSigned) const;
1765
1766 /// Converts this unsigned APInt to a double value.
1767 double roundToDouble() const { return roundToDouble(false); }
1768
1769 /// Converts this signed APInt to a double value.
1770 double signedRoundToDouble() const { return roundToDouble(true); }
1771
1772 /// Converts APInt bits to a double
1773 ///
1774 /// The conversion does not do a translation from integer to double, it just
1775 /// re-interprets the bits as a double. Note that it is valid to do this on
1776 /// any bit width. Exactly 64 bits will be translated.
1777 double bitsToDouble() const {
1778 return BitsToDouble(getWord(0));
1779 }
1780
1781 /// Converts APInt bits to a float
1782 ///
1783 /// The conversion does not do a translation from integer to float, it just
1784 /// re-interprets the bits as a float. Note that it is valid to do this on
1785 /// any bit width. Exactly 32 bits will be translated.
1786 float bitsToFloat() const {
1787 return BitsToFloat(static_cast<uint32_t>(getWord(0)));
1788 }
1789
1790 /// Converts a double to APInt bits.
1791 ///
1792 /// The conversion does not do a translation from double to integer, it just
1793 /// re-interprets the bits of the double.
1794 static APInt doubleToBits(double V) {
1795 return APInt(sizeof(double) * CHAR_BIT8, DoubleToBits(V));
1796 }
1797
1798 /// Converts a float to APInt bits.
1799 ///
1800 /// The conversion does not do a translation from float to integer, it just
1801 /// re-interprets the bits of the float.
1802 static APInt floatToBits(float V) {
1803 return APInt(sizeof(float) * CHAR_BIT8, FloatToBits(V));
1804 }
1805
1806 /// @}
1807 /// \name Mathematics Operations
1808 /// @{
1809
1810 /// \returns the floor log base 2 of this APInt.
1811 unsigned logBase2() const { return getActiveBits() - 1; }
1812
1813 /// \returns the ceil log base 2 of this APInt.
1814 unsigned ceilLogBase2() const {
1815 APInt temp(*this);
1816 --temp;
1817 return temp.getActiveBits();
1818 }
1819
1820 /// \returns the nearest log base 2 of this APInt. Ties round up.
1821 ///
1822 /// NOTE: When we have a BitWidth of 1, we define:
1823 ///
1824 /// log2(0) = UINT32_MAX
1825 /// log2(1) = 0
1826 ///
1827 /// to get around any mathematical concerns resulting from
1828 /// referencing 2 in a space where 2 does no exist.
1829 unsigned nearestLogBase2() const {
1830 // Special case when we have a bitwidth of 1. If VAL is 1, then we
1831 // get 0. If VAL is 0, we get WORDTYPE_MAX which gets truncated to
1832 // UINT32_MAX.
1833 if (BitWidth == 1)
1834 return U.VAL - 1;
1835
1836 // Handle the zero case.
1837 if (isNullValue())
1838 return UINT32_MAX0xffffffffU;
1839
1840 // The non-zero case is handled by computing:
1841 //
1842 // nearestLogBase2(x) = logBase2(x) + x[logBase2(x)-1].
1843 //
1844 // where x[i] is referring to the value of the ith bit of x.
1845 unsigned lg = logBase2();
1846 return lg + unsigned((*this)[lg - 1]);
1847 }
1848
1849 /// \returns the log base 2 of this APInt if its an exact power of two, -1
1850 /// otherwise
1851 int32_t exactLogBase2() const {
1852 if (!isPowerOf2())
1853 return -1;
1854 return logBase2();
1855 }
1856
1857 /// Compute the square root
1858 APInt sqrt() const;
1859
1860 /// Get the absolute value;
1861 ///
1862 /// If *this is < 0 then return -(*this), otherwise *this;
1863 APInt abs() const {
1864 if (isNegative())
1865 return -(*this);
1866 return *this;
1867 }
1868
1869 /// \returns the multiplicative inverse for a given modulo.
1870 APInt multiplicativeInverse(const APInt &modulo) const;
1871
1872 /// @}
1873 /// \name Support for division by constant
1874 /// @{
1875
1876 /// Calculate the magic number for signed division by a constant.
1877 struct ms;
1878 ms magic() const;
1879
1880 /// Calculate the magic number for unsigned division by a constant.
1881 struct mu;
1882 mu magicu(unsigned LeadingZeros = 0) const;
1883
1884 /// @}
1885 /// \name Building-block Operations for APInt and APFloat
1886 /// @{
1887
1888 // These building block operations operate on a representation of arbitrary
1889 // precision, two's-complement, bignum integer values. They should be
1890 // sufficient to implement APInt and APFloat bignum requirements. Inputs are
1891 // generally a pointer to the base of an array of integer parts, representing
1892 // an unsigned bignum, and a count of how many parts there are.
1893
1894 /// Sets the least significant part of a bignum to the input value, and zeroes
1895 /// out higher parts.
1896 static void tcSet(WordType *, WordType, unsigned);
1897
1898 /// Assign one bignum to another.
1899 static void tcAssign(WordType *, const WordType *, unsigned);
1900
1901 /// Returns true if a bignum is zero, false otherwise.
1902 static bool tcIsZero(const WordType *, unsigned);
1903
1904 /// Extract the given bit of a bignum; returns 0 or 1. Zero-based.
1905 static int tcExtractBit(const WordType *, unsigned bit);
1906
1907 /// Copy the bit vector of width srcBITS from SRC, starting at bit srcLSB, to
1908 /// DST, of dstCOUNT parts, such that the bit srcLSB becomes the least
1909 /// significant bit of DST. All high bits above srcBITS in DST are
1910 /// zero-filled.
1911 static void tcExtract(WordType *, unsigned dstCount,
1912 const WordType *, unsigned srcBits,
1913 unsigned srcLSB);
1914
1915 /// Set the given bit of a bignum. Zero-based.
1916 static void tcSetBit(WordType *, unsigned bit);
1917
1918 /// Clear the given bit of a bignum. Zero-based.
1919 static void tcClearBit(WordType *, unsigned bit);
1920
1921 /// Returns the bit number of the least or most significant set bit of a
1922 /// number. If the input number has no bits set -1U is returned.
1923 static unsigned tcLSB(const WordType *, unsigned n);
1924 static unsigned tcMSB(const WordType *parts, unsigned n);
1925
1926 /// Negate a bignum in-place.
1927 static void tcNegate(WordType *, unsigned);
1928
1929 /// DST += RHS + CARRY where CARRY is zero or one. Returns the carry flag.
1930 static WordType tcAdd(WordType *, const WordType *,
1931 WordType carry, unsigned);
1932 /// DST += RHS. Returns the carry flag.
1933 static WordType tcAddPart(WordType *, WordType, unsigned);
1934
1935 /// DST -= RHS + CARRY where CARRY is zero or one. Returns the carry flag.
1936 static WordType tcSubtract(WordType *, const WordType *,
1937 WordType carry, unsigned);
1938 /// DST -= RHS. Returns the carry flag.
1939 static WordType tcSubtractPart(WordType *, WordType, unsigned);
1940
1941 /// DST += SRC * MULTIPLIER + PART if add is true
1942 /// DST = SRC * MULTIPLIER + PART if add is false
1943 ///
1944 /// Requires 0 <= DSTPARTS <= SRCPARTS + 1. If DST overlaps SRC they must
1945 /// start at the same point, i.e. DST == SRC.
1946 ///
1947 /// If DSTPARTS == SRC_PARTS + 1 no overflow occurs and zero is returned.
1948 /// Otherwise DST is filled with the least significant DSTPARTS parts of the
1949 /// result, and if all of the omitted higher parts were zero return zero,
1950 /// otherwise overflow occurred and return one.
1951 static int tcMultiplyPart(WordType *dst, const WordType *src,
1952 WordType multiplier, WordType carry,
1953 unsigned srcParts, unsigned dstParts,
1954 bool add);
1955
1956 /// DST = LHS * RHS, where DST has the same width as the operands and is
1957 /// filled with the least significant parts of the result. Returns one if
1958 /// overflow occurred, otherwise zero. DST must be disjoint from both
1959 /// operands.
1960 static int tcMultiply(WordType *, const WordType *, const WordType *,
1961 unsigned);
1962
1963 /// DST = LHS * RHS, where DST has width the sum of the widths of the
1964 /// operands. No overflow occurs. DST must be disjoint from both operands.
1965 static void tcFullMultiply(WordType *, const WordType *,
1966 const WordType *, unsigned, unsigned);
1967
1968 /// If RHS is zero LHS and REMAINDER are left unchanged, return one.
1969 /// Otherwise set LHS to LHS / RHS with the fractional part discarded, set
1970 /// REMAINDER to the remainder, return zero. i.e.
1971 ///
1972 /// OLD_LHS = RHS * LHS + REMAINDER
1973 ///
1974 /// SCRATCH is a bignum of the same size as the operands and result for use by
1975 /// the routine; its contents need not be initialized and are destroyed. LHS,
1976 /// REMAINDER and SCRATCH must be distinct.
1977 static int tcDivide(WordType *lhs, const WordType *rhs,
1978 WordType *remainder, WordType *scratch,
1979 unsigned parts);
1980
1981 /// Shift a bignum left Count bits. Shifted in bits are zero. There are no
1982 /// restrictions on Count.
1983 static void tcShiftLeft(WordType *, unsigned Words, unsigned Count);
1984
1985 /// Shift a bignum right Count bits. Shifted in bits are zero. There are no
1986 /// restrictions on Count.
1987 static void tcShiftRight(WordType *, unsigned Words, unsigned Count);
1988
1989 /// The obvious AND, OR and XOR and complement operations.
1990 static void tcAnd(WordType *, const WordType *, unsigned);
1991 static void tcOr(WordType *, const WordType *, unsigned);
1992 static void tcXor(WordType *, const WordType *, unsigned);
1993 static void tcComplement(WordType *, unsigned);
1994
1995 /// Comparison (unsigned) of two bignums.
1996 static int tcCompare(const WordType *, const WordType *, unsigned);
1997
1998 /// Increment a bignum in-place. Return the carry flag.
1999 static WordType tcIncrement(WordType *dst, unsigned parts) {
2000 return tcAddPart(dst, 1, parts);
2001 }
2002
2003 /// Decrement a bignum in-place. Return the borrow flag.
2004 static WordType tcDecrement(WordType *dst, unsigned parts) {
2005 return tcSubtractPart(dst, 1, parts);
2006 }
2007
2008 /// Set the least significant BITS and clear the rest.
2009 static void tcSetLeastSignificantBits(WordType *, unsigned, unsigned bits);
2010
2011 /// debug method
2012 void dump() const;
2013
2014 /// @}
2015};
2016
2017/// Magic data for optimising signed division by a constant.
2018struct APInt::ms {
2019 APInt m; ///< magic number
2020 unsigned s; ///< shift amount
2021};
2022
2023/// Magic data for optimising unsigned division by a constant.
2024struct APInt::mu {
2025 APInt m; ///< magic number
2026 bool a; ///< add indicator
2027 unsigned s; ///< shift amount
2028};
2029
2030inline bool operator==(uint64_t V1, const APInt &V2) { return V2 == V1; }
2031
2032inline bool operator!=(uint64_t V1, const APInt &V2) { return V2 != V1; }
2033
2034/// Unary bitwise complement operator.
2035///
2036/// \returns an APInt that is the bitwise complement of \p v.
2037inline APInt operator~(APInt v) {
2038 v.flipAllBits();
2039 return v;
2040}
2041
2042inline APInt operator&(APInt a, const APInt &b) {
2043 a &= b;
2044 return a;
2045}
2046
2047inline APInt operator&(const APInt &a, APInt &&b) {
2048 b &= a;
2049 return std::move(b);
2050}
2051
2052inline APInt operator&(APInt a, uint64_t RHS) {
2053 a &= RHS;
2054 return a;
2055}
2056
2057inline APInt operator&(uint64_t LHS, APInt b) {
2058 b &= LHS;
2059 return b;
2060}
2061
2062inline APInt operator|(APInt a, const APInt &b) {
2063 a |= b;
2064 return a;
2065}
2066
2067inline APInt operator|(const APInt &a, APInt &&b) {
2068 b |= a;
2069 return std::move(b);
2070}
2071
2072inline APInt operator|(APInt a, uint64_t RHS) {
2073 a |= RHS;
2074 return a;
2075}
2076
2077inline APInt operator|(uint64_t LHS, APInt b) {
2078 b |= LHS;
2079 return b;
2080}
2081
2082inline APInt operator^(APInt a, const APInt &b) {
2083 a ^= b;
2084 return a;
2085}
2086
2087inline APInt operator^(const APInt &a, APInt &&b) {
2088 b ^= a;
2089 return std::move(b);
2090}
2091
2092inline APInt operator^(APInt a, uint64_t RHS) {
2093 a ^= RHS;
2094 return a;
2095}
2096
2097inline APInt operator^(uint64_t LHS, APInt b) {
2098 b ^= LHS;
2099 return b;
2100}
2101
2102inline raw_ostream &operator<<(raw_ostream &OS, const APInt &I) {
2103 I.print(OS, true);
2104 return OS;
2105}
2106
2107inline APInt operator-(APInt v) {
2108 v.negate();
2109 return v;
2110}
2111
2112inline APInt operator+(APInt a, const APInt &b) {
2113 a += b;
2114 return a;
2115}
2116
2117inline APInt operator+(const APInt &a, APInt &&b) {
2118 b += a;
2119 return std::move(b);
2120}
2121
2122inline APInt operator+(APInt a, uint64_t RHS) {
2123 a += RHS;
2124 return a;
2125}
2126
2127inline APInt operator+(uint64_t LHS, APInt b) {
2128 b += LHS;
2129 return b;
2130}
2131
2132inline APInt operator-(APInt a, const APInt &b) {
2133 a -= b;
2134 return a;
2135}
2136
2137inline APInt operator-(const APInt &a, APInt &&b) {
2138 b.negate();
2139 b += a;
2140 return std::move(b);
2141}
2142
2143inline APInt operator-(APInt a, uint64_t RHS) {
2144 a -= RHS;
2145 return a;
2146}
2147
2148inline APInt operator-(uint64_t LHS, APInt b) {
2149 b.negate();
2150 b += LHS;
2151 return b;
2152}
2153
2154inline APInt operator*(APInt a, uint64_t RHS) {
2155 a *= RHS;
2156 return a;
2157}
2158
2159inline APInt operator*(uint64_t LHS, APInt b) {
2160 b *= LHS;
2161 return b;
2162}
2163
2164
2165namespace APIntOps {
2166
2167/// Determine the smaller of two APInts considered to be signed.
2168inline const APInt &smin(const APInt &A, const APInt &B) {
2169 return A.slt(B) ? A : B;
2170}
2171
2172/// Determine the larger of two APInts considered to be signed.
2173inline const APInt &smax(const APInt &A, const APInt &B) {
2174 return A.sgt(B) ? A : B;
2175}
2176
2177/// Determine the smaller of two APInts considered to be unsigned.
2178inline const APInt &umin(const APInt &A, const APInt &B) {
2179 return A.ult(B) ? A : B;
2180}
2181
2182/// Determine the larger of two APInts considered to be unsigned.
2183inline const APInt &umax(const APInt &A, const APInt &B) {
2184 return A.ugt(B) ? A : B;
2185}
2186
2187/// Compute GCD of two unsigned APInt values.
2188///
2189/// This function returns the greatest common divisor of the two APInt values
2190/// using Stein's algorithm.
2191///
2192/// \returns the greatest common divisor of A and B.
2193APInt GreatestCommonDivisor(APInt A, APInt B);
2194
2195/// Converts the given APInt to a double value.
2196///
2197/// Treats the APInt as an unsigned value for conversion purposes.
2198inline double RoundAPIntToDouble(const APInt &APIVal) {
2199 return APIVal.roundToDouble();
2200}
2201
2202/// Converts the given APInt to a double value.
2203///
2204/// Treats the APInt as a signed value for conversion purposes.
2205inline double RoundSignedAPIntToDouble(const APInt &APIVal) {
2206 return APIVal.signedRoundToDouble();
2207}
2208
2209/// Converts the given APInt to a float value.
2210inline float RoundAPIntToFloat(const APInt &APIVal) {
2211 return float(RoundAPIntToDouble(APIVal));
2212}
2213
2214/// Converts the given APInt to a float value.
2215///
2216/// Treats the APInt as a signed value for conversion purposes.
2217inline float RoundSignedAPIntToFloat(const APInt &APIVal) {
2218 return float(APIVal.signedRoundToDouble());
2219}
2220
2221/// Converts the given double value into a APInt.
2222///
2223/// This function convert a double value to an APInt value.
2224APInt RoundDoubleToAPInt(double Double, unsigned width);
2225
2226/// Converts a float value into a APInt.
2227///
2228/// Converts a float value into an APInt value.
2229inline APInt RoundFloatToAPInt(float Float, unsigned width) {
2230 return RoundDoubleToAPInt(double(Float), width);
2231}
2232
2233/// Return A unsign-divided by B, rounded by the given rounding mode.
2234APInt RoundingUDiv(const APInt &A, const APInt &B, APInt::Rounding RM);
2235
2236/// Return A sign-divided by B, rounded by the given rounding mode.
2237APInt RoundingSDiv(const APInt &A, const APInt &B, APInt::Rounding RM);
2238
2239/// Let q(n) = An^2 + Bn + C, and BW = bit width of the value range
2240/// (e.g. 32 for i32).
2241/// This function finds the smallest number n, such that
2242/// (a) n >= 0 and q(n) = 0, or
2243/// (b) n >= 1 and q(n-1) and q(n), when evaluated in the set of all
2244/// integers, belong to two different intervals [Rk, Rk+R),
2245/// where R = 2^BW, and k is an integer.
2246/// The idea here is to find when q(n) "overflows" 2^BW, while at the
2247/// same time "allowing" subtraction. In unsigned modulo arithmetic a
2248/// subtraction (treated as addition of negated numbers) would always
2249/// count as an overflow, but here we want to allow values to decrease
2250/// and increase as long as they are within the same interval.
2251/// Specifically, adding of two negative numbers should not cause an
2252/// overflow (as long as the magnitude does not exceed the bit width).
2253/// On the other hand, given a positive number, adding a negative
2254/// number to it can give a negative result, which would cause the
2255/// value to go from [-2^BW, 0) to [0, 2^BW). In that sense, zero is
2256/// treated as a special case of an overflow.
2257///
2258/// This function returns None if after finding k that minimizes the
2259/// positive solution to q(n) = kR, both solutions are contained between
2260/// two consecutive integers.
2261///
2262/// There are cases where q(n) > T, and q(n+1) < T (assuming evaluation
2263/// in arithmetic modulo 2^BW, and treating the values as signed) by the
2264/// virtue of *signed* overflow. This function will *not* find such an n,
2265/// however it may find a value of n satisfying the inequalities due to
2266/// an *unsigned* overflow (if the values are treated as unsigned).
2267/// To find a solution for a signed overflow, treat it as a problem of
2268/// finding an unsigned overflow with a range with of BW-1.
2269///
2270/// The returned value may have a different bit width from the input
2271/// coefficients.
2272Optional<APInt> SolveQuadraticEquationWrap(APInt A, APInt B, APInt C,
2273 unsigned RangeWidth);
2274
2275/// Compare two values, and if they are different, return the position of the
2276/// most significant bit that is different in the values.
2277Optional<unsigned> GetMostSignificantDifferentBit(const APInt &A,
2278 const APInt &B);
2279
2280} // End of APIntOps namespace
2281
2282// See friend declaration above. This additional declaration is required in
2283// order to compile LLVM with IBM xlC compiler.
2284hash_code hash_value(const APInt &Arg);
2285
2286/// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
2287/// with the integer held in IntVal.
2288void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst, unsigned StoreBytes);
2289
2290/// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
2291/// from Src into IntVal, which is assumed to be wide enough and to hold zero.
2292void LoadIntFromMemory(APInt &IntVal, const uint8_t *Src, unsigned LoadBytes);
2293
2294/// Provide DenseMapInfo for APInt.
2295template <> struct DenseMapInfo<APInt> {
2296 static inline APInt getEmptyKey() {
2297 APInt V(nullptr, 0);
2298 V.U.VAL = 0;
2299 return V;
2300 }
2301
2302 static inline APInt getTombstoneKey() {
2303 APInt V(nullptr, 0);
2304 V.U.VAL = 1;
2305 return V;
2306 }
2307
2308 static unsigned getHashValue(const APInt &Key);
2309
2310 static bool isEqual(const APInt &LHS, const APInt &RHS) {
2311 return LHS.getBitWidth() == RHS.getBitWidth() && LHS == RHS;
2312 }
2313};
2314
2315} // namespace llvm
2316
2317#endif