163faed5bSDimitry Andric //===-- Analysis.cpp - CodeGen LLVM IR Analysis Utilities -----------------===//
2d7f7719eSRoman Divacky //
3e6d15924SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e6d15924SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e6d15924SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6d7f7719eSRoman Divacky //
7d7f7719eSRoman Divacky //===----------------------------------------------------------------------===//
8d7f7719eSRoman Divacky //
95ca98fd9SDimitry Andric // This file defines several CodeGen-specific LLVM IR analysis utilities.
10d7f7719eSRoman Divacky //
11d7f7719eSRoman Divacky //===----------------------------------------------------------------------===//
12d7f7719eSRoman Divacky
13d7f7719eSRoman Divacky #include "llvm/CodeGen/Analysis.h"
1463faed5bSDimitry Andric #include "llvm/Analysis/ValueTracking.h"
15d7f7719eSRoman Divacky #include "llvm/CodeGen/MachineFunction.h"
16044eb2f6SDimitry Andric #include "llvm/CodeGen/TargetInstrInfo.h"
17044eb2f6SDimitry Andric #include "llvm/CodeGen/TargetLowering.h"
18044eb2f6SDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
194a16efa3SDimitry Andric #include "llvm/IR/DataLayout.h"
204a16efa3SDimitry Andric #include "llvm/IR/DerivedTypes.h"
214a16efa3SDimitry Andric #include "llvm/IR/Function.h"
224a16efa3SDimitry Andric #include "llvm/IR/Instructions.h"
234a16efa3SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
244a16efa3SDimitry Andric #include "llvm/IR/Module.h"
25d7f7719eSRoman Divacky #include "llvm/Support/ErrorHandling.h"
26cfca06d7SDimitry Andric #include "llvm/Target/TargetMachine.h"
2767c32a98SDimitry Andric
28d7f7719eSRoman Divacky using namespace llvm;
29d7f7719eSRoman Divacky
3067c32a98SDimitry Andric /// Compute the linearized index of a member in a nested aggregate/struct/array
3167c32a98SDimitry Andric /// by recursing and accumulating CurIndex as long as there are indices in the
3267c32a98SDimitry Andric /// index list.
ComputeLinearIndex(Type * Ty,const unsigned * Indices,const unsigned * IndicesEnd,unsigned CurIndex)3330815c53SDimitry Andric unsigned llvm::ComputeLinearIndex(Type *Ty,
34d7f7719eSRoman Divacky const unsigned *Indices,
35d7f7719eSRoman Divacky const unsigned *IndicesEnd,
36d7f7719eSRoman Divacky unsigned CurIndex) {
37d7f7719eSRoman Divacky // Base case: We're done.
38d7f7719eSRoman Divacky if (Indices && Indices == IndicesEnd)
39d7f7719eSRoman Divacky return CurIndex;
40d7f7719eSRoman Divacky
41d7f7719eSRoman Divacky // Given a struct type, recursively traverse the elements.
4230815c53SDimitry Andric if (StructType *STy = dyn_cast<StructType>(Ty)) {
43344a3780SDimitry Andric for (auto I : llvm::enumerate(STy->elements())) {
44344a3780SDimitry Andric Type *ET = I.value();
45344a3780SDimitry Andric if (Indices && *Indices == I.index())
46344a3780SDimitry Andric return ComputeLinearIndex(ET, Indices + 1, IndicesEnd, CurIndex);
47344a3780SDimitry Andric CurIndex = ComputeLinearIndex(ET, nullptr, nullptr, CurIndex);
48d7f7719eSRoman Divacky }
4967c32a98SDimitry Andric assert(!Indices && "Unexpected out of bound");
50d7f7719eSRoman Divacky return CurIndex;
51d7f7719eSRoman Divacky }
52d7f7719eSRoman Divacky // Given an array type, recursively traverse the elements.
5330815c53SDimitry Andric else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
5430815c53SDimitry Andric Type *EltTy = ATy->getElementType();
5567c32a98SDimitry Andric unsigned NumElts = ATy->getNumElements();
5667c32a98SDimitry Andric // Compute the Linear offset when jumping one element of the array
5767c32a98SDimitry Andric unsigned EltLinearOffset = ComputeLinearIndex(EltTy, nullptr, nullptr, 0);
5867c32a98SDimitry Andric if (Indices) {
5967c32a98SDimitry Andric assert(*Indices < NumElts && "Unexpected out of bound");
6067c32a98SDimitry Andric // If the indice is inside the array, compute the index to the requested
6167c32a98SDimitry Andric // elt and recurse inside the element with the end of the indices list
6267c32a98SDimitry Andric CurIndex += EltLinearOffset* *Indices;
63cf099d11SDimitry Andric return ComputeLinearIndex(EltTy, Indices+1, IndicesEnd, CurIndex);
64d7f7719eSRoman Divacky }
6567c32a98SDimitry Andric CurIndex += EltLinearOffset*NumElts;
66d7f7719eSRoman Divacky return CurIndex;
67d7f7719eSRoman Divacky }
68d7f7719eSRoman Divacky // We haven't found the type we're looking for, so keep searching.
69d7f7719eSRoman Divacky return CurIndex + 1;
70d7f7719eSRoman Divacky }
71d7f7719eSRoman Divacky
72d7f7719eSRoman Divacky /// ComputeValueVTs - Given an LLVM IR type, compute a sequence of
73d7f7719eSRoman Divacky /// EVTs that represent all the individual underlying
74d7f7719eSRoman Divacky /// non-aggregate types that comprise it.
75d7f7719eSRoman Divacky ///
76d7f7719eSRoman Divacky /// If Offsets is non-null, it points to a vector to be filled in
77d7f7719eSRoman Divacky /// with the in-memory offsets of each of the individual values.
78d7f7719eSRoman Divacky ///
ComputeValueVTs(const TargetLowering & TLI,const DataLayout & DL,Type * Ty,SmallVectorImpl<EVT> & ValueVTs,SmallVectorImpl<EVT> * MemVTs,SmallVectorImpl<TypeSize> * Offsets,TypeSize StartingOffset)79ee8648bdSDimitry Andric void llvm::ComputeValueVTs(const TargetLowering &TLI, const DataLayout &DL,
80ee8648bdSDimitry Andric Type *Ty, SmallVectorImpl<EVT> &ValueVTs,
81e6d15924SDimitry Andric SmallVectorImpl<EVT> *MemVTs,
827fa27ce4SDimitry Andric SmallVectorImpl<TypeSize> *Offsets,
837fa27ce4SDimitry Andric TypeSize StartingOffset) {
84ac9a064cSDimitry Andric assert((Ty->isScalableTy() == StartingOffset.isScalable() ||
85ac9a064cSDimitry Andric StartingOffset.isZero()) &&
86ac9a064cSDimitry Andric "Offset/TypeSize mismatch!");
87d7f7719eSRoman Divacky // Given a struct type, recursively traverse the elements.
8830815c53SDimitry Andric if (StructType *STy = dyn_cast<StructType>(Ty)) {
89b60736ecSDimitry Andric // If the Offsets aren't needed, don't query the struct layout. This allows
90b60736ecSDimitry Andric // us to support structs with scalable vectors for operations that don't
91b60736ecSDimitry Andric // need offsets.
92b60736ecSDimitry Andric const StructLayout *SL = Offsets ? DL.getStructLayout(STy) : nullptr;
93d7f7719eSRoman Divacky for (StructType::element_iterator EB = STy->element_begin(),
94d7f7719eSRoman Divacky EI = EB,
95d7f7719eSRoman Divacky EE = STy->element_end();
96b60736ecSDimitry Andric EI != EE; ++EI) {
97b60736ecSDimitry Andric // Don't compute the element offset if we didn't get a StructLayout above.
98ac9a064cSDimitry Andric TypeSize EltOffset =
99ac9a064cSDimitry Andric SL ? SL->getElementOffset(EI - EB) : TypeSize::getZero();
100e6d15924SDimitry Andric ComputeValueVTs(TLI, DL, *EI, ValueVTs, MemVTs, Offsets,
101b60736ecSDimitry Andric StartingOffset + EltOffset);
102b60736ecSDimitry Andric }
103d7f7719eSRoman Divacky return;
104d7f7719eSRoman Divacky }
105d7f7719eSRoman Divacky // Given an array type, recursively traverse the elements.
10630815c53SDimitry Andric if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
10730815c53SDimitry Andric Type *EltTy = ATy->getElementType();
1087fa27ce4SDimitry Andric TypeSize EltSize = DL.getTypeAllocSize(EltTy);
109d7f7719eSRoman Divacky for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
110e6d15924SDimitry Andric ComputeValueVTs(TLI, DL, EltTy, ValueVTs, MemVTs, Offsets,
111d7f7719eSRoman Divacky StartingOffset + i * EltSize);
112d7f7719eSRoman Divacky return;
113d7f7719eSRoman Divacky }
114d7f7719eSRoman Divacky // Interpret void as zero return values.
115d7f7719eSRoman Divacky if (Ty->isVoidTy())
116d7f7719eSRoman Divacky return;
117d7f7719eSRoman Divacky // Base case: we can get an EVT for this LLVM IR type.
118ee8648bdSDimitry Andric ValueVTs.push_back(TLI.getValueType(DL, Ty));
119e6d15924SDimitry Andric if (MemVTs)
120e6d15924SDimitry Andric MemVTs->push_back(TLI.getMemValueType(DL, Ty));
121d7f7719eSRoman Divacky if (Offsets)
122d7f7719eSRoman Divacky Offsets->push_back(StartingOffset);
123d7f7719eSRoman Divacky }
124d7f7719eSRoman Divacky
ComputeValueVTs(const TargetLowering & TLI,const DataLayout & DL,Type * Ty,SmallVectorImpl<EVT> & ValueVTs,SmallVectorImpl<EVT> * MemVTs,SmallVectorImpl<uint64_t> * FixedOffsets,uint64_t StartingOffset)125e6d15924SDimitry Andric void llvm::ComputeValueVTs(const TargetLowering &TLI, const DataLayout &DL,
126e6d15924SDimitry Andric Type *Ty, SmallVectorImpl<EVT> &ValueVTs,
1277fa27ce4SDimitry Andric SmallVectorImpl<EVT> *MemVTs,
1287fa27ce4SDimitry Andric SmallVectorImpl<uint64_t> *FixedOffsets,
1297fa27ce4SDimitry Andric uint64_t StartingOffset) {
130ac9a064cSDimitry Andric TypeSize Offset = TypeSize::getFixed(StartingOffset);
131b1c73532SDimitry Andric if (FixedOffsets) {
1327fa27ce4SDimitry Andric SmallVector<TypeSize, 4> Offsets;
1337fa27ce4SDimitry Andric ComputeValueVTs(TLI, DL, Ty, ValueVTs, MemVTs, &Offsets, Offset);
1347fa27ce4SDimitry Andric for (TypeSize Offset : Offsets)
135b1c73532SDimitry Andric FixedOffsets->push_back(Offset.getFixedValue());
136b1c73532SDimitry Andric } else {
137b1c73532SDimitry Andric ComputeValueVTs(TLI, DL, Ty, ValueVTs, MemVTs, nullptr, Offset);
138b1c73532SDimitry Andric }
1397fa27ce4SDimitry Andric }
1407fa27ce4SDimitry Andric
computeValueLLTs(const DataLayout & DL,Type & Ty,SmallVectorImpl<LLT> & ValueTys,SmallVectorImpl<uint64_t> * Offsets,uint64_t StartingOffset)141e6d15924SDimitry Andric void llvm::computeValueLLTs(const DataLayout &DL, Type &Ty,
142e6d15924SDimitry Andric SmallVectorImpl<LLT> &ValueTys,
143e6d15924SDimitry Andric SmallVectorImpl<uint64_t> *Offsets,
144e6d15924SDimitry Andric uint64_t StartingOffset) {
145e6d15924SDimitry Andric // Given a struct type, recursively traverse the elements.
146e6d15924SDimitry Andric if (StructType *STy = dyn_cast<StructType>(&Ty)) {
147b60736ecSDimitry Andric // If the Offsets aren't needed, don't query the struct layout. This allows
148b60736ecSDimitry Andric // us to support structs with scalable vectors for operations that don't
149b60736ecSDimitry Andric // need offsets.
150b60736ecSDimitry Andric const StructLayout *SL = Offsets ? DL.getStructLayout(STy) : nullptr;
151b60736ecSDimitry Andric for (unsigned I = 0, E = STy->getNumElements(); I != E; ++I) {
152b60736ecSDimitry Andric uint64_t EltOffset = SL ? SL->getElementOffset(I) : 0;
153e6d15924SDimitry Andric computeValueLLTs(DL, *STy->getElementType(I), ValueTys, Offsets,
154b60736ecSDimitry Andric StartingOffset + EltOffset);
155b60736ecSDimitry Andric }
156e6d15924SDimitry Andric return;
157e6d15924SDimitry Andric }
158e6d15924SDimitry Andric // Given an array type, recursively traverse the elements.
159e6d15924SDimitry Andric if (ArrayType *ATy = dyn_cast<ArrayType>(&Ty)) {
160e6d15924SDimitry Andric Type *EltTy = ATy->getElementType();
161b60736ecSDimitry Andric uint64_t EltSize = DL.getTypeAllocSize(EltTy).getFixedValue();
162e6d15924SDimitry Andric for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
163e6d15924SDimitry Andric computeValueLLTs(DL, *EltTy, ValueTys, Offsets,
164e6d15924SDimitry Andric StartingOffset + i * EltSize);
165e6d15924SDimitry Andric return;
166e6d15924SDimitry Andric }
167e6d15924SDimitry Andric // Interpret void as zero return values.
168e6d15924SDimitry Andric if (Ty.isVoidTy())
169e6d15924SDimitry Andric return;
170e6d15924SDimitry Andric // Base case: we can get an LLT for this LLVM IR type.
171e6d15924SDimitry Andric ValueTys.push_back(getLLTForType(Ty, DL));
172e6d15924SDimitry Andric if (Offsets != nullptr)
173e6d15924SDimitry Andric Offsets->push_back(StartingOffset * 8);
174e6d15924SDimitry Andric }
175e6d15924SDimitry Andric
176d7f7719eSRoman Divacky /// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
ExtractTypeInfo(Value * V)17767c32a98SDimitry Andric GlobalValue *llvm::ExtractTypeInfo(Value *V) {
178d7f7719eSRoman Divacky V = V->stripPointerCasts();
17967c32a98SDimitry Andric GlobalValue *GV = dyn_cast<GlobalValue>(V);
18067c32a98SDimitry Andric GlobalVariable *Var = dyn_cast<GlobalVariable>(V);
181d7f7719eSRoman Divacky
18267c32a98SDimitry Andric if (Var && Var->getName() == "llvm.eh.catch.all.value") {
18367c32a98SDimitry Andric assert(Var->hasInitializer() &&
184d7f7719eSRoman Divacky "The EH catch-all value must have an initializer");
18567c32a98SDimitry Andric Value *Init = Var->getInitializer();
18667c32a98SDimitry Andric GV = dyn_cast<GlobalValue>(Init);
187d7f7719eSRoman Divacky if (!GV) V = cast<ConstantPointerNull>(Init);
188d7f7719eSRoman Divacky }
189d7f7719eSRoman Divacky
190d7f7719eSRoman Divacky assert((GV || isa<ConstantPointerNull>(V)) &&
191d7f7719eSRoman Divacky "TypeInfo must be a global variable or NULL");
192d7f7719eSRoman Divacky return GV;
193d7f7719eSRoman Divacky }
194d7f7719eSRoman Divacky
195d7f7719eSRoman Divacky /// getFCmpCondCode - Return the ISD condition code corresponding to
196d7f7719eSRoman Divacky /// the given LLVM IR floating-point condition code. This includes
197d7f7719eSRoman Divacky /// consideration of global floating-point math flags.
198d7f7719eSRoman Divacky ///
getFCmpCondCode(FCmpInst::Predicate Pred)199d7f7719eSRoman Divacky ISD::CondCode llvm::getFCmpCondCode(FCmpInst::Predicate Pred) {
200d7f7719eSRoman Divacky switch (Pred) {
20163faed5bSDimitry Andric case FCmpInst::FCMP_FALSE: return ISD::SETFALSE;
20263faed5bSDimitry Andric case FCmpInst::FCMP_OEQ: return ISD::SETOEQ;
20363faed5bSDimitry Andric case FCmpInst::FCMP_OGT: return ISD::SETOGT;
20463faed5bSDimitry Andric case FCmpInst::FCMP_OGE: return ISD::SETOGE;
20563faed5bSDimitry Andric case FCmpInst::FCMP_OLT: return ISD::SETOLT;
20663faed5bSDimitry Andric case FCmpInst::FCMP_OLE: return ISD::SETOLE;
20763faed5bSDimitry Andric case FCmpInst::FCMP_ONE: return ISD::SETONE;
20863faed5bSDimitry Andric case FCmpInst::FCMP_ORD: return ISD::SETO;
20963faed5bSDimitry Andric case FCmpInst::FCMP_UNO: return ISD::SETUO;
21063faed5bSDimitry Andric case FCmpInst::FCMP_UEQ: return ISD::SETUEQ;
21163faed5bSDimitry Andric case FCmpInst::FCMP_UGT: return ISD::SETUGT;
21263faed5bSDimitry Andric case FCmpInst::FCMP_UGE: return ISD::SETUGE;
21363faed5bSDimitry Andric case FCmpInst::FCMP_ULT: return ISD::SETULT;
21463faed5bSDimitry Andric case FCmpInst::FCMP_ULE: return ISD::SETULE;
21563faed5bSDimitry Andric case FCmpInst::FCMP_UNE: return ISD::SETUNE;
21663faed5bSDimitry Andric case FCmpInst::FCMP_TRUE: return ISD::SETTRUE;
21763faed5bSDimitry Andric default: llvm_unreachable("Invalid FCmp predicate opcode!");
218d7f7719eSRoman Divacky }
21963faed5bSDimitry Andric }
22063faed5bSDimitry Andric
getFCmpCodeWithoutNaN(ISD::CondCode CC)22163faed5bSDimitry Andric ISD::CondCode llvm::getFCmpCodeWithoutNaN(ISD::CondCode CC) {
22263faed5bSDimitry Andric switch (CC) {
22363faed5bSDimitry Andric case ISD::SETOEQ: case ISD::SETUEQ: return ISD::SETEQ;
22463faed5bSDimitry Andric case ISD::SETONE: case ISD::SETUNE: return ISD::SETNE;
22563faed5bSDimitry Andric case ISD::SETOLT: case ISD::SETULT: return ISD::SETLT;
22663faed5bSDimitry Andric case ISD::SETOLE: case ISD::SETULE: return ISD::SETLE;
22763faed5bSDimitry Andric case ISD::SETOGT: case ISD::SETUGT: return ISD::SETGT;
22863faed5bSDimitry Andric case ISD::SETOGE: case ISD::SETUGE: return ISD::SETGE;
22963faed5bSDimitry Andric default: return CC;
23063faed5bSDimitry Andric }
231d7f7719eSRoman Divacky }
232d7f7719eSRoman Divacky
getICmpCondCode(ICmpInst::Predicate Pred)233d7f7719eSRoman Divacky ISD::CondCode llvm::getICmpCondCode(ICmpInst::Predicate Pred) {
234d7f7719eSRoman Divacky switch (Pred) {
235d7f7719eSRoman Divacky case ICmpInst::ICMP_EQ: return ISD::SETEQ;
236d7f7719eSRoman Divacky case ICmpInst::ICMP_NE: return ISD::SETNE;
237d7f7719eSRoman Divacky case ICmpInst::ICMP_SLE: return ISD::SETLE;
238d7f7719eSRoman Divacky case ICmpInst::ICMP_ULE: return ISD::SETULE;
239d7f7719eSRoman Divacky case ICmpInst::ICMP_SGE: return ISD::SETGE;
240d7f7719eSRoman Divacky case ICmpInst::ICMP_UGE: return ISD::SETUGE;
241d7f7719eSRoman Divacky case ICmpInst::ICMP_SLT: return ISD::SETLT;
242d7f7719eSRoman Divacky case ICmpInst::ICMP_ULT: return ISD::SETULT;
243d7f7719eSRoman Divacky case ICmpInst::ICMP_SGT: return ISD::SETGT;
244d7f7719eSRoman Divacky case ICmpInst::ICMP_UGT: return ISD::SETUGT;
245d7f7719eSRoman Divacky default:
246d7f7719eSRoman Divacky llvm_unreachable("Invalid ICmp predicate opcode!");
247d7f7719eSRoman Divacky }
248d7f7719eSRoman Divacky }
249d7f7719eSRoman Divacky
getICmpCondCode(ISD::CondCode Pred)250c0981da4SDimitry Andric ICmpInst::Predicate llvm::getICmpCondCode(ISD::CondCode Pred) {
251c0981da4SDimitry Andric switch (Pred) {
252c0981da4SDimitry Andric case ISD::SETEQ:
253c0981da4SDimitry Andric return ICmpInst::ICMP_EQ;
254c0981da4SDimitry Andric case ISD::SETNE:
255c0981da4SDimitry Andric return ICmpInst::ICMP_NE;
256c0981da4SDimitry Andric case ISD::SETLE:
257c0981da4SDimitry Andric return ICmpInst::ICMP_SLE;
258c0981da4SDimitry Andric case ISD::SETULE:
259c0981da4SDimitry Andric return ICmpInst::ICMP_ULE;
260c0981da4SDimitry Andric case ISD::SETGE:
261c0981da4SDimitry Andric return ICmpInst::ICMP_SGE;
262c0981da4SDimitry Andric case ISD::SETUGE:
263c0981da4SDimitry Andric return ICmpInst::ICMP_UGE;
264c0981da4SDimitry Andric case ISD::SETLT:
265c0981da4SDimitry Andric return ICmpInst::ICMP_SLT;
266c0981da4SDimitry Andric case ISD::SETULT:
267c0981da4SDimitry Andric return ICmpInst::ICMP_ULT;
268c0981da4SDimitry Andric case ISD::SETGT:
269c0981da4SDimitry Andric return ICmpInst::ICMP_SGT;
270c0981da4SDimitry Andric case ISD::SETUGT:
271c0981da4SDimitry Andric return ICmpInst::ICMP_UGT;
272c0981da4SDimitry Andric default:
273c0981da4SDimitry Andric llvm_unreachable("Invalid ISD integer condition code!");
274c0981da4SDimitry Andric }
275c0981da4SDimitry Andric }
276c0981da4SDimitry Andric
isNoopBitcast(Type * T1,Type * T2,const TargetLoweringBase & TLI)27759d6cff9SDimitry Andric static bool isNoopBitcast(Type *T1, Type *T2,
278f8af5cf6SDimitry Andric const TargetLoweringBase& TLI) {
27959d6cff9SDimitry Andric return T1 == T2 || (T1->isPointerTy() && T2->isPointerTy()) ||
28059d6cff9SDimitry Andric (isa<VectorType>(T1) && isa<VectorType>(T2) &&
28159d6cff9SDimitry Andric TLI.isTypeLegal(EVT::getEVT(T1)) && TLI.isTypeLegal(EVT::getEVT(T2)));
28259d6cff9SDimitry Andric }
28358b69754SDimitry Andric
284f8af5cf6SDimitry Andric /// Look through operations that will be free to find the earliest source of
285f8af5cf6SDimitry Andric /// this value.
286f8af5cf6SDimitry Andric ///
287706b4fc4SDimitry Andric /// @param ValLoc If V has aggregate type, we will be interested in a particular
288f8af5cf6SDimitry Andric /// scalar component. This records its address; the reverse of this list gives a
289f8af5cf6SDimitry Andric /// sequence of indices appropriate for an extractvalue to locate the important
290f8af5cf6SDimitry Andric /// value. This value is updated during the function and on exit will indicate
291f8af5cf6SDimitry Andric /// similar information for the Value returned.
292f8af5cf6SDimitry Andric ///
293f8af5cf6SDimitry Andric /// @param DataBits If this function looks through truncate instructions, this
294f8af5cf6SDimitry Andric /// will record the smallest size attained.
getNoopInput(const Value * V,SmallVectorImpl<unsigned> & ValLoc,unsigned & DataBits,const TargetLoweringBase & TLI,const DataLayout & DL)295f8af5cf6SDimitry Andric static const Value *getNoopInput(const Value *V,
296f8af5cf6SDimitry Andric SmallVectorImpl<unsigned> &ValLoc,
297f8af5cf6SDimitry Andric unsigned &DataBits,
298ee8648bdSDimitry Andric const TargetLoweringBase &TLI,
299ee8648bdSDimitry Andric const DataLayout &DL) {
30059d6cff9SDimitry Andric while (true) {
30159d6cff9SDimitry Andric // Try to look through V1; if V1 is not an instruction, it can't be looked
30259d6cff9SDimitry Andric // through.
303f8af5cf6SDimitry Andric const Instruction *I = dyn_cast<Instruction>(V);
304f8af5cf6SDimitry Andric if (!I || I->getNumOperands() == 0) return V;
3055ca98fd9SDimitry Andric const Value *NoopInput = nullptr;
306f8af5cf6SDimitry Andric
30758b69754SDimitry Andric Value *Op = I->getOperand(0);
308f8af5cf6SDimitry Andric if (isa<BitCastInst>(I)) {
30958b69754SDimitry Andric // Look through truly no-op bitcasts.
31059d6cff9SDimitry Andric if (isNoopBitcast(Op->getType(), I->getType(), TLI))
31159d6cff9SDimitry Andric NoopInput = Op;
31259d6cff9SDimitry Andric } else if (isa<GetElementPtrInst>(I)) {
31359d6cff9SDimitry Andric // Look through getelementptr
31459d6cff9SDimitry Andric if (cast<GetElementPtrInst>(I)->hasAllZeroIndices())
31559d6cff9SDimitry Andric NoopInput = Op;
31659d6cff9SDimitry Andric } else if (isa<IntToPtrInst>(I)) {
31758b69754SDimitry Andric // Look through inttoptr.
31859d6cff9SDimitry Andric // Make sure this isn't a truncating or extending cast. We could
31959d6cff9SDimitry Andric // support this eventually, but don't bother for now.
32059d6cff9SDimitry Andric if (!isa<VectorType>(I->getType()) &&
321ee8648bdSDimitry Andric DL.getPointerSizeInBits() ==
32258b69754SDimitry Andric cast<IntegerType>(Op->getType())->getBitWidth())
32359d6cff9SDimitry Andric NoopInput = Op;
32459d6cff9SDimitry Andric } else if (isa<PtrToIntInst>(I)) {
32558b69754SDimitry Andric // Look through ptrtoint.
32659d6cff9SDimitry Andric // Make sure this isn't a truncating or extending cast. We could
32759d6cff9SDimitry Andric // support this eventually, but don't bother for now.
32859d6cff9SDimitry Andric if (!isa<VectorType>(I->getType()) &&
329ee8648bdSDimitry Andric DL.getPointerSizeInBits() ==
33058b69754SDimitry Andric cast<IntegerType>(I->getType())->getBitWidth())
33159d6cff9SDimitry Andric NoopInput = Op;
332f8af5cf6SDimitry Andric } else if (isa<TruncInst>(I) &&
333f8af5cf6SDimitry Andric TLI.allowTruncateForTailCall(Op->getType(), I->getType())) {
334e3b55780SDimitry Andric DataBits =
335e3b55780SDimitry Andric std::min((uint64_t)DataBits,
336e3b55780SDimitry Andric I->getType()->getPrimitiveSizeInBits().getFixedValue());
337f8af5cf6SDimitry Andric NoopInput = Op;
338cfca06d7SDimitry Andric } else if (auto *CB = dyn_cast<CallBase>(I)) {
339cfca06d7SDimitry Andric const Value *ReturnedOp = CB->getReturnedArgOperand();
340c82ad72fSDimitry Andric if (ReturnedOp && isNoopBitcast(ReturnedOp->getType(), I->getType(), TLI))
341c82ad72fSDimitry Andric NoopInput = ReturnedOp;
342f8af5cf6SDimitry Andric } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(V)) {
343f8af5cf6SDimitry Andric // Value may come from either the aggregate or the scalar
344f8af5cf6SDimitry Andric ArrayRef<unsigned> InsertLoc = IVI->getIndices();
3455a5ac124SDimitry Andric if (ValLoc.size() >= InsertLoc.size() &&
3465a5ac124SDimitry Andric std::equal(InsertLoc.begin(), InsertLoc.end(), ValLoc.rbegin())) {
347f8af5cf6SDimitry Andric // The type being inserted is a nested sub-type of the aggregate; we
348f8af5cf6SDimitry Andric // have to remove those initial indices to get the location we're
349f8af5cf6SDimitry Andric // interested in for the operand.
350f8af5cf6SDimitry Andric ValLoc.resize(ValLoc.size() - InsertLoc.size());
351f8af5cf6SDimitry Andric NoopInput = IVI->getInsertedValueOperand();
352f8af5cf6SDimitry Andric } else {
353f8af5cf6SDimitry Andric // The struct we're inserting into has the value we're interested in, no
354f8af5cf6SDimitry Andric // change of address.
355f8af5cf6SDimitry Andric NoopInput = Op;
356f8af5cf6SDimitry Andric }
357f8af5cf6SDimitry Andric } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(V)) {
358f8af5cf6SDimitry Andric // The part we're interested in will inevitably be some sub-section of the
359f8af5cf6SDimitry Andric // previous aggregate. Combine the two paths to obtain the true address of
360f8af5cf6SDimitry Andric // our element.
361f8af5cf6SDimitry Andric ArrayRef<unsigned> ExtractLoc = EVI->getIndices();
3625a5ac124SDimitry Andric ValLoc.append(ExtractLoc.rbegin(), ExtractLoc.rend());
363f8af5cf6SDimitry Andric NoopInput = Op;
364f8af5cf6SDimitry Andric }
365f8af5cf6SDimitry Andric // Terminate if we couldn't find anything to look through.
366f8af5cf6SDimitry Andric if (!NoopInput)
367f8af5cf6SDimitry Andric return V;
368f8af5cf6SDimitry Andric
369f8af5cf6SDimitry Andric V = NoopInput;
37059d6cff9SDimitry Andric }
37158b69754SDimitry Andric }
37258b69754SDimitry Andric
373f8af5cf6SDimitry Andric /// Return true if this scalar return value only has bits discarded on its path
374f8af5cf6SDimitry Andric /// from the "tail call" to the "ret". This includes the obvious noop
375f8af5cf6SDimitry Andric /// instructions handled by getNoopInput above as well as free truncations (or
376f8af5cf6SDimitry Andric /// extensions prior to the call).
slotOnlyDiscardsData(const Value * RetVal,const Value * CallVal,SmallVectorImpl<unsigned> & RetIndices,SmallVectorImpl<unsigned> & CallIndices,bool AllowDifferingSizes,const TargetLoweringBase & TLI,const DataLayout & DL)377f8af5cf6SDimitry Andric static bool slotOnlyDiscardsData(const Value *RetVal, const Value *CallVal,
378f8af5cf6SDimitry Andric SmallVectorImpl<unsigned> &RetIndices,
379f8af5cf6SDimitry Andric SmallVectorImpl<unsigned> &CallIndices,
380f8af5cf6SDimitry Andric bool AllowDifferingSizes,
381ee8648bdSDimitry Andric const TargetLoweringBase &TLI,
382ee8648bdSDimitry Andric const DataLayout &DL) {
38358b69754SDimitry Andric
384f8af5cf6SDimitry Andric // Trace the sub-value needed by the return value as far back up the graph as
385f8af5cf6SDimitry Andric // possible, in the hope that it will intersect with the value produced by the
386f8af5cf6SDimitry Andric // call. In the simple case with no "returned" attribute, the hope is actually
387f8af5cf6SDimitry Andric // that we end up back at the tail call instruction itself.
388f8af5cf6SDimitry Andric unsigned BitsRequired = UINT_MAX;
389ee8648bdSDimitry Andric RetVal = getNoopInput(RetVal, RetIndices, BitsRequired, TLI, DL);
39059d6cff9SDimitry Andric
391f8af5cf6SDimitry Andric // If this slot in the value returned is undef, it doesn't matter what the
392f8af5cf6SDimitry Andric // call puts there, it'll be fine.
393f8af5cf6SDimitry Andric if (isa<UndefValue>(RetVal))
394f8af5cf6SDimitry Andric return true;
39559d6cff9SDimitry Andric
396f8af5cf6SDimitry Andric // Now do a similar search up through the graph to find where the value
397f8af5cf6SDimitry Andric // actually returned by the "tail call" comes from. In the simple case without
398f8af5cf6SDimitry Andric // a "returned" attribute, the search will be blocked immediately and the loop
399f8af5cf6SDimitry Andric // a Noop.
400f8af5cf6SDimitry Andric unsigned BitsProvided = UINT_MAX;
401ee8648bdSDimitry Andric CallVal = getNoopInput(CallVal, CallIndices, BitsProvided, TLI, DL);
402f8af5cf6SDimitry Andric
403f8af5cf6SDimitry Andric // There's no hope if we can't actually trace them to (the same part of!) the
404f8af5cf6SDimitry Andric // same value.
405f8af5cf6SDimitry Andric if (CallVal != RetVal || CallIndices != RetIndices)
406f8af5cf6SDimitry Andric return false;
407f8af5cf6SDimitry Andric
408f8af5cf6SDimitry Andric // However, intervening truncates may have made the call non-tail. Make sure
409f8af5cf6SDimitry Andric // all the bits that are needed by the "ret" have been provided by the "tail
410f8af5cf6SDimitry Andric // call". FIXME: with sufficiently cunning bit-tracking, we could look through
411f8af5cf6SDimitry Andric // extensions too.
412f8af5cf6SDimitry Andric if (BitsProvided < BitsRequired ||
413f8af5cf6SDimitry Andric (!AllowDifferingSizes && BitsProvided != BitsRequired))
414f8af5cf6SDimitry Andric return false;
415f8af5cf6SDimitry Andric
41659d6cff9SDimitry Andric return true;
41759d6cff9SDimitry Andric }
418f8af5cf6SDimitry Andric
419f8af5cf6SDimitry Andric /// For an aggregate type, determine whether a given index is within bounds or
420f8af5cf6SDimitry Andric /// not.
indexReallyValid(Type * T,unsigned Idx)421cfca06d7SDimitry Andric static bool indexReallyValid(Type *T, unsigned Idx) {
422f8af5cf6SDimitry Andric if (ArrayType *AT = dyn_cast<ArrayType>(T))
423f8af5cf6SDimitry Andric return Idx < AT->getNumElements();
424f8af5cf6SDimitry Andric
425f8af5cf6SDimitry Andric return Idx < cast<StructType>(T)->getNumElements();
42659d6cff9SDimitry Andric }
427f8af5cf6SDimitry Andric
428f8af5cf6SDimitry Andric /// Move the given iterators to the next leaf type in depth first traversal.
429f8af5cf6SDimitry Andric ///
430f8af5cf6SDimitry Andric /// Performs a depth-first traversal of the type as specified by its arguments,
431f8af5cf6SDimitry Andric /// stopping at the next leaf node (which may be a legitimate scalar type or an
432f8af5cf6SDimitry Andric /// empty struct or array).
433f8af5cf6SDimitry Andric ///
434f8af5cf6SDimitry Andric /// @param SubTypes List of the partial components making up the type from
435f8af5cf6SDimitry Andric /// outermost to innermost non-empty aggregate. The element currently
436f8af5cf6SDimitry Andric /// represented is SubTypes.back()->getTypeAtIndex(Path.back() - 1).
437f8af5cf6SDimitry Andric ///
438f8af5cf6SDimitry Andric /// @param Path Set of extractvalue indices leading from the outermost type
439f8af5cf6SDimitry Andric /// (SubTypes[0]) to the leaf node currently represented.
440f8af5cf6SDimitry Andric ///
441f8af5cf6SDimitry Andric /// @returns true if a new type was found, false otherwise. Calling this
442f8af5cf6SDimitry Andric /// function again on a finished iterator will repeatedly return
443f8af5cf6SDimitry Andric /// false. SubTypes.back()->getTypeAtIndex(Path.back()) is either an empty
444f8af5cf6SDimitry Andric /// aggregate or a non-aggregate
advanceToNextLeafType(SmallVectorImpl<Type * > & SubTypes,SmallVectorImpl<unsigned> & Path)445cfca06d7SDimitry Andric static bool advanceToNextLeafType(SmallVectorImpl<Type *> &SubTypes,
446f8af5cf6SDimitry Andric SmallVectorImpl<unsigned> &Path) {
447f8af5cf6SDimitry Andric // First march back up the tree until we can successfully increment one of the
448f8af5cf6SDimitry Andric // coordinates in Path.
449f8af5cf6SDimitry Andric while (!Path.empty() && !indexReallyValid(SubTypes.back(), Path.back() + 1)) {
450f8af5cf6SDimitry Andric Path.pop_back();
451f8af5cf6SDimitry Andric SubTypes.pop_back();
452f8af5cf6SDimitry Andric }
453f8af5cf6SDimitry Andric
454f8af5cf6SDimitry Andric // If we reached the top, then the iterator is done.
455f8af5cf6SDimitry Andric if (Path.empty())
456f8af5cf6SDimitry Andric return false;
457f8af5cf6SDimitry Andric
458f8af5cf6SDimitry Andric // We know there's *some* valid leaf now, so march back down the tree picking
459f8af5cf6SDimitry Andric // out the left-most element at each node.
460f8af5cf6SDimitry Andric ++Path.back();
461cfca06d7SDimitry Andric Type *DeeperType =
462cfca06d7SDimitry Andric ExtractValueInst::getIndexedType(SubTypes.back(), Path.back());
463f8af5cf6SDimitry Andric while (DeeperType->isAggregateType()) {
464cfca06d7SDimitry Andric if (!indexReallyValid(DeeperType, 0))
465f8af5cf6SDimitry Andric return true;
466f8af5cf6SDimitry Andric
467cfca06d7SDimitry Andric SubTypes.push_back(DeeperType);
468f8af5cf6SDimitry Andric Path.push_back(0);
469f8af5cf6SDimitry Andric
470cfca06d7SDimitry Andric DeeperType = ExtractValueInst::getIndexedType(DeeperType, 0);
471f8af5cf6SDimitry Andric }
472f8af5cf6SDimitry Andric
47359d6cff9SDimitry Andric return true;
47459d6cff9SDimitry Andric }
475f8af5cf6SDimitry Andric
476f8af5cf6SDimitry Andric /// Find the first non-empty, scalar-like type in Next and setup the iterator
477f8af5cf6SDimitry Andric /// components.
478f8af5cf6SDimitry Andric ///
479f8af5cf6SDimitry Andric /// Assuming Next is an aggregate of some kind, this function will traverse the
480f8af5cf6SDimitry Andric /// tree from left to right (i.e. depth-first) looking for the first
481f8af5cf6SDimitry Andric /// non-aggregate type which will play a role in function return.
482f8af5cf6SDimitry Andric ///
483f8af5cf6SDimitry Andric /// For example, if Next was {[0 x i64], {{}, i32, {}}, i32} then we would setup
484f8af5cf6SDimitry Andric /// Path as [1, 1] and SubTypes as [Next, {{}, i32, {}}] to represent the first
485f8af5cf6SDimitry Andric /// i32 in that type.
firstRealType(Type * Next,SmallVectorImpl<Type * > & SubTypes,SmallVectorImpl<unsigned> & Path)486cfca06d7SDimitry Andric static bool firstRealType(Type *Next, SmallVectorImpl<Type *> &SubTypes,
487f8af5cf6SDimitry Andric SmallVectorImpl<unsigned> &Path) {
488f8af5cf6SDimitry Andric // First initialise the iterator components to the first "leaf" node
489f8af5cf6SDimitry Andric // (i.e. node with no valid sub-type at any index, so {} does count as a leaf
490f8af5cf6SDimitry Andric // despite nominally being an aggregate).
491cfca06d7SDimitry Andric while (Type *FirstInner = ExtractValueInst::getIndexedType(Next, 0)) {
492cfca06d7SDimitry Andric SubTypes.push_back(Next);
493f8af5cf6SDimitry Andric Path.push_back(0);
494cfca06d7SDimitry Andric Next = FirstInner;
49559d6cff9SDimitry Andric }
49659d6cff9SDimitry Andric
497f8af5cf6SDimitry Andric // If there's no Path now, Next was originally scalar already (or empty
498f8af5cf6SDimitry Andric // leaf). We're done.
499f8af5cf6SDimitry Andric if (Path.empty())
500f8af5cf6SDimitry Andric return true;
50159d6cff9SDimitry Andric
502f8af5cf6SDimitry Andric // Otherwise, use normal iteration to keep looking through the tree until we
503f8af5cf6SDimitry Andric // find a non-aggregate type.
504cfca06d7SDimitry Andric while (ExtractValueInst::getIndexedType(SubTypes.back(), Path.back())
505cfca06d7SDimitry Andric ->isAggregateType()) {
506f8af5cf6SDimitry Andric if (!advanceToNextLeafType(SubTypes, Path))
50759d6cff9SDimitry Andric return false;
50859d6cff9SDimitry Andric }
50958b69754SDimitry Andric
510f8af5cf6SDimitry Andric return true;
511f8af5cf6SDimitry Andric }
512f8af5cf6SDimitry Andric
513f8af5cf6SDimitry Andric /// Set the iterator data-structures to the next non-empty, non-aggregate
514f8af5cf6SDimitry Andric /// subtype.
nextRealType(SmallVectorImpl<Type * > & SubTypes,SmallVectorImpl<unsigned> & Path)515cfca06d7SDimitry Andric static bool nextRealType(SmallVectorImpl<Type *> &SubTypes,
516f8af5cf6SDimitry Andric SmallVectorImpl<unsigned> &Path) {
517f8af5cf6SDimitry Andric do {
518f8af5cf6SDimitry Andric if (!advanceToNextLeafType(SubTypes, Path))
519f8af5cf6SDimitry Andric return false;
520f8af5cf6SDimitry Andric
521f8af5cf6SDimitry Andric assert(!Path.empty() && "found a leaf but didn't set the path?");
522cfca06d7SDimitry Andric } while (ExtractValueInst::getIndexedType(SubTypes.back(), Path.back())
523cfca06d7SDimitry Andric ->isAggregateType());
524f8af5cf6SDimitry Andric
525f8af5cf6SDimitry Andric return true;
526f8af5cf6SDimitry Andric }
527f8af5cf6SDimitry Andric
528f8af5cf6SDimitry Andric
529d7f7719eSRoman Divacky /// Test if the given instruction is in a position to be optimized
530d7f7719eSRoman Divacky /// with a tail-call. This roughly means that it's in a block with
531d7f7719eSRoman Divacky /// a return and there's nothing that needs to be scheduled
532d7f7719eSRoman Divacky /// between it and the return.
533d7f7719eSRoman Divacky ///
534d7f7719eSRoman Divacky /// This function only tests target-independent requirements.
isInTailCallPosition(const CallBase & Call,const TargetMachine & TM,bool ReturnsFirstArg)535ac9a064cSDimitry Andric bool llvm::isInTailCallPosition(const CallBase &Call, const TargetMachine &TM,
536ac9a064cSDimitry Andric bool ReturnsFirstArg) {
537cfca06d7SDimitry Andric const BasicBlock *ExitBB = Call.getParent();
538d8e91e46SDimitry Andric const Instruction *Term = ExitBB->getTerminator();
539d7f7719eSRoman Divacky const ReturnInst *Ret = dyn_cast<ReturnInst>(Term);
540d7f7719eSRoman Divacky
541d7f7719eSRoman Divacky // The block must end in a return statement or unreachable.
542d7f7719eSRoman Divacky //
543d7f7719eSRoman Divacky // FIXME: Decline tailcall if it's not guaranteed and if the block ends in
544d7f7719eSRoman Divacky // an unreachable, for now. The way tailcall optimization is currently
545d7f7719eSRoman Divacky // implemented means it will add an epilogue followed by a jump. That is
546d7f7719eSRoman Divacky // not profitable. Also, if the callee is a special function (e.g.
547d7f7719eSRoman Divacky // longjmp on x86), it can end up causing miscompilation that has not
548d7f7719eSRoman Divacky // been fully understood.
549344a3780SDimitry Andric if (!Ret && ((!TM.Options.GuaranteedTailCallOpt &&
550344a3780SDimitry Andric Call.getCallingConv() != CallingConv::Tail &&
551344a3780SDimitry Andric Call.getCallingConv() != CallingConv::SwiftTail) ||
552344a3780SDimitry Andric !isa<UnreachableInst>(Term)))
55358b69754SDimitry Andric return false;
554d7f7719eSRoman Divacky
555d7f7719eSRoman Divacky // If I will have a chain, make sure no other instruction that will have a
556d7f7719eSRoman Divacky // chain interposes between I and the return.
557cfca06d7SDimitry Andric // Check for all calls including speculatable functions.
5585ca98fd9SDimitry Andric for (BasicBlock::const_iterator BBI = std::prev(ExitBB->end(), 2);; --BBI) {
559cfca06d7SDimitry Andric if (&*BBI == &Call)
560d7f7719eSRoman Divacky break;
561d7f7719eSRoman Divacky // Debug info intrinsics do not get in the way of tail call optimization.
562b60736ecSDimitry Andric // Pseudo probe intrinsics do not block tail call optimization either.
563c0981da4SDimitry Andric if (BBI->isDebugOrPseudoInst())
564b60736ecSDimitry Andric continue;
565b60736ecSDimitry Andric // A lifetime end, assume or noalias.decl intrinsic should not stop tail
566b60736ecSDimitry Andric // call optimization.
567d8e91e46SDimitry Andric if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(BBI))
5681d5ae102SDimitry Andric if (II->getIntrinsicID() == Intrinsic::lifetime_end ||
569b60736ecSDimitry Andric II->getIntrinsicID() == Intrinsic::assume ||
570b60736ecSDimitry Andric II->getIntrinsicID() == Intrinsic::experimental_noalias_scope_decl)
571d8e91e46SDimitry Andric continue;
572d7f7719eSRoman Divacky if (BBI->mayHaveSideEffects() || BBI->mayReadFromMemory() ||
573dd58ef01SDimitry Andric !isSafeToSpeculativelyExecute(&*BBI))
574d7f7719eSRoman Divacky return false;
575d7f7719eSRoman Divacky }
576d7f7719eSRoman Divacky
5775a5ac124SDimitry Andric const Function *F = ExitBB->getParent();
57867c32a98SDimitry Andric return returnTypeIsEligibleForTailCall(
579ac9a064cSDimitry Andric F, &Call, Ret, *TM.getSubtargetImpl(*F)->getTargetLowering(),
580ac9a064cSDimitry Andric ReturnsFirstArg);
581f8af5cf6SDimitry Andric }
582f8af5cf6SDimitry Andric
attributesPermitTailCall(const Function * F,const Instruction * I,const ReturnInst * Ret,const TargetLoweringBase & TLI,bool * AllowDifferingSizes)583b915e9e0SDimitry Andric bool llvm::attributesPermitTailCall(const Function *F, const Instruction *I,
584b915e9e0SDimitry Andric const ReturnInst *Ret,
585b915e9e0SDimitry Andric const TargetLoweringBase &TLI,
586b915e9e0SDimitry Andric bool *AllowDifferingSizes) {
587b915e9e0SDimitry Andric // ADS may be null, so don't write to it directly.
588b915e9e0SDimitry Andric bool DummyADS;
589b915e9e0SDimitry Andric bool &ADS = AllowDifferingSizes ? *AllowDifferingSizes : DummyADS;
590b915e9e0SDimitry Andric ADS = true;
591b915e9e0SDimitry Andric
5926f8fc217SDimitry Andric AttrBuilder CallerAttrs(F->getContext(), F->getAttributes().getRetAttrs());
5936f8fc217SDimitry Andric AttrBuilder CalleeAttrs(F->getContext(),
5946f8fc217SDimitry Andric cast<CallInst>(I)->getAttributes().getRetAttrs());
595b915e9e0SDimitry Andric
596706b4fc4SDimitry Andric // Following attributes are completely benign as far as calling convention
597d8e91e46SDimitry Andric // goes, they shouldn't affect whether the call is a tail call.
598ac9a064cSDimitry Andric for (const auto &Attr :
599ac9a064cSDimitry Andric {Attribute::Alignment, Attribute::Dereferenceable,
600344a3780SDimitry Andric Attribute::DereferenceableOrNull, Attribute::NoAlias,
601ac9a064cSDimitry Andric Attribute::NonNull, Attribute::NoUndef, Attribute::Range}) {
602344a3780SDimitry Andric CallerAttrs.removeAttribute(Attr);
603344a3780SDimitry Andric CalleeAttrs.removeAttribute(Attr);
604344a3780SDimitry Andric }
605b915e9e0SDimitry Andric
606b915e9e0SDimitry Andric if (CallerAttrs.contains(Attribute::ZExt)) {
607b915e9e0SDimitry Andric if (!CalleeAttrs.contains(Attribute::ZExt))
608b915e9e0SDimitry Andric return false;
609b915e9e0SDimitry Andric
610b915e9e0SDimitry Andric ADS = false;
611b915e9e0SDimitry Andric CallerAttrs.removeAttribute(Attribute::ZExt);
612b915e9e0SDimitry Andric CalleeAttrs.removeAttribute(Attribute::ZExt);
613b915e9e0SDimitry Andric } else if (CallerAttrs.contains(Attribute::SExt)) {
614b915e9e0SDimitry Andric if (!CalleeAttrs.contains(Attribute::SExt))
615b915e9e0SDimitry Andric return false;
616b915e9e0SDimitry Andric
617b915e9e0SDimitry Andric ADS = false;
618b915e9e0SDimitry Andric CallerAttrs.removeAttribute(Attribute::SExt);
619b915e9e0SDimitry Andric CalleeAttrs.removeAttribute(Attribute::SExt);
620b915e9e0SDimitry Andric }
621b915e9e0SDimitry Andric
622d8e91e46SDimitry Andric // Drop sext and zext return attributes if the result is not used.
623d8e91e46SDimitry Andric // This enables tail calls for code like:
624d8e91e46SDimitry Andric //
625d8e91e46SDimitry Andric // define void @caller() {
626d8e91e46SDimitry Andric // entry:
627d8e91e46SDimitry Andric // %unused_result = tail call zeroext i1 @callee()
628d8e91e46SDimitry Andric // br label %retlabel
629d8e91e46SDimitry Andric // retlabel:
630d8e91e46SDimitry Andric // ret void
631d8e91e46SDimitry Andric // }
632d8e91e46SDimitry Andric if (I->use_empty()) {
633d8e91e46SDimitry Andric CalleeAttrs.removeAttribute(Attribute::SExt);
634d8e91e46SDimitry Andric CalleeAttrs.removeAttribute(Attribute::ZExt);
635d8e91e46SDimitry Andric }
636d8e91e46SDimitry Andric
637b915e9e0SDimitry Andric // If they're still different, there's some facet we don't understand
638b915e9e0SDimitry Andric // (currently only "inreg", but in future who knows). It may be OK but the
639b915e9e0SDimitry Andric // only safe option is to reject the tail call.
640b915e9e0SDimitry Andric return CallerAttrs == CalleeAttrs;
641b915e9e0SDimitry Andric }
642b915e9e0SDimitry Andric
returnTypeIsEligibleForTailCall(const Function * F,const Instruction * I,const ReturnInst * Ret,const TargetLoweringBase & TLI,bool ReturnsFirstArg)643f8af5cf6SDimitry Andric bool llvm::returnTypeIsEligibleForTailCall(const Function *F,
644f8af5cf6SDimitry Andric const Instruction *I,
645f8af5cf6SDimitry Andric const ReturnInst *Ret,
646ac9a064cSDimitry Andric const TargetLoweringBase &TLI,
647ac9a064cSDimitry Andric bool ReturnsFirstArg) {
648d7f7719eSRoman Divacky // If the block ends with a void return or unreachable, it doesn't matter
649d7f7719eSRoman Divacky // what the call's return type is.
650d7f7719eSRoman Divacky if (!Ret || Ret->getNumOperands() == 0) return true;
651d7f7719eSRoman Divacky
652d7f7719eSRoman Divacky // If the return value is undef, it doesn't matter what the call's
653d7f7719eSRoman Divacky // return type is.
654d7f7719eSRoman Divacky if (isa<UndefValue>(Ret->getOperand(0))) return true;
655d7f7719eSRoman Divacky
656f8af5cf6SDimitry Andric // Make sure the attributes attached to each return are compatible.
657b915e9e0SDimitry Andric bool AllowDifferingSizes;
658b915e9e0SDimitry Andric if (!attributesPermitTailCall(F, I, Ret, TLI, &AllowDifferingSizes))
659f8af5cf6SDimitry Andric return false;
660f8af5cf6SDimitry Andric
661ac9a064cSDimitry Andric // If the return value is the first argument of the call.
662ac9a064cSDimitry Andric if (ReturnsFirstArg)
663044eb2f6SDimitry Andric return true;
664044eb2f6SDimitry Andric
665ac9a064cSDimitry Andric const Value *RetVal = Ret->getOperand(0), *CallVal = I;
666f8af5cf6SDimitry Andric SmallVector<unsigned, 4> RetPath, CallPath;
667cfca06d7SDimitry Andric SmallVector<Type *, 4> RetSubTypes, CallSubTypes;
668f8af5cf6SDimitry Andric
669f8af5cf6SDimitry Andric bool RetEmpty = !firstRealType(RetVal->getType(), RetSubTypes, RetPath);
670f8af5cf6SDimitry Andric bool CallEmpty = !firstRealType(CallVal->getType(), CallSubTypes, CallPath);
671f8af5cf6SDimitry Andric
672f8af5cf6SDimitry Andric // Nothing's actually returned, it doesn't matter what the callee put there
673f8af5cf6SDimitry Andric // it's a valid tail call.
674f8af5cf6SDimitry Andric if (RetEmpty)
675f8af5cf6SDimitry Andric return true;
676f8af5cf6SDimitry Andric
677f8af5cf6SDimitry Andric // Iterate pairwise through each of the value types making up the tail call
678f8af5cf6SDimitry Andric // and the corresponding return. For each one we want to know whether it's
679f8af5cf6SDimitry Andric // essentially going directly from the tail call to the ret, via operations
680f8af5cf6SDimitry Andric // that end up not generating any code.
681f8af5cf6SDimitry Andric //
682f8af5cf6SDimitry Andric // We allow a certain amount of covariance here. For example it's permitted
683f8af5cf6SDimitry Andric // for the tail call to define more bits than the ret actually cares about
684f8af5cf6SDimitry Andric // (e.g. via a truncate).
685f8af5cf6SDimitry Andric do {
686f8af5cf6SDimitry Andric if (CallEmpty) {
687f8af5cf6SDimitry Andric // We've exhausted the values produced by the tail call instruction, the
688f8af5cf6SDimitry Andric // rest are essentially undef. The type doesn't really matter, but we need
689f8af5cf6SDimitry Andric // *something*.
690cfca06d7SDimitry Andric Type *SlotType =
691cfca06d7SDimitry Andric ExtractValueInst::getIndexedType(RetSubTypes.back(), RetPath.back());
692f8af5cf6SDimitry Andric CallVal = UndefValue::get(SlotType);
693f8af5cf6SDimitry Andric }
694f8af5cf6SDimitry Andric
695f8af5cf6SDimitry Andric // The manipulations performed when we're looking through an insertvalue or
696f8af5cf6SDimitry Andric // an extractvalue would happen at the front of the RetPath list, so since
697f8af5cf6SDimitry Andric // we have to copy it anyway it's more efficient to create a reversed copy.
69877fc4c14SDimitry Andric SmallVector<unsigned, 4> TmpRetPath(llvm::reverse(RetPath));
69977fc4c14SDimitry Andric SmallVector<unsigned, 4> TmpCallPath(llvm::reverse(CallPath));
700f8af5cf6SDimitry Andric
701f8af5cf6SDimitry Andric // Finally, we can check whether the value produced by the tail call at this
702f8af5cf6SDimitry Andric // index is compatible with the value we return.
703f8af5cf6SDimitry Andric if (!slotOnlyDiscardsData(RetVal, CallVal, TmpRetPath, TmpCallPath,
704ee8648bdSDimitry Andric AllowDifferingSizes, TLI,
705ac9a064cSDimitry Andric F->getDataLayout()))
706f8af5cf6SDimitry Andric return false;
707f8af5cf6SDimitry Andric
708f8af5cf6SDimitry Andric CallEmpty = !nextRealType(CallSubTypes, CallPath);
709f8af5cf6SDimitry Andric } while(nextRealType(RetSubTypes, RetPath));
710f8af5cf6SDimitry Andric
711f8af5cf6SDimitry Andric return true;
712d7f7719eSRoman Divacky }
71367c32a98SDimitry Andric
funcReturnsFirstArgOfCall(const CallInst & CI)714ac9a064cSDimitry Andric bool llvm::funcReturnsFirstArgOfCall(const CallInst &CI) {
715ac9a064cSDimitry Andric const ReturnInst *Ret = dyn_cast<ReturnInst>(CI.getParent()->getTerminator());
716ac9a064cSDimitry Andric Value *RetVal = Ret ? Ret->getReturnValue() : nullptr;
717ac9a064cSDimitry Andric bool ReturnsFirstArg = false;
718ac9a064cSDimitry Andric if (RetVal && ((RetVal == CI.getArgOperand(0))))
719ac9a064cSDimitry Andric ReturnsFirstArg = true;
720ac9a064cSDimitry Andric return ReturnsFirstArg;
721ac9a064cSDimitry Andric }
722ac9a064cSDimitry Andric
collectEHScopeMembers(DenseMap<const MachineBasicBlock *,int> & EHScopeMembership,int EHScope,const MachineBasicBlock * MBB)723eb11fae6SDimitry Andric static void collectEHScopeMembers(
724eb11fae6SDimitry Andric DenseMap<const MachineBasicBlock *, int> &EHScopeMembership, int EHScope,
725dd58ef01SDimitry Andric const MachineBasicBlock *MBB) {
72601095a5dSDimitry Andric SmallVector<const MachineBasicBlock *, 16> Worklist = {MBB};
72701095a5dSDimitry Andric while (!Worklist.empty()) {
72801095a5dSDimitry Andric const MachineBasicBlock *Visiting = Worklist.pop_back_val();
729eb11fae6SDimitry Andric // Don't follow blocks which start new scopes.
73001095a5dSDimitry Andric if (Visiting->isEHPad() && Visiting != MBB)
73101095a5dSDimitry Andric continue;
73201095a5dSDimitry Andric
733eb11fae6SDimitry Andric // Add this MBB to our scope.
734eb11fae6SDimitry Andric auto P = EHScopeMembership.insert(std::make_pair(Visiting, EHScope));
735dd58ef01SDimitry Andric
736dd58ef01SDimitry Andric // Don't revisit blocks.
737dd58ef01SDimitry Andric if (!P.second) {
738eb11fae6SDimitry Andric assert(P.first->second == EHScope && "MBB is part of two scopes!");
73901095a5dSDimitry Andric continue;
740dd58ef01SDimitry Andric }
741dd58ef01SDimitry Andric
742eb11fae6SDimitry Andric // Returns are boundaries where scope transfer can occur, don't follow
743dd58ef01SDimitry Andric // successors.
744d8e91e46SDimitry Andric if (Visiting->isEHScopeReturnBlock())
74501095a5dSDimitry Andric continue;
746dd58ef01SDimitry Andric
747b60736ecSDimitry Andric append_range(Worklist, Visiting->successors());
74801095a5dSDimitry Andric }
749dd58ef01SDimitry Andric }
750dd58ef01SDimitry Andric
751dd58ef01SDimitry Andric DenseMap<const MachineBasicBlock *, int>
getEHScopeMembership(const MachineFunction & MF)752eb11fae6SDimitry Andric llvm::getEHScopeMembership(const MachineFunction &MF) {
753eb11fae6SDimitry Andric DenseMap<const MachineBasicBlock *, int> EHScopeMembership;
754dd58ef01SDimitry Andric
755dd58ef01SDimitry Andric // We don't have anything to do if there aren't any EH pads.
756eb11fae6SDimitry Andric if (!MF.hasEHScopes())
757eb11fae6SDimitry Andric return EHScopeMembership;
758dd58ef01SDimitry Andric
759dd58ef01SDimitry Andric int EntryBBNumber = MF.front().getNumber();
760dd58ef01SDimitry Andric bool IsSEH = isAsynchronousEHPersonality(
761044eb2f6SDimitry Andric classifyEHPersonality(MF.getFunction().getPersonalityFn()));
762dd58ef01SDimitry Andric
763dd58ef01SDimitry Andric const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
764eb11fae6SDimitry Andric SmallVector<const MachineBasicBlock *, 16> EHScopeBlocks;
765dd58ef01SDimitry Andric SmallVector<const MachineBasicBlock *, 16> UnreachableBlocks;
766dd58ef01SDimitry Andric SmallVector<const MachineBasicBlock *, 16> SEHCatchPads;
767dd58ef01SDimitry Andric SmallVector<std::pair<const MachineBasicBlock *, int>, 16> CatchRetSuccessors;
768dd58ef01SDimitry Andric for (const MachineBasicBlock &MBB : MF) {
769eb11fae6SDimitry Andric if (MBB.isEHScopeEntry()) {
770eb11fae6SDimitry Andric EHScopeBlocks.push_back(&MBB);
771dd58ef01SDimitry Andric } else if (IsSEH && MBB.isEHPad()) {
772dd58ef01SDimitry Andric SEHCatchPads.push_back(&MBB);
773dd58ef01SDimitry Andric } else if (MBB.pred_empty()) {
774dd58ef01SDimitry Andric UnreachableBlocks.push_back(&MBB);
775dd58ef01SDimitry Andric }
776dd58ef01SDimitry Andric
777dd58ef01SDimitry Andric MachineBasicBlock::const_iterator MBBI = MBB.getFirstTerminator();
778b915e9e0SDimitry Andric
779eb11fae6SDimitry Andric // CatchPads are not scopes for SEH so do not consider CatchRet to
780eb11fae6SDimitry Andric // transfer control to another scope.
781b915e9e0SDimitry Andric if (MBBI == MBB.end() || MBBI->getOpcode() != TII->getCatchReturnOpcode())
782dd58ef01SDimitry Andric continue;
783dd58ef01SDimitry Andric
784dd58ef01SDimitry Andric // FIXME: SEH CatchPads are not necessarily in the parent function:
785dd58ef01SDimitry Andric // they could be inside a finally block.
786dd58ef01SDimitry Andric const MachineBasicBlock *Successor = MBBI->getOperand(0).getMBB();
787dd58ef01SDimitry Andric const MachineBasicBlock *SuccessorColor = MBBI->getOperand(1).getMBB();
788dd58ef01SDimitry Andric CatchRetSuccessors.push_back(
789dd58ef01SDimitry Andric {Successor, IsSEH ? EntryBBNumber : SuccessorColor->getNumber()});
790dd58ef01SDimitry Andric }
791dd58ef01SDimitry Andric
792dd58ef01SDimitry Andric // We don't have anything to do if there aren't any EH pads.
793eb11fae6SDimitry Andric if (EHScopeBlocks.empty())
794eb11fae6SDimitry Andric return EHScopeMembership;
795dd58ef01SDimitry Andric
796dd58ef01SDimitry Andric // Identify all the basic blocks reachable from the function entry.
797eb11fae6SDimitry Andric collectEHScopeMembers(EHScopeMembership, EntryBBNumber, &MF.front());
798eb11fae6SDimitry Andric // All blocks not part of a scope are in the parent function.
799dd58ef01SDimitry Andric for (const MachineBasicBlock *MBB : UnreachableBlocks)
800eb11fae6SDimitry Andric collectEHScopeMembers(EHScopeMembership, EntryBBNumber, MBB);
801eb11fae6SDimitry Andric // Next, identify all the blocks inside the scopes.
802eb11fae6SDimitry Andric for (const MachineBasicBlock *MBB : EHScopeBlocks)
803eb11fae6SDimitry Andric collectEHScopeMembers(EHScopeMembership, MBB->getNumber(), MBB);
804eb11fae6SDimitry Andric // SEH CatchPads aren't really scopes, handle them separately.
805dd58ef01SDimitry Andric for (const MachineBasicBlock *MBB : SEHCatchPads)
806eb11fae6SDimitry Andric collectEHScopeMembers(EHScopeMembership, EntryBBNumber, MBB);
807dd58ef01SDimitry Andric // Finally, identify all the targets of a catchret.
808dd58ef01SDimitry Andric for (std::pair<const MachineBasicBlock *, int> CatchRetPair :
809dd58ef01SDimitry Andric CatchRetSuccessors)
810eb11fae6SDimitry Andric collectEHScopeMembers(EHScopeMembership, CatchRetPair.second,
811dd58ef01SDimitry Andric CatchRetPair.first);
812eb11fae6SDimitry Andric return EHScopeMembership;
813dd58ef01SDimitry Andric }
814