LLVM 19.0.0git
InstCombineLoadStoreAlloca.cpp
Go to the documentation of this file.
1//===- InstCombineLoadStoreAlloca.cpp -------------------------------------===//
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 file implements the visit functions for load, store and alloca.
10//
11//===----------------------------------------------------------------------===//
12
13#include "InstCombineInternal.h"
14#include "llvm/ADT/MapVector.h"
16#include "llvm/ADT/Statistic.h"
18#include "llvm/Analysis/Loads.h"
19#include "llvm/IR/DataLayout.h"
22#include "llvm/IR/LLVMContext.h"
26using namespace llvm;
27using namespace PatternMatch;
28
29#define DEBUG_TYPE "instcombine"
30
31STATISTIC(NumDeadStore, "Number of dead stores eliminated");
32STATISTIC(NumGlobalCopies, "Number of allocas copied from constant global");
33
35 "instcombine-max-copied-from-constant-users", cl::init(300),
36 cl::desc("Maximum users to visit in copy from constant transform"),
38
39namespace llvm {
41 "enable-infer-alignment-pass", cl::init(true), cl::Hidden, cl::ZeroOrMore,
42 cl::desc("Enable the InferAlignment pass, disabling alignment inference in "
43 "InstCombine"));
44}
45
46/// isOnlyCopiedFromConstantMemory - Recursively walk the uses of a (derived)
47/// pointer to an alloca. Ignore any reads of the pointer, return false if we
48/// see any stores or other unknown uses. If we see pointer arithmetic, keep
49/// track of whether it moves the pointer (with IsOffset) but otherwise traverse
50/// the uses. If we see a memcpy/memmove that targets an unoffseted pointer to
51/// the alloca, and if the source pointer is a pointer to a constant memory
52/// location, we can optimize this.
53static bool
55 MemTransferInst *&TheCopy,
57 // We track lifetime intrinsics as we encounter them. If we decide to go
58 // ahead and replace the value with the memory location, this lets the caller
59 // quickly eliminate the markers.
60
61 using ValueAndIsOffset = PointerIntPair<Value *, 1, bool>;
64 Worklist.emplace_back(V, false);
65 while (!Worklist.empty()) {
66 ValueAndIsOffset Elem = Worklist.pop_back_val();
67 if (!Visited.insert(Elem).second)
68 continue;
69 if (Visited.size() > MaxCopiedFromConstantUsers)
70 return false;
71
72 const auto [Value, IsOffset] = Elem;
73 for (auto &U : Value->uses()) {
74 auto *I = cast<Instruction>(U.getUser());
75
76 if (auto *LI = dyn_cast<LoadInst>(I)) {
77 // Ignore non-volatile loads, they are always ok.
78 if (!LI->isSimple()) return false;
79 continue;
80 }
81
82 if (isa<PHINode, SelectInst>(I)) {
83 // We set IsOffset=true, to forbid the memcpy from occurring after the
84 // phi: If one of the phi operands is not based on the alloca, we
85 // would incorrectly omit a write.
86 Worklist.emplace_back(I, true);
87 continue;
88 }
89 if (isa<BitCastInst, AddrSpaceCastInst>(I)) {
90 // If uses of the bitcast are ok, we are ok.
91 Worklist.emplace_back(I, IsOffset);
92 continue;
93 }
94 if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
95 // If the GEP has all zero indices, it doesn't offset the pointer. If it
96 // doesn't, it does.
97 Worklist.emplace_back(I, IsOffset || !GEP->hasAllZeroIndices());
98 continue;
99 }
100
101 if (auto *Call = dyn_cast<CallBase>(I)) {
102 // If this is the function being called then we treat it like a load and
103 // ignore it.
104 if (Call->isCallee(&U))
105 continue;
106
107 unsigned DataOpNo = Call->getDataOperandNo(&U);
108 bool IsArgOperand = Call->isArgOperand(&U);
109
110 // Inalloca arguments are clobbered by the call.
111 if (IsArgOperand && Call->isInAllocaArgument(DataOpNo))
112 return false;
113
114 // If this call site doesn't modify the memory, then we know it is just
115 // a load (but one that potentially returns the value itself), so we can
116 // ignore it if we know that the value isn't captured.
117 bool NoCapture = Call->doesNotCapture(DataOpNo);
118 if ((Call->onlyReadsMemory() && (Call->use_empty() || NoCapture)) ||
119 (Call->onlyReadsMemory(DataOpNo) && NoCapture))
120 continue;
121
122 // If this is being passed as a byval argument, the caller is making a
123 // copy, so it is only a read of the alloca.
124 if (IsArgOperand && Call->isByValArgument(DataOpNo))
125 continue;
126 }
127
128 // Lifetime intrinsics can be handled by the caller.
129 if (I->isLifetimeStartOrEnd()) {
130 assert(I->use_empty() && "Lifetime markers have no result to use!");
131 ToDelete.push_back(I);
132 continue;
133 }
134
135 // If this is isn't our memcpy/memmove, reject it as something we can't
136 // handle.
137 MemTransferInst *MI = dyn_cast<MemTransferInst>(I);
138 if (!MI)
139 return false;
140
141 // If the transfer is volatile, reject it.
142 if (MI->isVolatile())
143 return false;
144
145 // If the transfer is using the alloca as a source of the transfer, then
146 // ignore it since it is a load (unless the transfer is volatile).
147 if (U.getOperandNo() == 1)
148 continue;
149
150 // If we already have seen a copy, reject the second one.
151 if (TheCopy) return false;
152
153 // If the pointer has been offset from the start of the alloca, we can't
154 // safely handle this.
155 if (IsOffset) return false;
156
157 // If the memintrinsic isn't using the alloca as the dest, reject it.
158 if (U.getOperandNo() != 0) return false;
159
160 // If the source of the memcpy/move is not constant, reject it.
161 if (isModSet(AA->getModRefInfoMask(MI->getSource())))
162 return false;
163
164 // Otherwise, the transform is safe. Remember the copy instruction.
165 TheCopy = MI;
166 }
167 }
168 return true;
169}
170
171/// isOnlyCopiedFromConstantMemory - Return true if the specified alloca is only
172/// modified by a copy from a constant memory location. If we can prove this, we
173/// can replace any uses of the alloca with uses of the memory location
174/// directly.
175static MemTransferInst *
177 AllocaInst *AI,
179 MemTransferInst *TheCopy = nullptr;
180 if (isOnlyCopiedFromConstantMemory(AA, AI, TheCopy, ToDelete))
181 return TheCopy;
182 return nullptr;
183}
184
185/// Returns true if V is dereferenceable for size of alloca.
186static bool isDereferenceableForAllocaSize(const Value *V, const AllocaInst *AI,
187 const DataLayout &DL) {
188 if (AI->isArrayAllocation())
189 return false;
190 uint64_t AllocaSize = DL.getTypeStoreSize(AI->getAllocatedType());
191 if (!AllocaSize)
192 return false;
194 APInt(64, AllocaSize), DL);
195}
196
198 AllocaInst &AI, DominatorTree &DT) {
199 // Check for array size of 1 (scalar allocation).
200 if (!AI.isArrayAllocation()) {
201 // i32 1 is the canonical array size for scalar allocations.
202 if (AI.getArraySize()->getType()->isIntegerTy(32))
203 return nullptr;
204
205 // Canonicalize it.
206 return IC.replaceOperand(AI, 0, IC.Builder.getInt32(1));
207 }
208
209 // Convert: alloca Ty, C - where C is a constant != 1 into: alloca [C x Ty], 1
210 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
211 if (C->getValue().getActiveBits() <= 64) {
212 Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
213 AllocaInst *New = IC.Builder.CreateAlloca(NewTy, AI.getAddressSpace(),
214 nullptr, AI.getName());
215 New->setAlignment(AI.getAlign());
216 New->setUsedWithInAlloca(AI.isUsedWithInAlloca());
217
218 replaceAllDbgUsesWith(AI, *New, *New, DT);
219 return IC.replaceInstUsesWith(AI, New);
220 }
221 }
222
223 if (isa<UndefValue>(AI.getArraySize()))
225
226 // Ensure that the alloca array size argument has type equal to the offset
227 // size of the alloca() pointer, which, in the tyical case, is intptr_t,
228 // so that any casting is exposed early.
229 Type *PtrIdxTy = IC.getDataLayout().getIndexType(AI.getType());
230 if (AI.getArraySize()->getType() != PtrIdxTy) {
231 Value *V = IC.Builder.CreateIntCast(AI.getArraySize(), PtrIdxTy, false);
232 return IC.replaceOperand(AI, 0, V);
233 }
234
235 return nullptr;
236}
237
238namespace {
239// If I and V are pointers in different address space, it is not allowed to
240// use replaceAllUsesWith since I and V have different types. A
241// non-target-specific transformation should not use addrspacecast on V since
242// the two address space may be disjoint depending on target.
243//
244// This class chases down uses of the old pointer until reaching the load
245// instructions, then replaces the old pointer in the load instructions with
246// the new pointer. If during the chasing it sees bitcast or GEP, it will
247// create new bitcast or GEP with the new pointer and use them in the load
248// instruction.
249class PointerReplacer {
250public:
251 PointerReplacer(InstCombinerImpl &IC, Instruction &Root, unsigned SrcAS)
252 : IC(IC), Root(Root), FromAS(SrcAS) {}
253
254 bool collectUsers();
255 void replacePointer(Value *V);
256
257private:
258 bool collectUsersRecursive(Instruction &I);
259 void replace(Instruction *I);
260 Value *getReplacement(Value *I);
261 bool isAvailable(Instruction *I) const {
262 return I == &Root || Worklist.contains(I);
263 }
264
265 bool isEqualOrValidAddrSpaceCast(const Instruction *I,
266 unsigned FromAS) const {
267 const auto *ASC = dyn_cast<AddrSpaceCastInst>(I);
268 if (!ASC)
269 return false;
270 unsigned ToAS = ASC->getDestAddressSpace();
271 return (FromAS == ToAS) || IC.isValidAddrSpaceCast(FromAS, ToAS);
272 }
273
274 SmallPtrSet<Instruction *, 32> ValuesToRevisit;
278 Instruction &Root;
279 unsigned FromAS;
280};
281} // end anonymous namespace
282
283bool PointerReplacer::collectUsers() {
284 if (!collectUsersRecursive(Root))
285 return false;
286
287 // Ensure that all outstanding (indirect) users of I
288 // are inserted into the Worklist. Return false
289 // otherwise.
290 for (auto *Inst : ValuesToRevisit)
291 if (!Worklist.contains(Inst))
292 return false;
293 return true;
294}
295
296bool PointerReplacer::collectUsersRecursive(Instruction &I) {
297 for (auto *U : I.users()) {
298 auto *Inst = cast<Instruction>(&*U);
299 if (auto *Load = dyn_cast<LoadInst>(Inst)) {
300 if (Load->isVolatile())
301 return false;
302 Worklist.insert(Load);
303 } else if (auto *PHI = dyn_cast<PHINode>(Inst)) {
304 // All incoming values must be instructions for replacability
305 if (any_of(PHI->incoming_values(),
306 [](Value *V) { return !isa<Instruction>(V); }))
307 return false;
308
309 // If at least one incoming value of the PHI is not in Worklist,
310 // store the PHI for revisiting and skip this iteration of the
311 // loop.
312 if (any_of(PHI->incoming_values(), [this](Value *V) {
313 return !isAvailable(cast<Instruction>(V));
314 })) {
315 ValuesToRevisit.insert(Inst);
316 continue;
317 }
318
319 Worklist.insert(PHI);
320 if (!collectUsersRecursive(*PHI))
321 return false;
322 } else if (auto *SI = dyn_cast<SelectInst>(Inst)) {
323 if (!isa<Instruction>(SI->getTrueValue()) ||
324 !isa<Instruction>(SI->getFalseValue()))
325 return false;
326
327 if (!isAvailable(cast<Instruction>(SI->getTrueValue())) ||
328 !isAvailable(cast<Instruction>(SI->getFalseValue()))) {
329 ValuesToRevisit.insert(Inst);
330 continue;
331 }
332 Worklist.insert(SI);
333 if (!collectUsersRecursive(*SI))
334 return false;
335 } else if (isa<GetElementPtrInst>(Inst)) {
336 Worklist.insert(Inst);
337 if (!collectUsersRecursive(*Inst))
338 return false;
339 } else if (auto *MI = dyn_cast<MemTransferInst>(Inst)) {
340 if (MI->isVolatile())
341 return false;
342 Worklist.insert(Inst);
343 } else if (isEqualOrValidAddrSpaceCast(Inst, FromAS)) {
344 Worklist.insert(Inst);
345 if (!collectUsersRecursive(*Inst))
346 return false;
347 } else if (Inst->isLifetimeStartOrEnd()) {
348 continue;
349 } else {
350 // TODO: For arbitrary uses with address space mismatches, should we check
351 // if we can introduce a valid addrspacecast?
352 LLVM_DEBUG(dbgs() << "Cannot handle pointer user: " << *U << '\n');
353 return false;
354 }
355 }
356
357 return true;
358}
359
360Value *PointerReplacer::getReplacement(Value *V) { return WorkMap.lookup(V); }
361
362void PointerReplacer::replace(Instruction *I) {
363 if (getReplacement(I))
364 return;
365
366 if (auto *LT = dyn_cast<LoadInst>(I)) {
367 auto *V = getReplacement(LT->getPointerOperand());
368 assert(V && "Operand not replaced");
369 auto *NewI = new LoadInst(LT->getType(), V, "", LT->isVolatile(),
370 LT->getAlign(), LT->getOrdering(),
371 LT->getSyncScopeID());
372 NewI->takeName(LT);
373 copyMetadataForLoad(*NewI, *LT);
374
375 IC.InsertNewInstWith(NewI, LT->getIterator());
376 IC.replaceInstUsesWith(*LT, NewI);
377 WorkMap[LT] = NewI;
378 } else if (auto *PHI = dyn_cast<PHINode>(I)) {
379 Type *NewTy = getReplacement(PHI->getIncomingValue(0))->getType();
380 auto *NewPHI = PHINode::Create(NewTy, PHI->getNumIncomingValues(),
381 PHI->getName(), PHI->getIterator());
382 for (unsigned int I = 0; I < PHI->getNumIncomingValues(); ++I)
383 NewPHI->addIncoming(getReplacement(PHI->getIncomingValue(I)),
384 PHI->getIncomingBlock(I));
385 WorkMap[PHI] = NewPHI;
386 } else if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
387 auto *V = getReplacement(GEP->getPointerOperand());
388 assert(V && "Operand not replaced");
389 SmallVector<Value *, 8> Indices(GEP->indices());
390 auto *NewI =
391 GetElementPtrInst::Create(GEP->getSourceElementType(), V, Indices);
392 IC.InsertNewInstWith(NewI, GEP->getIterator());
393 NewI->takeName(GEP);
394 NewI->setNoWrapFlags(GEP->getNoWrapFlags());
395 WorkMap[GEP] = NewI;
396 } else if (auto *SI = dyn_cast<SelectInst>(I)) {
397 auto *NewSI = SelectInst::Create(
398 SI->getCondition(), getReplacement(SI->getTrueValue()),
399 getReplacement(SI->getFalseValue()), SI->getName(), nullptr, SI);
400 IC.InsertNewInstWith(NewSI, SI->getIterator());
401 NewSI->takeName(SI);
402 WorkMap[SI] = NewSI;
403 } else if (auto *MemCpy = dyn_cast<MemTransferInst>(I)) {
404 auto *DestV = MemCpy->getRawDest();
405 auto *SrcV = MemCpy->getRawSource();
406
407 if (auto *DestReplace = getReplacement(DestV))
408 DestV = DestReplace;
409 if (auto *SrcReplace = getReplacement(SrcV))
410 SrcV = SrcReplace;
411
412 IC.Builder.SetInsertPoint(MemCpy);
413 auto *NewI = IC.Builder.CreateMemTransferInst(
414 MemCpy->getIntrinsicID(), DestV, MemCpy->getDestAlign(), SrcV,
415 MemCpy->getSourceAlign(), MemCpy->getLength(), MemCpy->isVolatile());
416 AAMDNodes AAMD = MemCpy->getAAMetadata();
417 if (AAMD)
418 NewI->setAAMetadata(AAMD);
419
420 IC.eraseInstFromFunction(*MemCpy);
421 WorkMap[MemCpy] = NewI;
422 } else if (auto *ASC = dyn_cast<AddrSpaceCastInst>(I)) {
423 auto *V = getReplacement(ASC->getPointerOperand());
424 assert(V && "Operand not replaced");
425 assert(isEqualOrValidAddrSpaceCast(
426 ASC, V->getType()->getPointerAddressSpace()) &&
427 "Invalid address space cast!");
428
429 if (V->getType()->getPointerAddressSpace() !=
430 ASC->getType()->getPointerAddressSpace()) {
431 auto *NewI = new AddrSpaceCastInst(V, ASC->getType(), "");
432 NewI->takeName(ASC);
433 IC.InsertNewInstWith(NewI, ASC->getIterator());
434 WorkMap[ASC] = NewI;
435 } else {
436 WorkMap[ASC] = V;
437 }
438
439 } else {
440 llvm_unreachable("should never reach here");
441 }
442}
443
444void PointerReplacer::replacePointer(Value *V) {
445#ifndef NDEBUG
446 auto *PT = cast<PointerType>(Root.getType());
447 auto *NT = cast<PointerType>(V->getType());
448 assert(PT != NT && "Invalid usage");
449#endif
450 WorkMap[&Root] = V;
451
452 for (Instruction *Workitem : Worklist)
453 replace(Workitem);
454}
455
457 if (auto *I = simplifyAllocaArraySize(*this, AI, DT))
458 return I;
459
460 if (AI.getAllocatedType()->isSized()) {
461 // Move all alloca's of zero byte objects to the entry block and merge them
462 // together. Note that we only do this for alloca's, because malloc should
463 // allocate and return a unique pointer, even for a zero byte allocation.
465 // For a zero sized alloca there is no point in doing an array allocation.
466 // This is helpful if the array size is a complicated expression not used
467 // elsewhere.
468 if (AI.isArrayAllocation())
469 return replaceOperand(AI, 0,
470 ConstantInt::get(AI.getArraySize()->getType(), 1));
471
472 // Get the first instruction in the entry block.
473 BasicBlock &EntryBlock = AI.getParent()->getParent()->getEntryBlock();
474 Instruction *FirstInst = EntryBlock.getFirstNonPHIOrDbg();
475 if (FirstInst != &AI) {
476 // If the entry block doesn't start with a zero-size alloca then move
477 // this one to the start of the entry block. There is no problem with
478 // dominance as the array size was forced to a constant earlier already.
479 AllocaInst *EntryAI = dyn_cast<AllocaInst>(FirstInst);
480 if (!EntryAI || !EntryAI->getAllocatedType()->isSized() ||
482 .getKnownMinValue() != 0) {
483 AI.moveBefore(FirstInst);
484 return &AI;
485 }
486
487 // Replace this zero-sized alloca with the one at the start of the entry
488 // block after ensuring that the address will be aligned enough for both
489 // types.
490 const Align MaxAlign = std::max(EntryAI->getAlign(), AI.getAlign());
491 EntryAI->setAlignment(MaxAlign);
492 return replaceInstUsesWith(AI, EntryAI);
493 }
494 }
495 }
496
497 // Check to see if this allocation is only modified by a memcpy/memmove from
498 // a memory location whose alignment is equal to or exceeds that of the
499 // allocation. If this is the case, we can change all users to use the
500 // constant memory location instead. This is commonly produced by the CFE by
501 // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
502 // is only subsequently read.
504 if (MemTransferInst *Copy = isOnlyCopiedFromConstantMemory(AA, &AI, ToDelete)) {
505 Value *TheSrc = Copy->getSource();
506 Align AllocaAlign = AI.getAlign();
507 Align SourceAlign = getOrEnforceKnownAlignment(
508 TheSrc, AllocaAlign, DL, &AI, &AC, &DT);
509 if (AllocaAlign <= SourceAlign &&
510 isDereferenceableForAllocaSize(TheSrc, &AI, DL) &&
511 !isa<Instruction>(TheSrc)) {
512 // FIXME: Can we sink instructions without violating dominance when TheSrc
513 // is an instruction instead of a constant or argument?
514 LLVM_DEBUG(dbgs() << "Found alloca equal to global: " << AI << '\n');
515 LLVM_DEBUG(dbgs() << " memcpy = " << *Copy << '\n');
516 unsigned SrcAddrSpace = TheSrc->getType()->getPointerAddressSpace();
517 if (AI.getAddressSpace() == SrcAddrSpace) {
518 for (Instruction *Delete : ToDelete)
519 eraseInstFromFunction(*Delete);
520
521 Instruction *NewI = replaceInstUsesWith(AI, TheSrc);
523 ++NumGlobalCopies;
524 return NewI;
525 }
526
527 PointerReplacer PtrReplacer(*this, AI, SrcAddrSpace);
528 if (PtrReplacer.collectUsers()) {
529 for (Instruction *Delete : ToDelete)
530 eraseInstFromFunction(*Delete);
531
532 PtrReplacer.replacePointer(TheSrc);
533 ++NumGlobalCopies;
534 }
535 }
536 }
537
538 // At last, use the generic allocation site handler to aggressively remove
539 // unused allocas.
540 return visitAllocSite(AI);
541}
542
543// Are we allowed to form a atomic load or store of this type?
544static bool isSupportedAtomicType(Type *Ty) {
545 return Ty->isIntOrPtrTy() || Ty->isFloatingPointTy();
546}
547
548/// Helper to combine a load to a new type.
549///
550/// This just does the work of combining a load to a new type. It handles
551/// metadata, etc., and returns the new instruction. The \c NewTy should be the
552/// loaded *value* type. This will convert it to a pointer, cast the operand to
553/// that pointer type, load it, etc.
554///
555/// Note that this will create all of the instructions with whatever insert
556/// point the \c InstCombinerImpl currently is using.
558 const Twine &Suffix) {
559 assert((!LI.isAtomic() || isSupportedAtomicType(NewTy)) &&
560 "can't fold an atomic load to requested type");
561
562 LoadInst *NewLoad =
563 Builder.CreateAlignedLoad(NewTy, LI.getPointerOperand(), LI.getAlign(),
564 LI.isVolatile(), LI.getName() + Suffix);
565 NewLoad->setAtomic(LI.getOrdering(), LI.getSyncScopeID());
566 copyMetadataForLoad(*NewLoad, LI);
567 return NewLoad;
568}
569
570/// Combine a store to a new type.
571///
572/// Returns the newly created store instruction.
574 Value *V) {
575 assert((!SI.isAtomic() || isSupportedAtomicType(V->getType())) &&
576 "can't fold an atomic store of requested type");
577
578 Value *Ptr = SI.getPointerOperand();
580 SI.getAllMetadata(MD);
581
582 StoreInst *NewStore =
583 IC.Builder.CreateAlignedStore(V, Ptr, SI.getAlign(), SI.isVolatile());
584 NewStore->setAtomic(SI.getOrdering(), SI.getSyncScopeID());
585 for (const auto &MDPair : MD) {
586 unsigned ID = MDPair.first;
587 MDNode *N = MDPair.second;
588 // Note, essentially every kind of metadata should be preserved here! This
589 // routine is supposed to clone a store instruction changing *only its
590 // type*. The only metadata it makes sense to drop is metadata which is
591 // invalidated when the pointer type changes. This should essentially
592 // never be the case in LLVM, but we explicitly switch over only known
593 // metadata to be conservatively correct. If you are adding metadata to
594 // LLVM which pertains to stores, you almost certainly want to add it
595 // here.
596 switch (ID) {
597 case LLVMContext::MD_dbg:
598 case LLVMContext::MD_DIAssignID:
599 case LLVMContext::MD_tbaa:
600 case LLVMContext::MD_prof:
601 case LLVMContext::MD_fpmath:
602 case LLVMContext::MD_tbaa_struct:
603 case LLVMContext::MD_alias_scope:
604 case LLVMContext::MD_noalias:
605 case LLVMContext::MD_nontemporal:
606 case LLVMContext::MD_mem_parallel_loop_access:
607 case LLVMContext::MD_access_group:
608 // All of these directly apply.
609 NewStore->setMetadata(ID, N);
610 break;
611 case LLVMContext::MD_invariant_load:
612 case LLVMContext::MD_nonnull:
613 case LLVMContext::MD_noundef:
614 case LLVMContext::MD_range:
615 case LLVMContext::MD_align:
616 case LLVMContext::MD_dereferenceable:
617 case LLVMContext::MD_dereferenceable_or_null:
618 // These don't apply for stores.
619 break;
620 }
621 }
622
623 return NewStore;
624}
625
626/// Combine loads to match the type of their uses' value after looking
627/// through intervening bitcasts.
628///
629/// The core idea here is that if the result of a load is used in an operation,
630/// we should load the type most conducive to that operation. For example, when
631/// loading an integer and converting that immediately to a pointer, we should
632/// instead directly load a pointer.
633///
634/// However, this routine must never change the width of a load or the number of
635/// loads as that would introduce a semantic change. This combine is expected to
636/// be a semantic no-op which just allows loads to more closely model the types
637/// of their consuming operations.
638///
639/// Currently, we also refuse to change the precise type used for an atomic load
640/// or a volatile load. This is debatable, and might be reasonable to change
641/// later. However, it is risky in case some backend or other part of LLVM is
642/// relying on the exact type loaded to select appropriate atomic operations.
644 LoadInst &Load) {
645 // FIXME: We could probably with some care handle both volatile and ordered
646 // atomic loads here but it isn't clear that this is important.
647 if (!Load.isUnordered())
648 return nullptr;
649
650 if (Load.use_empty())
651 return nullptr;
652
653 // swifterror values can't be bitcasted.
654 if (Load.getPointerOperand()->isSwiftError())
655 return nullptr;
656
657 // Fold away bit casts of the loaded value by loading the desired type.
658 // Note that we should not do this for pointer<->integer casts,
659 // because that would result in type punning.
660 if (Load.hasOneUse()) {
661 // Don't transform when the type is x86_amx, it makes the pass that lower
662 // x86_amx type happy.
663 Type *LoadTy = Load.getType();
664 if (auto *BC = dyn_cast<BitCastInst>(Load.user_back())) {
665 assert(!LoadTy->isX86_AMXTy() && "Load from x86_amx* should not happen!");
666 if (BC->getType()->isX86_AMXTy())
667 return nullptr;
668 }
669
670 if (auto *CastUser = dyn_cast<CastInst>(Load.user_back())) {
671 Type *DestTy = CastUser->getDestTy();
672 if (CastUser->isNoopCast(IC.getDataLayout()) &&
673 LoadTy->isPtrOrPtrVectorTy() == DestTy->isPtrOrPtrVectorTy() &&
674 (!Load.isAtomic() || isSupportedAtomicType(DestTy))) {
675 LoadInst *NewLoad = IC.combineLoadToNewType(Load, DestTy);
676 CastUser->replaceAllUsesWith(NewLoad);
677 IC.eraseInstFromFunction(*CastUser);
678 return &Load;
679 }
680 }
681 }
682
683 // FIXME: We should also canonicalize loads of vectors when their elements are
684 // cast to other types.
685 return nullptr;
686}
687
689 // FIXME: We could probably with some care handle both volatile and atomic
690 // stores here but it isn't clear that this is important.
691 if (!LI.isSimple())
692 return nullptr;
693
694 Type *T = LI.getType();
695 if (!T->isAggregateType())
696 return nullptr;
697
698 StringRef Name = LI.getName();
699
700 if (auto *ST = dyn_cast<StructType>(T)) {
701 // If the struct only have one element, we unpack.
702 auto NumElements = ST->getNumElements();
703 if (NumElements == 1) {
704 LoadInst *NewLoad = IC.combineLoadToNewType(LI, ST->getTypeAtIndex(0U),
705 ".unpack");
706 NewLoad->setAAMetadata(LI.getAAMetadata());
708 PoisonValue::get(T), NewLoad, 0, Name));
709 }
710
711 // We don't want to break loads with padding here as we'd loose
712 // the knowledge that padding exists for the rest of the pipeline.
713 const DataLayout &DL = IC.getDataLayout();
714 auto *SL = DL.getStructLayout(ST);
715
716 // Don't unpack for structure with scalable vector.
717 if (SL->getSizeInBits().isScalable())
718 return nullptr;
719
720 if (SL->hasPadding())
721 return nullptr;
722
723 const auto Align = LI.getAlign();
724 auto *Addr = LI.getPointerOperand();
725 auto *IdxType = Type::getInt32Ty(T->getContext());
726 auto *Zero = ConstantInt::get(IdxType, 0);
727
729 for (unsigned i = 0; i < NumElements; i++) {
730 Value *Indices[2] = {
731 Zero,
732 ConstantInt::get(IdxType, i),
733 };
734 auto *Ptr = IC.Builder.CreateInBoundsGEP(ST, Addr, ArrayRef(Indices),
735 Name + ".elt");
736 auto *L = IC.Builder.CreateAlignedLoad(
737 ST->getElementType(i), Ptr,
738 commonAlignment(Align, SL->getElementOffset(i)), Name + ".unpack");
739 // Propagate AA metadata. It'll still be valid on the narrowed load.
740 L->setAAMetadata(LI.getAAMetadata());
741 V = IC.Builder.CreateInsertValue(V, L, i);
742 }
743
744 V->setName(Name);
745 return IC.replaceInstUsesWith(LI, V);
746 }
747
748 if (auto *AT = dyn_cast<ArrayType>(T)) {
749 auto *ET = AT->getElementType();
750 auto NumElements = AT->getNumElements();
751 if (NumElements == 1) {
752 LoadInst *NewLoad = IC.combineLoadToNewType(LI, ET, ".unpack");
753 NewLoad->setAAMetadata(LI.getAAMetadata());
755 PoisonValue::get(T), NewLoad, 0, Name));
756 }
757
758 // Bail out if the array is too large. Ideally we would like to optimize
759 // arrays of arbitrary size but this has a terrible impact on compile time.
760 // The threshold here is chosen arbitrarily, maybe needs a little bit of
761 // tuning.
762 if (NumElements > IC.MaxArraySizeForCombine)
763 return nullptr;
764
765 const DataLayout &DL = IC.getDataLayout();
766 TypeSize EltSize = DL.getTypeAllocSize(ET);
767 const auto Align = LI.getAlign();
768
769 auto *Addr = LI.getPointerOperand();
770 auto *IdxType = Type::getInt64Ty(T->getContext());
771 auto *Zero = ConstantInt::get(IdxType, 0);
772
775 for (uint64_t i = 0; i < NumElements; i++) {
776 Value *Indices[2] = {
777 Zero,
778 ConstantInt::get(IdxType, i),
779 };
780 auto *Ptr = IC.Builder.CreateInBoundsGEP(AT, Addr, ArrayRef(Indices),
781 Name + ".elt");
782 auto EltAlign = commonAlignment(Align, Offset.getKnownMinValue());
783 auto *L = IC.Builder.CreateAlignedLoad(AT->getElementType(), Ptr,
784 EltAlign, Name + ".unpack");
785 L->setAAMetadata(LI.getAAMetadata());
786 V = IC.Builder.CreateInsertValue(V, L, i);
787 Offset += EltSize;
788 }
789
790 V->setName(Name);
791 return IC.replaceInstUsesWith(LI, V);
792 }
793
794 return nullptr;
795}
796
797// If we can determine that all possible objects pointed to by the provided
798// pointer value are, not only dereferenceable, but also definitively less than
799// or equal to the provided maximum size, then return true. Otherwise, return
800// false (constant global values and allocas fall into this category).
801//
802// FIXME: This should probably live in ValueTracking (or similar).
804 const DataLayout &DL) {
806 SmallVector<Value *, 4> Worklist(1, V);
807
808 do {
809 Value *P = Worklist.pop_back_val();
810 P = P->stripPointerCasts();
811
812 if (!Visited.insert(P).second)
813 continue;
814
815 if (SelectInst *SI = dyn_cast<SelectInst>(P)) {
816 Worklist.push_back(SI->getTrueValue());
817 Worklist.push_back(SI->getFalseValue());
818 continue;
819 }
820
821 if (PHINode *PN = dyn_cast<PHINode>(P)) {
822 append_range(Worklist, PN->incoming_values());
823 continue;
824 }
825
826 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(P)) {
827 if (GA->isInterposable())
828 return false;
829 Worklist.push_back(GA->getAliasee());
830 continue;
831 }
832
833 // If we know how big this object is, and it is less than MaxSize, continue
834 // searching. Otherwise, return false.
835 if (AllocaInst *AI = dyn_cast<AllocaInst>(P)) {
836 if (!AI->getAllocatedType()->isSized())
837 return false;
838
839 ConstantInt *CS = dyn_cast<ConstantInt>(AI->getArraySize());
840 if (!CS)
841 return false;
842
843 TypeSize TS = DL.getTypeAllocSize(AI->getAllocatedType());
844 if (TS.isScalable())
845 return false;
846 // Make sure that, even if the multiplication below would wrap as an
847 // uint64_t, we still do the right thing.
848 if ((CS->getValue().zext(128) * APInt(128, TS.getFixedValue()))
849 .ugt(MaxSize))
850 return false;
851 continue;
852 }
853
854 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
855 if (!GV->hasDefinitiveInitializer() || !GV->isConstant())
856 return false;
857
858 uint64_t InitSize = DL.getTypeAllocSize(GV->getValueType());
859 if (InitSize > MaxSize)
860 return false;
861 continue;
862 }
863
864 return false;
865 } while (!Worklist.empty());
866
867 return true;
868}
869
870// If we're indexing into an object of a known size, and the outer index is
871// not a constant, but having any value but zero would lead to undefined
872// behavior, replace it with zero.
873//
874// For example, if we have:
875// @f.a = private unnamed_addr constant [1 x i32] [i32 12], align 4
876// ...
877// %arrayidx = getelementptr inbounds [1 x i32]* @f.a, i64 0, i64 %x
878// ... = load i32* %arrayidx, align 4
879// Then we know that we can replace %x in the GEP with i64 0.
880//
881// FIXME: We could fold any GEP index to zero that would cause UB if it were
882// not zero. Currently, we only handle the first such index. Also, we could
883// also search through non-zero constant indices if we kept track of the
884// offsets those indices implied.
886 GetElementPtrInst *GEPI, Instruction *MemI,
887 unsigned &Idx) {
888 if (GEPI->getNumOperands() < 2)
889 return false;
890
891 // Find the first non-zero index of a GEP. If all indices are zero, return
892 // one past the last index.
893 auto FirstNZIdx = [](const GetElementPtrInst *GEPI) {
894 unsigned I = 1;
895 for (unsigned IE = GEPI->getNumOperands(); I != IE; ++I) {
896 Value *V = GEPI->getOperand(I);
897 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
898 if (CI->isZero())
899 continue;
900
901 break;
902 }
903
904 return I;
905 };
906
907 // Skip through initial 'zero' indices, and find the corresponding pointer
908 // type. See if the next index is not a constant.
909 Idx = FirstNZIdx(GEPI);
910 if (Idx == GEPI->getNumOperands())
911 return false;
912 if (isa<Constant>(GEPI->getOperand(Idx)))
913 return false;
914
915 SmallVector<Value *, 4> Ops(GEPI->idx_begin(), GEPI->idx_begin() + Idx);
916 Type *SourceElementType = GEPI->getSourceElementType();
917 // Size information about scalable vectors is not available, so we cannot
918 // deduce whether indexing at n is undefined behaviour or not. Bail out.
919 if (SourceElementType->isScalableTy())
920 return false;
921
922 Type *AllocTy = GetElementPtrInst::getIndexedType(SourceElementType, Ops);
923 if (!AllocTy || !AllocTy->isSized())
924 return false;
925 const DataLayout &DL = IC.getDataLayout();
926 uint64_t TyAllocSize = DL.getTypeAllocSize(AllocTy).getFixedValue();
927
928 // If there are more indices after the one we might replace with a zero, make
929 // sure they're all non-negative. If any of them are negative, the overall
930 // address being computed might be before the base address determined by the
931 // first non-zero index.
932 auto IsAllNonNegative = [&]() {
933 for (unsigned i = Idx+1, e = GEPI->getNumOperands(); i != e; ++i) {
934 KnownBits Known = IC.computeKnownBits(GEPI->getOperand(i), 0, MemI);
935 if (Known.isNonNegative())
936 continue;
937 return false;
938 }
939
940 return true;
941 };
942
943 // FIXME: If the GEP is not inbounds, and there are extra indices after the
944 // one we'll replace, those could cause the address computation to wrap
945 // (rendering the IsAllNonNegative() check below insufficient). We can do
946 // better, ignoring zero indices (and other indices we can prove small
947 // enough not to wrap).
948 if (Idx+1 != GEPI->getNumOperands() && !GEPI->isInBounds())
949 return false;
950
951 // Note that isObjectSizeLessThanOrEq will return true only if the pointer is
952 // also known to be dereferenceable.
953 return isObjectSizeLessThanOrEq(GEPI->getOperand(0), TyAllocSize, DL) &&
954 IsAllNonNegative();
955}
956
957// If we're indexing into an object with a variable index for the memory
958// access, but the object has only one element, we can assume that the index
959// will always be zero. If we replace the GEP, return it.
961 Instruction &MemI) {
962 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Ptr)) {
963 unsigned Idx;
964 if (canReplaceGEPIdxWithZero(IC, GEPI, &MemI, Idx)) {
965 Instruction *NewGEPI = GEPI->clone();
966 NewGEPI->setOperand(Idx,
967 ConstantInt::get(GEPI->getOperand(Idx)->getType(), 0));
968 IC.InsertNewInstBefore(NewGEPI, GEPI->getIterator());
969 return NewGEPI;
970 }
971 }
972
973 return nullptr;
974}
975
977 if (NullPointerIsDefined(SI.getFunction(), SI.getPointerAddressSpace()))
978 return false;
979
980 auto *Ptr = SI.getPointerOperand();
981 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Ptr))
982 Ptr = GEPI->getOperand(0);
983 return (isa<ConstantPointerNull>(Ptr) &&
984 !NullPointerIsDefined(SI.getFunction(), SI.getPointerAddressSpace()));
985}
986
988 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
989 const Value *GEPI0 = GEPI->getOperand(0);
990 if (isa<ConstantPointerNull>(GEPI0) &&
991 !NullPointerIsDefined(LI.getFunction(), GEPI->getPointerAddressSpace()))
992 return true;
993 }
994 if (isa<UndefValue>(Op) ||
995 (isa<ConstantPointerNull>(Op) &&
997 return true;
998 return false;
999}
1000
1002 Value *Op = LI.getOperand(0);
1004 return replaceInstUsesWith(LI, Res);
1005
1006 // Try to canonicalize the loaded type.
1007 if (Instruction *Res = combineLoadToOperationType(*this, LI))
1008 return Res;
1009
1011 // Attempt to improve the alignment.
1012 Align KnownAlign = getOrEnforceKnownAlignment(
1013 Op, DL.getPrefTypeAlign(LI.getType()), DL, &LI, &AC, &DT);
1014 if (KnownAlign > LI.getAlign())
1015 LI.setAlignment(KnownAlign);
1016 }
1017
1018 // Replace GEP indices if possible.
1019 if (Instruction *NewGEPI = replaceGEPIdxWithZero(*this, Op, LI))
1020 return replaceOperand(LI, 0, NewGEPI);
1021
1022 if (Instruction *Res = unpackLoadToAggregate(*this, LI))
1023 return Res;
1024
1025 // Do really simple store-to-load forwarding and load CSE, to catch cases
1026 // where there are several consecutive memory accesses to the same location,
1027 // separated by a few arithmetic operations.
1028 bool IsLoadCSE = false;
1029 BatchAAResults BatchAA(*AA);
1030 if (Value *AvailableVal = FindAvailableLoadedValue(&LI, BatchAA, &IsLoadCSE)) {
1031 if (IsLoadCSE)
1032 combineMetadataForCSE(cast<LoadInst>(AvailableVal), &LI, false);
1033
1034 return replaceInstUsesWith(
1035 LI, Builder.CreateBitOrPointerCast(AvailableVal, LI.getType(),
1036 LI.getName() + ".cast"));
1037 }
1038
1039 // None of the following transforms are legal for volatile/ordered atomic
1040 // loads. Most of them do apply for unordered atomics.
1041 if (!LI.isUnordered()) return nullptr;
1042
1043 // load(gep null, ...) -> unreachable
1044 // load null/undef -> unreachable
1045 // TODO: Consider a target hook for valid address spaces for this xforms.
1048 return replaceInstUsesWith(LI, PoisonValue::get(LI.getType()));
1049 }
1050
1051 if (Op->hasOneUse()) {
1052 // Change select and PHI nodes to select values instead of addresses: this
1053 // helps alias analysis out a lot, allows many others simplifications, and
1054 // exposes redundancy in the code.
1055 //
1056 // Note that we cannot do the transformation unless we know that the
1057 // introduced loads cannot trap! Something like this is valid as long as
1058 // the condition is always false: load (select bool %C, int* null, int* %G),
1059 // but it would not be valid if we transformed it to load from null
1060 // unconditionally.
1061 //
1062 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
1063 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
1064 Align Alignment = LI.getAlign();
1065 if (isSafeToLoadUnconditionally(SI->getOperand(1), LI.getType(),
1066 Alignment, DL, SI) &&
1067 isSafeToLoadUnconditionally(SI->getOperand(2), LI.getType(),
1068 Alignment, DL, SI)) {
1069 LoadInst *V1 =
1070 Builder.CreateLoad(LI.getType(), SI->getOperand(1),
1071 SI->getOperand(1)->getName() + ".val");
1072 LoadInst *V2 =
1073 Builder.CreateLoad(LI.getType(), SI->getOperand(2),
1074 SI->getOperand(2)->getName() + ".val");
1075 assert(LI.isUnordered() && "implied by above");
1076 V1->setAlignment(Alignment);
1077 V1->setAtomic(LI.getOrdering(), LI.getSyncScopeID());
1078 V2->setAlignment(Alignment);
1079 V2->setAtomic(LI.getOrdering(), LI.getSyncScopeID());
1080 return SelectInst::Create(SI->getCondition(), V1, V2);
1081 }
1082
1083 // load (select (cond, null, P)) -> load P
1084 if (isa<ConstantPointerNull>(SI->getOperand(1)) &&
1085 !NullPointerIsDefined(SI->getFunction(),
1086 LI.getPointerAddressSpace()))
1087 return replaceOperand(LI, 0, SI->getOperand(2));
1088
1089 // load (select (cond, P, null)) -> load P
1090 if (isa<ConstantPointerNull>(SI->getOperand(2)) &&
1091 !NullPointerIsDefined(SI->getFunction(),
1092 LI.getPointerAddressSpace()))
1093 return replaceOperand(LI, 0, SI->getOperand(1));
1094 }
1095 }
1096 return nullptr;
1097}
1098
1099/// Look for extractelement/insertvalue sequence that acts like a bitcast.
1100///
1101/// \returns underlying value that was "cast", or nullptr otherwise.
1102///
1103/// For example, if we have:
1104///
1105/// %E0 = extractelement <2 x double> %U, i32 0
1106/// %V0 = insertvalue [2 x double] undef, double %E0, 0
1107/// %E1 = extractelement <2 x double> %U, i32 1
1108/// %V1 = insertvalue [2 x double] %V0, double %E1, 1
1109///
1110/// and the layout of a <2 x double> is isomorphic to a [2 x double],
1111/// then %V1 can be safely approximated by a conceptual "bitcast" of %U.
1112/// Note that %U may contain non-undef values where %V1 has undef.
1114 Value *U = nullptr;
1115 while (auto *IV = dyn_cast<InsertValueInst>(V)) {
1116 auto *E = dyn_cast<ExtractElementInst>(IV->getInsertedValueOperand());
1117 if (!E)
1118 return nullptr;
1119 auto *W = E->getVectorOperand();
1120 if (!U)
1121 U = W;
1122 else if (U != W)
1123 return nullptr;
1124 auto *CI = dyn_cast<ConstantInt>(E->getIndexOperand());
1125 if (!CI || IV->getNumIndices() != 1 || CI->getZExtValue() != *IV->idx_begin())
1126 return nullptr;
1127 V = IV->getAggregateOperand();
1128 }
1129 if (!match(V, m_Undef()) || !U)
1130 return nullptr;
1131
1132 auto *UT = cast<VectorType>(U->getType());
1133 auto *VT = V->getType();
1134 // Check that types UT and VT are bitwise isomorphic.
1135 const auto &DL = IC.getDataLayout();
1136 if (DL.getTypeStoreSizeInBits(UT) != DL.getTypeStoreSizeInBits(VT)) {
1137 return nullptr;
1138 }
1139 if (auto *AT = dyn_cast<ArrayType>(VT)) {
1140 if (AT->getNumElements() != cast<FixedVectorType>(UT)->getNumElements())
1141 return nullptr;
1142 } else {
1143 auto *ST = cast<StructType>(VT);
1144 if (ST->getNumElements() != cast<FixedVectorType>(UT)->getNumElements())
1145 return nullptr;
1146 for (const auto *EltT : ST->elements()) {
1147 if (EltT != UT->getElementType())
1148 return nullptr;
1149 }
1150 }
1151 return U;
1152}
1153
1154/// Combine stores to match the type of value being stored.
1155///
1156/// The core idea here is that the memory does not have any intrinsic type and
1157/// where we can we should match the type of a store to the type of value being
1158/// stored.
1159///
1160/// However, this routine must never change the width of a store or the number of
1161/// stores as that would introduce a semantic change. This combine is expected to
1162/// be a semantic no-op which just allows stores to more closely model the types
1163/// of their incoming values.
1164///
1165/// Currently, we also refuse to change the precise type used for an atomic or
1166/// volatile store. This is debatable, and might be reasonable to change later.
1167/// However, it is risky in case some backend or other part of LLVM is relying
1168/// on the exact type stored to select appropriate atomic operations.
1169///
1170/// \returns true if the store was successfully combined away. This indicates
1171/// the caller must erase the store instruction. We have to let the caller erase
1172/// the store instruction as otherwise there is no way to signal whether it was
1173/// combined or not: IC.EraseInstFromFunction returns a null pointer.
1175 // FIXME: We could probably with some care handle both volatile and ordered
1176 // atomic stores here but it isn't clear that this is important.
1177 if (!SI.isUnordered())
1178 return false;
1179
1180 // swifterror values can't be bitcasted.
1181 if (SI.getPointerOperand()->isSwiftError())
1182 return false;
1183
1184 Value *V = SI.getValueOperand();
1185
1186 // Fold away bit casts of the stored value by storing the original type.
1187 if (auto *BC = dyn_cast<BitCastInst>(V)) {
1188 assert(!BC->getType()->isX86_AMXTy() &&
1189 "store to x86_amx* should not happen!");
1190 V = BC->getOperand(0);
1191 // Don't transform when the type is x86_amx, it makes the pass that lower
1192 // x86_amx type happy.
1193 if (V->getType()->isX86_AMXTy())
1194 return false;
1195 if (!SI.isAtomic() || isSupportedAtomicType(V->getType())) {
1196 combineStoreToNewValue(IC, SI, V);
1197 return true;
1198 }
1199 }
1200
1201 if (Value *U = likeBitCastFromVector(IC, V))
1202 if (!SI.isAtomic() || isSupportedAtomicType(U->getType())) {
1203 combineStoreToNewValue(IC, SI, U);
1204 return true;
1205 }
1206
1207 // FIXME: We should also canonicalize stores of vectors when their elements
1208 // are cast to other types.
1209 return false;
1210}
1211
1213 // FIXME: We could probably with some care handle both volatile and atomic
1214 // stores here but it isn't clear that this is important.
1215 if (!SI.isSimple())
1216 return false;
1217
1218 Value *V = SI.getValueOperand();
1219 Type *T = V->getType();
1220
1221 if (!T->isAggregateType())
1222 return false;
1223
1224 if (auto *ST = dyn_cast<StructType>(T)) {
1225 // If the struct only have one element, we unpack.
1226 unsigned Count = ST->getNumElements();
1227 if (Count == 1) {
1228 V = IC.Builder.CreateExtractValue(V, 0);
1229 combineStoreToNewValue(IC, SI, V);
1230 return true;
1231 }
1232
1233 // We don't want to break loads with padding here as we'd loose
1234 // the knowledge that padding exists for the rest of the pipeline.
1235 const DataLayout &DL = IC.getDataLayout();
1236 auto *SL = DL.getStructLayout(ST);
1237
1238 // Don't unpack for structure with scalable vector.
1239 if (SL->getSizeInBits().isScalable())
1240 return false;
1241
1242 if (SL->hasPadding())
1243 return false;
1244
1245 const auto Align = SI.getAlign();
1246
1247 SmallString<16> EltName = V->getName();
1248 EltName += ".elt";
1249 auto *Addr = SI.getPointerOperand();
1250 SmallString<16> AddrName = Addr->getName();
1251 AddrName += ".repack";
1252
1253 auto *IdxType = Type::getInt32Ty(ST->getContext());
1254 auto *Zero = ConstantInt::get(IdxType, 0);
1255 for (unsigned i = 0; i < Count; i++) {
1256 Value *Indices[2] = {
1257 Zero,
1258 ConstantInt::get(IdxType, i),
1259 };
1260 auto *Ptr =
1261 IC.Builder.CreateInBoundsGEP(ST, Addr, ArrayRef(Indices), AddrName);
1262 auto *Val = IC.Builder.CreateExtractValue(V, i, EltName);
1263 auto EltAlign = commonAlignment(Align, SL->getElementOffset(i));
1264 llvm::Instruction *NS = IC.Builder.CreateAlignedStore(Val, Ptr, EltAlign);
1265 NS->setAAMetadata(SI.getAAMetadata());
1266 }
1267
1268 return true;
1269 }
1270
1271 if (auto *AT = dyn_cast<ArrayType>(T)) {
1272 // If the array only have one element, we unpack.
1273 auto NumElements = AT->getNumElements();
1274 if (NumElements == 1) {
1275 V = IC.Builder.CreateExtractValue(V, 0);
1276 combineStoreToNewValue(IC, SI, V);
1277 return true;
1278 }
1279
1280 // Bail out if the array is too large. Ideally we would like to optimize
1281 // arrays of arbitrary size but this has a terrible impact on compile time.
1282 // The threshold here is chosen arbitrarily, maybe needs a little bit of
1283 // tuning.
1284 if (NumElements > IC.MaxArraySizeForCombine)
1285 return false;
1286
1287 const DataLayout &DL = IC.getDataLayout();
1288 TypeSize EltSize = DL.getTypeAllocSize(AT->getElementType());
1289 const auto Align = SI.getAlign();
1290
1291 SmallString<16> EltName = V->getName();
1292 EltName += ".elt";
1293 auto *Addr = SI.getPointerOperand();
1294 SmallString<16> AddrName = Addr->getName();
1295 AddrName += ".repack";
1296
1297 auto *IdxType = Type::getInt64Ty(T->getContext());
1298 auto *Zero = ConstantInt::get(IdxType, 0);
1299
1301 for (uint64_t i = 0; i < NumElements; i++) {
1302 Value *Indices[2] = {
1303 Zero,
1304 ConstantInt::get(IdxType, i),
1305 };
1306 auto *Ptr =
1307 IC.Builder.CreateInBoundsGEP(AT, Addr, ArrayRef(Indices), AddrName);
1308 auto *Val = IC.Builder.CreateExtractValue(V, i, EltName);
1309 auto EltAlign = commonAlignment(Align, Offset.getKnownMinValue());
1310 Instruction *NS = IC.Builder.CreateAlignedStore(Val, Ptr, EltAlign);
1311 NS->setAAMetadata(SI.getAAMetadata());
1312 Offset += EltSize;
1313 }
1314
1315 return true;
1316 }
1317
1318 return false;
1319}
1320
1321/// equivalentAddressValues - Test if A and B will obviously have the same
1322/// value. This includes recognizing that %t0 and %t1 will have the same
1323/// value in code like this:
1324/// %t0 = getelementptr \@a, 0, 3
1325/// store i32 0, i32* %t0
1326/// %t1 = getelementptr \@a, 0, 3
1327/// %t2 = load i32* %t1
1328///
1330 // Test if the values are trivially equivalent.
1331 if (A == B) return true;
1332
1333 // Test if the values come form identical arithmetic instructions.
1334 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
1335 // its only used to compare two uses within the same basic block, which
1336 // means that they'll always either have the same value or one of them
1337 // will have an undefined value.
1338 if (isa<BinaryOperator>(A) ||
1339 isa<CastInst>(A) ||
1340 isa<PHINode>(A) ||
1341 isa<GetElementPtrInst>(A))
1342 if (Instruction *BI = dyn_cast<Instruction>(B))
1343 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
1344 return true;
1345
1346 // Otherwise they may not be equivalent.
1347 return false;
1348}
1349
1351 Value *Val = SI.getOperand(0);
1352 Value *Ptr = SI.getOperand(1);
1353
1354 // Try to canonicalize the stored type.
1355 if (combineStoreToValueType(*this, SI))
1356 return eraseInstFromFunction(SI);
1357
1359 // Attempt to improve the alignment.
1360 const Align KnownAlign = getOrEnforceKnownAlignment(
1361 Ptr, DL.getPrefTypeAlign(Val->getType()), DL, &SI, &AC, &DT);
1362 if (KnownAlign > SI.getAlign())
1363 SI.setAlignment(KnownAlign);
1364 }
1365
1366 // Try to canonicalize the stored type.
1367 if (unpackStoreToAggregate(*this, SI))
1368 return eraseInstFromFunction(SI);
1369
1370 // Replace GEP indices if possible.
1371 if (Instruction *NewGEPI = replaceGEPIdxWithZero(*this, Ptr, SI))
1372 return replaceOperand(SI, 1, NewGEPI);
1373
1374 // Don't hack volatile/ordered stores.
1375 // FIXME: Some bits are legal for ordered atomic stores; needs refactoring.
1376 if (!SI.isUnordered()) return nullptr;
1377
1378 // If the RHS is an alloca with a single use, zapify the store, making the
1379 // alloca dead.
1380 if (Ptr->hasOneUse()) {
1381 if (isa<AllocaInst>(Ptr))
1382 return eraseInstFromFunction(SI);
1383 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
1384 if (isa<AllocaInst>(GEP->getOperand(0))) {
1385 if (GEP->getOperand(0)->hasOneUse())
1386 return eraseInstFromFunction(SI);
1387 }
1388 }
1389 }
1390
1391 // If we have a store to a location which is known constant, we can conclude
1392 // that the store must be storing the constant value (else the memory
1393 // wouldn't be constant), and this must be a noop.
1395 return eraseInstFromFunction(SI);
1396
1397 // Do really simple DSE, to catch cases where there are several consecutive
1398 // stores to the same location, separated by a few arithmetic operations. This
1399 // situation often occurs with bitfield accesses.
1400 BasicBlock::iterator BBI(SI);
1401 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
1402 --ScanInsts) {
1403 --BBI;
1404 // Don't count debug info directives, lest they affect codegen,
1405 // and we skip pointer-to-pointer bitcasts, which are NOPs.
1406 if (BBI->isDebugOrPseudoInst()) {
1407 ScanInsts++;
1408 continue;
1409 }
1410
1411 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
1412 // Prev store isn't volatile, and stores to the same location?
1413 if (PrevSI->isUnordered() &&
1414 equivalentAddressValues(PrevSI->getOperand(1), SI.getOperand(1)) &&
1415 PrevSI->getValueOperand()->getType() ==
1416 SI.getValueOperand()->getType()) {
1417 ++NumDeadStore;
1418 // Manually add back the original store to the worklist now, so it will
1419 // be processed after the operands of the removed store, as this may
1420 // expose additional DSE opportunities.
1421 Worklist.push(&SI);
1422 eraseInstFromFunction(*PrevSI);
1423 return nullptr;
1424 }
1425 break;
1426 }
1427
1428 // If this is a load, we have to stop. However, if the loaded value is from
1429 // the pointer we're loading and is producing the pointer we're storing,
1430 // then *this* store is dead (X = load P; store X -> P).
1431 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
1432 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr)) {
1433 assert(SI.isUnordered() && "can't eliminate ordering operation");
1434 return eraseInstFromFunction(SI);
1435 }
1436
1437 // Otherwise, this is a load from some other location. Stores before it
1438 // may not be dead.
1439 break;
1440 }
1441
1442 // Don't skip over loads, throws or things that can modify memory.
1443 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory() || BBI->mayThrow())
1444 break;
1445 }
1446
1447 // store X, null -> turns into 'unreachable' in SimplifyCFG
1448 // store X, GEP(null, Y) -> turns into 'unreachable' in SimplifyCFG
1449 if (canSimplifyNullStoreOrGEP(SI)) {
1450 if (!isa<PoisonValue>(Val))
1451 return replaceOperand(SI, 0, PoisonValue::get(Val->getType()));
1452 return nullptr; // Do not modify these!
1453 }
1454
1455 // This is a non-terminator unreachable marker. Don't remove it.
1456 if (isa<UndefValue>(Ptr)) {
1457 // Remove guaranteed-to-transfer instructions before the marker.
1459 return &SI;
1460
1461 // Remove all instructions after the marker and handle dead blocks this
1462 // implies.
1464 handleUnreachableFrom(SI.getNextNode(), Worklist);
1466 return nullptr;
1467 }
1468
1469 // store undef, Ptr -> noop
1470 // FIXME: This is technically incorrect because it might overwrite a poison
1471 // value. Change to PoisonValue once #52930 is resolved.
1472 if (isa<UndefValue>(Val))
1473 return eraseInstFromFunction(SI);
1474
1475 return nullptr;
1476}
1477
1478/// Try to transform:
1479/// if () { *P = v1; } else { *P = v2 }
1480/// or:
1481/// *P = v1; if () { *P = v2; }
1482/// into a phi node with a store in the successor.
1484 if (!SI.isUnordered())
1485 return false; // This code has not been audited for volatile/ordered case.
1486
1487 // Check if the successor block has exactly 2 incoming edges.
1488 BasicBlock *StoreBB = SI.getParent();
1489 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
1490 if (!DestBB->hasNPredecessors(2))
1491 return false;
1492
1493 // Capture the other block (the block that doesn't contain our store).
1494 pred_iterator PredIter = pred_begin(DestBB);
1495 if (*PredIter == StoreBB)
1496 ++PredIter;
1497 BasicBlock *OtherBB = *PredIter;
1498
1499 // Bail out if all of the relevant blocks aren't distinct. This can happen,
1500 // for example, if SI is in an infinite loop.
1501 if (StoreBB == DestBB || OtherBB == DestBB)
1502 return false;
1503
1504 // Verify that the other block ends in a branch and is not otherwise empty.
1505 BasicBlock::iterator BBI(OtherBB->getTerminator());
1506 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
1507 if (!OtherBr || BBI == OtherBB->begin())
1508 return false;
1509
1510 auto OtherStoreIsMergeable = [&](StoreInst *OtherStore) -> bool {
1511 if (!OtherStore ||
1512 OtherStore->getPointerOperand() != SI.getPointerOperand())
1513 return false;
1514
1515 auto *SIVTy = SI.getValueOperand()->getType();
1516 auto *OSVTy = OtherStore->getValueOperand()->getType();
1517 return CastInst::isBitOrNoopPointerCastable(OSVTy, SIVTy, DL) &&
1518 SI.hasSameSpecialState(OtherStore);
1519 };
1520
1521 // If the other block ends in an unconditional branch, check for the 'if then
1522 // else' case. There is an instruction before the branch.
1523 StoreInst *OtherStore = nullptr;
1524 if (OtherBr->isUnconditional()) {
1525 --BBI;
1526 // Skip over debugging info and pseudo probes.
1527 while (BBI->isDebugOrPseudoInst()) {
1528 if (BBI==OtherBB->begin())
1529 return false;
1530 --BBI;
1531 }
1532 // If this isn't a store, isn't a store to the same location, or is not the
1533 // right kind of store, bail out.
1534 OtherStore = dyn_cast<StoreInst>(BBI);
1535 if (!OtherStoreIsMergeable(OtherStore))
1536 return false;
1537 } else {
1538 // Otherwise, the other block ended with a conditional branch. If one of the
1539 // destinations is StoreBB, then we have the if/then case.
1540 if (OtherBr->getSuccessor(0) != StoreBB &&
1541 OtherBr->getSuccessor(1) != StoreBB)
1542 return false;
1543
1544 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
1545 // if/then triangle. See if there is a store to the same ptr as SI that
1546 // lives in OtherBB.
1547 for (;; --BBI) {
1548 // Check to see if we find the matching store.
1549 OtherStore = dyn_cast<StoreInst>(BBI);
1550 if (OtherStoreIsMergeable(OtherStore))
1551 break;
1552
1553 // If we find something that may be using or overwriting the stored
1554 // value, or if we run out of instructions, we can't do the transform.
1555 if (BBI->mayReadFromMemory() || BBI->mayThrow() ||
1556 BBI->mayWriteToMemory() || BBI == OtherBB->begin())
1557 return false;
1558 }
1559
1560 // In order to eliminate the store in OtherBr, we have to make sure nothing
1561 // reads or overwrites the stored value in StoreBB.
1562 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
1563 // FIXME: This should really be AA driven.
1564 if (I->mayReadFromMemory() || I->mayThrow() || I->mayWriteToMemory())
1565 return false;
1566 }
1567 }
1568
1569 // Insert a PHI node now if we need it.
1570 Value *MergedVal = OtherStore->getValueOperand();
1571 // The debug locations of the original instructions might differ. Merge them.
1572 DebugLoc MergedLoc = DILocation::getMergedLocation(SI.getDebugLoc(),
1573 OtherStore->getDebugLoc());
1574 if (MergedVal != SI.getValueOperand()) {
1575 PHINode *PN =
1576 PHINode::Create(SI.getValueOperand()->getType(), 2, "storemerge");
1577 PN->addIncoming(SI.getValueOperand(), SI.getParent());
1578 Builder.SetInsertPoint(OtherStore);
1579 PN->addIncoming(Builder.CreateBitOrPointerCast(MergedVal, PN->getType()),
1580 OtherBB);
1581 MergedVal = InsertNewInstBefore(PN, DestBB->begin());
1582 PN->setDebugLoc(MergedLoc);
1583 }
1584
1585 // Advance to a place where it is safe to insert the new store and insert it.
1586 BBI = DestBB->getFirstInsertionPt();
1587 StoreInst *NewSI =
1588 new StoreInst(MergedVal, SI.getOperand(1), SI.isVolatile(), SI.getAlign(),
1589 SI.getOrdering(), SI.getSyncScopeID());
1590 InsertNewInstBefore(NewSI, BBI);
1591 NewSI->setDebugLoc(MergedLoc);
1592 NewSI->mergeDIAssignID({&SI, OtherStore});
1593
1594 // If the two stores had AA tags, merge them.
1595 AAMDNodes AATags = SI.getAAMetadata();
1596 if (AATags)
1597 NewSI->setAAMetadata(AATags.merge(OtherStore->getAAMetadata()));
1598
1599 // Nuke the old stores.
1601 eraseInstFromFunction(*OtherStore);
1602 return true;
1603}
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Rewrite undef for PHI
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
#define LLVM_DEBUG(X)
Definition: Debug.h:101
uint64_t Addr
std::string Name
Hexagon Common GEP
IRTranslator LLVM IR MI
This file provides internal interfaces used to implement the InstCombine.
static StoreInst * combineStoreToNewValue(InstCombinerImpl &IC, StoreInst &SI, Value *V)
Combine a store to a new type.
static Instruction * combineLoadToOperationType(InstCombinerImpl &IC, LoadInst &Load)
Combine loads to match the type of their uses' value after looking through intervening bitcasts.
static Instruction * replaceGEPIdxWithZero(InstCombinerImpl &IC, Value *Ptr, Instruction &MemI)
static Instruction * simplifyAllocaArraySize(InstCombinerImpl &IC, AllocaInst &AI, DominatorTree &DT)
static bool canSimplifyNullStoreOrGEP(StoreInst &SI)
static bool equivalentAddressValues(Value *A, Value *B)
equivalentAddressValues - Test if A and B will obviously have the same value.
static bool canReplaceGEPIdxWithZero(InstCombinerImpl &IC, GetElementPtrInst *GEPI, Instruction *MemI, unsigned &Idx)
static bool canSimplifyNullLoadOrGEP(LoadInst &LI, Value *Op)
static bool isSupportedAtomicType(Type *Ty)
static bool isDereferenceableForAllocaSize(const Value *V, const AllocaInst *AI, const DataLayout &DL)
Returns true if V is dereferenceable for size of alloca.
static Instruction * unpackLoadToAggregate(InstCombinerImpl &IC, LoadInst &LI)
static cl::opt< unsigned > MaxCopiedFromConstantUsers("instcombine-max-copied-from-constant-users", cl::init(300), cl::desc("Maximum users to visit in copy from constant transform"), cl::Hidden)
static bool combineStoreToValueType(InstCombinerImpl &IC, StoreInst &SI)
Combine stores to match the type of value being stored.
static bool unpackStoreToAggregate(InstCombinerImpl &IC, StoreInst &SI)
static Value * likeBitCastFromVector(InstCombinerImpl &IC, Value *V)
Look for extractelement/insertvalue sequence that acts like a bitcast.
static bool isOnlyCopiedFromConstantMemory(AAResults *AA, AllocaInst *V, MemTransferInst *&TheCopy, SmallVectorImpl< Instruction * > &ToDelete)
isOnlyCopiedFromConstantMemory - Recursively walk the uses of a (derived) pointer to an alloca.
static bool isObjectSizeLessThanOrEq(Value *V, uint64_t MaxSize, const DataLayout &DL)
This file provides the interface for the instcombine pass implementation.
#define I(x, y, z)
Definition: MD5.cpp:58
This file implements a map that provides insertion order iteration.
#define P(N)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file defines the SmallString class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition: Statistic.h:167
static const uint32_t IV[8]
Definition: blake3_impl.h:78
ModRefInfo getModRefInfoMask(const MemoryLocation &Loc, bool IgnoreLocals=false)
Returns a bitmask that should be unconditionally applied to the ModRef info of a memory location.
Class for arbitrary precision integers.
Definition: APInt.h:77
APInt zext(unsigned width) const
Zero extend to a new width.
Definition: APInt.cpp:981
This class represents a conversion between pointers from one address space to another.
an instruction to allocate memory on the stack
Definition: Instructions.h:60
Align getAlign() const
Return the alignment of the memory that is being allocated by the instruction.
Definition: Instructions.h:121
PointerType * getType() const
Overload to return most specific pointer type.
Definition: Instructions.h:96
Type * getAllocatedType() const
Return the type that is being allocated by the instruction.
Definition: Instructions.h:114
bool isUsedWithInAlloca() const
Return true if this alloca is used as an inalloca argument to a call.
Definition: Instructions.h:136
unsigned getAddressSpace() const
Return the address space for the allocation.
Definition: Instructions.h:101
bool isArrayAllocation() const
Return true if there is an allocation size parameter to the allocation instruction that is not 1.
void setAlignment(Align Align)
Definition: Instructions.h:125
const Value * getArraySize() const
Get the number of elements allocated.
Definition: Instructions.h:92
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
LLVM Basic Block Representation.
Definition: BasicBlock.h:61
iterator begin()
Instruction iterator methods.
Definition: BasicBlock.h:438
const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
Definition: BasicBlock.cpp:414
bool hasNPredecessors(unsigned N) const
Return true if this block has exactly N predecessors.
Definition: BasicBlock.cpp:479
const Instruction * getFirstNonPHIOrDbg(bool SkipPseudoOp=true) const
Returns a pointer to the first instruction in this block that is not a PHINode or a debug intrinsic,...
Definition: BasicBlock.cpp:384
InstListType::iterator iterator
Instruction iterators...
Definition: BasicBlock.h:167
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition: BasicBlock.h:229
This class is a wrapper over an AAResults, and it is intended to be used only when there are no IR ch...
Conditional or Unconditional Branch instruction.
BasicBlock * getSuccessor(unsigned i) const
bool isUnconditional() const
static bool isBitOrNoopPointerCastable(Type *SrcTy, Type *DestTy, const DataLayout &DL)
Check whether a bitcast, inttoptr, or ptrtoint cast between these types is valid and a no-op.
This is the shared class of boolean and integer constants.
Definition: Constants.h:81
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition: Constants.h:146
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
Definition: Constants.cpp:370
static DILocation * getMergedLocation(DILocation *LocA, DILocation *LocB)
When two instructions are combined into a single instruction we also need to combine the original loc...
This class represents an Operation in the Expression.
A parsed version of the target data layout string in and methods for querying it.
Definition: DataLayout.h:110
IntegerType * getIndexType(LLVMContext &C, unsigned AddressSpace) const
Returns the type of a GEP index in AddressSpace.
Definition: DataLayout.cpp:905
TypeSize getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
Definition: DataLayout.h:504
Align getPrefTypeAlign(Type *Ty) const
Returns the preferred stack/global alignment for the specified type.
Definition: DataLayout.cpp:874
A debug info location.
Definition: DebugLoc.h:33
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition: Dominators.h:162
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
Definition: Instructions.h:914
bool isInBounds() const
Determine whether the GEP has the inbounds flag.
static GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Definition: Instructions.h:937
static Type * getIndexedType(Type *Ty, ArrayRef< Value * > IdxList)
Returns the result type of a getelementptr with the given source element type and indexes.
Type * getSourceElementType() const
Definition: Instructions.h:970
AllocaInst * CreateAlloca(Type *Ty, unsigned AddrSpace, Value *ArraySize=nullptr, const Twine &Name="")
Definition: IRBuilder.h:1771
Value * CreateInsertValue(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &Name="")
Definition: IRBuilder.h:2521
LoadInst * CreateAlignedLoad(Type *Ty, Value *Ptr, MaybeAlign Align, const char *Name)
Definition: IRBuilder.h:1805
Value * CreateExtractValue(Value *Agg, ArrayRef< unsigned > Idxs, const Twine &Name="")
Definition: IRBuilder.h:2514
Value * CreateInBoundsGEP(Type *Ty, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &Name="")
Definition: IRBuilder.h:1872
ConstantInt * getInt32(uint32_t C)
Get a constant 32-bit value.
Definition: IRBuilder.h:484
Value * CreateBitOrPointerCast(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:2203
LoadInst * CreateLoad(Type *Ty, Value *Ptr, const char *Name)
Provided to resolve 'CreateLoad(Ty, Ptr, "...")' correctly, instead of converting the string to 'bool...
Definition: IRBuilder.h:1788
Value * CreateIntCast(Value *V, Type *DestTy, bool isSigned, const Twine &Name="")
Definition: IRBuilder.h:2194
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition: IRBuilder.h:178
StoreInst * CreateAlignedStore(Value *Val, Value *Ptr, MaybeAlign Align, bool isVolatile=false)
Definition: IRBuilder.h:1824
void handleUnreachableFrom(Instruction *I, SmallVectorImpl< BasicBlock * > &Worklist)
Instruction * visitLoadInst(LoadInst &LI)
void handlePotentiallyDeadBlocks(SmallVectorImpl< BasicBlock * > &Worklist)
Instruction * eraseInstFromFunction(Instruction &I) override
Combiner aware instruction erasure.
Instruction * visitStoreInst(StoreInst &SI)
bool mergeStoreIntoSuccessor(StoreInst &SI)
Try to transform: if () { *P = v1; } else { *P = v2 } or: *P = v1; if () { *P = v2; } into a phi node...
void CreateNonTerminatorUnreachable(Instruction *InsertAt)
Create and insert the idiom we use to indicate a block is unreachable without having to rewrite the C...
bool removeInstructionsBeforeUnreachable(Instruction &I)
LoadInst * combineLoadToNewType(LoadInst &LI, Type *NewTy, const Twine &Suffix="")
Helper to combine a load to a new type.
Instruction * visitAllocSite(Instruction &FI)
Instruction * visitAllocaInst(AllocaInst &AI)
SimplifyQuery SQ
Definition: InstCombiner.h:76
const DataLayout & getDataLayout() const
Definition: InstCombiner.h:341
Instruction * InsertNewInstBefore(Instruction *New, BasicBlock::iterator Old)
Inserts an instruction New before instruction Old.
Definition: InstCombiner.h:366
AAResults * AA
Definition: InstCombiner.h:69
Instruction * replaceInstUsesWith(Instruction &I, Value *V)
A combiner-aware RAUW-like routine.
Definition: InstCombiner.h:386
uint64_t MaxArraySizeForCombine
Maximum size of array considered when transforming.
Definition: InstCombiner.h:55
InstructionWorklist & Worklist
A worklist of the instructions that need to be simplified.
Definition: InstCombiner.h:64
const DataLayout & DL
Definition: InstCombiner.h:75
AssumptionCache & AC
Definition: InstCombiner.h:72
Instruction * replaceOperand(Instruction &I, unsigned OpNum, Value *V)
Replace operand of instruction and add old operand to the worklist.
Definition: InstCombiner.h:410
DominatorTree & DT
Definition: InstCombiner.h:74
void computeKnownBits(const Value *V, KnownBits &Known, unsigned Depth, const Instruction *CxtI) const
Definition: InstCombiner.h:431
BuilderTy & Builder
Definition: InstCombiner.h:60
void push(Instruction *I)
Push the instruction onto the worklist stack.
Instruction * clone() const
Create a copy of 'this' instruction that is identical in all ways except the following:
void mergeDIAssignID(ArrayRef< const Instruction * > SourceInstructions)
Merge the DIAssignID metadata from this instruction and those attached to instructions in SourceInstr...
Definition: DebugInfo.cpp:936
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
Definition: Instruction.h:476
void setAAMetadata(const AAMDNodes &N)
Sets the AA metadata on this instruction from the AAMDNodes structure.
Definition: Metadata.cpp:1720
const Function * getFunction() const
Return the function this instruction belongs to.
Definition: Instruction.cpp:70
BasicBlock * getSuccessor(unsigned Idx) const LLVM_READONLY
Return the specified successor. This instruction must be a terminator.
void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
Definition: Metadata.cpp:1635
AAMDNodes getAAMetadata() const
Returns the AA metadata for this instruction.
Definition: Metadata.cpp:1706
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
Definition: Instruction.h:473
void moveBefore(Instruction *MovePos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
An instruction for reading from memory.
Definition: Instructions.h:173
unsigned getPointerAddressSpace() const
Returns the address space of the pointer operand.
Definition: Instructions.h:258
void setAlignment(Align Align)
Definition: Instructions.h:212
Value * getPointerOperand()
Definition: Instructions.h:252
void setAtomic(AtomicOrdering Ordering, SyncScope::ID SSID=SyncScope::System)
Sets the ordering constraint and the synchronization scope ID of this load instruction.
Definition: Instructions.h:238
bool isSimple() const
Definition: Instructions.h:244
Align getAlign() const
Return the alignment of the access that is being performed.
Definition: Instructions.h:208
Metadata node.
Definition: Metadata.h:1067
This class implements a map that also provides access to all stored values in a deterministic order.
Definition: MapVector.h:36
This class wraps the llvm.memcpy/memmove intrinsics.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
PointerIntPair - This class implements a pair of a pointer and small integer.
static PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Definition: Constants.cpp:1814
This class represents the LLVM 'select' instruction.
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", InsertPosition InsertBefore=nullptr, Instruction *MDFrom=nullptr)
size_type size() const
Definition: SmallPtrSet.h:94
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:344
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:479
A SetVector that performs no allocations if smaller than a certain size.
Definition: SetVector.h:370
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition: SmallString.h:26
bool empty() const
Definition: SmallVector.h:94
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:586
reference emplace_back(ArgTypes &&... Args)
Definition: SmallVector.h:950
void push_back(const T &Elt)
Definition: SmallVector.h:426
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
An instruction for storing to memory.
Definition: Instructions.h:289
Value * getValueOperand()
Definition: Instructions.h:373
void setAtomic(AtomicOrdering Ordering, SyncScope::ID SSID=SyncScope::System)
Sets the ordering constraint and the synchronization scope ID of this store instruction.
Definition: Instructions.h:359
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
static constexpr TypeSize getZero()
Definition: TypeSize.h:348
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
bool isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
Definition: Type.h:302
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition: Type.h:185
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
Definition: Type.h:262
bool isX86_AMXTy() const
Return true if this is X86 AMX.
Definition: Type.h:204
bool isScalableTy() const
Return true if this is a type whose size is a known multiple of vscale.
bool isIntOrPtrTy() const
Return true if this is an integer type or a pointer type.
Definition: Type.h:243
static IntegerType * getInt32Ty(LLVMContext &C)
static IntegerType * getInt64Ty(LLVMContext &C)
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition: Type.h:228
void setOperand(unsigned i, Value *Val)
Definition: User.h:174
Value * getOperand(unsigned i) const
Definition: User.h:169
unsigned getNumOperands() const
Definition: User.h:191
LLVM Value Representation.
Definition: Value.h:74
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:255
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition: Value.cpp:534
iterator_range< use_iterator > uses()
Definition: Value.h:376
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:309
constexpr ScalarTy getFixedValue() const
Definition: TypeSize.h:199
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition: TypeSize.h:171
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition: TypeSize.h:168
const ParentTy * getParent() const
Definition: ilist_node.h:32
self_iterator getIterator()
Definition: ilist_node.h:132
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
bool match(Val *V, const Pattern &P)
Definition: PatternMatch.h:49
auto m_Undef()
Match an arbitrary undef constant.
Definition: PatternMatch.h:152
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:443
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
@ Offset
Definition: DWP.cpp:480
bool isSafeToLoadUnconditionally(Value *V, Align Alignment, const APInt &Size, const DataLayout &DL, Instruction *ScanFrom=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr)
Return true if we know that executing a load from this value cannot trap.
Definition: Loads.cpp:352
bool isDereferenceableAndAlignedPointer(const Value *V, Type *Ty, Align Alignment, const DataLayout &DL, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr)
Returns true if V is always a dereferenceable pointer with alignment greater or equal than requested.
Definition: Loads.cpp:201
void copyMetadataForLoad(LoadInst &Dest, const LoadInst &Source)
Copy the metadata from the source instruction to the destination (the replacement for the source inst...
Definition: Local.cpp:3369
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition: STLExtras.h:2067
Value * FindAvailableLoadedValue(LoadInst *Load, BasicBlock *ScanBB, BasicBlock::iterator &ScanFrom, unsigned MaxInstsToScan=DefMaxInstsToScan, BatchAAResults *AA=nullptr, bool *IsLoadCSE=nullptr, unsigned *NumScanedInst=nullptr)
Scan backwards to see if we have the value of the given load available locally within a small number ...
Definition: Loads.cpp:455
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1729
pred_iterator pred_begin(BasicBlock *BB)
Definition: CFG.h:110
Align getOrEnforceKnownAlignment(Value *V, MaybeAlign PrefAlign, const DataLayout &DL, const Instruction *CxtI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr)
Try to ensure that the alignment of V is at least PrefAlign bytes.
Definition: Local.cpp:1543
bool isModSet(const ModRefInfo MRI)
Definition: ModRef.h:48
bool NullPointerIsDefined(const Function *F, unsigned AS=0)
Check whether null pointer dereferencing is considered undefined behavior for a given function or an ...
Definition: Function.cpp:2073
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
bool replaceAllDbgUsesWith(Instruction &From, Value &To, Instruction &DomPoint, DominatorTree &DT)
Point debug users of From to To or salvage them.
Definition: Local.cpp:2717
Value * simplifyLoadInst(LoadInst *LI, Value *PtrOp, const SimplifyQuery &Q)
Given a load instruction and its pointer operand, fold the result or return null.
void combineMetadataForCSE(Instruction *K, const Instruction *J, bool DoesKMove)
Combine the metadata of two instructions so that K can replace J.
Definition: Local.cpp:3347
cl::opt< bool > EnableInferAlignmentPass
void replace(Container &Cont, typename Container::iterator ContIt, typename Container::iterator ContEnd, RandomAccessIterator ValIt, RandomAccessIterator ValEnd)
Given a sequence container Cont, replace the range [ContIt, ContEnd) with the range [ValIt,...
Definition: STLExtras.h:2082
Align commonAlignment(Align A, uint64_t Offset)
Returns the alignment that satisfies both alignments.
Definition: Alignment.h:212
#define N
A collection of metadata nodes that might be associated with a memory access used by the alias-analys...
Definition: Metadata.h:760
AAMDNodes merge(const AAMDNodes &Other) const
Given two sets of AAMDNodes applying to potentially different locations, determine the best AAMDNodes...
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition: Alignment.h:39
bool isNonNegative() const
Returns true if this value is known to be non-negative.
Definition: KnownBits.h:97
SimplifyQuery getWithInstruction(const Instruction *I) const
Definition: SimplifyQuery.h:96