10b57cec5SDimitry Andric //===-- Analysis.cpp - CodeGen LLVM IR Analysis Utilities -----------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This file defines several CodeGen-specific LLVM IR analysis utilities.
100b57cec5SDimitry Andric //
110b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
120b57cec5SDimitry Andric 
130b57cec5SDimitry Andric #include "llvm/CodeGen/Analysis.h"
140b57cec5SDimitry Andric #include "llvm/Analysis/ValueTracking.h"
150b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
160b57cec5SDimitry Andric #include "llvm/CodeGen/TargetInstrInfo.h"
170b57cec5SDimitry Andric #include "llvm/CodeGen/TargetLowering.h"
180b57cec5SDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
190b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h"
200b57cec5SDimitry Andric #include "llvm/IR/DerivedTypes.h"
210b57cec5SDimitry Andric #include "llvm/IR/Function.h"
220b57cec5SDimitry Andric #include "llvm/IR/Instructions.h"
230b57cec5SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
240b57cec5SDimitry Andric #include "llvm/IR/Module.h"
250b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
265ffd83dbSDimitry Andric #include "llvm/Target/TargetMachine.h"
270b57cec5SDimitry Andric 
280b57cec5SDimitry Andric using namespace llvm;
290b57cec5SDimitry Andric 
300b57cec5SDimitry Andric /// Compute the linearized index of a member in a nested aggregate/struct/array
310b57cec5SDimitry Andric /// by recursing and accumulating CurIndex as long as there are indices in the
320b57cec5SDimitry Andric /// index list.
ComputeLinearIndex(Type * Ty,const unsigned * Indices,const unsigned * IndicesEnd,unsigned CurIndex)330b57cec5SDimitry Andric unsigned llvm::ComputeLinearIndex(Type *Ty,
340b57cec5SDimitry Andric                                   const unsigned *Indices,
350b57cec5SDimitry Andric                                   const unsigned *IndicesEnd,
360b57cec5SDimitry Andric                                   unsigned CurIndex) {
370b57cec5SDimitry Andric   // Base case: We're done.
380b57cec5SDimitry Andric   if (Indices && Indices == IndicesEnd)
390b57cec5SDimitry Andric     return CurIndex;
400b57cec5SDimitry Andric 
410b57cec5SDimitry Andric   // Given a struct type, recursively traverse the elements.
420b57cec5SDimitry Andric   if (StructType *STy = dyn_cast<StructType>(Ty)) {
43fe6060f1SDimitry Andric     for (auto I : llvm::enumerate(STy->elements())) {
44fe6060f1SDimitry Andric       Type *ET = I.value();
45fe6060f1SDimitry Andric       if (Indices && *Indices == I.index())
46fe6060f1SDimitry Andric         return ComputeLinearIndex(ET, Indices + 1, IndicesEnd, CurIndex);
47fe6060f1SDimitry Andric       CurIndex = ComputeLinearIndex(ET, nullptr, nullptr, CurIndex);
480b57cec5SDimitry Andric     }
490b57cec5SDimitry Andric     assert(!Indices && "Unexpected out of bound");
500b57cec5SDimitry Andric     return CurIndex;
510b57cec5SDimitry Andric   }
520b57cec5SDimitry Andric   // Given an array type, recursively traverse the elements.
530b57cec5SDimitry Andric   else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
540b57cec5SDimitry Andric     Type *EltTy = ATy->getElementType();
550b57cec5SDimitry Andric     unsigned NumElts = ATy->getNumElements();
560b57cec5SDimitry Andric     // Compute the Linear offset when jumping one element of the array
570b57cec5SDimitry Andric     unsigned EltLinearOffset = ComputeLinearIndex(EltTy, nullptr, nullptr, 0);
580b57cec5SDimitry Andric     if (Indices) {
590b57cec5SDimitry Andric       assert(*Indices < NumElts && "Unexpected out of bound");
600b57cec5SDimitry Andric       // If the indice is inside the array, compute the index to the requested
610b57cec5SDimitry Andric       // elt and recurse inside the element with the end of the indices list
620b57cec5SDimitry Andric       CurIndex += EltLinearOffset* *Indices;
630b57cec5SDimitry Andric       return ComputeLinearIndex(EltTy, Indices+1, IndicesEnd, CurIndex);
640b57cec5SDimitry Andric     }
650b57cec5SDimitry Andric     CurIndex += EltLinearOffset*NumElts;
660b57cec5SDimitry Andric     return CurIndex;
670b57cec5SDimitry Andric   }
680b57cec5SDimitry Andric   // We haven't found the type we're looking for, so keep searching.
690b57cec5SDimitry Andric   return CurIndex + 1;
700b57cec5SDimitry Andric }
710b57cec5SDimitry Andric 
720b57cec5SDimitry Andric /// ComputeValueVTs - Given an LLVM IR type, compute a sequence of
730b57cec5SDimitry Andric /// EVTs that represent all the individual underlying
740b57cec5SDimitry Andric /// non-aggregate types that comprise it.
750b57cec5SDimitry Andric ///
760b57cec5SDimitry Andric /// If Offsets is non-null, it points to a vector to be filled in
770b57cec5SDimitry Andric /// with the in-memory offsets of each of the individual values.
780b57cec5SDimitry Andric ///
ComputeValueVTs(const TargetLowering & TLI,const DataLayout & DL,Type * Ty,SmallVectorImpl<EVT> & ValueVTs,SmallVectorImpl<EVT> * MemVTs,SmallVectorImpl<TypeSize> * Offsets,TypeSize StartingOffset)790b57cec5SDimitry Andric void llvm::ComputeValueVTs(const TargetLowering &TLI, const DataLayout &DL,
800b57cec5SDimitry Andric                            Type *Ty, SmallVectorImpl<EVT> &ValueVTs,
810b57cec5SDimitry Andric                            SmallVectorImpl<EVT> *MemVTs,
82fe013be4SDimitry Andric                            SmallVectorImpl<TypeSize> *Offsets,
83fe013be4SDimitry Andric                            TypeSize StartingOffset) {
840b57cec5SDimitry Andric   // Given a struct type, recursively traverse the elements.
850b57cec5SDimitry Andric   if (StructType *STy = dyn_cast<StructType>(Ty)) {
86e8d8bef9SDimitry Andric     // If the Offsets aren't needed, don't query the struct layout. This allows
87e8d8bef9SDimitry Andric     // us to support structs with scalable vectors for operations that don't
88e8d8bef9SDimitry Andric     // need offsets.
89e8d8bef9SDimitry Andric     const StructLayout *SL = Offsets ? DL.getStructLayout(STy) : nullptr;
900b57cec5SDimitry Andric     for (StructType::element_iterator EB = STy->element_begin(),
910b57cec5SDimitry Andric                                       EI = EB,
920b57cec5SDimitry Andric                                       EE = STy->element_end();
93e8d8bef9SDimitry Andric          EI != EE; ++EI) {
94e8d8bef9SDimitry Andric       // Don't compute the element offset if we didn't get a StructLayout above.
95fe013be4SDimitry Andric       TypeSize EltOffset = SL ? SL->getElementOffset(EI - EB)
96fe013be4SDimitry Andric                               : TypeSize::get(0, StartingOffset.isScalable());
970b57cec5SDimitry Andric       ComputeValueVTs(TLI, DL, *EI, ValueVTs, MemVTs, Offsets,
98e8d8bef9SDimitry Andric                       StartingOffset + EltOffset);
99e8d8bef9SDimitry Andric     }
1000b57cec5SDimitry Andric     return;
1010b57cec5SDimitry Andric   }
1020b57cec5SDimitry Andric   // Given an array type, recursively traverse the elements.
1030b57cec5SDimitry Andric   if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1040b57cec5SDimitry Andric     Type *EltTy = ATy->getElementType();
105fe013be4SDimitry Andric     TypeSize EltSize = DL.getTypeAllocSize(EltTy);
1060b57cec5SDimitry Andric     for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
1070b57cec5SDimitry Andric       ComputeValueVTs(TLI, DL, EltTy, ValueVTs, MemVTs, Offsets,
1080b57cec5SDimitry Andric                       StartingOffset + i * EltSize);
1090b57cec5SDimitry Andric     return;
1100b57cec5SDimitry Andric   }
1110b57cec5SDimitry Andric   // Interpret void as zero return values.
1120b57cec5SDimitry Andric   if (Ty->isVoidTy())
1130b57cec5SDimitry Andric     return;
1140b57cec5SDimitry Andric   // Base case: we can get an EVT for this LLVM IR type.
1150b57cec5SDimitry Andric   ValueVTs.push_back(TLI.getValueType(DL, Ty));
1160b57cec5SDimitry Andric   if (MemVTs)
1170b57cec5SDimitry Andric     MemVTs->push_back(TLI.getMemValueType(DL, Ty));
1180b57cec5SDimitry Andric   if (Offsets)
1190b57cec5SDimitry Andric     Offsets->push_back(StartingOffset);
1200b57cec5SDimitry Andric }
1210b57cec5SDimitry Andric 
ComputeValueVTs(const TargetLowering & TLI,const DataLayout & DL,Type * Ty,SmallVectorImpl<EVT> & ValueVTs,SmallVectorImpl<TypeSize> * Offsets,TypeSize StartingOffset)1220b57cec5SDimitry Andric void llvm::ComputeValueVTs(const TargetLowering &TLI, const DataLayout &DL,
1230b57cec5SDimitry Andric                            Type *Ty, SmallVectorImpl<EVT> &ValueVTs,
124fe013be4SDimitry Andric                            SmallVectorImpl<TypeSize> *Offsets,
125fe013be4SDimitry Andric                            TypeSize StartingOffset) {
1260b57cec5SDimitry Andric   return ComputeValueVTs(TLI, DL, Ty, ValueVTs, /*MemVTs=*/nullptr, Offsets,
1270b57cec5SDimitry Andric                          StartingOffset);
1280b57cec5SDimitry Andric }
1290b57cec5SDimitry Andric 
ComputeValueVTs(const TargetLowering & TLI,const DataLayout & DL,Type * Ty,SmallVectorImpl<EVT> & ValueVTs,SmallVectorImpl<TypeSize> * Offsets,uint64_t StartingOffset)130fe013be4SDimitry Andric void llvm::ComputeValueVTs(const TargetLowering &TLI, const DataLayout &DL,
131fe013be4SDimitry Andric                            Type *Ty, SmallVectorImpl<EVT> &ValueVTs,
132fe013be4SDimitry Andric                            SmallVectorImpl<TypeSize> *Offsets,
133fe013be4SDimitry Andric                            uint64_t StartingOffset) {
134fe013be4SDimitry Andric   TypeSize Offset = TypeSize::get(StartingOffset, Ty->isScalableTy());
135fe013be4SDimitry Andric   return ComputeValueVTs(TLI, DL, Ty, ValueVTs, Offsets, Offset);
136fe013be4SDimitry Andric }
137fe013be4SDimitry Andric 
ComputeValueVTs(const TargetLowering & TLI,const DataLayout & DL,Type * Ty,SmallVectorImpl<EVT> & ValueVTs,SmallVectorImpl<uint64_t> * FixedOffsets,uint64_t StartingOffset)138fe013be4SDimitry Andric void llvm::ComputeValueVTs(const TargetLowering &TLI, const DataLayout &DL,
139fe013be4SDimitry Andric                            Type *Ty, SmallVectorImpl<EVT> &ValueVTs,
140fe013be4SDimitry Andric                            SmallVectorImpl<uint64_t> *FixedOffsets,
141fe013be4SDimitry Andric                            uint64_t StartingOffset) {
142fe013be4SDimitry Andric   TypeSize Offset = TypeSize::get(StartingOffset, Ty->isScalableTy());
143*c9157d92SDimitry Andric   if (FixedOffsets) {
144fe013be4SDimitry Andric     SmallVector<TypeSize, 4> Offsets;
145fe013be4SDimitry Andric     ComputeValueVTs(TLI, DL, Ty, ValueVTs, &Offsets, Offset);
146fe013be4SDimitry Andric     for (TypeSize Offset : Offsets)
147*c9157d92SDimitry Andric       FixedOffsets->push_back(Offset.getFixedValue());
148*c9157d92SDimitry Andric   } else {
149*c9157d92SDimitry Andric     ComputeValueVTs(TLI, DL, Ty, ValueVTs, nullptr, Offset);
150*c9157d92SDimitry Andric   }
151fe013be4SDimitry Andric }
152fe013be4SDimitry Andric 
ComputeValueVTs(const TargetLowering & TLI,const DataLayout & DL,Type * Ty,SmallVectorImpl<EVT> & ValueVTs,SmallVectorImpl<EVT> * MemVTs,SmallVectorImpl<TypeSize> * Offsets,uint64_t StartingOffset)153fe013be4SDimitry Andric void llvm::ComputeValueVTs(const TargetLowering &TLI, const DataLayout &DL,
154fe013be4SDimitry Andric                            Type *Ty, SmallVectorImpl<EVT> &ValueVTs,
155fe013be4SDimitry Andric                            SmallVectorImpl<EVT> *MemVTs,
156fe013be4SDimitry Andric                            SmallVectorImpl<TypeSize> *Offsets,
157fe013be4SDimitry Andric                            uint64_t StartingOffset) {
158fe013be4SDimitry Andric   TypeSize Offset = TypeSize::get(StartingOffset, Ty->isScalableTy());
159fe013be4SDimitry Andric   return ComputeValueVTs(TLI, DL, Ty, ValueVTs, MemVTs, Offsets, Offset);
160fe013be4SDimitry Andric }
161fe013be4SDimitry Andric 
ComputeValueVTs(const TargetLowering & TLI,const DataLayout & DL,Type * Ty,SmallVectorImpl<EVT> & ValueVTs,SmallVectorImpl<EVT> * MemVTs,SmallVectorImpl<uint64_t> * FixedOffsets,uint64_t StartingOffset)162fe013be4SDimitry Andric void llvm::ComputeValueVTs(const TargetLowering &TLI, const DataLayout &DL,
163fe013be4SDimitry Andric                            Type *Ty, SmallVectorImpl<EVT> &ValueVTs,
164fe013be4SDimitry Andric                            SmallVectorImpl<EVT> *MemVTs,
165fe013be4SDimitry Andric                            SmallVectorImpl<uint64_t> *FixedOffsets,
166fe013be4SDimitry Andric                            uint64_t StartingOffset) {
167fe013be4SDimitry Andric   TypeSize Offset = TypeSize::get(StartingOffset, Ty->isScalableTy());
168*c9157d92SDimitry Andric   if (FixedOffsets) {
169fe013be4SDimitry Andric     SmallVector<TypeSize, 4> Offsets;
170fe013be4SDimitry Andric     ComputeValueVTs(TLI, DL, Ty, ValueVTs, MemVTs, &Offsets, Offset);
171fe013be4SDimitry Andric     for (TypeSize Offset : Offsets)
172*c9157d92SDimitry Andric       FixedOffsets->push_back(Offset.getFixedValue());
173*c9157d92SDimitry Andric   } else {
174*c9157d92SDimitry Andric     ComputeValueVTs(TLI, DL, Ty, ValueVTs, MemVTs, nullptr, Offset);
175*c9157d92SDimitry Andric   }
176fe013be4SDimitry Andric }
177fe013be4SDimitry Andric 
computeValueLLTs(const DataLayout & DL,Type & Ty,SmallVectorImpl<LLT> & ValueTys,SmallVectorImpl<uint64_t> * Offsets,uint64_t StartingOffset)1780b57cec5SDimitry Andric void llvm::computeValueLLTs(const DataLayout &DL, Type &Ty,
1790b57cec5SDimitry Andric                             SmallVectorImpl<LLT> &ValueTys,
1800b57cec5SDimitry Andric                             SmallVectorImpl<uint64_t> *Offsets,
1810b57cec5SDimitry Andric                             uint64_t StartingOffset) {
1820b57cec5SDimitry Andric   // Given a struct type, recursively traverse the elements.
1830b57cec5SDimitry Andric   if (StructType *STy = dyn_cast<StructType>(&Ty)) {
184e8d8bef9SDimitry Andric     // If the Offsets aren't needed, don't query the struct layout. This allows
185e8d8bef9SDimitry Andric     // us to support structs with scalable vectors for operations that don't
186e8d8bef9SDimitry Andric     // need offsets.
187e8d8bef9SDimitry Andric     const StructLayout *SL = Offsets ? DL.getStructLayout(STy) : nullptr;
188e8d8bef9SDimitry Andric     for (unsigned I = 0, E = STy->getNumElements(); I != E; ++I) {
189e8d8bef9SDimitry Andric       uint64_t EltOffset = SL ? SL->getElementOffset(I) : 0;
1900b57cec5SDimitry Andric       computeValueLLTs(DL, *STy->getElementType(I), ValueTys, Offsets,
191e8d8bef9SDimitry Andric                        StartingOffset + EltOffset);
192e8d8bef9SDimitry Andric     }
1930b57cec5SDimitry Andric     return;
1940b57cec5SDimitry Andric   }
1950b57cec5SDimitry Andric   // Given an array type, recursively traverse the elements.
1960b57cec5SDimitry Andric   if (ArrayType *ATy = dyn_cast<ArrayType>(&Ty)) {
1970b57cec5SDimitry Andric     Type *EltTy = ATy->getElementType();
198e8d8bef9SDimitry Andric     uint64_t EltSize = DL.getTypeAllocSize(EltTy).getFixedValue();
1990b57cec5SDimitry Andric     for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
2000b57cec5SDimitry Andric       computeValueLLTs(DL, *EltTy, ValueTys, Offsets,
2010b57cec5SDimitry Andric                        StartingOffset + i * EltSize);
2020b57cec5SDimitry Andric     return;
2030b57cec5SDimitry Andric   }
2040b57cec5SDimitry Andric   // Interpret void as zero return values.
2050b57cec5SDimitry Andric   if (Ty.isVoidTy())
2060b57cec5SDimitry Andric     return;
2070b57cec5SDimitry Andric   // Base case: we can get an LLT for this LLVM IR type.
2080b57cec5SDimitry Andric   ValueTys.push_back(getLLTForType(Ty, DL));
2090b57cec5SDimitry Andric   if (Offsets != nullptr)
2100b57cec5SDimitry Andric     Offsets->push_back(StartingOffset * 8);
2110b57cec5SDimitry Andric }
2120b57cec5SDimitry Andric 
2130b57cec5SDimitry Andric /// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
ExtractTypeInfo(Value * V)2140b57cec5SDimitry Andric GlobalValue *llvm::ExtractTypeInfo(Value *V) {
2150b57cec5SDimitry Andric   V = V->stripPointerCasts();
2160b57cec5SDimitry Andric   GlobalValue *GV = dyn_cast<GlobalValue>(V);
2170b57cec5SDimitry Andric   GlobalVariable *Var = dyn_cast<GlobalVariable>(V);
2180b57cec5SDimitry Andric 
2190b57cec5SDimitry Andric   if (Var && Var->getName() == "llvm.eh.catch.all.value") {
2200b57cec5SDimitry Andric     assert(Var->hasInitializer() &&
2210b57cec5SDimitry Andric            "The EH catch-all value must have an initializer");
2220b57cec5SDimitry Andric     Value *Init = Var->getInitializer();
2230b57cec5SDimitry Andric     GV = dyn_cast<GlobalValue>(Init);
2240b57cec5SDimitry Andric     if (!GV) V = cast<ConstantPointerNull>(Init);
2250b57cec5SDimitry Andric   }
2260b57cec5SDimitry Andric 
2270b57cec5SDimitry Andric   assert((GV || isa<ConstantPointerNull>(V)) &&
2280b57cec5SDimitry Andric          "TypeInfo must be a global variable or NULL");
2290b57cec5SDimitry Andric   return GV;
2300b57cec5SDimitry Andric }
2310b57cec5SDimitry Andric 
2320b57cec5SDimitry Andric /// getFCmpCondCode - Return the ISD condition code corresponding to
2330b57cec5SDimitry Andric /// the given LLVM IR floating-point condition code.  This includes
2340b57cec5SDimitry Andric /// consideration of global floating-point math flags.
2350b57cec5SDimitry Andric ///
getFCmpCondCode(FCmpInst::Predicate Pred)2360b57cec5SDimitry Andric ISD::CondCode llvm::getFCmpCondCode(FCmpInst::Predicate Pred) {
2370b57cec5SDimitry Andric   switch (Pred) {
2380b57cec5SDimitry Andric   case FCmpInst::FCMP_FALSE: return ISD::SETFALSE;
2390b57cec5SDimitry Andric   case FCmpInst::FCMP_OEQ:   return ISD::SETOEQ;
2400b57cec5SDimitry Andric   case FCmpInst::FCMP_OGT:   return ISD::SETOGT;
2410b57cec5SDimitry Andric   case FCmpInst::FCMP_OGE:   return ISD::SETOGE;
2420b57cec5SDimitry Andric   case FCmpInst::FCMP_OLT:   return ISD::SETOLT;
2430b57cec5SDimitry Andric   case FCmpInst::FCMP_OLE:   return ISD::SETOLE;
2440b57cec5SDimitry Andric   case FCmpInst::FCMP_ONE:   return ISD::SETONE;
2450b57cec5SDimitry Andric   case FCmpInst::FCMP_ORD:   return ISD::SETO;
2460b57cec5SDimitry Andric   case FCmpInst::FCMP_UNO:   return ISD::SETUO;
2470b57cec5SDimitry Andric   case FCmpInst::FCMP_UEQ:   return ISD::SETUEQ;
2480b57cec5SDimitry Andric   case FCmpInst::FCMP_UGT:   return ISD::SETUGT;
2490b57cec5SDimitry Andric   case FCmpInst::FCMP_UGE:   return ISD::SETUGE;
2500b57cec5SDimitry Andric   case FCmpInst::FCMP_ULT:   return ISD::SETULT;
2510b57cec5SDimitry Andric   case FCmpInst::FCMP_ULE:   return ISD::SETULE;
2520b57cec5SDimitry Andric   case FCmpInst::FCMP_UNE:   return ISD::SETUNE;
2530b57cec5SDimitry Andric   case FCmpInst::FCMP_TRUE:  return ISD::SETTRUE;
2540b57cec5SDimitry Andric   default: llvm_unreachable("Invalid FCmp predicate opcode!");
2550b57cec5SDimitry Andric   }
2560b57cec5SDimitry Andric }
2570b57cec5SDimitry Andric 
getFCmpCodeWithoutNaN(ISD::CondCode CC)2580b57cec5SDimitry Andric ISD::CondCode llvm::getFCmpCodeWithoutNaN(ISD::CondCode CC) {
2590b57cec5SDimitry Andric   switch (CC) {
2600b57cec5SDimitry Andric     case ISD::SETOEQ: case ISD::SETUEQ: return ISD::SETEQ;
2610b57cec5SDimitry Andric     case ISD::SETONE: case ISD::SETUNE: return ISD::SETNE;
2620b57cec5SDimitry Andric     case ISD::SETOLT: case ISD::SETULT: return ISD::SETLT;
2630b57cec5SDimitry Andric     case ISD::SETOLE: case ISD::SETULE: return ISD::SETLE;
2640b57cec5SDimitry Andric     case ISD::SETOGT: case ISD::SETUGT: return ISD::SETGT;
2650b57cec5SDimitry Andric     case ISD::SETOGE: case ISD::SETUGE: return ISD::SETGE;
2660b57cec5SDimitry Andric     default: return CC;
2670b57cec5SDimitry Andric   }
2680b57cec5SDimitry Andric }
2690b57cec5SDimitry Andric 
getICmpCondCode(ICmpInst::Predicate Pred)2700b57cec5SDimitry Andric ISD::CondCode llvm::getICmpCondCode(ICmpInst::Predicate Pred) {
2710b57cec5SDimitry Andric   switch (Pred) {
2720b57cec5SDimitry Andric   case ICmpInst::ICMP_EQ:  return ISD::SETEQ;
2730b57cec5SDimitry Andric   case ICmpInst::ICMP_NE:  return ISD::SETNE;
2740b57cec5SDimitry Andric   case ICmpInst::ICMP_SLE: return ISD::SETLE;
2750b57cec5SDimitry Andric   case ICmpInst::ICMP_ULE: return ISD::SETULE;
2760b57cec5SDimitry Andric   case ICmpInst::ICMP_SGE: return ISD::SETGE;
2770b57cec5SDimitry Andric   case ICmpInst::ICMP_UGE: return ISD::SETUGE;
2780b57cec5SDimitry Andric   case ICmpInst::ICMP_SLT: return ISD::SETLT;
2790b57cec5SDimitry Andric   case ICmpInst::ICMP_ULT: return ISD::SETULT;
2800b57cec5SDimitry Andric   case ICmpInst::ICMP_SGT: return ISD::SETGT;
2810b57cec5SDimitry Andric   case ICmpInst::ICMP_UGT: return ISD::SETUGT;
2820b57cec5SDimitry Andric   default:
2830b57cec5SDimitry Andric     llvm_unreachable("Invalid ICmp predicate opcode!");
2840b57cec5SDimitry Andric   }
2850b57cec5SDimitry Andric }
2860b57cec5SDimitry Andric 
getICmpCondCode(ISD::CondCode Pred)287349cc55cSDimitry Andric ICmpInst::Predicate llvm::getICmpCondCode(ISD::CondCode Pred) {
288349cc55cSDimitry Andric   switch (Pred) {
289349cc55cSDimitry Andric   case ISD::SETEQ:
290349cc55cSDimitry Andric     return ICmpInst::ICMP_EQ;
291349cc55cSDimitry Andric   case ISD::SETNE:
292349cc55cSDimitry Andric     return ICmpInst::ICMP_NE;
293349cc55cSDimitry Andric   case ISD::SETLE:
294349cc55cSDimitry Andric     return ICmpInst::ICMP_SLE;
295349cc55cSDimitry Andric   case ISD::SETULE:
296349cc55cSDimitry Andric     return ICmpInst::ICMP_ULE;
297349cc55cSDimitry Andric   case ISD::SETGE:
298349cc55cSDimitry Andric     return ICmpInst::ICMP_SGE;
299349cc55cSDimitry Andric   case ISD::SETUGE:
300349cc55cSDimitry Andric     return ICmpInst::ICMP_UGE;
301349cc55cSDimitry Andric   case ISD::SETLT:
302349cc55cSDimitry Andric     return ICmpInst::ICMP_SLT;
303349cc55cSDimitry Andric   case ISD::SETULT:
304349cc55cSDimitry Andric     return ICmpInst::ICMP_ULT;
305349cc55cSDimitry Andric   case ISD::SETGT:
306349cc55cSDimitry Andric     return ICmpInst::ICMP_SGT;
307349cc55cSDimitry Andric   case ISD::SETUGT:
308349cc55cSDimitry Andric     return ICmpInst::ICMP_UGT;
309349cc55cSDimitry Andric   default:
310349cc55cSDimitry Andric     llvm_unreachable("Invalid ISD integer condition code!");
311349cc55cSDimitry Andric   }
312349cc55cSDimitry Andric }
313349cc55cSDimitry Andric 
isNoopBitcast(Type * T1,Type * T2,const TargetLoweringBase & TLI)3140b57cec5SDimitry Andric static bool isNoopBitcast(Type *T1, Type *T2,
3150b57cec5SDimitry Andric                           const TargetLoweringBase& TLI) {
3160b57cec5SDimitry Andric   return T1 == T2 || (T1->isPointerTy() && T2->isPointerTy()) ||
3170b57cec5SDimitry Andric          (isa<VectorType>(T1) && isa<VectorType>(T2) &&
3180b57cec5SDimitry Andric           TLI.isTypeLegal(EVT::getEVT(T1)) && TLI.isTypeLegal(EVT::getEVT(T2)));
3190b57cec5SDimitry Andric }
3200b57cec5SDimitry Andric 
3210b57cec5SDimitry Andric /// Look through operations that will be free to find the earliest source of
3220b57cec5SDimitry Andric /// this value.
3230b57cec5SDimitry Andric ///
324480093f4SDimitry Andric /// @param ValLoc If V has aggregate type, we will be interested in a particular
3250b57cec5SDimitry Andric /// scalar component. This records its address; the reverse of this list gives a
3260b57cec5SDimitry Andric /// sequence of indices appropriate for an extractvalue to locate the important
3270b57cec5SDimitry Andric /// value. This value is updated during the function and on exit will indicate
3280b57cec5SDimitry Andric /// similar information for the Value returned.
3290b57cec5SDimitry Andric ///
3300b57cec5SDimitry Andric /// @param DataBits If this function looks through truncate instructions, this
3310b57cec5SDimitry Andric /// will record the smallest size attained.
getNoopInput(const Value * V,SmallVectorImpl<unsigned> & ValLoc,unsigned & DataBits,const TargetLoweringBase & TLI,const DataLayout & DL)3320b57cec5SDimitry Andric static const Value *getNoopInput(const Value *V,
3330b57cec5SDimitry Andric                                  SmallVectorImpl<unsigned> &ValLoc,
3340b57cec5SDimitry Andric                                  unsigned &DataBits,
3350b57cec5SDimitry Andric                                  const TargetLoweringBase &TLI,
3360b57cec5SDimitry Andric                                  const DataLayout &DL) {
3370b57cec5SDimitry Andric   while (true) {
3380b57cec5SDimitry Andric     // Try to look through V1; if V1 is not an instruction, it can't be looked
3390b57cec5SDimitry Andric     // through.
3400b57cec5SDimitry Andric     const Instruction *I = dyn_cast<Instruction>(V);
3410b57cec5SDimitry Andric     if (!I || I->getNumOperands() == 0) return V;
3420b57cec5SDimitry Andric     const Value *NoopInput = nullptr;
3430b57cec5SDimitry Andric 
3440b57cec5SDimitry Andric     Value *Op = I->getOperand(0);
3450b57cec5SDimitry Andric     if (isa<BitCastInst>(I)) {
3460b57cec5SDimitry Andric       // Look through truly no-op bitcasts.
3470b57cec5SDimitry Andric       if (isNoopBitcast(Op->getType(), I->getType(), TLI))
3480b57cec5SDimitry Andric         NoopInput = Op;
3490b57cec5SDimitry Andric     } else if (isa<GetElementPtrInst>(I)) {
3500b57cec5SDimitry Andric       // Look through getelementptr
3510b57cec5SDimitry Andric       if (cast<GetElementPtrInst>(I)->hasAllZeroIndices())
3520b57cec5SDimitry Andric         NoopInput = Op;
3530b57cec5SDimitry Andric     } else if (isa<IntToPtrInst>(I)) {
3540b57cec5SDimitry Andric       // Look through inttoptr.
3550b57cec5SDimitry Andric       // Make sure this isn't a truncating or extending cast.  We could
3560b57cec5SDimitry Andric       // support this eventually, but don't bother for now.
3570b57cec5SDimitry Andric       if (!isa<VectorType>(I->getType()) &&
3580b57cec5SDimitry Andric           DL.getPointerSizeInBits() ==
3590b57cec5SDimitry Andric               cast<IntegerType>(Op->getType())->getBitWidth())
3600b57cec5SDimitry Andric         NoopInput = Op;
3610b57cec5SDimitry Andric     } else if (isa<PtrToIntInst>(I)) {
3620b57cec5SDimitry Andric       // Look through ptrtoint.
3630b57cec5SDimitry Andric       // Make sure this isn't a truncating or extending cast.  We could
3640b57cec5SDimitry Andric       // support this eventually, but don't bother for now.
3650b57cec5SDimitry Andric       if (!isa<VectorType>(I->getType()) &&
3660b57cec5SDimitry Andric           DL.getPointerSizeInBits() ==
3670b57cec5SDimitry Andric               cast<IntegerType>(I->getType())->getBitWidth())
3680b57cec5SDimitry Andric         NoopInput = Op;
3690b57cec5SDimitry Andric     } else if (isa<TruncInst>(I) &&
3700b57cec5SDimitry Andric                TLI.allowTruncateForTailCall(Op->getType(), I->getType())) {
371bdd1243dSDimitry Andric       DataBits =
372bdd1243dSDimitry Andric           std::min((uint64_t)DataBits,
373bdd1243dSDimitry Andric                    I->getType()->getPrimitiveSizeInBits().getFixedValue());
3740b57cec5SDimitry Andric       NoopInput = Op;
3755ffd83dbSDimitry Andric     } else if (auto *CB = dyn_cast<CallBase>(I)) {
3765ffd83dbSDimitry Andric       const Value *ReturnedOp = CB->getReturnedArgOperand();
3770b57cec5SDimitry Andric       if (ReturnedOp && isNoopBitcast(ReturnedOp->getType(), I->getType(), TLI))
3780b57cec5SDimitry Andric         NoopInput = ReturnedOp;
3790b57cec5SDimitry Andric     } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(V)) {
3800b57cec5SDimitry Andric       // Value may come from either the aggregate or the scalar
3810b57cec5SDimitry Andric       ArrayRef<unsigned> InsertLoc = IVI->getIndices();
3820b57cec5SDimitry Andric       if (ValLoc.size() >= InsertLoc.size() &&
3830b57cec5SDimitry Andric           std::equal(InsertLoc.begin(), InsertLoc.end(), ValLoc.rbegin())) {
3840b57cec5SDimitry Andric         // The type being inserted is a nested sub-type of the aggregate; we
3850b57cec5SDimitry Andric         // have to remove those initial indices to get the location we're
3860b57cec5SDimitry Andric         // interested in for the operand.
3870b57cec5SDimitry Andric         ValLoc.resize(ValLoc.size() - InsertLoc.size());
3880b57cec5SDimitry Andric         NoopInput = IVI->getInsertedValueOperand();
3890b57cec5SDimitry Andric       } else {
3900b57cec5SDimitry Andric         // The struct we're inserting into has the value we're interested in, no
3910b57cec5SDimitry Andric         // change of address.
3920b57cec5SDimitry Andric         NoopInput = Op;
3930b57cec5SDimitry Andric       }
3940b57cec5SDimitry Andric     } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(V)) {
3950b57cec5SDimitry Andric       // The part we're interested in will inevitably be some sub-section of the
3960b57cec5SDimitry Andric       // previous aggregate. Combine the two paths to obtain the true address of
3970b57cec5SDimitry Andric       // our element.
3980b57cec5SDimitry Andric       ArrayRef<unsigned> ExtractLoc = EVI->getIndices();
3990b57cec5SDimitry Andric       ValLoc.append(ExtractLoc.rbegin(), ExtractLoc.rend());
4000b57cec5SDimitry Andric       NoopInput = Op;
4010b57cec5SDimitry Andric     }
4020b57cec5SDimitry Andric     // Terminate if we couldn't find anything to look through.
4030b57cec5SDimitry Andric     if (!NoopInput)
4040b57cec5SDimitry Andric       return V;
4050b57cec5SDimitry Andric 
4060b57cec5SDimitry Andric     V = NoopInput;
4070b57cec5SDimitry Andric   }
4080b57cec5SDimitry Andric }
4090b57cec5SDimitry Andric 
4100b57cec5SDimitry Andric /// Return true if this scalar return value only has bits discarded on its path
4110b57cec5SDimitry Andric /// from the "tail call" to the "ret". This includes the obvious noop
4120b57cec5SDimitry Andric /// instructions handled by getNoopInput above as well as free truncations (or
4130b57cec5SDimitry 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)4140b57cec5SDimitry Andric static bool slotOnlyDiscardsData(const Value *RetVal, const Value *CallVal,
4150b57cec5SDimitry Andric                                  SmallVectorImpl<unsigned> &RetIndices,
4160b57cec5SDimitry Andric                                  SmallVectorImpl<unsigned> &CallIndices,
4170b57cec5SDimitry Andric                                  bool AllowDifferingSizes,
4180b57cec5SDimitry Andric                                  const TargetLoweringBase &TLI,
4190b57cec5SDimitry Andric                                  const DataLayout &DL) {
4200b57cec5SDimitry Andric 
4210b57cec5SDimitry Andric   // Trace the sub-value needed by the return value as far back up the graph as
4220b57cec5SDimitry Andric   // possible, in the hope that it will intersect with the value produced by the
4230b57cec5SDimitry Andric   // call. In the simple case with no "returned" attribute, the hope is actually
4240b57cec5SDimitry Andric   // that we end up back at the tail call instruction itself.
4250b57cec5SDimitry Andric   unsigned BitsRequired = UINT_MAX;
4260b57cec5SDimitry Andric   RetVal = getNoopInput(RetVal, RetIndices, BitsRequired, TLI, DL);
4270b57cec5SDimitry Andric 
4280b57cec5SDimitry Andric   // If this slot in the value returned is undef, it doesn't matter what the
4290b57cec5SDimitry Andric   // call puts there, it'll be fine.
4300b57cec5SDimitry Andric   if (isa<UndefValue>(RetVal))
4310b57cec5SDimitry Andric     return true;
4320b57cec5SDimitry Andric 
4330b57cec5SDimitry Andric   // Now do a similar search up through the graph to find where the value
4340b57cec5SDimitry Andric   // actually returned by the "tail call" comes from. In the simple case without
4350b57cec5SDimitry Andric   // a "returned" attribute, the search will be blocked immediately and the loop
4360b57cec5SDimitry Andric   // a Noop.
4370b57cec5SDimitry Andric   unsigned BitsProvided = UINT_MAX;
4380b57cec5SDimitry Andric   CallVal = getNoopInput(CallVal, CallIndices, BitsProvided, TLI, DL);
4390b57cec5SDimitry Andric 
4400b57cec5SDimitry Andric   // There's no hope if we can't actually trace them to (the same part of!) the
4410b57cec5SDimitry Andric   // same value.
4420b57cec5SDimitry Andric   if (CallVal != RetVal || CallIndices != RetIndices)
4430b57cec5SDimitry Andric     return false;
4440b57cec5SDimitry Andric 
4450b57cec5SDimitry Andric   // However, intervening truncates may have made the call non-tail. Make sure
4460b57cec5SDimitry Andric   // all the bits that are needed by the "ret" have been provided by the "tail
4470b57cec5SDimitry Andric   // call". FIXME: with sufficiently cunning bit-tracking, we could look through
4480b57cec5SDimitry Andric   // extensions too.
4490b57cec5SDimitry Andric   if (BitsProvided < BitsRequired ||
4500b57cec5SDimitry Andric       (!AllowDifferingSizes && BitsProvided != BitsRequired))
4510b57cec5SDimitry Andric     return false;
4520b57cec5SDimitry Andric 
4530b57cec5SDimitry Andric   return true;
4540b57cec5SDimitry Andric }
4550b57cec5SDimitry Andric 
4560b57cec5SDimitry Andric /// For an aggregate type, determine whether a given index is within bounds or
4570b57cec5SDimitry Andric /// not.
indexReallyValid(Type * T,unsigned Idx)4585ffd83dbSDimitry Andric static bool indexReallyValid(Type *T, unsigned Idx) {
4590b57cec5SDimitry Andric   if (ArrayType *AT = dyn_cast<ArrayType>(T))
4600b57cec5SDimitry Andric     return Idx < AT->getNumElements();
4610b57cec5SDimitry Andric 
4620b57cec5SDimitry Andric   return Idx < cast<StructType>(T)->getNumElements();
4630b57cec5SDimitry Andric }
4640b57cec5SDimitry Andric 
4650b57cec5SDimitry Andric /// Move the given iterators to the next leaf type in depth first traversal.
4660b57cec5SDimitry Andric ///
4670b57cec5SDimitry Andric /// Performs a depth-first traversal of the type as specified by its arguments,
4680b57cec5SDimitry Andric /// stopping at the next leaf node (which may be a legitimate scalar type or an
4690b57cec5SDimitry Andric /// empty struct or array).
4700b57cec5SDimitry Andric ///
4710b57cec5SDimitry Andric /// @param SubTypes List of the partial components making up the type from
4720b57cec5SDimitry Andric /// outermost to innermost non-empty aggregate. The element currently
4730b57cec5SDimitry Andric /// represented is SubTypes.back()->getTypeAtIndex(Path.back() - 1).
4740b57cec5SDimitry Andric ///
4750b57cec5SDimitry Andric /// @param Path Set of extractvalue indices leading from the outermost type
4760b57cec5SDimitry Andric /// (SubTypes[0]) to the leaf node currently represented.
4770b57cec5SDimitry Andric ///
4780b57cec5SDimitry Andric /// @returns true if a new type was found, false otherwise. Calling this
4790b57cec5SDimitry Andric /// function again on a finished iterator will repeatedly return
4800b57cec5SDimitry Andric /// false. SubTypes.back()->getTypeAtIndex(Path.back()) is either an empty
4810b57cec5SDimitry Andric /// aggregate or a non-aggregate
advanceToNextLeafType(SmallVectorImpl<Type * > & SubTypes,SmallVectorImpl<unsigned> & Path)4825ffd83dbSDimitry Andric static bool advanceToNextLeafType(SmallVectorImpl<Type *> &SubTypes,
4830b57cec5SDimitry Andric                                   SmallVectorImpl<unsigned> &Path) {
4840b57cec5SDimitry Andric   // First march back up the tree until we can successfully increment one of the
4850b57cec5SDimitry Andric   // coordinates in Path.
4860b57cec5SDimitry Andric   while (!Path.empty() && !indexReallyValid(SubTypes.back(), Path.back() + 1)) {
4870b57cec5SDimitry Andric     Path.pop_back();
4880b57cec5SDimitry Andric     SubTypes.pop_back();
4890b57cec5SDimitry Andric   }
4900b57cec5SDimitry Andric 
4910b57cec5SDimitry Andric   // If we reached the top, then the iterator is done.
4920b57cec5SDimitry Andric   if (Path.empty())
4930b57cec5SDimitry Andric     return false;
4940b57cec5SDimitry Andric 
4950b57cec5SDimitry Andric   // We know there's *some* valid leaf now, so march back down the tree picking
4960b57cec5SDimitry Andric   // out the left-most element at each node.
4970b57cec5SDimitry Andric   ++Path.back();
4985ffd83dbSDimitry Andric   Type *DeeperType =
4995ffd83dbSDimitry Andric       ExtractValueInst::getIndexedType(SubTypes.back(), Path.back());
5000b57cec5SDimitry Andric   while (DeeperType->isAggregateType()) {
5015ffd83dbSDimitry Andric     if (!indexReallyValid(DeeperType, 0))
5020b57cec5SDimitry Andric       return true;
5030b57cec5SDimitry Andric 
5045ffd83dbSDimitry Andric     SubTypes.push_back(DeeperType);
5050b57cec5SDimitry Andric     Path.push_back(0);
5060b57cec5SDimitry Andric 
5075ffd83dbSDimitry Andric     DeeperType = ExtractValueInst::getIndexedType(DeeperType, 0);
5080b57cec5SDimitry Andric   }
5090b57cec5SDimitry Andric 
5100b57cec5SDimitry Andric   return true;
5110b57cec5SDimitry Andric }
5120b57cec5SDimitry Andric 
5130b57cec5SDimitry Andric /// Find the first non-empty, scalar-like type in Next and setup the iterator
5140b57cec5SDimitry Andric /// components.
5150b57cec5SDimitry Andric ///
5160b57cec5SDimitry Andric /// Assuming Next is an aggregate of some kind, this function will traverse the
5170b57cec5SDimitry Andric /// tree from left to right (i.e. depth-first) looking for the first
5180b57cec5SDimitry Andric /// non-aggregate type which will play a role in function return.
5190b57cec5SDimitry Andric ///
5200b57cec5SDimitry Andric /// For example, if Next was {[0 x i64], {{}, i32, {}}, i32} then we would setup
5210b57cec5SDimitry Andric /// Path as [1, 1] and SubTypes as [Next, {{}, i32, {}}] to represent the first
5220b57cec5SDimitry Andric /// i32 in that type.
firstRealType(Type * Next,SmallVectorImpl<Type * > & SubTypes,SmallVectorImpl<unsigned> & Path)5235ffd83dbSDimitry Andric static bool firstRealType(Type *Next, SmallVectorImpl<Type *> &SubTypes,
5240b57cec5SDimitry Andric                           SmallVectorImpl<unsigned> &Path) {
5250b57cec5SDimitry Andric   // First initialise the iterator components to the first "leaf" node
5260b57cec5SDimitry Andric   // (i.e. node with no valid sub-type at any index, so {} does count as a leaf
5270b57cec5SDimitry Andric   // despite nominally being an aggregate).
5285ffd83dbSDimitry Andric   while (Type *FirstInner = ExtractValueInst::getIndexedType(Next, 0)) {
5295ffd83dbSDimitry Andric     SubTypes.push_back(Next);
5300b57cec5SDimitry Andric     Path.push_back(0);
5315ffd83dbSDimitry Andric     Next = FirstInner;
5320b57cec5SDimitry Andric   }
5330b57cec5SDimitry Andric 
5340b57cec5SDimitry Andric   // If there's no Path now, Next was originally scalar already (or empty
5350b57cec5SDimitry Andric   // leaf). We're done.
5360b57cec5SDimitry Andric   if (Path.empty())
5370b57cec5SDimitry Andric     return true;
5380b57cec5SDimitry Andric 
5390b57cec5SDimitry Andric   // Otherwise, use normal iteration to keep looking through the tree until we
5400b57cec5SDimitry Andric   // find a non-aggregate type.
5415ffd83dbSDimitry Andric   while (ExtractValueInst::getIndexedType(SubTypes.back(), Path.back())
5425ffd83dbSDimitry Andric              ->isAggregateType()) {
5430b57cec5SDimitry Andric     if (!advanceToNextLeafType(SubTypes, Path))
5440b57cec5SDimitry Andric       return false;
5450b57cec5SDimitry Andric   }
5460b57cec5SDimitry Andric 
5470b57cec5SDimitry Andric   return true;
5480b57cec5SDimitry Andric }
5490b57cec5SDimitry Andric 
5500b57cec5SDimitry Andric /// Set the iterator data-structures to the next non-empty, non-aggregate
5510b57cec5SDimitry Andric /// subtype.
nextRealType(SmallVectorImpl<Type * > & SubTypes,SmallVectorImpl<unsigned> & Path)5525ffd83dbSDimitry Andric static bool nextRealType(SmallVectorImpl<Type *> &SubTypes,
5530b57cec5SDimitry Andric                          SmallVectorImpl<unsigned> &Path) {
5540b57cec5SDimitry Andric   do {
5550b57cec5SDimitry Andric     if (!advanceToNextLeafType(SubTypes, Path))
5560b57cec5SDimitry Andric       return false;
5570b57cec5SDimitry Andric 
5580b57cec5SDimitry Andric     assert(!Path.empty() && "found a leaf but didn't set the path?");
5595ffd83dbSDimitry Andric   } while (ExtractValueInst::getIndexedType(SubTypes.back(), Path.back())
5605ffd83dbSDimitry Andric                ->isAggregateType());
5610b57cec5SDimitry Andric 
5620b57cec5SDimitry Andric   return true;
5630b57cec5SDimitry Andric }
5640b57cec5SDimitry Andric 
5650b57cec5SDimitry Andric 
5660b57cec5SDimitry Andric /// Test if the given instruction is in a position to be optimized
5670b57cec5SDimitry Andric /// with a tail-call. This roughly means that it's in a block with
5680b57cec5SDimitry Andric /// a return and there's nothing that needs to be scheduled
5690b57cec5SDimitry Andric /// between it and the return.
5700b57cec5SDimitry Andric ///
5710b57cec5SDimitry Andric /// This function only tests target-independent requirements.
isInTailCallPosition(const CallBase & Call,const TargetMachine & TM)5725ffd83dbSDimitry Andric bool llvm::isInTailCallPosition(const CallBase &Call, const TargetMachine &TM) {
5735ffd83dbSDimitry Andric   const BasicBlock *ExitBB = Call.getParent();
5740b57cec5SDimitry Andric   const Instruction *Term = ExitBB->getTerminator();
5750b57cec5SDimitry Andric   const ReturnInst *Ret = dyn_cast<ReturnInst>(Term);
5760b57cec5SDimitry Andric 
5770b57cec5SDimitry Andric   // The block must end in a return statement or unreachable.
5780b57cec5SDimitry Andric   //
5790b57cec5SDimitry Andric   // FIXME: Decline tailcall if it's not guaranteed and if the block ends in
5800b57cec5SDimitry Andric   // an unreachable, for now. The way tailcall optimization is currently
5810b57cec5SDimitry Andric   // implemented means it will add an epilogue followed by a jump. That is
5820b57cec5SDimitry Andric   // not profitable. Also, if the callee is a special function (e.g.
5830b57cec5SDimitry Andric   // longjmp on x86), it can end up causing miscompilation that has not
5840b57cec5SDimitry Andric   // been fully understood.
585fe6060f1SDimitry Andric   if (!Ret && ((!TM.Options.GuaranteedTailCallOpt &&
586fe6060f1SDimitry Andric                 Call.getCallingConv() != CallingConv::Tail &&
587fe6060f1SDimitry Andric                 Call.getCallingConv() != CallingConv::SwiftTail) ||
588fe6060f1SDimitry Andric                !isa<UnreachableInst>(Term)))
5890b57cec5SDimitry Andric     return false;
5900b57cec5SDimitry Andric 
5910b57cec5SDimitry Andric   // If I will have a chain, make sure no other instruction that will have a
5920b57cec5SDimitry Andric   // chain interposes between I and the return.
5935ffd83dbSDimitry Andric   // Check for all calls including speculatable functions.
5940b57cec5SDimitry Andric   for (BasicBlock::const_iterator BBI = std::prev(ExitBB->end(), 2);; --BBI) {
5955ffd83dbSDimitry Andric     if (&*BBI == &Call)
5960b57cec5SDimitry Andric       break;
5970b57cec5SDimitry Andric     // Debug info intrinsics do not get in the way of tail call optimization.
598e8d8bef9SDimitry Andric     // Pseudo probe intrinsics do not block tail call optimization either.
599349cc55cSDimitry Andric     if (BBI->isDebugOrPseudoInst())
600e8d8bef9SDimitry Andric       continue;
601e8d8bef9SDimitry Andric     // A lifetime end, assume or noalias.decl intrinsic should not stop tail
602e8d8bef9SDimitry Andric     // call optimization.
6030b57cec5SDimitry Andric     if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(BBI))
6048bcb0991SDimitry Andric       if (II->getIntrinsicID() == Intrinsic::lifetime_end ||
605e8d8bef9SDimitry Andric           II->getIntrinsicID() == Intrinsic::assume ||
606e8d8bef9SDimitry Andric           II->getIntrinsicID() == Intrinsic::experimental_noalias_scope_decl)
6070b57cec5SDimitry Andric         continue;
6080b57cec5SDimitry Andric     if (BBI->mayHaveSideEffects() || BBI->mayReadFromMemory() ||
6090b57cec5SDimitry Andric         !isSafeToSpeculativelyExecute(&*BBI))
6100b57cec5SDimitry Andric       return false;
6110b57cec5SDimitry Andric   }
6120b57cec5SDimitry Andric 
6130b57cec5SDimitry Andric   const Function *F = ExitBB->getParent();
6140b57cec5SDimitry Andric   return returnTypeIsEligibleForTailCall(
6155ffd83dbSDimitry Andric       F, &Call, Ret, *TM.getSubtargetImpl(*F)->getTargetLowering());
6160b57cec5SDimitry Andric }
6170b57cec5SDimitry Andric 
attributesPermitTailCall(const Function * F,const Instruction * I,const ReturnInst * Ret,const TargetLoweringBase & TLI,bool * AllowDifferingSizes)6180b57cec5SDimitry Andric bool llvm::attributesPermitTailCall(const Function *F, const Instruction *I,
6190b57cec5SDimitry Andric                                     const ReturnInst *Ret,
6200b57cec5SDimitry Andric                                     const TargetLoweringBase &TLI,
6210b57cec5SDimitry Andric                                     bool *AllowDifferingSizes) {
6220b57cec5SDimitry Andric   // ADS may be null, so don't write to it directly.
6230b57cec5SDimitry Andric   bool DummyADS;
6240b57cec5SDimitry Andric   bool &ADS = AllowDifferingSizes ? *AllowDifferingSizes : DummyADS;
6250b57cec5SDimitry Andric   ADS = true;
6260b57cec5SDimitry Andric 
62704eeddc0SDimitry Andric   AttrBuilder CallerAttrs(F->getContext(), F->getAttributes().getRetAttrs());
62804eeddc0SDimitry Andric   AttrBuilder CalleeAttrs(F->getContext(),
62904eeddc0SDimitry Andric                           cast<CallInst>(I)->getAttributes().getRetAttrs());
6300b57cec5SDimitry Andric 
631480093f4SDimitry Andric   // Following attributes are completely benign as far as calling convention
6320b57cec5SDimitry Andric   // goes, they shouldn't affect whether the call is a tail call.
633fe6060f1SDimitry Andric   for (const auto &Attr : {Attribute::Alignment, Attribute::Dereferenceable,
634fe6060f1SDimitry Andric                            Attribute::DereferenceableOrNull, Attribute::NoAlias,
6351fd87a68SDimitry Andric                            Attribute::NonNull, Attribute::NoUndef}) {
636fe6060f1SDimitry Andric     CallerAttrs.removeAttribute(Attr);
637fe6060f1SDimitry Andric     CalleeAttrs.removeAttribute(Attr);
638fe6060f1SDimitry Andric   }
6390b57cec5SDimitry Andric 
6400b57cec5SDimitry Andric   if (CallerAttrs.contains(Attribute::ZExt)) {
6410b57cec5SDimitry Andric     if (!CalleeAttrs.contains(Attribute::ZExt))
6420b57cec5SDimitry Andric       return false;
6430b57cec5SDimitry Andric 
6440b57cec5SDimitry Andric     ADS = false;
6450b57cec5SDimitry Andric     CallerAttrs.removeAttribute(Attribute::ZExt);
6460b57cec5SDimitry Andric     CalleeAttrs.removeAttribute(Attribute::ZExt);
6470b57cec5SDimitry Andric   } else if (CallerAttrs.contains(Attribute::SExt)) {
6480b57cec5SDimitry Andric     if (!CalleeAttrs.contains(Attribute::SExt))
6490b57cec5SDimitry Andric       return false;
6500b57cec5SDimitry Andric 
6510b57cec5SDimitry Andric     ADS = false;
6520b57cec5SDimitry Andric     CallerAttrs.removeAttribute(Attribute::SExt);
6530b57cec5SDimitry Andric     CalleeAttrs.removeAttribute(Attribute::SExt);
6540b57cec5SDimitry Andric   }
6550b57cec5SDimitry Andric 
6560b57cec5SDimitry Andric   // Drop sext and zext return attributes if the result is not used.
6570b57cec5SDimitry Andric   // This enables tail calls for code like:
6580b57cec5SDimitry Andric   //
6590b57cec5SDimitry Andric   // define void @caller() {
6600b57cec5SDimitry Andric   // entry:
6610b57cec5SDimitry Andric   //   %unused_result = tail call zeroext i1 @callee()
6620b57cec5SDimitry Andric   //   br label %retlabel
6630b57cec5SDimitry Andric   // retlabel:
6640b57cec5SDimitry Andric   //   ret void
6650b57cec5SDimitry Andric   // }
6660b57cec5SDimitry Andric   if (I->use_empty()) {
6670b57cec5SDimitry Andric     CalleeAttrs.removeAttribute(Attribute::SExt);
6680b57cec5SDimitry Andric     CalleeAttrs.removeAttribute(Attribute::ZExt);
6690b57cec5SDimitry Andric   }
6700b57cec5SDimitry Andric 
6710b57cec5SDimitry Andric   // If they're still different, there's some facet we don't understand
6720b57cec5SDimitry Andric   // (currently only "inreg", but in future who knows). It may be OK but the
6730b57cec5SDimitry Andric   // only safe option is to reject the tail call.
6740b57cec5SDimitry Andric   return CallerAttrs == CalleeAttrs;
6750b57cec5SDimitry Andric }
6760b57cec5SDimitry Andric 
677480093f4SDimitry Andric /// Check whether B is a bitcast of a pointer type to another pointer type,
678480093f4SDimitry Andric /// which is equal to A.
isPointerBitcastEqualTo(const Value * A,const Value * B)679480093f4SDimitry Andric static bool isPointerBitcastEqualTo(const Value *A, const Value *B) {
680480093f4SDimitry Andric   assert(A && B && "Expected non-null inputs!");
681480093f4SDimitry Andric 
682480093f4SDimitry Andric   auto *BitCastIn = dyn_cast<BitCastInst>(B);
683480093f4SDimitry Andric 
684480093f4SDimitry Andric   if (!BitCastIn)
685480093f4SDimitry Andric     return false;
686480093f4SDimitry Andric 
687480093f4SDimitry Andric   if (!A->getType()->isPointerTy() || !B->getType()->isPointerTy())
688480093f4SDimitry Andric     return false;
689480093f4SDimitry Andric 
690480093f4SDimitry Andric   return A == BitCastIn->getOperand(0);
691480093f4SDimitry Andric }
692480093f4SDimitry Andric 
returnTypeIsEligibleForTailCall(const Function * F,const Instruction * I,const ReturnInst * Ret,const TargetLoweringBase & TLI)6930b57cec5SDimitry Andric bool llvm::returnTypeIsEligibleForTailCall(const Function *F,
6940b57cec5SDimitry Andric                                            const Instruction *I,
6950b57cec5SDimitry Andric                                            const ReturnInst *Ret,
6960b57cec5SDimitry Andric                                            const TargetLoweringBase &TLI) {
6970b57cec5SDimitry Andric   // If the block ends with a void return or unreachable, it doesn't matter
6980b57cec5SDimitry Andric   // what the call's return type is.
6990b57cec5SDimitry Andric   if (!Ret || Ret->getNumOperands() == 0) return true;
7000b57cec5SDimitry Andric 
7010b57cec5SDimitry Andric   // If the return value is undef, it doesn't matter what the call's
7020b57cec5SDimitry Andric   // return type is.
7030b57cec5SDimitry Andric   if (isa<UndefValue>(Ret->getOperand(0))) return true;
7040b57cec5SDimitry Andric 
7050b57cec5SDimitry Andric   // Make sure the attributes attached to each return are compatible.
7060b57cec5SDimitry Andric   bool AllowDifferingSizes;
7070b57cec5SDimitry Andric   if (!attributesPermitTailCall(F, I, Ret, TLI, &AllowDifferingSizes))
7080b57cec5SDimitry Andric     return false;
7090b57cec5SDimitry Andric 
7100b57cec5SDimitry Andric   const Value *RetVal = Ret->getOperand(0), *CallVal = I;
7110b57cec5SDimitry Andric   // Intrinsic like llvm.memcpy has no return value, but the expanded
7120b57cec5SDimitry Andric   // libcall may or may not have return value. On most platforms, it
7130b57cec5SDimitry Andric   // will be expanded as memcpy in libc, which returns the first
7140b57cec5SDimitry Andric   // argument. On other platforms like arm-none-eabi, memcpy may be
7150b57cec5SDimitry Andric   // expanded as library call without return value, like __aeabi_memcpy.
7160b57cec5SDimitry Andric   const CallInst *Call = cast<CallInst>(I);
7170b57cec5SDimitry Andric   if (Function *F = Call->getCalledFunction()) {
7180b57cec5SDimitry Andric     Intrinsic::ID IID = F->getIntrinsicID();
7190b57cec5SDimitry Andric     if (((IID == Intrinsic::memcpy &&
7200b57cec5SDimitry Andric           TLI.getLibcallName(RTLIB::MEMCPY) == StringRef("memcpy")) ||
7210b57cec5SDimitry Andric          (IID == Intrinsic::memmove &&
7220b57cec5SDimitry Andric           TLI.getLibcallName(RTLIB::MEMMOVE) == StringRef("memmove")) ||
7230b57cec5SDimitry Andric          (IID == Intrinsic::memset &&
7240b57cec5SDimitry Andric           TLI.getLibcallName(RTLIB::MEMSET) == StringRef("memset"))) &&
725480093f4SDimitry Andric         (RetVal == Call->getArgOperand(0) ||
726480093f4SDimitry Andric          isPointerBitcastEqualTo(RetVal, Call->getArgOperand(0))))
7270b57cec5SDimitry Andric       return true;
7280b57cec5SDimitry Andric   }
7290b57cec5SDimitry Andric 
7300b57cec5SDimitry Andric   SmallVector<unsigned, 4> RetPath, CallPath;
7315ffd83dbSDimitry Andric   SmallVector<Type *, 4> RetSubTypes, CallSubTypes;
7320b57cec5SDimitry Andric 
7330b57cec5SDimitry Andric   bool RetEmpty = !firstRealType(RetVal->getType(), RetSubTypes, RetPath);
7340b57cec5SDimitry Andric   bool CallEmpty = !firstRealType(CallVal->getType(), CallSubTypes, CallPath);
7350b57cec5SDimitry Andric 
7360b57cec5SDimitry Andric   // Nothing's actually returned, it doesn't matter what the callee put there
7370b57cec5SDimitry Andric   // it's a valid tail call.
7380b57cec5SDimitry Andric   if (RetEmpty)
7390b57cec5SDimitry Andric     return true;
7400b57cec5SDimitry Andric 
7410b57cec5SDimitry Andric   // Iterate pairwise through each of the value types making up the tail call
7420b57cec5SDimitry Andric   // and the corresponding return. For each one we want to know whether it's
7430b57cec5SDimitry Andric   // essentially going directly from the tail call to the ret, via operations
7440b57cec5SDimitry Andric   // that end up not generating any code.
7450b57cec5SDimitry Andric   //
7460b57cec5SDimitry Andric   // We allow a certain amount of covariance here. For example it's permitted
7470b57cec5SDimitry Andric   // for the tail call to define more bits than the ret actually cares about
7480b57cec5SDimitry Andric   // (e.g. via a truncate).
7490b57cec5SDimitry Andric   do {
7500b57cec5SDimitry Andric     if (CallEmpty) {
7510b57cec5SDimitry Andric       // We've exhausted the values produced by the tail call instruction, the
7520b57cec5SDimitry Andric       // rest are essentially undef. The type doesn't really matter, but we need
7530b57cec5SDimitry Andric       // *something*.
7545ffd83dbSDimitry Andric       Type *SlotType =
7555ffd83dbSDimitry Andric           ExtractValueInst::getIndexedType(RetSubTypes.back(), RetPath.back());
7560b57cec5SDimitry Andric       CallVal = UndefValue::get(SlotType);
7570b57cec5SDimitry Andric     }
7580b57cec5SDimitry Andric 
7590b57cec5SDimitry Andric     // The manipulations performed when we're looking through an insertvalue or
7600b57cec5SDimitry Andric     // an extractvalue would happen at the front of the RetPath list, so since
7610b57cec5SDimitry Andric     // we have to copy it anyway it's more efficient to create a reversed copy.
7620eae32dcSDimitry Andric     SmallVector<unsigned, 4> TmpRetPath(llvm::reverse(RetPath));
7630eae32dcSDimitry Andric     SmallVector<unsigned, 4> TmpCallPath(llvm::reverse(CallPath));
7640b57cec5SDimitry Andric 
7650b57cec5SDimitry Andric     // Finally, we can check whether the value produced by the tail call at this
7660b57cec5SDimitry Andric     // index is compatible with the value we return.
7670b57cec5SDimitry Andric     if (!slotOnlyDiscardsData(RetVal, CallVal, TmpRetPath, TmpCallPath,
7680b57cec5SDimitry Andric                               AllowDifferingSizes, TLI,
7690b57cec5SDimitry Andric                               F->getParent()->getDataLayout()))
7700b57cec5SDimitry Andric       return false;
7710b57cec5SDimitry Andric 
7720b57cec5SDimitry Andric     CallEmpty  = !nextRealType(CallSubTypes, CallPath);
7730b57cec5SDimitry Andric   } while(nextRealType(RetSubTypes, RetPath));
7740b57cec5SDimitry Andric 
7750b57cec5SDimitry Andric   return true;
7760b57cec5SDimitry Andric }
7770b57cec5SDimitry Andric 
collectEHScopeMembers(DenseMap<const MachineBasicBlock *,int> & EHScopeMembership,int EHScope,const MachineBasicBlock * MBB)7780b57cec5SDimitry Andric static void collectEHScopeMembers(
7790b57cec5SDimitry Andric     DenseMap<const MachineBasicBlock *, int> &EHScopeMembership, int EHScope,
7800b57cec5SDimitry Andric     const MachineBasicBlock *MBB) {
7810b57cec5SDimitry Andric   SmallVector<const MachineBasicBlock *, 16> Worklist = {MBB};
7820b57cec5SDimitry Andric   while (!Worklist.empty()) {
7830b57cec5SDimitry Andric     const MachineBasicBlock *Visiting = Worklist.pop_back_val();
7840b57cec5SDimitry Andric     // Don't follow blocks which start new scopes.
7850b57cec5SDimitry Andric     if (Visiting->isEHPad() && Visiting != MBB)
7860b57cec5SDimitry Andric       continue;
7870b57cec5SDimitry Andric 
7880b57cec5SDimitry Andric     // Add this MBB to our scope.
7890b57cec5SDimitry Andric     auto P = EHScopeMembership.insert(std::make_pair(Visiting, EHScope));
7900b57cec5SDimitry Andric 
7910b57cec5SDimitry Andric     // Don't revisit blocks.
7920b57cec5SDimitry Andric     if (!P.second) {
7930b57cec5SDimitry Andric       assert(P.first->second == EHScope && "MBB is part of two scopes!");
7940b57cec5SDimitry Andric       continue;
7950b57cec5SDimitry Andric     }
7960b57cec5SDimitry Andric 
7970b57cec5SDimitry Andric     // Returns are boundaries where scope transfer can occur, don't follow
7980b57cec5SDimitry Andric     // successors.
7990b57cec5SDimitry Andric     if (Visiting->isEHScopeReturnBlock())
8000b57cec5SDimitry Andric       continue;
8010b57cec5SDimitry Andric 
802e8d8bef9SDimitry Andric     append_range(Worklist, Visiting->successors());
8030b57cec5SDimitry Andric   }
8040b57cec5SDimitry Andric }
8050b57cec5SDimitry Andric 
8060b57cec5SDimitry Andric DenseMap<const MachineBasicBlock *, int>
getEHScopeMembership(const MachineFunction & MF)8070b57cec5SDimitry Andric llvm::getEHScopeMembership(const MachineFunction &MF) {
8080b57cec5SDimitry Andric   DenseMap<const MachineBasicBlock *, int> EHScopeMembership;
8090b57cec5SDimitry Andric 
8100b57cec5SDimitry Andric   // We don't have anything to do if there aren't any EH pads.
8110b57cec5SDimitry Andric   if (!MF.hasEHScopes())
8120b57cec5SDimitry Andric     return EHScopeMembership;
8130b57cec5SDimitry Andric 
8140b57cec5SDimitry Andric   int EntryBBNumber = MF.front().getNumber();
8150b57cec5SDimitry Andric   bool IsSEH = isAsynchronousEHPersonality(
8160b57cec5SDimitry Andric       classifyEHPersonality(MF.getFunction().getPersonalityFn()));
8170b57cec5SDimitry Andric 
8180b57cec5SDimitry Andric   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
8190b57cec5SDimitry Andric   SmallVector<const MachineBasicBlock *, 16> EHScopeBlocks;
8200b57cec5SDimitry Andric   SmallVector<const MachineBasicBlock *, 16> UnreachableBlocks;
8210b57cec5SDimitry Andric   SmallVector<const MachineBasicBlock *, 16> SEHCatchPads;
8220b57cec5SDimitry Andric   SmallVector<std::pair<const MachineBasicBlock *, int>, 16> CatchRetSuccessors;
8230b57cec5SDimitry Andric   for (const MachineBasicBlock &MBB : MF) {
8240b57cec5SDimitry Andric     if (MBB.isEHScopeEntry()) {
8250b57cec5SDimitry Andric       EHScopeBlocks.push_back(&MBB);
8260b57cec5SDimitry Andric     } else if (IsSEH && MBB.isEHPad()) {
8270b57cec5SDimitry Andric       SEHCatchPads.push_back(&MBB);
8280b57cec5SDimitry Andric     } else if (MBB.pred_empty()) {
8290b57cec5SDimitry Andric       UnreachableBlocks.push_back(&MBB);
8300b57cec5SDimitry Andric     }
8310b57cec5SDimitry Andric 
8320b57cec5SDimitry Andric     MachineBasicBlock::const_iterator MBBI = MBB.getFirstTerminator();
8330b57cec5SDimitry Andric 
8340b57cec5SDimitry Andric     // CatchPads are not scopes for SEH so do not consider CatchRet to
8350b57cec5SDimitry Andric     // transfer control to another scope.
8360b57cec5SDimitry Andric     if (MBBI == MBB.end() || MBBI->getOpcode() != TII->getCatchReturnOpcode())
8370b57cec5SDimitry Andric       continue;
8380b57cec5SDimitry Andric 
8390b57cec5SDimitry Andric     // FIXME: SEH CatchPads are not necessarily in the parent function:
8400b57cec5SDimitry Andric     // they could be inside a finally block.
8410b57cec5SDimitry Andric     const MachineBasicBlock *Successor = MBBI->getOperand(0).getMBB();
8420b57cec5SDimitry Andric     const MachineBasicBlock *SuccessorColor = MBBI->getOperand(1).getMBB();
8430b57cec5SDimitry Andric     CatchRetSuccessors.push_back(
8440b57cec5SDimitry Andric         {Successor, IsSEH ? EntryBBNumber : SuccessorColor->getNumber()});
8450b57cec5SDimitry Andric   }
8460b57cec5SDimitry Andric 
8470b57cec5SDimitry Andric   // We don't have anything to do if there aren't any EH pads.
8480b57cec5SDimitry Andric   if (EHScopeBlocks.empty())
8490b57cec5SDimitry Andric     return EHScopeMembership;
8500b57cec5SDimitry Andric 
8510b57cec5SDimitry Andric   // Identify all the basic blocks reachable from the function entry.
8520b57cec5SDimitry Andric   collectEHScopeMembers(EHScopeMembership, EntryBBNumber, &MF.front());
8530b57cec5SDimitry Andric   // All blocks not part of a scope are in the parent function.
8540b57cec5SDimitry Andric   for (const MachineBasicBlock *MBB : UnreachableBlocks)
8550b57cec5SDimitry Andric     collectEHScopeMembers(EHScopeMembership, EntryBBNumber, MBB);
8560b57cec5SDimitry Andric   // Next, identify all the blocks inside the scopes.
8570b57cec5SDimitry Andric   for (const MachineBasicBlock *MBB : EHScopeBlocks)
8580b57cec5SDimitry Andric     collectEHScopeMembers(EHScopeMembership, MBB->getNumber(), MBB);
8590b57cec5SDimitry Andric   // SEH CatchPads aren't really scopes, handle them separately.
8600b57cec5SDimitry Andric   for (const MachineBasicBlock *MBB : SEHCatchPads)
8610b57cec5SDimitry Andric     collectEHScopeMembers(EHScopeMembership, EntryBBNumber, MBB);
8620b57cec5SDimitry Andric   // Finally, identify all the targets of a catchret.
8630b57cec5SDimitry Andric   for (std::pair<const MachineBasicBlock *, int> CatchRetPair :
8640b57cec5SDimitry Andric        CatchRetSuccessors)
8650b57cec5SDimitry Andric     collectEHScopeMembers(EHScopeMembership, CatchRetPair.second,
8660b57cec5SDimitry Andric                           CatchRetPair.first);
8670b57cec5SDimitry Andric   return EHScopeMembership;
8680b57cec5SDimitry Andric }
869