Path: blob/main/contrib/llvm-project/llvm/lib/Transforms/Utils/FunctionComparator.cpp
35271 views
//===- FunctionComparator.h - Function Comparator -------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This file implements the FunctionComparator and GlobalNumberState classes9// which are used by the MergeFunctions pass for comparing functions.10//11//===----------------------------------------------------------------------===//1213#include "llvm/Transforms/Utils/FunctionComparator.h"14#include "llvm/ADT/APFloat.h"15#include "llvm/ADT/APInt.h"16#include "llvm/ADT/ArrayRef.h"17#include "llvm/ADT/Hashing.h"18#include "llvm/ADT/SmallPtrSet.h"19#include "llvm/ADT/SmallVector.h"20#include "llvm/IR/Attributes.h"21#include "llvm/IR/BasicBlock.h"22#include "llvm/IR/Constant.h"23#include "llvm/IR/Constants.h"24#include "llvm/IR/DataLayout.h"25#include "llvm/IR/DerivedTypes.h"26#include "llvm/IR/Function.h"27#include "llvm/IR/GlobalValue.h"28#include "llvm/IR/InlineAsm.h"29#include "llvm/IR/InstrTypes.h"30#include "llvm/IR/Instruction.h"31#include "llvm/IR/Instructions.h"32#include "llvm/IR/LLVMContext.h"33#include "llvm/IR/Metadata.h"34#include "llvm/IR/Module.h"35#include "llvm/IR/Operator.h"36#include "llvm/IR/Type.h"37#include "llvm/IR/Value.h"38#include "llvm/Support/Casting.h"39#include "llvm/Support/Compiler.h"40#include "llvm/Support/Debug.h"41#include "llvm/Support/ErrorHandling.h"42#include "llvm/Support/raw_ostream.h"43#include <cassert>44#include <cstddef>45#include <cstdint>46#include <utility>4748using namespace llvm;4950#define DEBUG_TYPE "functioncomparator"5152int FunctionComparator::cmpNumbers(uint64_t L, uint64_t R) const {53if (L < R)54return -1;55if (L > R)56return 1;57return 0;58}5960int FunctionComparator::cmpAligns(Align L, Align R) const {61if (L.value() < R.value())62return -1;63if (L.value() > R.value())64return 1;65return 0;66}6768int FunctionComparator::cmpOrderings(AtomicOrdering L, AtomicOrdering R) const {69if ((int)L < (int)R)70return -1;71if ((int)L > (int)R)72return 1;73return 0;74}7576int FunctionComparator::cmpAPInts(const APInt &L, const APInt &R) const {77if (int Res = cmpNumbers(L.getBitWidth(), R.getBitWidth()))78return Res;79if (L.ugt(R))80return 1;81if (R.ugt(L))82return -1;83return 0;84}8586int FunctionComparator::cmpAPFloats(const APFloat &L, const APFloat &R) const {87// Floats are ordered first by semantics (i.e. float, double, half, etc.),88// then by value interpreted as a bitstring (aka APInt).89const fltSemantics &SL = L.getSemantics(), &SR = R.getSemantics();90if (int Res = cmpNumbers(APFloat::semanticsPrecision(SL),91APFloat::semanticsPrecision(SR)))92return Res;93if (int Res = cmpNumbers(APFloat::semanticsMaxExponent(SL),94APFloat::semanticsMaxExponent(SR)))95return Res;96if (int Res = cmpNumbers(APFloat::semanticsMinExponent(SL),97APFloat::semanticsMinExponent(SR)))98return Res;99if (int Res = cmpNumbers(APFloat::semanticsSizeInBits(SL),100APFloat::semanticsSizeInBits(SR)))101return Res;102return cmpAPInts(L.bitcastToAPInt(), R.bitcastToAPInt());103}104105int FunctionComparator::cmpMem(StringRef L, StringRef R) const {106// Prevent heavy comparison, compare sizes first.107if (int Res = cmpNumbers(L.size(), R.size()))108return Res;109110// Compare strings lexicographically only when it is necessary: only when111// strings are equal in size.112return std::clamp(L.compare(R), -1, 1);113}114115int FunctionComparator::cmpAttrs(const AttributeList L,116const AttributeList R) const {117if (int Res = cmpNumbers(L.getNumAttrSets(), R.getNumAttrSets()))118return Res;119120for (unsigned i : L.indexes()) {121AttributeSet LAS = L.getAttributes(i);122AttributeSet RAS = R.getAttributes(i);123AttributeSet::iterator LI = LAS.begin(), LE = LAS.end();124AttributeSet::iterator RI = RAS.begin(), RE = RAS.end();125for (; LI != LE && RI != RE; ++LI, ++RI) {126Attribute LA = *LI;127Attribute RA = *RI;128if (LA.isTypeAttribute() && RA.isTypeAttribute()) {129if (LA.getKindAsEnum() != RA.getKindAsEnum())130return cmpNumbers(LA.getKindAsEnum(), RA.getKindAsEnum());131132Type *TyL = LA.getValueAsType();133Type *TyR = RA.getValueAsType();134if (TyL && TyR) {135if (int Res = cmpTypes(TyL, TyR))136return Res;137continue;138}139140// Two pointers, at least one null, so the comparison result is141// independent of the value of a real pointer.142if (int Res = cmpNumbers((uint64_t)TyL, (uint64_t)TyR))143return Res;144continue;145} else if (LA.isConstantRangeAttribute() &&146RA.isConstantRangeAttribute()) {147if (LA.getKindAsEnum() != RA.getKindAsEnum())148return cmpNumbers(LA.getKindAsEnum(), RA.getKindAsEnum());149150const ConstantRange &LCR = LA.getRange();151const ConstantRange &RCR = RA.getRange();152if (int Res = cmpAPInts(LCR.getLower(), RCR.getLower()))153return Res;154if (int Res = cmpAPInts(LCR.getUpper(), RCR.getUpper()))155return Res;156continue;157}158if (LA < RA)159return -1;160if (RA < LA)161return 1;162}163if (LI != LE)164return 1;165if (RI != RE)166return -1;167}168return 0;169}170171int FunctionComparator::cmpMetadata(const Metadata *L,172const Metadata *R) const {173// TODO: the following routine coerce the metadata contents into constants174// or MDStrings before comparison.175// It ignores any other cases, so that the metadata nodes are considered176// equal even though this is not correct.177// We should structurally compare the metadata nodes to be perfect here.178179auto *MDStringL = dyn_cast<MDString>(L);180auto *MDStringR = dyn_cast<MDString>(R);181if (MDStringL && MDStringR) {182if (MDStringL == MDStringR)183return 0;184return MDStringL->getString().compare(MDStringR->getString());185}186if (MDStringR)187return -1;188if (MDStringL)189return 1;190191auto *CL = dyn_cast<ConstantAsMetadata>(L);192auto *CR = dyn_cast<ConstantAsMetadata>(R);193if (CL == CR)194return 0;195if (!CL)196return -1;197if (!CR)198return 1;199return cmpConstants(CL->getValue(), CR->getValue());200}201202int FunctionComparator::cmpMDNode(const MDNode *L, const MDNode *R) const {203if (L == R)204return 0;205if (!L)206return -1;207if (!R)208return 1;209// TODO: Note that as this is metadata, it is possible to drop and/or merge210// this data when considering functions to merge. Thus this comparison would211// return 0 (i.e. equivalent), but merging would become more complicated212// because the ranges would need to be unioned. It is not likely that213// functions differ ONLY in this metadata if they are actually the same214// function semantically.215if (int Res = cmpNumbers(L->getNumOperands(), R->getNumOperands()))216return Res;217for (size_t I = 0; I < L->getNumOperands(); ++I)218if (int Res = cmpMetadata(L->getOperand(I), R->getOperand(I)))219return Res;220return 0;221}222223int FunctionComparator::cmpInstMetadata(Instruction const *L,224Instruction const *R) const {225/// These metadata affects the other optimization passes by making assertions226/// or constraints.227/// Values that carry different expectations should be considered different.228SmallVector<std::pair<unsigned, MDNode *>> MDL, MDR;229L->getAllMetadataOtherThanDebugLoc(MDL);230R->getAllMetadataOtherThanDebugLoc(MDR);231if (MDL.size() > MDR.size())232return 1;233else if (MDL.size() < MDR.size())234return -1;235for (size_t I = 0, N = MDL.size(); I < N; ++I) {236auto const [KeyL, ML] = MDL[I];237auto const [KeyR, MR] = MDR[I];238if (int Res = cmpNumbers(KeyL, KeyR))239return Res;240if (int Res = cmpMDNode(ML, MR))241return Res;242}243return 0;244}245246int FunctionComparator::cmpOperandBundlesSchema(const CallBase &LCS,247const CallBase &RCS) const {248assert(LCS.getOpcode() == RCS.getOpcode() && "Can't compare otherwise!");249250if (int Res =251cmpNumbers(LCS.getNumOperandBundles(), RCS.getNumOperandBundles()))252return Res;253254for (unsigned I = 0, E = LCS.getNumOperandBundles(); I != E; ++I) {255auto OBL = LCS.getOperandBundleAt(I);256auto OBR = RCS.getOperandBundleAt(I);257258if (int Res = OBL.getTagName().compare(OBR.getTagName()))259return Res;260261if (int Res = cmpNumbers(OBL.Inputs.size(), OBR.Inputs.size()))262return Res;263}264265return 0;266}267268/// Constants comparison:269/// 1. Check whether type of L constant could be losslessly bitcasted to R270/// type.271/// 2. Compare constant contents.272/// For more details see declaration comments.273int FunctionComparator::cmpConstants(const Constant *L,274const Constant *R) const {275Type *TyL = L->getType();276Type *TyR = R->getType();277278// Check whether types are bitcastable. This part is just re-factored279// Type::canLosslesslyBitCastTo method, but instead of returning true/false,280// we also pack into result which type is "less" for us.281int TypesRes = cmpTypes(TyL, TyR);282if (TypesRes != 0) {283// Types are different, but check whether we can bitcast them.284if (!TyL->isFirstClassType()) {285if (TyR->isFirstClassType())286return -1;287// Neither TyL nor TyR are values of first class type. Return the result288// of comparing the types289return TypesRes;290}291if (!TyR->isFirstClassType()) {292if (TyL->isFirstClassType())293return 1;294return TypesRes;295}296297// Vector -> Vector conversions are always lossless if the two vector types298// have the same size, otherwise not.299unsigned TyLWidth = 0;300unsigned TyRWidth = 0;301302if (auto *VecTyL = dyn_cast<VectorType>(TyL))303TyLWidth = VecTyL->getPrimitiveSizeInBits().getFixedValue();304if (auto *VecTyR = dyn_cast<VectorType>(TyR))305TyRWidth = VecTyR->getPrimitiveSizeInBits().getFixedValue();306307if (TyLWidth != TyRWidth)308return cmpNumbers(TyLWidth, TyRWidth);309310// Zero bit-width means neither TyL nor TyR are vectors.311if (!TyLWidth) {312PointerType *PTyL = dyn_cast<PointerType>(TyL);313PointerType *PTyR = dyn_cast<PointerType>(TyR);314if (PTyL && PTyR) {315unsigned AddrSpaceL = PTyL->getAddressSpace();316unsigned AddrSpaceR = PTyR->getAddressSpace();317if (int Res = cmpNumbers(AddrSpaceL, AddrSpaceR))318return Res;319}320if (PTyL)321return 1;322if (PTyR)323return -1;324325// TyL and TyR aren't vectors, nor pointers. We don't know how to326// bitcast them.327return TypesRes;328}329}330331// OK, types are bitcastable, now check constant contents.332333if (L->isNullValue() && R->isNullValue())334return TypesRes;335if (L->isNullValue() && !R->isNullValue())336return 1;337if (!L->isNullValue() && R->isNullValue())338return -1;339340auto GlobalValueL = const_cast<GlobalValue *>(dyn_cast<GlobalValue>(L));341auto GlobalValueR = const_cast<GlobalValue *>(dyn_cast<GlobalValue>(R));342if (GlobalValueL && GlobalValueR) {343return cmpGlobalValues(GlobalValueL, GlobalValueR);344}345346if (int Res = cmpNumbers(L->getValueID(), R->getValueID()))347return Res;348349if (const auto *SeqL = dyn_cast<ConstantDataSequential>(L)) {350const auto *SeqR = cast<ConstantDataSequential>(R);351// This handles ConstantDataArray and ConstantDataVector. Note that we352// compare the two raw data arrays, which might differ depending on the host353// endianness. This isn't a problem though, because the endiness of a module354// will affect the order of the constants, but this order is the same355// for a given input module and host platform.356return cmpMem(SeqL->getRawDataValues(), SeqR->getRawDataValues());357}358359switch (L->getValueID()) {360case Value::UndefValueVal:361case Value::PoisonValueVal:362case Value::ConstantTokenNoneVal:363return TypesRes;364case Value::ConstantIntVal: {365const APInt &LInt = cast<ConstantInt>(L)->getValue();366const APInt &RInt = cast<ConstantInt>(R)->getValue();367return cmpAPInts(LInt, RInt);368}369case Value::ConstantFPVal: {370const APFloat &LAPF = cast<ConstantFP>(L)->getValueAPF();371const APFloat &RAPF = cast<ConstantFP>(R)->getValueAPF();372return cmpAPFloats(LAPF, RAPF);373}374case Value::ConstantArrayVal: {375const ConstantArray *LA = cast<ConstantArray>(L);376const ConstantArray *RA = cast<ConstantArray>(R);377uint64_t NumElementsL = cast<ArrayType>(TyL)->getNumElements();378uint64_t NumElementsR = cast<ArrayType>(TyR)->getNumElements();379if (int Res = cmpNumbers(NumElementsL, NumElementsR))380return Res;381for (uint64_t i = 0; i < NumElementsL; ++i) {382if (int Res = cmpConstants(cast<Constant>(LA->getOperand(i)),383cast<Constant>(RA->getOperand(i))))384return Res;385}386return 0;387}388case Value::ConstantStructVal: {389const ConstantStruct *LS = cast<ConstantStruct>(L);390const ConstantStruct *RS = cast<ConstantStruct>(R);391unsigned NumElementsL = cast<StructType>(TyL)->getNumElements();392unsigned NumElementsR = cast<StructType>(TyR)->getNumElements();393if (int Res = cmpNumbers(NumElementsL, NumElementsR))394return Res;395for (unsigned i = 0; i != NumElementsL; ++i) {396if (int Res = cmpConstants(cast<Constant>(LS->getOperand(i)),397cast<Constant>(RS->getOperand(i))))398return Res;399}400return 0;401}402case Value::ConstantVectorVal: {403const ConstantVector *LV = cast<ConstantVector>(L);404const ConstantVector *RV = cast<ConstantVector>(R);405unsigned NumElementsL = cast<FixedVectorType>(TyL)->getNumElements();406unsigned NumElementsR = cast<FixedVectorType>(TyR)->getNumElements();407if (int Res = cmpNumbers(NumElementsL, NumElementsR))408return Res;409for (uint64_t i = 0; i < NumElementsL; ++i) {410if (int Res = cmpConstants(cast<Constant>(LV->getOperand(i)),411cast<Constant>(RV->getOperand(i))))412return Res;413}414return 0;415}416case Value::ConstantExprVal: {417const ConstantExpr *LE = cast<ConstantExpr>(L);418const ConstantExpr *RE = cast<ConstantExpr>(R);419if (int Res = cmpNumbers(LE->getOpcode(), RE->getOpcode()))420return Res;421unsigned NumOperandsL = LE->getNumOperands();422unsigned NumOperandsR = RE->getNumOperands();423if (int Res = cmpNumbers(NumOperandsL, NumOperandsR))424return Res;425for (unsigned i = 0; i < NumOperandsL; ++i) {426if (int Res = cmpConstants(cast<Constant>(LE->getOperand(i)),427cast<Constant>(RE->getOperand(i))))428return Res;429}430if (auto *GEPL = dyn_cast<GEPOperator>(LE)) {431auto *GEPR = cast<GEPOperator>(RE);432if (int Res = cmpTypes(GEPL->getSourceElementType(),433GEPR->getSourceElementType()))434return Res;435if (int Res = cmpNumbers(GEPL->getNoWrapFlags().getRaw(),436GEPR->getNoWrapFlags().getRaw()))437return Res;438439std::optional<ConstantRange> InRangeL = GEPL->getInRange();440std::optional<ConstantRange> InRangeR = GEPR->getInRange();441if (InRangeL) {442if (!InRangeR)443return 1;444if (int Res = cmpAPInts(InRangeL->getLower(), InRangeR->getLower()))445return Res;446if (int Res = cmpAPInts(InRangeL->getUpper(), InRangeR->getUpper()))447return Res;448} else if (InRangeR) {449return -1;450}451}452if (auto *OBOL = dyn_cast<OverflowingBinaryOperator>(LE)) {453auto *OBOR = cast<OverflowingBinaryOperator>(RE);454if (int Res =455cmpNumbers(OBOL->hasNoUnsignedWrap(), OBOR->hasNoUnsignedWrap()))456return Res;457if (int Res =458cmpNumbers(OBOL->hasNoSignedWrap(), OBOR->hasNoSignedWrap()))459return Res;460}461return 0;462}463case Value::BlockAddressVal: {464const BlockAddress *LBA = cast<BlockAddress>(L);465const BlockAddress *RBA = cast<BlockAddress>(R);466if (int Res = cmpValues(LBA->getFunction(), RBA->getFunction()))467return Res;468if (LBA->getFunction() == RBA->getFunction()) {469// They are BBs in the same function. Order by which comes first in the470// BB order of the function. This order is deterministic.471Function *F = LBA->getFunction();472BasicBlock *LBB = LBA->getBasicBlock();473BasicBlock *RBB = RBA->getBasicBlock();474if (LBB == RBB)475return 0;476for (BasicBlock &BB : *F) {477if (&BB == LBB) {478assert(&BB != RBB);479return -1;480}481if (&BB == RBB)482return 1;483}484llvm_unreachable("Basic Block Address does not point to a basic block in "485"its function.");486return -1;487} else {488// cmpValues said the functions are the same. So because they aren't489// literally the same pointer, they must respectively be the left and490// right functions.491assert(LBA->getFunction() == FnL && RBA->getFunction() == FnR);492// cmpValues will tell us if these are equivalent BasicBlocks, in the493// context of their respective functions.494return cmpValues(LBA->getBasicBlock(), RBA->getBasicBlock());495}496}497case Value::DSOLocalEquivalentVal: {498// dso_local_equivalent is functionally equivalent to whatever it points to.499// This means the behavior of the IR should be the exact same as if the500// function was referenced directly rather than through a501// dso_local_equivalent.502const auto *LEquiv = cast<DSOLocalEquivalent>(L);503const auto *REquiv = cast<DSOLocalEquivalent>(R);504return cmpGlobalValues(LEquiv->getGlobalValue(), REquiv->getGlobalValue());505}506default: // Unknown constant, abort.507LLVM_DEBUG(dbgs() << "Looking at valueID " << L->getValueID() << "\n");508llvm_unreachable("Constant ValueID not recognized.");509return -1;510}511}512513int FunctionComparator::cmpGlobalValues(GlobalValue *L, GlobalValue *R) const {514uint64_t LNumber = GlobalNumbers->getNumber(L);515uint64_t RNumber = GlobalNumbers->getNumber(R);516return cmpNumbers(LNumber, RNumber);517}518519/// cmpType - compares two types,520/// defines total ordering among the types set.521/// See method declaration comments for more details.522int FunctionComparator::cmpTypes(Type *TyL, Type *TyR) const {523PointerType *PTyL = dyn_cast<PointerType>(TyL);524PointerType *PTyR = dyn_cast<PointerType>(TyR);525526const DataLayout &DL = FnL->getDataLayout();527if (PTyL && PTyL->getAddressSpace() == 0)528TyL = DL.getIntPtrType(TyL);529if (PTyR && PTyR->getAddressSpace() == 0)530TyR = DL.getIntPtrType(TyR);531532if (TyL == TyR)533return 0;534535if (int Res = cmpNumbers(TyL->getTypeID(), TyR->getTypeID()))536return Res;537538switch (TyL->getTypeID()) {539default:540llvm_unreachable("Unknown type!");541case Type::IntegerTyID:542return cmpNumbers(cast<IntegerType>(TyL)->getBitWidth(),543cast<IntegerType>(TyR)->getBitWidth());544// TyL == TyR would have returned true earlier, because types are uniqued.545case Type::VoidTyID:546case Type::FloatTyID:547case Type::DoubleTyID:548case Type::X86_FP80TyID:549case Type::FP128TyID:550case Type::PPC_FP128TyID:551case Type::LabelTyID:552case Type::MetadataTyID:553case Type::TokenTyID:554return 0;555556case Type::PointerTyID:557assert(PTyL && PTyR && "Both types must be pointers here.");558return cmpNumbers(PTyL->getAddressSpace(), PTyR->getAddressSpace());559560case Type::StructTyID: {561StructType *STyL = cast<StructType>(TyL);562StructType *STyR = cast<StructType>(TyR);563if (STyL->getNumElements() != STyR->getNumElements())564return cmpNumbers(STyL->getNumElements(), STyR->getNumElements());565566if (STyL->isPacked() != STyR->isPacked())567return cmpNumbers(STyL->isPacked(), STyR->isPacked());568569for (unsigned i = 0, e = STyL->getNumElements(); i != e; ++i) {570if (int Res = cmpTypes(STyL->getElementType(i), STyR->getElementType(i)))571return Res;572}573return 0;574}575576case Type::FunctionTyID: {577FunctionType *FTyL = cast<FunctionType>(TyL);578FunctionType *FTyR = cast<FunctionType>(TyR);579if (FTyL->getNumParams() != FTyR->getNumParams())580return cmpNumbers(FTyL->getNumParams(), FTyR->getNumParams());581582if (FTyL->isVarArg() != FTyR->isVarArg())583return cmpNumbers(FTyL->isVarArg(), FTyR->isVarArg());584585if (int Res = cmpTypes(FTyL->getReturnType(), FTyR->getReturnType()))586return Res;587588for (unsigned i = 0, e = FTyL->getNumParams(); i != e; ++i) {589if (int Res = cmpTypes(FTyL->getParamType(i), FTyR->getParamType(i)))590return Res;591}592return 0;593}594595case Type::ArrayTyID: {596auto *STyL = cast<ArrayType>(TyL);597auto *STyR = cast<ArrayType>(TyR);598if (STyL->getNumElements() != STyR->getNumElements())599return cmpNumbers(STyL->getNumElements(), STyR->getNumElements());600return cmpTypes(STyL->getElementType(), STyR->getElementType());601}602case Type::FixedVectorTyID:603case Type::ScalableVectorTyID: {604auto *STyL = cast<VectorType>(TyL);605auto *STyR = cast<VectorType>(TyR);606if (STyL->getElementCount().isScalable() !=607STyR->getElementCount().isScalable())608return cmpNumbers(STyL->getElementCount().isScalable(),609STyR->getElementCount().isScalable());610if (STyL->getElementCount() != STyR->getElementCount())611return cmpNumbers(STyL->getElementCount().getKnownMinValue(),612STyR->getElementCount().getKnownMinValue());613return cmpTypes(STyL->getElementType(), STyR->getElementType());614}615}616}617618// Determine whether the two operations are the same except that pointer-to-A619// and pointer-to-B are equivalent. This should be kept in sync with620// Instruction::isSameOperationAs.621// Read method declaration comments for more details.622int FunctionComparator::cmpOperations(const Instruction *L,623const Instruction *R,624bool &needToCmpOperands) const {625needToCmpOperands = true;626if (int Res = cmpValues(L, R))627return Res;628629// Differences from Instruction::isSameOperationAs:630// * replace type comparison with calls to cmpTypes.631// * we test for I->getRawSubclassOptionalData (nuw/nsw/tail) at the top.632// * because of the above, we don't test for the tail bit on calls later on.633if (int Res = cmpNumbers(L->getOpcode(), R->getOpcode()))634return Res;635636if (const GetElementPtrInst *GEPL = dyn_cast<GetElementPtrInst>(L)) {637needToCmpOperands = false;638const GetElementPtrInst *GEPR = cast<GetElementPtrInst>(R);639if (int Res =640cmpValues(GEPL->getPointerOperand(), GEPR->getPointerOperand()))641return Res;642return cmpGEPs(GEPL, GEPR);643}644645if (int Res = cmpNumbers(L->getNumOperands(), R->getNumOperands()))646return Res;647648if (int Res = cmpTypes(L->getType(), R->getType()))649return Res;650651if (int Res = cmpNumbers(L->getRawSubclassOptionalData(),652R->getRawSubclassOptionalData()))653return Res;654655// We have two instructions of identical opcode and #operands. Check to see656// if all operands are the same type657for (unsigned i = 0, e = L->getNumOperands(); i != e; ++i) {658if (int Res =659cmpTypes(L->getOperand(i)->getType(), R->getOperand(i)->getType()))660return Res;661}662663// Check special state that is a part of some instructions.664if (const AllocaInst *AI = dyn_cast<AllocaInst>(L)) {665if (int Res = cmpTypes(AI->getAllocatedType(),666cast<AllocaInst>(R)->getAllocatedType()))667return Res;668return cmpAligns(AI->getAlign(), cast<AllocaInst>(R)->getAlign());669}670if (const LoadInst *LI = dyn_cast<LoadInst>(L)) {671if (int Res = cmpNumbers(LI->isVolatile(), cast<LoadInst>(R)->isVolatile()))672return Res;673if (int Res = cmpAligns(LI->getAlign(), cast<LoadInst>(R)->getAlign()))674return Res;675if (int Res =676cmpOrderings(LI->getOrdering(), cast<LoadInst>(R)->getOrdering()))677return Res;678if (int Res = cmpNumbers(LI->getSyncScopeID(),679cast<LoadInst>(R)->getSyncScopeID()))680return Res;681return cmpInstMetadata(L, R);682}683if (const StoreInst *SI = dyn_cast<StoreInst>(L)) {684if (int Res =685cmpNumbers(SI->isVolatile(), cast<StoreInst>(R)->isVolatile()))686return Res;687if (int Res = cmpAligns(SI->getAlign(), cast<StoreInst>(R)->getAlign()))688return Res;689if (int Res =690cmpOrderings(SI->getOrdering(), cast<StoreInst>(R)->getOrdering()))691return Res;692return cmpNumbers(SI->getSyncScopeID(),693cast<StoreInst>(R)->getSyncScopeID());694}695if (const CmpInst *CI = dyn_cast<CmpInst>(L))696return cmpNumbers(CI->getPredicate(), cast<CmpInst>(R)->getPredicate());697if (auto *CBL = dyn_cast<CallBase>(L)) {698auto *CBR = cast<CallBase>(R);699if (int Res = cmpNumbers(CBL->getCallingConv(), CBR->getCallingConv()))700return Res;701if (int Res = cmpAttrs(CBL->getAttributes(), CBR->getAttributes()))702return Res;703if (int Res = cmpOperandBundlesSchema(*CBL, *CBR))704return Res;705if (const CallInst *CI = dyn_cast<CallInst>(L))706if (int Res = cmpNumbers(CI->getTailCallKind(),707cast<CallInst>(R)->getTailCallKind()))708return Res;709return cmpMDNode(L->getMetadata(LLVMContext::MD_range),710R->getMetadata(LLVMContext::MD_range));711}712if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(L)) {713ArrayRef<unsigned> LIndices = IVI->getIndices();714ArrayRef<unsigned> RIndices = cast<InsertValueInst>(R)->getIndices();715if (int Res = cmpNumbers(LIndices.size(), RIndices.size()))716return Res;717for (size_t i = 0, e = LIndices.size(); i != e; ++i) {718if (int Res = cmpNumbers(LIndices[i], RIndices[i]))719return Res;720}721return 0;722}723if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(L)) {724ArrayRef<unsigned> LIndices = EVI->getIndices();725ArrayRef<unsigned> RIndices = cast<ExtractValueInst>(R)->getIndices();726if (int Res = cmpNumbers(LIndices.size(), RIndices.size()))727return Res;728for (size_t i = 0, e = LIndices.size(); i != e; ++i) {729if (int Res = cmpNumbers(LIndices[i], RIndices[i]))730return Res;731}732}733if (const FenceInst *FI = dyn_cast<FenceInst>(L)) {734if (int Res =735cmpOrderings(FI->getOrdering(), cast<FenceInst>(R)->getOrdering()))736return Res;737return cmpNumbers(FI->getSyncScopeID(),738cast<FenceInst>(R)->getSyncScopeID());739}740if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(L)) {741if (int Res = cmpNumbers(CXI->isVolatile(),742cast<AtomicCmpXchgInst>(R)->isVolatile()))743return Res;744if (int Res =745cmpNumbers(CXI->isWeak(), cast<AtomicCmpXchgInst>(R)->isWeak()))746return Res;747if (int Res =748cmpOrderings(CXI->getSuccessOrdering(),749cast<AtomicCmpXchgInst>(R)->getSuccessOrdering()))750return Res;751if (int Res =752cmpOrderings(CXI->getFailureOrdering(),753cast<AtomicCmpXchgInst>(R)->getFailureOrdering()))754return Res;755return cmpNumbers(CXI->getSyncScopeID(),756cast<AtomicCmpXchgInst>(R)->getSyncScopeID());757}758if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(L)) {759if (int Res = cmpNumbers(RMWI->getOperation(),760cast<AtomicRMWInst>(R)->getOperation()))761return Res;762if (int Res = cmpNumbers(RMWI->isVolatile(),763cast<AtomicRMWInst>(R)->isVolatile()))764return Res;765if (int Res = cmpOrderings(RMWI->getOrdering(),766cast<AtomicRMWInst>(R)->getOrdering()))767return Res;768return cmpNumbers(RMWI->getSyncScopeID(),769cast<AtomicRMWInst>(R)->getSyncScopeID());770}771if (const ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(L)) {772ArrayRef<int> LMask = SVI->getShuffleMask();773ArrayRef<int> RMask = cast<ShuffleVectorInst>(R)->getShuffleMask();774if (int Res = cmpNumbers(LMask.size(), RMask.size()))775return Res;776for (size_t i = 0, e = LMask.size(); i != e; ++i) {777if (int Res = cmpNumbers(LMask[i], RMask[i]))778return Res;779}780}781if (const PHINode *PNL = dyn_cast<PHINode>(L)) {782const PHINode *PNR = cast<PHINode>(R);783// Ensure that in addition to the incoming values being identical784// (checked by the caller of this function), the incoming blocks785// are also identical.786for (unsigned i = 0, e = PNL->getNumIncomingValues(); i != e; ++i) {787if (int Res =788cmpValues(PNL->getIncomingBlock(i), PNR->getIncomingBlock(i)))789return Res;790}791}792return 0;793}794795// Determine whether two GEP operations perform the same underlying arithmetic.796// Read method declaration comments for more details.797int FunctionComparator::cmpGEPs(const GEPOperator *GEPL,798const GEPOperator *GEPR) const {799unsigned int ASL = GEPL->getPointerAddressSpace();800unsigned int ASR = GEPR->getPointerAddressSpace();801802if (int Res = cmpNumbers(ASL, ASR))803return Res;804805// When we have target data, we can reduce the GEP down to the value in bytes806// added to the address.807const DataLayout &DL = FnL->getDataLayout();808unsigned OffsetBitWidth = DL.getIndexSizeInBits(ASL);809APInt OffsetL(OffsetBitWidth, 0), OffsetR(OffsetBitWidth, 0);810if (GEPL->accumulateConstantOffset(DL, OffsetL) &&811GEPR->accumulateConstantOffset(DL, OffsetR))812return cmpAPInts(OffsetL, OffsetR);813if (int Res =814cmpTypes(GEPL->getSourceElementType(), GEPR->getSourceElementType()))815return Res;816817if (int Res = cmpNumbers(GEPL->getNumOperands(), GEPR->getNumOperands()))818return Res;819820for (unsigned i = 0, e = GEPL->getNumOperands(); i != e; ++i) {821if (int Res = cmpValues(GEPL->getOperand(i), GEPR->getOperand(i)))822return Res;823}824825return 0;826}827828int FunctionComparator::cmpInlineAsm(const InlineAsm *L,829const InlineAsm *R) const {830// InlineAsm's are uniqued. If they are the same pointer, obviously they are831// the same, otherwise compare the fields.832if (L == R)833return 0;834if (int Res = cmpTypes(L->getFunctionType(), R->getFunctionType()))835return Res;836if (int Res = cmpMem(L->getAsmString(), R->getAsmString()))837return Res;838if (int Res = cmpMem(L->getConstraintString(), R->getConstraintString()))839return Res;840if (int Res = cmpNumbers(L->hasSideEffects(), R->hasSideEffects()))841return Res;842if (int Res = cmpNumbers(L->isAlignStack(), R->isAlignStack()))843return Res;844if (int Res = cmpNumbers(L->getDialect(), R->getDialect()))845return Res;846assert(L->getFunctionType() != R->getFunctionType());847return 0;848}849850/// Compare two values used by the two functions under pair-wise comparison. If851/// this is the first time the values are seen, they're added to the mapping so852/// that we will detect mismatches on next use.853/// See comments in declaration for more details.854int FunctionComparator::cmpValues(const Value *L, const Value *R) const {855// Catch self-reference case.856if (L == FnL) {857if (R == FnR)858return 0;859return -1;860}861if (R == FnR) {862if (L == FnL)863return 0;864return 1;865}866867const Constant *ConstL = dyn_cast<Constant>(L);868const Constant *ConstR = dyn_cast<Constant>(R);869if (ConstL && ConstR) {870if (L == R)871return 0;872return cmpConstants(ConstL, ConstR);873}874875if (ConstL)876return 1;877if (ConstR)878return -1;879880const MetadataAsValue *MetadataValueL = dyn_cast<MetadataAsValue>(L);881const MetadataAsValue *MetadataValueR = dyn_cast<MetadataAsValue>(R);882if (MetadataValueL && MetadataValueR) {883if (MetadataValueL == MetadataValueR)884return 0;885886return cmpMetadata(MetadataValueL->getMetadata(),887MetadataValueR->getMetadata());888}889890if (MetadataValueL)891return 1;892if (MetadataValueR)893return -1;894895const InlineAsm *InlineAsmL = dyn_cast<InlineAsm>(L);896const InlineAsm *InlineAsmR = dyn_cast<InlineAsm>(R);897898if (InlineAsmL && InlineAsmR)899return cmpInlineAsm(InlineAsmL, InlineAsmR);900if (InlineAsmL)901return 1;902if (InlineAsmR)903return -1;904905auto LeftSN = sn_mapL.insert(std::make_pair(L, sn_mapL.size())),906RightSN = sn_mapR.insert(std::make_pair(R, sn_mapR.size()));907908return cmpNumbers(LeftSN.first->second, RightSN.first->second);909}910911// Test whether two basic blocks have equivalent behaviour.912int FunctionComparator::cmpBasicBlocks(const BasicBlock *BBL,913const BasicBlock *BBR) const {914BasicBlock::const_iterator InstL = BBL->begin(), InstLE = BBL->end();915BasicBlock::const_iterator InstR = BBR->begin(), InstRE = BBR->end();916917do {918bool needToCmpOperands = true;919if (int Res = cmpOperations(&*InstL, &*InstR, needToCmpOperands))920return Res;921if (needToCmpOperands) {922assert(InstL->getNumOperands() == InstR->getNumOperands());923924for (unsigned i = 0, e = InstL->getNumOperands(); i != e; ++i) {925Value *OpL = InstL->getOperand(i);926Value *OpR = InstR->getOperand(i);927if (int Res = cmpValues(OpL, OpR))928return Res;929// cmpValues should ensure this is true.930assert(cmpTypes(OpL->getType(), OpR->getType()) == 0);931}932}933934++InstL;935++InstR;936} while (InstL != InstLE && InstR != InstRE);937938if (InstL != InstLE && InstR == InstRE)939return 1;940if (InstL == InstLE && InstR != InstRE)941return -1;942return 0;943}944945int FunctionComparator::compareSignature() const {946if (int Res = cmpAttrs(FnL->getAttributes(), FnR->getAttributes()))947return Res;948949if (int Res = cmpNumbers(FnL->hasGC(), FnR->hasGC()))950return Res;951952if (FnL->hasGC()) {953if (int Res = cmpMem(FnL->getGC(), FnR->getGC()))954return Res;955}956957if (int Res = cmpNumbers(FnL->hasSection(), FnR->hasSection()))958return Res;959960if (FnL->hasSection()) {961if (int Res = cmpMem(FnL->getSection(), FnR->getSection()))962return Res;963}964965if (int Res = cmpNumbers(FnL->isVarArg(), FnR->isVarArg()))966return Res;967968// TODO: if it's internal and only used in direct calls, we could handle this969// case too.970if (int Res = cmpNumbers(FnL->getCallingConv(), FnR->getCallingConv()))971return Res;972973if (int Res = cmpTypes(FnL->getFunctionType(), FnR->getFunctionType()))974return Res;975976assert(FnL->arg_size() == FnR->arg_size() &&977"Identically typed functions have different numbers of args!");978979// Visit the arguments so that they get enumerated in the order they're980// passed in.981for (Function::const_arg_iterator ArgLI = FnL->arg_begin(),982ArgRI = FnR->arg_begin(),983ArgLE = FnL->arg_end();984ArgLI != ArgLE; ++ArgLI, ++ArgRI) {985if (cmpValues(&*ArgLI, &*ArgRI) != 0)986llvm_unreachable("Arguments repeat!");987}988return 0;989}990991// Test whether the two functions have equivalent behaviour.992int FunctionComparator::compare() {993beginCompare();994995if (int Res = compareSignature())996return Res;997998// We do a CFG-ordered walk since the actual ordering of the blocks in the999// linked list is immaterial. Our walk starts at the entry block for both1000// functions, then takes each block from each terminator in order. As an1001// artifact, this also means that unreachable blocks are ignored.1002SmallVector<const BasicBlock *, 8> FnLBBs, FnRBBs;1003SmallPtrSet<const BasicBlock *, 32> VisitedBBs; // in terms of F1.10041005FnLBBs.push_back(&FnL->getEntryBlock());1006FnRBBs.push_back(&FnR->getEntryBlock());10071008VisitedBBs.insert(FnLBBs[0]);1009while (!FnLBBs.empty()) {1010const BasicBlock *BBL = FnLBBs.pop_back_val();1011const BasicBlock *BBR = FnRBBs.pop_back_val();10121013if (int Res = cmpValues(BBL, BBR))1014return Res;10151016if (int Res = cmpBasicBlocks(BBL, BBR))1017return Res;10181019const Instruction *TermL = BBL->getTerminator();1020const Instruction *TermR = BBR->getTerminator();10211022assert(TermL->getNumSuccessors() == TermR->getNumSuccessors());1023for (unsigned i = 0, e = TermL->getNumSuccessors(); i != e; ++i) {1024if (!VisitedBBs.insert(TermL->getSuccessor(i)).second)1025continue;10261027FnLBBs.push_back(TermL->getSuccessor(i));1028FnRBBs.push_back(TermR->getSuccessor(i));1029}1030}1031return 0;1032}103310341035