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