diff --git a/src/bin/jbc2mpl b/src/bin/jbc2mpl index 5ce8087cabb84c9e47c3e6a6b2cdf3e3433a553b..db9ba51a1bfe858befdea1b402bf3d0229e7ed3e 100755 Binary files a/src/bin/jbc2mpl and b/src/bin/jbc2mpl differ diff --git a/src/bin/maple b/src/bin/maple index 45d4a723374285e6381cddbe0208779457db8c6f..ac6404b4536804c413fdf1a87f909be4e839c668 100755 Binary files a/src/bin/maple and b/src/bin/maple differ diff --git a/src/bin/mplcg b/src/bin/mplcg index 7af871ddf162916caf57efeeac2fcee293a99848..701d8a4e0ef1d758094d0887a33ef83cb8680fb9 100755 Binary files a/src/bin/mplcg and b/src/bin/mplcg differ diff --git a/src/deplibs/libmaple_driverutil.a b/src/deplibs/libmaple_driverutil.a index fe4cf6462bc044da716079c257603c20f8d69122..cf44edeeeff0e798e9d621f0eec64c6bcbb8a44e 100644 Binary files a/src/deplibs/libmaple_driverutil.a and b/src/deplibs/libmaple_driverutil.a differ diff --git a/src/deplibs/libmplutil.a b/src/deplibs/libmplutil.a index ed68378bc7b23d0f2c8ac207a8f8bb9e93b58883..be5dd045e06df5ee2d6cd59ce9d2b1c40584c7e6 100644 Binary files a/src/deplibs/libmplutil.a and b/src/deplibs/libmplutil.a differ diff --git a/src/maple_driver/include/driver_runner.h b/src/maple_driver/include/driver_runner.h index 75f8bc2f65a44b628f717750b07ca220ade2674b..95121c081af984ae48830a81f9b11cf7ecd23902 100644 --- a/src/maple_driver/include/driver_runner.h +++ b/src/maple_driver/include/driver_runner.h @@ -57,6 +57,7 @@ class DriverRunner final { int Run(); void ReleaseOptions(); bool ParseInput(std::string outputFile, std::string oriBasename) const; + bool VerifyModule(MIRModulePtr &mModule) const; void ProcessMpl2mplAndMePhases(std::string outputFile, std::string vtableImplFile) const; void SetMpl2mplInfo(Options *mpl2mplOptions, const std::string &mpl2mplInput) { diff --git a/src/maple_driver/include/mpl_options.h b/src/maple_driver/include/mpl_options.h index 012aff7fe461bb4d45dbf28d6011cf257eaeac11..72e87d8e40204b47dc80fe53e98ef51d4ddd5bce 100644 --- a/src/maple_driver/include/mpl_options.h +++ b/src/maple_driver/include/mpl_options.h @@ -108,6 +108,7 @@ class MplOptions { bool timePhases; bool genMemPl; bool genVtableImpl; + bool verify; MplOptions() : optionParser(nullptr), options(UserOption()), @@ -130,7 +131,8 @@ class MplOptions { debugFlag(false), timePhases(false), genMemPl(false), - genVtableImpl(false) {} + genVtableImpl(false), + verify(false) {} ~MplOptions() { if (optionParser != nullptr) { delete optionParser; diff --git a/src/maple_driver/include/usages.h b/src/maple_driver/include/usages.h index fd32d8b8c63426a1fd959bfcc1e7441d422cf19a..5395ae04f4abce4b088feadceed48dc5e6355672 100644 --- a/src/maple_driver/include/usages.h +++ b/src/maple_driver/include/usages.h @@ -36,6 +36,7 @@ enum OptionIndex : uint64 { kCombTimePhases, kGenMeMpl, kGenVtableImpl, + kVerify, //----------me begin----------- kMeHelp, kMeDumpPhases, @@ -265,6 +266,18 @@ const static mapleOption::Descriptor USAGES[] = { " --genVtableImpl \tGenerate VtableImpl.mpl file\n", "all", { { nullptr } } }, + { kVerify, + 0, + nullptr, + "verify", + nullptr, + false, + nullptr, + mapleOption::BuildType::kBuildTypeAll, + mapleOption::ArgCheckPolicy::kArgCheckPolicyNone, + " --verify \tVerify mpl file\n", + "all", + { { nullptr } } }, { kAllDebug, 0, nullptr, diff --git a/src/maple_driver/src/driver_runner.cpp b/src/maple_driver/src/driver_runner.cpp index 46ee4ac87d9bffaa9511dda03e2bb930c84971bc..5c30a831a0c9f10cce3d79545b783ab71a797e7f 100644 --- a/src/maple_driver/src/driver_runner.cpp +++ b/src/maple_driver/src/driver_runner.cpp @@ -74,6 +74,7 @@ int DriverRunner::Run() { std::string outputFile = baseName.append(GetPostfix()); bool parsed = ParseInput(outputFile, originBaseName); + if (parsed) { if (mpl2mplOptions || meOptions) { std::string vtableImplFile = originBaseName; @@ -133,6 +134,13 @@ bool DriverRunner::ParseInput(std::string outputFile, std::string originBaseName return parsed; } +bool DriverRunner::VerifyModule(MIRModulePtr &mModule) const { + LogInfo::MapleLogger() << "========== Starting Verify Module =====================" << std::endl; + bool res = true; + LogInfo::MapleLogger() << "========== Finished Verify Module =====================" << std::endl; + return res; +} + void DriverRunner::ProcessMpl2mplAndMePhases(std::string outputFile, std::string vtableImplFile) const { CHECK_MODULE(); diff --git a/src/maple_driver/src/maple_comb_compiler.cpp b/src/maple_driver/src/maple_comb_compiler.cpp index d8ffccb7ce052e7fad077937789ad647098e3867..3a78d90a0e1ae440eee190e961bc94e8f8d4f7c3 100644 --- a/src/maple_driver/src/maple_comb_compiler.cpp +++ b/src/maple_driver/src/maple_comb_compiler.cpp @@ -239,7 +239,7 @@ Options *MapleCombCompiler::MakeMpl2MplOptions(const MplOptions &options, maple: ErrorCode MapleCombCompiler::Compile(const MplOptions &options, MIRModulePtr &theModule) { MemPool *optMp = mempoolctrler.NewMemPool("maplecomb mempool"); std::string fileName = GetInputFileName(options); - theModule = new MIRModule(fileName.c_str()); + theModule = new MIRModule(fileName); MeOption *meOptions = nullptr; Options *mpl2mplOptions = nullptr; auto iterMe = std::find(options.runningExes.begin(), options.runningExes.end(), kBinNameMe); diff --git a/src/maple_driver/src/mpl_options.cpp b/src/maple_driver/src/mpl_options.cpp index 6cf30057bb3d07887ca07562897396779b468e1c..f059b031ee328503d60f82ea75398c4aed8bbd93 100644 --- a/src/maple_driver/src/mpl_options.cpp +++ b/src/maple_driver/src/mpl_options.cpp @@ -126,6 +126,10 @@ int MplOptions::Parse(int argc, char **argv) { this->genVtableImpl = true; this->printCommandStr += " --genVtableImpl"; break; + case kVerify: + this->verify = true; + this->printCommandStr += " --verify"; + break; case kSaveTemps: this->isSaveTmps = true; StringUtils::Split(opt.Args(), this->saveFiles, ','); diff --git a/src/maple_ir/include/bin_mpl_export.h b/src/maple_ir/include/bin_mpl_export.h index e8e2c42df5d6b19243581de43e02e52376e5189b..66ee4a56671bfdbe6824ded04ddcbd47276147f8 100644 --- a/src/maple_ir/include/bin_mpl_export.h +++ b/src/maple_ir/include/bin_mpl_export.h @@ -111,7 +111,7 @@ class BinaryMplExport { void WriteInt64(int64 x); void WriteNum(int64 x); void WriteAsciiStr(const std::string &str); - void Fixup(uint64 i, int32 x); + void Fixup(size_t i, int32 x); void DumpBuf(const std::string &modid); void AppendAt(const std::string &fname, int32 ipaIdx); const MIRModule &GetMIRModule() const { diff --git a/src/maple_ir/include/bin_mpl_import.h b/src/maple_ir/include/bin_mpl_import.h index 22fde151c9411d4daabd60fb71b5114e501b8589..3cf261a446890eb394eeba7faf76a49f2a29ba5e 100644 --- a/src/maple_ir/include/bin_mpl_import.h +++ b/src/maple_ir/include/bin_mpl_import.h @@ -73,7 +73,7 @@ class BinaryMplImport { void ReadTypeField(); void Jump2NextField(); void Reset(); - MIRSymbol *GetOrCreateSymbol(const TyIdx &tyIdx, const GStrIdx &strIdx, MIRSymKind mclass, MIRStorageClass sclass, + MIRSymbol *GetOrCreateSymbol(TyIdx tyIdx, GStrIdx strIdx, MIRSymKind mclass, MIRStorageClass sclass, MIRFunction *func, uint8 scpID); MIRType &InsertInTypeTables(MIRType &ptype); void InsertInHashTable(MIRType &ptype); @@ -99,9 +99,9 @@ class BinaryMplImport { void ImportMethodsOfStructType(MethodVector &methods); void ImportStructTypeData(MIRStructType &type); void ImportInterfacesOfClassType(std::vector &interfaces); - void ImportInfoIsStringOfClassType(std::vector &infoIsString); - void ImportInfoOfClassType(std::vector &infoIsString, std::vector &infos); - void ImportPragmaOfClassType(std::vector &pragmas); + void ImportInfoIsStringOfStructType(MIRStructType &type); + void ImportInfoOfStructType(MIRStructType &type); + void ImportPragmaOfStructType(MIRStructType &type); void SetClassTyidxOfMethods(MIRStructType &type); void ImportClassTypeData(MIRClassType &type); void ImportInterfaceTypeData(MIRInterfaceType &type); diff --git a/src/maple_ir/include/metadata_layout.h b/src/maple_ir/include/metadata_layout.h index d4e4f6df4ea79b60f8dd30679a880a7b6f026dfc..cb85221840cb2111a95928e7ed659b58718e488f 100644 --- a/src/maple_ir/include/metadata_layout.h +++ b/src/maple_ir/include/metadata_layout.h @@ -132,6 +132,32 @@ struct DexFile; struct DexClassDef; struct DexClassData; +static constexpr size_t PageSize = 4096; + +// Note there is no state to indicate a class is already initialized. +// Any state beyond listed below is treated as initialized. +enum ClassInitState { + kClassInitStateMin = 0, + kClassUninitialized = 1, + kClassInitializing = 2, + kClassInitFailed = 3, + kClassInitialized = 4, + kClassInitStateMax = 4, +}; + +enum SEGVAddr { + kSEGVAddrRangeStart = PageSize + 0, + + // Note any readable address is treated as Initialized. + kSEGVAddrForClassInitStateMin = kSEGVAddrRangeStart + kClassInitStateMin, + kSEGVAddrForClassUninitialized = kSEGVAddrForClassInitStateMin + kClassUninitialized, + kSEGVAddrForClassInitializing = kSEGVAddrForClassInitStateMin + kClassInitializing, + kSEGVAddrForClassInitFailed = kSEGVAddrForClassInitStateMin + kClassInitFailed, + kSEGVAddrFoClassInitStateMax = kSEGVAddrForClassInitStateMin + kClassInitStateMax, + + kSEGVAddrRangeEnd, +}; + struct ClassMetadata { // object common fields MetaRef shadow; // point to classinfo of java/lang/Class @@ -162,9 +188,22 @@ struct ClassMetadata { }; union { - intptr_t initState; // if class is not initialized + void *initState; // a readable address for initState means initialized void *cacheTrueClass; - }; // class init state, this field must be accessed atomically. + }; + + public: + bool IsInitialized(); + + ClassInitState GetInitState(); + void *GetInitStateRawValue() { + return __atomic_load_n(&initState, __ATOMIC_ACQUIRE); + } + + void SetInitState(ClassInitState state); + void SetInitStateRawValue(void *val) { + __atomic_store_n(&initState, val, __ATOMIC_RELEASE); + } }; static inline intptr_t ClassMetadataOffsetOfInitFlag() { diff --git a/src/maple_ir/include/mir_builder.h b/src/maple_ir/include/mir_builder.h index d1756b9a23478e0cfdededa03cc56c36db2361a2..a119fb4f437c66e7f690de44fcadf20e67cd443a 100644 --- a/src/maple_ir/include/mir_builder.h +++ b/src/maple_ir/include/mir_builder.h @@ -18,6 +18,9 @@ #include #include #include +#ifdef _WIN32 +#include +#endif #include "opcodes.h" #include "prim_types.h" #include "mir_type.h" diff --git a/src/maple_ir/include/mir_function.h b/src/maple_ir/include/mir_function.h index 5570831c8c428e91febdaea390c8cbf15a00b259..1c3d5dc69fef4dd441e11d35b762ad5e61ab7b82 100644 --- a/src/maple_ir/include/mir_function.h +++ b/src/maple_ir/include/mir_function.h @@ -65,8 +65,6 @@ class MIRFunction { : module(mod), puIdx(0), symbolTableIdx(sidx), - funcType(nullptr), - classTyIdx(0), formals(mod->GetMPAllocator().Adapter()), retRefSym(mod->GetMPAllocator().Adapter()), argumentsTyIdx(mod->GetMPAllocator().Adapter()), @@ -75,9 +73,6 @@ class MIRFunction { dataMPAllocator(dataMemPool), codeMemPool(mempoolctrler.NewMemPool("func code mempool")), codeMemPoolAllocator(codeMemPool), - body(nullptr), - flag(0), - fileIndex(0), info(mod->GetMPAllocator().Adapter()), infoIsString(mod->GetMPAllocator().Adapter()), aliasVarMap(std::less(), mod->GetMPAllocator().Adapter()), @@ -107,7 +102,7 @@ class MIRFunction { // tables will be allocated on the local data mempool. symTab = module->GetMemPool()->New(&module->GetMPAllocator()); pregTab = module->GetMemPool()->New(module, &module->GetMPAllocator()); - typeNameTab = module->GetMemPool()->New(&module->GetMPAllocator()); + typeNameTab = module->GetMemPool()->New(module->GetMPAllocator()); labelTab = module->GetMemPool()->New(&module->GetMPAllocator()); } @@ -648,6 +643,10 @@ class MIRFunction { return body; } + const BlockNode *GetBody() const { + return body; + } + void SetBody(BlockNode *node) { body = node; } @@ -908,12 +907,12 @@ class MIRFunction { private: MIRModule *module; // the module that owns this function - PUIdx puIdx; // the PU index of this function + PUIdx puIdx = 0; // the PU index of this function PUIdx puIdxOrigin; // the original puIdx when initial generation StIdx symbolTableIdx; // the symbol table index of this function - MIRFuncType *funcType; + MIRFuncType *funcType = nullptr; TyIdx returnTyIdx; // the declared return type of this function - TyIdx classTyIdx; // class/interface type this function belongs to + TyIdx classTyIdx{0}; // class/interface type this function belongs to MapleVector formals; // formal parameter symbols of this function MapleSet retRefSym; MapleVector argumentsTyIdx; // arguments types of this function @@ -927,12 +926,12 @@ class MIRFunction { MapleAllocator dataMPAllocator; MemPool *codeMemPool; MapleAllocator codeMemPoolAllocator; - BlockNode *body; + BlockNode *body = nullptr; SrcPosition srcPosition; FuncAttrs funcAttrs; - uint32 flag; + uint32 flag = 0; uint16 hashCode; // for methodmetadata order - uint32 fileIndex; // this function belongs to which file, used by VM for plugin manager + uint32 fileIndex = 0; // this function belongs to which file, used by VM for plugin manager MIRInfoVector info; MapleVector infoIsString; // tells if an entry has string value MapleMap aliasVarMap; // source code alias variables for debuginfo @@ -983,6 +982,8 @@ class MIRFunction { GStrIdx baseFuncWithTypeStrIdx; // funcname + types of args, no type of retv GStrIdx signatureStrIdx; + + void DumpFlavorLoweredThanMmpl() const; }; } // namespace maple #endif // MAPLE_IR_INCLUDE_MIR_FUNCTION_H diff --git a/src/maple_ir/include/mir_module.h b/src/maple_ir/include/mir_module.h index 4c86e9dcb83feb4cc3f97ef1a4aa0dfb461f2c6e..0b08be608e1e750572246a2c88cddc0e6c85fd77 100644 --- a/src/maple_ir/include/mir_module.h +++ b/src/maple_ir/include/mir_module.h @@ -61,7 +61,6 @@ class MIRType; class MIRFunction; class MIRSymbol; class MIRSymbolTable; -class MIRTypeNameTable; class MIRFloatConst; class MIRDoubleConst; class MIRBuilder; @@ -79,8 +78,8 @@ struct EncodedValue { class MIRTypeNameTable { public: - explicit MIRTypeNameTable(MapleAllocator *allocator) - : mAllocator(allocator), gStrIdxToTyIdxMap(std::less(), mAllocator->Adapter()) {} + explicit MIRTypeNameTable(MapleAllocator &allocator) + : mAllocator(allocator), gStrIdxToTyIdxMap(std::less(), mAllocator.Adapter()) {} ~MIRTypeNameTable() = default; @@ -104,9 +103,8 @@ class MIRTypeNameTable { return gStrIdxToTyIdxMap.size(); } private: - MapleAllocator *mAllocator; + MapleAllocator &mAllocator; MapleMap gStrIdxToTyIdxMap; - }; class MIRModule { @@ -116,7 +114,7 @@ class MIRModule { MIRModule(MIRModule &p) = delete; MIRModule &operator=(const MIRModule &module) = delete; - explicit MIRModule(const char *fn = ""); + explicit MIRModule(const std::string &fn = ""); ~MIRModule(); const MemPool *GetMemPool() const { @@ -212,7 +210,7 @@ class MIRModule { void DumpInlineCandidateToFile(const std::string &fileNameStr) const; const std::string &GetFileNameFromFileNum(uint32 fileNum) const; - void DumpClassToFile(const char *path) const; + void DumpClassToFile(const std::string &path) const; void DumpFunctionList(bool skipBody = false) const; void DumpGlobalArraySymbol() const; void Emit(const std::string &outfileName) const; @@ -230,8 +228,8 @@ class MIRModule { MIRFunction *FindEntryFunction(); uint32 GetFileinfo(GStrIdx strIdx) const; - void OutputAsciiMpl(const char *phaseName, bool emitStructureType = true); - void OutputFunctionListAsciiMpl(const char *phaseName); + void OutputAsciiMpl(const std::string &phaseName, bool emitStructureType = true); + void OutputFunctionListAsciiMpl(const std::string &phaseName); const std::string &GetFileName() const { return fileName; } diff --git a/src/maple_ir/include/mir_type.h b/src/maple_ir/include/mir_type.h index c1039b4a7a56e9b4d247d35fa6081ee4ddc6a1ce..78c4f338274d74fd35943a034184c0fcf4213800 100644 --- a/src/maple_ir/include/mir_type.h +++ b/src/maple_ir/include/mir_type.h @@ -390,12 +390,12 @@ constexpr int kShiftNumOfTypeKind = 8; constexpr int kShiftNumOfNameStrIdx = 6; class MIRType { public: - MIRType(MIRTypeKind kind, PrimType pType) : typeKind(kind), primType(pType), nameIsLocal(false), nameStrIdx(0) {} + MIRType(MIRTypeKind kind, PrimType pType) : typeKind(kind), primType(pType), nameStrIdx(0) {} MIRType(MIRTypeKind kind, PrimType pType, GStrIdx strIdx) - : typeKind(kind), primType(pType), nameIsLocal(false), tyIdx(0), nameStrIdx(strIdx) {} + : typeKind(kind), primType(pType), nameStrIdx(strIdx) {} - virtual ~MIRType() {} + virtual ~MIRType() = default; virtual void Dump(int indent, bool dontUseName = false) const; virtual void DumpAsCxx(int indent) const; @@ -407,62 +407,40 @@ class MIRType { return new MIRType(*this); } - PrimType GetPrimType() { + PrimType GetPrimType() const { return primType; } - - const PrimType GetPrimType() const { - return primType; - } - void SetPrimType(const PrimType pt) { primType = pt; } - TyIdx &GetTypeIndex() { - return tyIdx; - } - - const TyIdx &GetTypeIndex() const { + TyIdx GetTypeIndex() const { return tyIdx; } - - void SetTypeIndex(const TyIdx idx) { + void SetTypeIndex(TyIdx idx) { tyIdx = idx; } - MIRTypeKind GetKind() { - return typeKind; - } - - const MIRTypeKind GetKind() const { + MIRTypeKind GetKind() const { return typeKind; } - - void SetMIRTypeKind(const MIRTypeKind kind) { + void SetMIRTypeKind(MIRTypeKind kind) { typeKind = kind; } bool IsNameIsLocal() const { return nameIsLocal; } - void SetNameIsLocal(bool flag) { nameIsLocal = flag; } - GStrIdx &GetNameStrIdx() { - return nameStrIdx; - } - - const GStrIdx &GetNameStrIdx() const { + GStrIdx GetNameStrIdx() const { return nameStrIdx; } - void SetNameStrIdx(GStrIdx strIdx) { nameStrIdx = strIdx; } - void SetNameStrIdxItem(uint32 idx) { nameStrIdx.SetIdx(idx); } @@ -516,7 +494,7 @@ class MIRType { (typeKind == kTypeInterfaceIncomplete)); } - virtual bool ValidateClassOrInterface(const std::string &className, bool noWarning); + bool ValidateClassOrInterface(const std::string &className, bool noWarning) const; const std::string &GetName(void) const; virtual std::string GetMplTypeName() const; virtual std::string GetCompactMplTypeName() const; @@ -529,26 +507,16 @@ class MIRType { protected: MIRTypeKind typeKind; PrimType primType; - bool nameIsLocal; // needed when printing the type name - TyIdx tyIdx; + bool nameIsLocal = false; // needed when printing the type name + TyIdx tyIdx{0}; GStrIdx nameStrIdx; // name in global string table }; class MIRPtrType : public MIRType { public: - const TyIdx &GetPointedTyIdx() const { - return pointedTyIdx; - } + explicit MIRPtrType(TyIdx pointedTyidx) : MIRType(kTypePointer, PTY_ptr), pointedTyIdx(pointedTyidx) {} - void SetPointedTyIdx(const TyIdx idx) { - pointedTyIdx = idx; - } - - bool EqualTo(const MIRType &type) const override; - - explicit MIRPtrType(const TyIdx &pointedTyidx) : MIRType(kTypePointer, PTY_ptr), pointedTyIdx(pointedTyidx) {} - - MIRPtrType(const TyIdx &pointedTyidx, PrimType pty) : MIRType(kTypePointer, pty), pointedTyIdx(pointedTyidx) {} + MIRPtrType(TyIdx pointedTyidx, PrimType pty) : MIRType(kTypePointer, pty), pointedTyIdx(pointedTyidx) {} MIRPtrType(PrimType pty, const GStrIdx &strIdx) : MIRType(kTypePointer, pty, strIdx), pointedTyIdx(TyIdx(0)) {} @@ -560,6 +528,15 @@ class MIRPtrType : public MIRType { MIRType *GetPointedType() const; + TyIdx GetPointedTyIdx() const { + return pointedTyIdx; + } + void SetPointedTyIdx(const TyIdx idx) { + pointedTyIdx = idx; + } + + bool EqualTo(const MIRType &type) const override; + bool HasTypeParam() const override; void Dump(int indent, bool dontUseName = false) const override; @@ -581,10 +558,34 @@ class MIRPtrType : public MIRType { class MIRArrayType : public MIRType { public: - const TyIdx &GetElemTyIdx() const { - return eTyIdx; + MIRArrayType() : MIRType(kTypeArray, PTY_agg), eTyIdx(0), dim(0), sizeArray{ 0 } {} + + explicit MIRArrayType(const MIRArrayType &pat) + : MIRType(kTypeArray, PTY_agg), + eTyIdx(pat.eTyIdx), + dim(pat.dim) { + for (int i = 0; i < dim; i++) { + sizeArray[i] = pat.sizeArray[i]; + } + } + + explicit MIRArrayType(const GStrIdx strIdx) : MIRType(kTypeArray, PTY_agg, strIdx), dim(0), sizeArray{ 0 } {} + + MIRArrayType(TyIdx eTyIdx, const std::vector &sizeArray) + : MIRType(kTypeArray, PTY_agg), + eTyIdx(eTyIdx), dim(sizeArray.size()) { + for (int i = 0; i < kMaxArrayDim; i++) { + this->sizeArray[i] = (i < dim) ? sizeArray[i] : 0; + } } + ~MIRArrayType() = default; + + MIRArrayType &operator=(const MIRArrayType &p) = default; + + TyIdx GetElemTyIdx() const { + return eTyIdx; + } void SetElemtTyIdx(const TyIdx idx) { eTyIdx = idx; } @@ -593,40 +594,16 @@ class MIRArrayType : public MIRType { CHECK_FATAL((n >= 0 && n < kMaxArrayDim), "out of bound of array!"); return sizeArray[n]; } - void SetSizeArrayItem(uint32 idx, uint32 value) { CHECK_FATAL((idx >= 0 && idx < kMaxArrayDim), "out of bound of array!"); sizeArray[idx] = value; } bool EqualTo(const MIRType &type) const override; - MIRArrayType &operator=(const MIRArrayType &p) = default; - MIRArrayType() : MIRType(kTypeArray, PTY_agg), eTyIdx(0), dim(0), sizeArray{ 0 } {} - - ~MIRArrayType() {} - - explicit MIRArrayType(const MIRArrayType &pat) : MIRType(kTypeArray, PTY_agg) { - eTyIdx = pat.eTyIdx; - dim = pat.dim; - for (int i = 0; i < dim; i++) { - sizeArray[i] = pat.sizeArray[i]; - } - } - - MIRArrayType(const TyIdx eTyIdx, std::vector &sizeArray) : MIRType(kTypeArray, PTY_agg) { - this->eTyIdx = eTyIdx; - dim = sizeArray.size(); - for (int i = 0; i < kMaxArrayDim; i++) { - this->sizeArray[i] = (i < dim) ? sizeArray[i] : 0; - } - } - - explicit MIRArrayType(const GStrIdx strIdx) : MIRType(kTypeArray, PTY_agg, strIdx), dim(0), sizeArray{ 0 } {} uint16 GetDim() const { return dim; } - void SetDim(uint16 dim) { this->dim = dim; } @@ -642,6 +619,7 @@ class MIRArrayType : public MIRType { } void Dump(int indent, bool dontUseName) const override; + size_t GetSize() const override { size_t elemSize = GetElemType()->GetSize(); if (elemSize == 0) { @@ -676,21 +654,14 @@ class MIRArrayType : public MIRType { // flexible array type, must be last field of a top-level struct class MIRFarrayType : public MIRType { public: - const TyIdx &GetElemTyIdx() const { - return elemTyIdx; - } - - void SetElemtTyIdx(const TyIdx idx) { - elemTyIdx = idx; - } + MIRFarrayType() : MIRType(kTypeFArray, PTY_agg), elemTyIdx(TyIdx(0)) {}; - bool EqualTo(const MIRType &type) const override; - MIRFarrayType() : MIRType(kTypeFArray, PTY_agg), elemTyIdx(TyIdx(0)){}; explicit MIRFarrayType(TyIdx elemTyIdx) : MIRType(kTypeFArray, PTY_agg), elemTyIdx(elemTyIdx) {} explicit MIRFarrayType(GStrIdx strIdx) : MIRType(kTypeFArray, PTY_agg, strIdx), elemTyIdx(TyIdx(0)) {} ~MIRFarrayType() = default; + MIRType *CopyMIRTypeNode() const override; MIRType *GetElemType() const; @@ -698,12 +669,21 @@ class MIRFarrayType : public MIRType { return GetElemType()->HasTypeParam(); } + TyIdx GetElemTyIdx() const { + return elemTyIdx; + } + void SetElemtTyIdx(const TyIdx idx) { + elemTyIdx = idx; + } + + bool EqualTo(const MIRType &type) const override; void Dump(int indent, bool dontUseName = false) const override; size_t GetHashIndex() const override { constexpr uint8 kIdxShift = 5; return ((elemTyIdx.GetIdx() << kIdxShift) + (typeKind << kShiftNumOfTypeKind)) % kTypeHashLength; } + std::string GetMplTypeName() const override; std::string GetCompactMplTypeName() const override; private: @@ -715,38 +695,15 @@ using MethodPair = std::pair; using MethodVector = std::vector; using MethodPtrVector = std::vector; using MIREncodedArray = std::vector; -#define FIELDVECID2FIELDID(i) ((i) + 1) -#define PARENTFIELDVECID2FIELDID(i) ((-(i)) - 1) + // used by kTypeStruct, kTypeStructIncomplete, kTypeUnion class MIRStructType : public MIRType { public: - explicit MIRStructType(MIRTypeKind tkind) - : MIRType(tkind, PTY_agg), - fields(), - fieldInferredTyIdx(), - staticFields(), - parentFields(), - methods(), - vTableMethods(), - iTableMethods(), - isImported(false), - isUsed(false), - hasVolatileField(false), - hasVolatileFieldSet(false) {} - - MIRStructType(MIRTypeKind tkind, GStrIdx strIdx) - : MIRType(tkind, PTY_agg, strIdx), - fields(), - fieldInferredTyIdx(), - staticFields(), - parentFields(), - methods(), - vTableMethods(), - iTableMethods(), - isImported(false), - isUsed(false), - hasVolatileField(false), - hasVolatileFieldSet(false) {} + explicit MIRStructType(MIRTypeKind tKind) + : MIRType(tKind, PTY_agg) {} + + MIRStructType(MIRTypeKind tKind, GStrIdx strIdx) + : MIRType(tKind, PTY_agg, strIdx) {} ~MIRStructType() {} @@ -776,7 +733,7 @@ class MIRStructType : public MIRType { return fields.size(); } - std::vector &GetFieldInferredTyIdx() { + const std::vector &GetFieldInferredTyIdx() const { return fieldInferredTyIdx; } @@ -814,7 +771,7 @@ class MIRStructType : public MIRType { return vTableMethods; } - MethodPair *GetVTableMethodsElemt(size_t n) const { + const MethodPair *GetVTableMethodsElemt(size_t n) const { ASSERT(n < vTableMethods.size(), "array index out of range"); return vTableMethods.at(n); } @@ -893,8 +850,8 @@ class MIRStructType : public MIRType { return std::find(fields.begin(), fields.end(), pair) != fields.end(); } - virtual bool HasVolatileField() override; - virtual bool HasTypeParam() const override; + bool HasVolatileField() override; + bool HasTypeParam() const override; bool EqualTo(const MIRType &type) const override; MIRType *CopyMIRTypeNode() const override { return new MIRStructType(*this); @@ -973,31 +930,7 @@ class MIRStructType : public MIRType { // only meaningful for MIRClassType and MIRInterface types bool IsLocal() const; - size_t GetSize() const override { - if (typeKind == kTypeUnion) { - size_t maxSize = GetElemType(0)->GetSize(); - for (size_t i = 1; i < fields.size(); i++) { - size_t size = GetElemType(i)->GetSize(); - if (size == 0) { - return 0; - } - if (maxSize < size) { - maxSize = size; - } - } - return maxSize; - } else { - size_t size = 0; - for (size_t i = 0; i < fields.size(); i++) { - size_t fieldSize = GetElemType(i)->GetSize(); - if (fieldSize == 0) { - return 0; - } - size += fieldSize; - } - return size; - } - } + size_t GetSize() const override; size_t GetHashIndex() const override { return ((nameStrIdx.GetIdx() << kShiftNumOfNameStrIdx) + (typeKind << kShiftNumOfTypeKind)) % kTypeHashLength; @@ -1020,12 +953,8 @@ class MIRStructType : public MIRType { CHECK_FATAL(false, "can not use GetInfo"); } - virtual std::vector &GetInfo() { - CHECK_FATAL(false, "can not use GetInfo"); - } - - virtual const std::vector &GetIsStringInfo() const { - CHECK_FATAL(false, "can not use GetIsStringInfo"); + virtual const std::vector &GetInfoIsString() const { + CHECK_FATAL(false, "can not use GetInfoIsString"); } virtual const std::vector &GetPragmaVec() const { @@ -1036,39 +965,40 @@ class MIRStructType : public MIRType { CHECK_FATAL(false, "can not use GetStaticValue"); } - virtual void AddInfo(const MIRInfoPair&) { - CHECK_FATAL(false, "can not use AddInfo"); + virtual void PushbackMIRInfo(const MIRInfoPair &pair) { + CHECK_FATAL(false, "can not use PushbackMIRInfo"); } - virtual void AddIsStringInfo(bool) { - CHECK_FATAL(false, "can not use AddIsStringInfo"); + virtual void PushbackPragma(MIRPragma*) { + CHECK_FATAL(false, "can not use PushbackPragma"); } - virtual void AddPragmaVec(MIRPragma*) { - CHECK_FATAL(false, "can not use AddPragmaVec"); + virtual void PushbackStaticValue(EncodedValue&) { + CHECK_FATAL(false, "can not use PushbackStaticValue"); } - virtual void AddStaticValue(EncodedValue&) { - CHECK_FATAL(false, "can not use AddStaticValue"); + virtual void PushbackIsString(bool isString) { + CHECK_FATAL(false, "can not use PushbackIsString"); } virtual FieldPair TraverseToFieldRef(FieldID &fieldID) const; std::string GetMplTypeName() const override; std::string GetCompactMplTypeName() const override; protected: - FieldVector fields; - std::vector fieldInferredTyIdx; - FieldVector staticFields; - FieldVector parentFields; // fields belong to the ancestors not fully defined - MethodVector methods; // for the list of member function prototypes - MethodPtrVector vTableMethods; // the list of implmentation for all virtual functions for this type - MethodPtrVector iTableMethods; // the list of all interface functions for this type; For classes, they are + FieldVector fields{}; + std::vector fieldInferredTyIdx{}; + FieldVector staticFields{}; + FieldVector parentFields{}; // fields belong to the ancestors not fully defined + MethodVector methods{}; // for the list of member function prototypes + MethodPtrVector vTableMethods{}; // the list of implmentation for all virtual functions for this type + MethodPtrVector iTableMethods{}; // the list of all interface functions for this type; For classes, they are // implementation functions, For interfaces, they are abstact functions. // Weak indicates the actual definition is in another module. - bool isImported; - bool isUsed; - bool hasVolatileField; // for caching computed value - bool hasVolatileFieldSet; // if true, just read hasVolatileField; otherwise compute to initialize hasVolatileField + bool isImported = false; + bool isUsed = false; + bool hasVolatileField = false; // for caching computed value + bool hasVolatileFieldSet = false; // if true, just read hasVolatileField; + // otherwise compute to initialize hasVolatileField private: FieldPair TraverseToField(FieldID fieldID) const ; FieldPair TraverseToField(GStrIdx fieldStrIdx) const ; @@ -1079,22 +1009,23 @@ class MIRStructType : public MIRType { // java array type, must not be nested inside another aggregate class MIRJarrayType : public MIRFarrayType { public: - MIRJarrayType() : parentTyIdx(0), javaNameStrIdx(0), fromPrimitive(false), dim(0) { + MIRJarrayType() { typeKind = kTypeJArray; }; - ~MIRJarrayType() {} explicit MIRJarrayType(TyIdx elemTyIdx) - : MIRFarrayType(elemTyIdx), parentTyIdx(0), javaNameStrIdx(0), fromPrimitive(false), dim(0) { + : MIRFarrayType(elemTyIdx) { typeKind = kTypeJArray; } explicit MIRJarrayType(GStrIdx strIdx) - : MIRFarrayType(strIdx), parentTyIdx(0), javaNameStrIdx(0), fromPrimitive(false), dim(0) { + : MIRFarrayType(strIdx) { typeKind = kTypeJArray; } - MIRType *CopyMIRTypeNode() const { + ~MIRJarrayType() = default; + + MIRType *CopyMIRTypeNode() const override { return new MIRJarrayType(*this); } @@ -1114,82 +1045,44 @@ class MIRJarrayType : public MIRFarrayType { return dim; } - size_t GetHashIndex() const { + size_t GetHashIndex() const override { constexpr uint8 kIdxShift = 5; return ((GetElemTyIdx().GetIdx() << kIdxShift) + (typeKind << kShiftNumOfTypeKind)) % kTypeHashLength; } private: - TyIdx parentTyIdx; // since Jarray is also an object, this is java.lang.Object - GStrIdx javaNameStrIdx; // for internal java name of Jarray. nameStrIdx is used for other purpose - bool fromPrimitive; // the lowest dimension is primitive type - int dim; // the dimension if decidable at compile time. otherwise 0 + TyIdx parentTyIdx{0}; // since Jarray is also an object, this is java.lang.Object + GStrIdx javaNameStrIdx{0}; // for internal java name of Jarray. nameStrIdx is used for other purpose + bool fromPrimitive = false; // the lowest dimension is primitive type + int dim = 0; // the dimension if decidable at compile time. otherwise 0 void DetermineName(); // determine the internal name of this type }; -constexpr int kLocalFieldOffset = 1; -constexpr int kGlobalFieldOffset = 2; // used by kTypeClass, kTypeClassIncomplete class MIRClassType : public MIRStructType { public: - explicit MIRClassType(MIRTypeKind tkind) - : MIRStructType(tkind), - parentTyIdx(0), - interfacesImplemented(), - info(), - infoIsString(), - pragmaVec(), - staticValue() {} - - MIRClassType(MIRTypeKind tkind, GStrIdx strIdx) - : MIRStructType(tkind, strIdx), - parentTyIdx(0), - interfacesImplemented(), - info(), - infoIsString(), - pragmaVec(), - staticValue() {} + explicit MIRClassType(MIRTypeKind tKind) + : MIRStructType(tKind) {} + + MIRClassType(MIRTypeKind tKind, GStrIdx strIdx) + : MIRStructType(tKind, strIdx) {} ~MIRClassType() = default; + bool EqualTo(const MIRType &type) const override; + MIRType *CopyMIRTypeNode() const override { return new MIRClassType(*this); } - TyIdx &GetParentTyIdx() { - return parentTyIdx; - } - - const TyIdx &GetParentTyIdx() const { - return parentTyIdx; - } - - void SetParentTyIdx(const TyIdx idx) { - parentTyIdx = idx; - } - - std::vector &GetInterfaceImplemented() { - return interfacesImplemented; - } - - const TyIdx &GetNthInterfaceImplemented(size_t i) const { - ASSERT(i < interfacesImplemented.size(), "array index out of range"); - return interfacesImplemented.at(i); - } - - void SetNthInterfaceImplemented(uint32 i, TyIdx tyIdx) { - ASSERT(i < interfacesImplemented.size(), "array index out of range"); - interfacesImplemented.at(i) = tyIdx; - } - - std::vector &GetInfo() override { - return info; - } - const std::vector &GetInfo() const override { return info; } - + void PushbackMIRInfo(const MIRInfoPair &pair) override { + info.push_back(pair); + } + uint32 GetInfo(const std::string &infoStr) const; + uint32 GetInfo(GStrIdx strIdx) const; uint32 GetInfoSize() const { return info.size(); } @@ -1199,34 +1092,60 @@ class MIRClassType : public MIRStructType { return info.at(n); } - std::vector &GetInfoIsString() { + const std::vector &GetInfoIsString() const override { return infoIsString; } - - const std::vector &GetInfoIsString() const { - return infoIsString; + void PushbackIsString(bool isString) override { + infoIsString.push_back(isString); } - size_t GetInfoIsStringSize() const { return infoIsString.size(); } - bool GetInfoIsStringElemt(size_t n) const { ASSERT(n < infoIsString.size(), "array index out of range"); return infoIsString.at(n); } - std::vector &GetPragmVec() { + std::vector &GetPragmaVec() { return pragmaVec; } - - const std::vector &GetPragmVec() const { + const std::vector &GetPragmaVec() const override { return pragmaVec; } + void PushbackPragma(MIRPragma *pragma) override { + pragmaVec.push_back(pragma); + } - const MIREncodedArray &GetMIREncodedArray() const { + const MIREncodedArray &GetStaticValue() const override { return staticValue; } + void PushbackStaticValue(EncodedValue &encodedValue) override { + staticValue.push_back(encodedValue); + } + + TyIdx GetParentTyIdx() const { + return parentTyIdx; + } + void SetParentTyIdx(const TyIdx idx) { + parentTyIdx = idx; + } + + std::vector &GetInterfaceImplemented() { + return interfacesImplemented; + } + + TyIdx GetNthInterfaceImplemented(size_t i) const { + ASSERT(i < interfacesImplemented.size(), "array index out of range"); + return interfacesImplemented.at(i); + } + + void SetNthInterfaceImplemented(uint32 i, TyIdx tyIdx) { + ASSERT(i < interfacesImplemented.size(), "array index out of range"); + interfacesImplemented.at(i) = tyIdx; + } + void PushbackInterfaceImplemented(TyIdx idx) { + interfacesImplemented.push_back(idx); + } void Dump(int indent, bool dontUseName = false) const override; void DumpAsCxx(int indent) const override; @@ -1236,8 +1155,8 @@ class MIRClassType : public MIRStructType { bool IsFinal() const; bool IsInner() const; - virtual bool HasVolatileField() override; - virtual bool HasTypeParam() const override; + bool HasVolatileField() override; + bool HasTypeParam() const override; virtual FieldPair TraverseToFieldRef(FieldID &fieldID) const override; size_t GetSize() const override; @@ -1248,10 +1167,8 @@ class MIRClassType : public MIRStructType { FieldID GetFirstLocalFieldID() const; // return class id or superclass id accroding to input string - uint32 GetInfo(const std::string &infoStr) const; MIRClassType *GetExceptionRootType(); bool IsExceptionType(); - uint32 GetInfo(GStrIdx strIdx) const; void AddImplementedInterface(TyIdx interfaceTyIdx) { if (std::find(interfacesImplemented.begin(), interfacesImplemented.end(), interfaceTyIdx) != interfacesImplemented.end()) { @@ -1274,77 +1191,41 @@ class MIRClassType : public MIRStructType { return ((nameStrIdx.GetIdx() << kShiftNumOfNameStrIdx) + (typeKind << kShiftNumOfTypeKind)) % kTypeHashLength; } - const std::vector &GetIsStringInfo() const override { - return infoIsString; - } - - const std::vector &GetPragmaVec() const override { - return pragmaVec; - } - - const MIREncodedArray &GetStaticValue() const override { - return staticValue; - } - - void AddInfo(const MIRInfoPair &infoPair) override { - info.push_back(infoPair); - } - - void AddIsStringInfo(bool isString) override { - infoIsString.push_back(isString); - } - - void AddPragmaVec(MIRPragma *pragma) override { - pragmaVec.push_back(pragma); - } - - void AddStaticValue(EncodedValue &encodedValue) override { - staticValue.push_back(encodedValue); - } - private: - TyIdx parentTyIdx; - std::vector interfacesImplemented; // for the list of interfaces the class implements - std::vector info; - std::vector infoIsString; - std::vector pragmaVec; - MIREncodedArray staticValue; // DELETE THIS + TyIdx parentTyIdx{0}; + std::vector interfacesImplemented{}; // for the list of interfaces the class implements + std::vector info{}; + std::vector infoIsString{}; + std::vector pragmaVec{}; + MIREncodedArray staticValue{}; // DELETE THIS }; // used by kTypeInterface, kTypeInterfaceIncomplete class MIRInterfaceType : public MIRStructType { public: - explicit MIRInterfaceType(MIRTypeKind tkind) - : MIRStructType(tkind), parentsTyIdx(), info(), infoIsString(), pragmaVec(), staticValue() {} + explicit MIRInterfaceType(MIRTypeKind tKind) + : MIRStructType(tKind) {} - MIRInterfaceType(MIRTypeKind tkind, GStrIdx strIdx) - : MIRStructType(tkind, strIdx), parentsTyIdx(), info(), infoIsString(), pragmaVec(), staticValue() {} + MIRInterfaceType(MIRTypeKind tKind, GStrIdx strIdx) + : MIRStructType(tKind, strIdx) {} ~MIRInterfaceType() = default; - std::vector &GetParentsTyIdx() { - return parentsTyIdx; - } - - TyIdx GetParentsElementTyIdx(size_t i) const { - ASSERT(i < parentsTyIdx.size(), "array index out of range"); - return parentsTyIdx[i]; - } - - void SetParentsElementTyIdx(size_t i, TyIdx tyIdx) { - ASSERT(i < parentsTyIdx.size(), "array index out of range"); - parentsTyIdx[i] = tyIdx; - } + bool EqualTo(const MIRType &type) const override; - std::vector &GetInfo() override { - return info; + MIRType *CopyMIRTypeNode() const override { + return new MIRInterfaceType(*this); } const std::vector &GetInfo() const override { return info; } - - size_t GetInfoSize() const { + void PushbackMIRInfo(const MIRInfoPair &pair) override { + info.push_back(pair); + } + uint32 GetInfo(const std::string &infoStr) const; + uint32 GetInfo(GStrIdx strIdx) const; + uint32 GetInfoSize() const { return info.size(); } @@ -1353,43 +1234,54 @@ class MIRInterfaceType : public MIRStructType { return info.at(n); } - std::vector &GetInfoIsString() { + const std::vector &GetInfoIsString() const override { return infoIsString; } - - const std::vector &GetInfoIsString() const { - return infoIsString; + void PushbackIsString(bool isString) override { + infoIsString.push_back(isString); } - size_t GetInfoIsStringSize() const { return infoIsString.size(); } - bool GetInfoIsStringElemt(size_t n) const { ASSERT(n < infoIsString.size(), "array index out of range"); return infoIsString.at(n); } - std::vector &GetPragmVec() { + std::vector &GetPragmaVec() { return pragmaVec; } - - const std::vector &GetPragmVec() const { + const std::vector &GetPragmaVec() const override { return pragmaVec; } + void PushbackPragma(MIRPragma *pragma) override { + pragmaVec.push_back(pragma); + } - const MIREncodedArray &GetMIREncodedArray() const { + const MIREncodedArray &GetStaticValue() const override { return staticValue; } + void PushbackStaticValue(EncodedValue &encodedValue) override { + staticValue.push_back(encodedValue); + } - bool EqualTo(const MIRType &type) const override; - MIRType *CopyMIRTypeNode() const override { - return new MIRInterfaceType(*this); + std::vector &GetParentsTyIdx() { + return parentsTyIdx; + } + + TyIdx GetParentsElementTyIdx(size_t i) const { + ASSERT(i < parentsTyIdx.size(), "array index out of range"); + return parentsTyIdx[i]; + } + + void SetParentsElementTyIdx(size_t i, TyIdx tyIdx) { + ASSERT(i < parentsTyIdx.size(), "array index out of range"); + parentsTyIdx[i] = tyIdx; } void Dump(int indent, bool dontUseName = false) const override; - virtual bool HasVolatileField() override; - virtual bool HasTypeParam() const override; + bool HasVolatileField() override; + bool HasTypeParam() const override; virtual FieldPair TraverseToFieldRef(FieldID &fieldID) const override; void SetComplete() override { typeKind = kTypeInterface; @@ -1397,10 +1289,6 @@ class MIRInterfaceType : public MIRStructType { size_t GetSize() const override; - // return class id or superclass id accroding to input string - uint32 GetInfo(const std::string &infoStr) const; - uint32 GetInfo(GStrIdx strIdx) const; - void ClearContents() override { MIRStructType::ClearContents(); parentsTyIdx.clear(); @@ -1414,42 +1302,15 @@ class MIRInterfaceType : public MIRStructType { return ((nameStrIdx.GetIdx() << kShiftNumOfNameStrIdx) + (typeKind << kShiftNumOfTypeKind)) % kTypeHashLength; } - const std::vector &GetIsStringInfo() const override { - return infoIsString; - } - - const std::vector &GetPragmaVec() const override { - return pragmaVec; - } - - const MIREncodedArray &GetStaticValue() const override { - return staticValue; - } - - void AddInfo(const MIRInfoPair &infoPair) override { - info.push_back(infoPair); - } - - void AddIsStringInfo(bool isString) override { - infoIsString.push_back(isString); - } - - void AddPragmaVec(MIRPragma *pragma) override { - pragmaVec.push_back(pragma); - } - - void AddStaticValue(EncodedValue &encodedValue) override { - staticValue.push_back(encodedValue); - } - private: - std::vector parentsTyIdx; // multiple inheritence - std::vector info; - std::vector infoIsString; - std::vector pragmaVec; - MIREncodedArray staticValue; // DELETE THIS + std::vector parentsTyIdx{}; // multiple inheritence + std::vector info{}; + std::vector infoIsString{}; + std::vector pragmaVec{}; + MIREncodedArray staticValue{}; // DELETE THIS }; + class MIRBitFieldType : public MIRType { public: MIRBitFieldType(uint8 field, PrimType pt) : MIRType(kTypeBitField, pt), fieldSize(field) {} @@ -1458,21 +1319,21 @@ class MIRBitFieldType : public MIRType { ~MIRBitFieldType() = default; - uint8 GetFieldSize() { + uint8 GetFieldSize() const { return fieldSize; } - bool EqualTo(const MIRType &type) const; - void Dump(int indent, bool dontUseName = false) const; - MIRType *CopyMIRTypeNode() const { + bool EqualTo(const MIRType &type) const override; + void Dump(int indent, bool dontUseName = false) const override; + MIRType *CopyMIRTypeNode() const override { return new MIRBitFieldType(*this); } - size_t GetSize() const { + size_t GetSize() const override { return 0; } // size not be in bytes - size_t GetHashIndex() const { + size_t GetHashIndex() const override { return ((static_cast(primType) << fieldSize) + (typeKind << kShiftNumOfTypeKind)) % kTypeHashLength; } @@ -1482,55 +1343,46 @@ class MIRBitFieldType : public MIRType { class MIRFuncType : public MIRType { public: - bool EqualTo(const MIRType &type) const; - MIRType *CopyMIRTypeNode() const { - return new MIRFuncType(*this); - } - - MIRFuncType() : MIRType(kTypeFunction, PTY_ptr), paramTypeList(), paramAttrsList(), isVarArgs(false) {} + MIRFuncType() : MIRType(kTypeFunction, PTY_ptr), paramTypeList(), paramAttrsList() {} MIRFuncType(TyIdx retTyIdx, const std::vector &vecTy, const std::vector &vecAt) : MIRType(kTypeFunction, PTY_ptr), retTyIdx(retTyIdx), paramTypeList(vecTy), - paramAttrsList(vecAt), - isVarArgs(false) {} + paramAttrsList(vecAt) {} explicit MIRFuncType(GStrIdx strIdx) : MIRType(kTypeFunction, PTY_ptr, strIdx), retTyIdx(TyIdx(0)), paramTypeList(), - paramAttrsList(), - isVarArgs(false) {} + paramAttrsList() {} - ~MIRFuncType() {} + ~MIRFuncType() = default; - void Dump(int indent, bool dontUseName = false) const; - size_t GetSize() const { + bool EqualTo(const MIRType &type) const override; + MIRType *CopyMIRTypeNode() const override { + return new MIRFuncType(*this); + } + + void Dump(int indent, bool dontUseName = false) const override; + size_t GetSize() const override { return 0; } // size unknown - const TyIdx &GetRetTyIdx() const { + TyIdx GetRetTyIdx() const { return retTyIdx; } - - void SetRetTyIdx(const TyIdx idx) { + void SetRetTyIdx(TyIdx idx) { retTyIdx = idx; } std::vector &GetParamTypeList() { return paramTypeList; } - TyIdx GetNthParamType(size_t i) const { ASSERT(i < paramTypeList.size(), "array index out of range"); return paramTypeList[i]; } - - void AddParamTypeList(const TyIdx tyIdx) { - paramTypeList.push_back(tyIdx); - } - void SetParamTypeList(std::vector &list) { paramTypeList = list; } @@ -1538,30 +1390,26 @@ class MIRFuncType : public MIRType { std::vector &GetParamAttrsList() { return paramAttrsList; } - const TypeAttrs &GetNthParamAttrs(size_t i) const { ASSERT(i < paramAttrsList.size(), "array index out of range"); return paramAttrsList[i]; } - void SetParamAttrsList(const std::vector &list) { paramAttrsList = list; } - - void SetNthParamAttrs(size_t i, TypeAttrs &attrs) { + void SetNthParamAttrs(size_t i, const TypeAttrs &attrs) { ASSERT(i < paramAttrsList.size(), "array index out of range"); paramAttrsList[i] = attrs; } - bool IsVarargs() { + bool IsVarargs() const { return isVarArgs; } - void SetVarArgs(bool flag) { isVarArgs = flag; } - size_t GetHashIndex() const { + size_t GetHashIndex() const override { constexpr uint8 kIdxShift = 6; size_t hidx = (retTyIdx.GetIdx() << kIdxShift) + (typeKind << kShiftNumOfTypeKind); size_t size = paramTypeList.size(); @@ -1573,28 +1421,28 @@ class MIRFuncType : public MIRType { TyIdx retTyIdx; std::vector paramTypeList; std::vector paramAttrsList; - bool isVarArgs; + bool isVarArgs = false; }; class MIRTypeByName : public MIRType { // use nameStrIdx to store the name for both local and global public: - bool EqualTo(const MIRType &type) const; + bool EqualTo(const MIRType &type) const override; explicit MIRTypeByName(GStrIdx sidx) : MIRType(kTypeByName, PTY_void) { nameStrIdx = sidx; } ~MIRTypeByName() = default; - MIRType *CopyMIRTypeNode() const { + MIRType *CopyMIRTypeNode() const override { return new MIRTypeByName(*this); } - void Dump(int indent, bool dontUseName = false) const; - size_t GetSize() const { + void Dump(int indent, bool dontUseName = false) const override; + size_t GetSize() const override { return 0; } // size unknown - size_t GetHashIndex() const { + size_t GetHashIndex() const override { constexpr uint8 kIdxShift = 2; return ((nameStrIdx.GetIdx() << kIdxShift) + nameIsLocal + (typeKind << kShiftNumOfTypeKind)) % kTypeHashLength; } @@ -1607,23 +1455,23 @@ class MIRTypeParam : public MIRType { nameStrIdx = sidx; } - ~MIRTypeParam() {} + ~MIRTypeParam() = default; - MIRType *CopyMIRTypeNode() const { + MIRType *CopyMIRTypeNode() const override { return new MIRTypeParam(*this); } - bool EqualTo(const MIRType &type) const; - void Dump(int indent, bool dontUseName = false) const; - size_t GetSize() const { + bool EqualTo(const MIRType &type) const override; + void Dump(int indent, bool dontUseName = false) const override; + size_t GetSize() const override { return 0; } // size unknown - bool HasTypeParam() const { + bool HasTypeParam() const override { return true; } - size_t GetHashIndex() const { + size_t GetHashIndex() const override { constexpr uint8 kIdxShift = 3; return ((nameStrIdx.GetIdx() << kIdxShift) + (typeKind << kShiftNumOfTypeKind)) % kTypeHashLength; } @@ -1633,32 +1481,31 @@ using TypePair = std::pair; using GenericInstantVector = std::vector; class MIRInstantVectorType : public MIRType { public: - MIRInstantVectorType() : MIRType(kTypeInstantVector, PTY_agg), instantVec() {} + MIRInstantVectorType() : MIRType(kTypeInstantVector, PTY_agg) {} - explicit MIRInstantVectorType(MIRTypeKind kind) : MIRType(kind, PTY_agg), instantVec() {} + explicit MIRInstantVectorType(MIRTypeKind kind) : MIRType(kind, PTY_agg) {} - MIRInstantVectorType(MIRTypeKind kind, GStrIdx strIdx) : MIRType(kind, PTY_agg, strIdx), instantVec() {} + MIRInstantVectorType(MIRTypeKind kind, GStrIdx strIdx) : MIRType(kind, PTY_agg, strIdx) {} ~MIRInstantVectorType() = default; - MIRType *CopyMIRTypeNode() const { + MIRType *CopyMIRTypeNode() const override { return new MIRInstantVectorType(*this); } - bool EqualTo(const MIRType &type) const; - void Dump(int indent, bool dontUseName = false) const; - size_t GetSize() const { + bool EqualTo(const MIRType &type) const override; + void Dump(int indent, bool dontUseName = false) const override; + size_t GetSize() const override { return 0; } // size unknown GenericInstantVector &GetInstantVec() { return instantVec; } - const GenericInstantVector &GetInstantVec() const { return instantVec; } - size_t GetHashIndex() const { + size_t GetHashIndex() const override { uint32 hidx = typeKind << kShiftNumOfTypeKind; for (TypePair typePair : instantVec) { hidx += (typePair.first.GetIdx() + typePair.second.GetIdx()) << 3; @@ -1667,37 +1514,38 @@ class MIRInstantVectorType : public MIRType { } protected: - GenericInstantVector instantVec; // in each pair, first is generic type, - // second is real type + GenericInstantVector instantVec{}; // in each pair, first is generic type, second is real type }; class MIRGenericInstantType : public MIRInstantVectorType { public: - explicit MIRGenericInstantType(TyIdx genTyIdx) : MIRInstantVectorType(kTypeGenericInstant), genericTyIdx(genTyIdx) {} + explicit MIRGenericInstantType(TyIdx genTyIdx) + : MIRInstantVectorType(kTypeGenericInstant), genericTyIdx(genTyIdx) {} explicit MIRGenericInstantType(GStrIdx strIdx) : MIRInstantVectorType(kTypeGenericInstant, strIdx), genericTyIdx(TyIdx(0)) {} ~MIRGenericInstantType() = default; - MIRType *CopyMIRTypeNode() const { + + MIRType *CopyMIRTypeNode() const override { return new MIRGenericInstantType(*this); } - bool EqualTo(const MIRType &type) const; - void Dump(int indent, bool dontUseName = false) const; - size_t GetSize() const { + bool EqualTo(const MIRType &type) const override; + void Dump(int indent, bool dontUseName = false) const override; + + size_t GetSize() const override { return 0; } // size unknown - const TyIdx &GetGenericTyIdx() const { + TyIdx GetGenericTyIdx() const { return genericTyIdx; } - - void SetGenericTyIdx(const TyIdx idx) { + void SetGenericTyIdx(TyIdx idx) { genericTyIdx = idx; } - size_t GetHashIndex() const { + size_t GetHashIndex() const override { constexpr uint8 kIdxShift = 2; uint32 hidx = (genericTyIdx.GetIdx() << kIdxShift) + (typeKind << kShiftNumOfTypeKind); for (TypePair typePair : instantVec) { diff --git a/src/maple_ir/include/opcode_info.h b/src/maple_ir/include/opcode_info.h index 7708eb7f22ed4d37f7c36b313faa776595951a2e..357e2fe2f246a00957577a73eccd12aec13a7f3c 100644 --- a/src/maple_ir/include/opcode_info.h +++ b/src/maple_ir/include/opcode_info.h @@ -35,17 +35,17 @@ enum OpcodeProp { kOpcodePropMayThrowException, }; -constexpr unsigned long OPCODEISSTMT(1UL << kOpcodePropIsStmt); -constexpr unsigned long OPCODEISVARSIZE(1UL << kOpcodePropIsVarSize); -constexpr unsigned long OPCODENOTMMPL(1UL << kOpcodePropNotMMPL); -constexpr unsigned long OPCODEISCOMPARE(1UL << kOpcodePropIsCompare); -constexpr unsigned long OPCODEISTYPECVT(1UL << kOpcodePropIsTypeCvt); -constexpr unsigned long OPCODEHASSSAUSE(1UL << kOpcodePropHasSSAUse); -constexpr unsigned long OPCODEHASSSADEF(1UL << kOpcodePropHasSSADef); -constexpr unsigned long OPCODEISCALL(1UL << kOpcodePropIsCall); -constexpr unsigned long OPCODEISCALLASSIGNED(1UL << kOpcodePropIsCallAssigned); -constexpr unsigned long OPCODENOTPURE(1UL << kOpcodePropNotPure); -constexpr unsigned long OPCODEMAYTHROWEXCEPTION(1UL << kOpcodePropMayThrowException); +constexpr unsigned long OPCODEISSTMT(1ULL << kOpcodePropIsStmt); +constexpr unsigned long OPCODEISVARSIZE(1ULL << kOpcodePropIsVarSize); +constexpr unsigned long OPCODENOTMMPL(1ULL << kOpcodePropNotMMPL); +constexpr unsigned long OPCODEISCOMPARE(1ULL << kOpcodePropIsCompare); +constexpr unsigned long OPCODEISTYPECVT(1ULL << kOpcodePropIsTypeCvt); +constexpr unsigned long OPCODEHASSSAUSE(1ULL << kOpcodePropHasSSAUse); +constexpr unsigned long OPCODEHASSSADEF(1ULL << kOpcodePropHasSSADef); +constexpr unsigned long OPCODEISCALL(1ULL << kOpcodePropIsCall); +constexpr unsigned long OPCODEISCALLASSIGNED(1ULL << kOpcodePropIsCallAssigned); +constexpr unsigned long OPCODENOTPURE(1ULL << kOpcodePropNotPure); +constexpr unsigned long OPCODEMAYTHROWEXCEPTION(1ULL << kOpcodePropMayThrowException); struct OpcodeDesc { uint8 instrucSize; // size of instruction in bytes uint16 flag; // stores the opcode property flags diff --git a/src/maple_ir/src/bin_mpl_export.cpp b/src/maple_ir/src/bin_mpl_export.cpp index 8b28023504d0f0cd0e0804a5cdf309953e25be09..5f93c1f5b4aa3e279cc12a003a6851562718546d 100644 --- a/src/maple_ir/src/bin_mpl_export.cpp +++ b/src/maple_ir/src/bin_mpl_export.cpp @@ -346,7 +346,8 @@ void BinaryMplExport::WriteInt64(int64 x) { void BinaryMplExport::WriteNum(int64 x) { while (x < -0x40 || x >= 0x40) { Write(static_cast((static_cast(x) & 0x7F) + 0x80)); - x = x >> 7; + x = x >> 7; // This is a compress algorithm, do not cast int64 to uint64. If do so, small negtivate number like -3 + // will occupy 9 bits and we will not get the compressed benefit. } Write((uint8)(static_cast(x) & 0x7F)); } @@ -552,14 +553,14 @@ void BinaryMplExport::OutputClassTypeData(MIRClassType &type) { OutputImplementedInterfaces(type.GetInterfaceImplemented()); OutputInfoIsString(type.GetInfoIsString()); OutputInfo(type.GetInfo(), type.GetInfoIsString()); - OutputPragmaVec(type.GetPragmVec()); + OutputPragmaVec(type.GetPragmaVec()); } void BinaryMplExport::OutputInterfaceTypeData(MIRInterfaceType &type) { OutputImplementedInterfaces(type.GetParentsTyIdx()); OutputInfoIsString(type.GetInfoIsString()); OutputInfo(type.GetInfo(), type.GetInfoIsString()); - OutputPragmaVec(type.GetPragmVec()); + OutputPragmaVec(type.GetPragmaVec()); } void BinaryMplExport::Init() { diff --git a/src/maple_ir/src/bin_mpl_import.cpp b/src/maple_ir/src/bin_mpl_import.cpp index 3ac28206cfd4f7eff656fea96cdeee1123104a75..22e8549d5270b79b39f3fd0286adfe7fcc0857fa 100644 --- a/src/maple_ir/src/bin_mpl_import.cpp +++ b/src/maple_ir/src/bin_mpl_import.cpp @@ -360,40 +360,40 @@ void BinaryMplImport::ImportInterfacesOfClassType(std::vector &interfaces } } -void BinaryMplImport::ImportInfoIsStringOfClassType(std::vector &infoIsString) { +void BinaryMplImport::ImportInfoIsStringOfStructType(MIRStructType &type) { int64 size = ReadNum(); - bool isEmpty = infoIsString.empty(); + bool isEmpty = type.GetInfoIsString().empty(); for (int64 i = 0; i < size; i++) { bool isString = static_cast(ReadNum()); if (isEmpty) { - infoIsString.push_back(isString); + type.PushbackIsString(isString); } } } -void BinaryMplImport::ImportInfoOfClassType(std::vector &infoIsString, std::vector &infos) { +void BinaryMplImport::ImportInfoOfStructType(MIRStructType &type) { int64 size = ReadNum(); - bool isEmpty = infos.empty(); + bool isEmpty = type.GetInfo().empty(); for (int64 i = 0; i < size; i++) { GStrIdx idx = ImportStr(); - int64 x = (infoIsString[i]) ? ImportStr().GetIdx() : ReadNum(); + int64 x = (type.GetInfoIsString()[i]) ? ImportStr().GetIdx() : ReadNum(); ASSERT(x >= 0, "ReadNum nagative, x: %d", x); ASSERT(x <= std::numeric_limits::max(), "ReadNum too large, x: %d", x); if (isEmpty) { - infos.push_back(MIRInfoPair(idx, static_cast(x))); + type.PushbackMIRInfo(MIRInfoPair(idx, static_cast(x))); } } } -void BinaryMplImport::ImportPragmaOfClassType(std::vector &pragmas) { +void BinaryMplImport::ImportPragmaOfStructType(MIRStructType &type) { int64 size = ReadNum(); - bool isEmpty = pragmas.empty(); + bool isEmpty = type.GetPragmaVec().empty(); for (int64 i = 0; i < size; i++) { MIRPragma *pragma = ImportPragma(); if (isEmpty) { - pragmas.push_back(pragma); + type.PushbackPragma(pragma); } } } @@ -415,20 +415,20 @@ void BinaryMplImport::ImportClassTypeData(MIRClassType &type) { TyIdx tempType = ImportType(); // Keep the parent_tyidx we first met. if (type.GetParentTyIdx().GetIdx() == 0) { - type.GetParentTyIdx() = tempType; + type.SetParentTyIdx(tempType); } ImportInterfacesOfClassType(type.GetInterfaceImplemented()); - ImportInfoIsStringOfClassType(type.GetInfoIsString()); - ImportInfoOfClassType(type.GetInfoIsString(), type.GetInfo()); - ImportPragmaOfClassType(type.GetPragmVec()); + ImportInfoIsStringOfStructType(type); + ImportInfoOfStructType(type); + ImportPragmaOfStructType(type); SetClassTyidxOfMethods(type); } void BinaryMplImport::ImportInterfaceTypeData(MIRInterfaceType &type) { ImportInterfacesOfClassType(type.GetParentsTyIdx()); - ImportInfoIsStringOfClassType(type.GetInfoIsString()); - ImportInfoOfClassType(type.GetInfoIsString(), type.GetInfo()); - ImportPragmaOfClassType(type.GetPragmVec()); + ImportInfoIsStringOfStructType(type); + ImportInfoOfStructType(type); + ImportPragmaOfStructType(type); SetClassTyidxOfMethods(type); } @@ -731,7 +731,7 @@ void BinaryMplImport::SetupEHRootType() { } } -MIRSymbol *BinaryMplImport::GetOrCreateSymbol(const TyIdx &tyIdx, const GStrIdx &strIdx, MIRSymKind mclass, +MIRSymbol *BinaryMplImport::GetOrCreateSymbol(TyIdx tyIdx, GStrIdx strIdx, MIRSymKind mclass, MIRStorageClass sclass, MIRFunction *func, uint8 scpID) { MIRSymbol *st = GlobalTables::GetGsymTable().GetSymbolFromStrIdx(strIdx); if (st != nullptr && st->GetStorageClass() == sclass && st->GetSKind() == mclass && scpID == kScopeGlobal) { @@ -758,7 +758,6 @@ MIRSymbol *BinaryMplImport::InSymbol(MIRFunction *func) { symTab.push_back(sym); sym->SetAttrs(ImportTypeAttrs()); sym->SetIsTmp(ReadNum() != 0); - sym->SetIsImported(imported); if (skind == kStPreg) { ASSERT(false, "outing kStPreg"); diff --git a/src/maple_ir/src/mir_function.cpp b/src/maple_ir/src/mir_function.cpp index 024c5fdcab3dbd88403ecbf72c111086a1301249..bbf2a24954099b4bbb60f910ee632a0b73c0e5c6 100644 --- a/src/maple_ir/src/mir_function.cpp +++ b/src/maple_ir/src/mir_function.cpp @@ -32,6 +32,39 @@ void FuncAttrs::DumpAttributes() const { #undef FUNC_ATTR } +void MIRFunction::DumpFlavorLoweredThanMmpl() const { + LogInfo::MapleLogger() << " ("; + // Dump arguments + size_t argSize = GetParamSize(); + for (size_t i = 0; i < argSize; ++i) { + MIRSymbol *symbol = formals[i]; + if (symbol != nullptr) { + if (symbol->GetSKind() != kStPreg) { + LogInfo::MapleLogger() << "var %" << symbol->GetName() << " "; + } else { + LogInfo::MapleLogger() << "reg %" << symbol->GetPreg()->GetPregNo() << " "; + } + } + constexpr int kIndent = 2; + MIRType *ty = GetNthParamType(i); + ty->Dump(kIndent); + TypeAttrs tA = GetNthParamAttr(i); + tA.DumpAttributes(); + if (i != (argSize - 1)) { + LogInfo::MapleLogger() << ", "; + } + } + if (IsVarargs()) { + if (argSize == 0) { + LogInfo::MapleLogger() << "..."; + } else { + LogInfo::MapleLogger() << ", ..."; + } + } + LogInfo::MapleLogger() << ") "; + GetReturnType()->Dump(1); +} + void MIRFunction::Dump(bool withoutBody) { // skip the functions that are added during process methods in // class and interface decls. these has nothing in formals @@ -48,36 +81,7 @@ void MIRFunction::Dump(bool withoutBody) { LogInfo::MapleLogger() << "func " << "&" << fnSt->GetName(); funcAttrs.DumpAttributes(); if (module->GetFlavor() < kMmpl) { - LogInfo::MapleLogger() << " ("; - // Dump arguments - uint32 argSize = GetParamSize(); - for (uint32 i = 0; i < argSize; i++) { - MIRSymbol *symbol = formals[i]; - if (symbol != nullptr) { - if (symbol->GetSKind() != kStPreg) { - LogInfo::MapleLogger() << "var %" << symbol->GetName() << " "; - } else { - LogInfo::MapleLogger() << "reg %" << symbol->GetPreg()->GetPregNo() << " "; - } - } - constexpr int kIndent = 2; - MIRType *ty = GetNthParamType(i); - ty->Dump(kIndent); - TypeAttrs tA = GetNthParamAttr(i); - tA.DumpAttributes(); - if (i != (argSize - 1)) { - LogInfo::MapleLogger() << ", "; - } - } - if (IsVarargs()) { - if (argSize == 0) { - LogInfo::MapleLogger() << "..."; - } else { - LogInfo::MapleLogger() << ", ..."; - } - } - LogInfo::MapleLogger() << ") "; - GetReturnType()->Dump(1); + DumpFlavorLoweredThanMmpl(); } // codeMemPool is nullptr, means maple_ir has been released for memory's sake if (codeMemPool == nullptr) { @@ -306,7 +310,7 @@ void MIRFunction::NewBody() { MIRLabelTable *oldLabelTable = GetLabelTab(); symTab = dataMemPool->New(&dataMPAllocator); SetPregTab(dataMemPool->New(module, &dataMPAllocator)); - typeNameTab = dataMemPool->New(&dataMPAllocator); + typeNameTab = dataMemPool->New(dataMPAllocator); SetLabelTab(dataMemPool->New(&dataMPAllocator)); if (oldSymTable != nullptr) { for (size_t i = 1; i < oldSymTable->GetSymbolTableSize(); i++) { diff --git a/src/maple_ir/src/mir_module.cpp b/src/maple_ir/src/mir_module.cpp index b3965a955504e2d7af64f4dece6a406ded2b79bb..85e03294281b54d35e14df8b1bc701e3d9c45eaf 100644 --- a/src/maple_ir/src/mir_module.cpp +++ b/src/maple_ir/src/mir_module.cpp @@ -28,7 +28,7 @@ namespace maple { #if MIR_FEATURE_FULL // to avoid compilation error when MIR_FEATURE_FULL=0 -MIRModule::MIRModule(const char *fn) +MIRModule::MIRModule(const std::string &fn) : memPool(mempoolctrler.NewMemPool("maple_ir mempool")), memPoolAllocator(memPool), functionList(memPoolAllocator.Adapter()), @@ -50,7 +50,7 @@ MIRModule::MIRModule(const char *fn) optimizedFuncs(memPoolAllocator.Adapter()), puIdxFieldInitializedMap(std::less(), memPoolAllocator.Adapter()) { GlobalTables::GetGsymTable().SetModule(this); - typeNameTab = memPool->New(&memPoolAllocator); + typeNameTab = memPool->New(memPoolAllocator); mirBuilder = memPool->New(this); IntrinDesc::InitMIRModule(this); } @@ -306,7 +306,7 @@ void MIRModule::DumpFunctionList(bool skipBody) const { } } -void MIRModule::OutputFunctionListAsciiMpl(const char *phaseName) { +void MIRModule::OutputFunctionListAsciiMpl(const std::string &phaseName) { std::string fileStem; std::string::size_type lastDot = fileName.find_last_of('.'); if (lastDot == std::string::npos) { @@ -376,8 +376,7 @@ const std::string &MIRModule::GetFileNameFromFileNum(uint32 fileNum) const { } -void MIRModule::DumpClassToFile(const char *path) const { - ASSERT(path != nullptr, "null ptr check"); +void MIRModule::DumpClassToFile(const std::string &path) const { std::string spath(path); spath.append("/"); for (auto it : typeNameTab->GetGStrIdxToTyIdxMap()) { @@ -420,7 +419,7 @@ MIRFunction *MIRModule::FindEntryFunction() { // given the phase name (including '.' at beginning), output the program in the // module in ascii form to the file with either .mpl or .mmpl suffix, and file // stem from this->fileName appended with phasename -void MIRModule::OutputAsciiMpl(const char *phaseName, bool emitStructureType) { +void MIRModule::OutputAsciiMpl(const std::string &phaseName, bool emitStructureType) { std::string fileStem; std::string::size_type lastDot = fileName.find_last_of("."); if (lastDot == std::string::npos) { diff --git a/src/maple_ir/src/mir_symbol.cpp b/src/maple_ir/src/mir_symbol.cpp index 0122d5dfbd7b8a5ea385b3f8b3eb12e2967907bc..469aa1c3f75db7d662d8dc445008a7d6a1fc0f31 100644 --- a/src/maple_ir/src/mir_symbol.cpp +++ b/src/maple_ir/src/mir_symbol.cpp @@ -258,14 +258,9 @@ bool MIRSymbol::IgnoreRC() const { } void MIRSymbol::Dump(bool isLocal, int32 indent, bool suppressinit) const { - if (GetStorageClass() == kScUnused) { - return; - } - if (GetStorageClass() == kScFormal) { - return; - } - // no need for symbols of extern functions, only need declarations - if (GetStorageClass() == kScExtern && sKind == kStFunc) { + // exclude unused symbols, formal symbols and extern functions + if (GetStorageClass() == kScUnused || GetStorageClass() == kScFormal || + (GetStorageClass() == kScExtern && sKind == kStFunc)) { return; } if (GetTyIdx().GetIdx() >= GlobalTables::GetTypeTable().GetTypeTable().size()) { @@ -301,14 +296,14 @@ void MIRSymbol::Dump(bool isLocal, int32 indent, bool suppressinit) const { typeAttrs.DumpAttributes(); if (sKind == kStJavaClass || sKind == kStJavaInterface || GetStorageClass() == kScTypeInfoName || GetStorageClass() == kScTypeInfo || GetStorageClass() == kScTypeCxxAbi) { - LogInfo::MapleLogger() << std::endl; + LogInfo::MapleLogger() << '\n'; return; } if (IsConst() && !suppressinit && !(IsLiteral() && GetStorageClass() == kScExtern)) { LogInfo::MapleLogger() << " = "; GetKonst()->Dump(); } - LogInfo::MapleLogger() << std::endl; + LogInfo::MapleLogger() << '\n'; } void MIRSymbol::DumpAsLiteralVar(int32 indent) const { diff --git a/src/maple_ir/src/mir_type.cpp b/src/maple_ir/src/mir_type.cpp index 6f1da7719eb63db64978835507cba597eda3224e..78a1f9abe3980d55ad025caa078b3448a2bf82c2 100644 --- a/src/maple_ir/src/mir_type.cpp +++ b/src/maple_ir/src/mir_type.cpp @@ -310,25 +310,24 @@ const std::string &MIRType::GetName(void) const { return GlobalTables::GetStrTable().GetStringFromStrIdx(nameStrIdx); } -bool MIRType::ValidateClassOrInterface(const std::string &className, bool noWarning) { +bool MIRType::ValidateClassOrInterface(const std::string &className, bool noWarning) const { if (primType == maple::PTY_agg && (typeKind == maple::kTypeClass || typeKind == maple::kTypeInterface) && nameStrIdx.GetIdx()) { return true; - } else { - if (!noWarning) { - int len = className.size(); - constexpr int minClassNameLen = 4; - constexpr char suffix[] = "_3B"; - int suffixLen = std::strlen(suffix); - if (len > minClassNameLen && strncmp(className.c_str() + len - suffixLen, suffix, suffixLen) == 0) { - LogInfo::MapleLogger(kLlErr) << "error: missing proper mplt file for " << className << std::endl; - } else { - LogInfo::MapleLogger(kLlErr) << "internal error: type is not java class or interface " - << className << std::endl; - } + } + if (!noWarning) { + int len = className.size(); + constexpr int minClassNameLen = 4; + constexpr char suffix[] = "_3B"; + int suffixLen = std::strlen(suffix); + if (len > minClassNameLen && strncmp(className.c_str() + len - suffixLen, suffix, suffixLen) == 0) { + LogInfo::MapleLogger(kLlErr) << "error: missing proper mplt file for " << className << std::endl; + } else { + LogInfo::MapleLogger(kLlErr) << "internal error: type is not java class or interface " + << className << std::endl; } - return false; } + return false; } bool MIRType::PointsToConstString() const { @@ -338,17 +337,15 @@ bool MIRType::PointsToConstString() const { std::string MIRType::GetMplTypeName() const { if (typeKind == kTypeScalar) { return GetPrimTypeName(primType); - } else { - return ""; } + return ""; } std::string MIRType::GetCompactMplTypeName() const { if (typeKind == kTypeScalar) { return GetPrimTypeJavaName(primType); - } else { - return ""; } + return ""; } void MIRType::Dump(int indent, bool dontUseName) const { @@ -612,12 +609,6 @@ FieldID MIRClassType::GetFirstLocalFieldID() const { return 1; } -// return class id or superclass id accroding to input string -uint32 MIRClassType::GetInfo(const std::string &infoStr) const { - GStrIdx stridx = GlobalTables::GetStrTable().GetStrIdxFromName(infoStr); - return GetInfo(stridx); -} - MIRClassType *MIRClassType::GetExceptionRootType() { GStrIdx ehTypeNameIdx = GlobalTables::GetStrTable().GetStrIdxFromName(NameMangler::kJavaLangObjectStr); MIRClassType *subClassType = this; @@ -652,7 +643,7 @@ FieldID MIRClassType::GetLastFieldID() const { static void DumpClassOrInterfaceInfo(const MIRStructType &type, int indent) { const std::vector &info = type.GetInfo(); - std::vector infoIsString = type.GetIsStringInfo(); + std::vector infoIsString = type.GetInfoIsString(); size_t size = info.size(); for (size_t i = 0; i < size; i++) { LogInfo::MapleLogger() << std::endl; @@ -670,17 +661,24 @@ static void DumpClassOrInterfaceInfo(const MIRStructType &type, int indent) { } } -uint32 MIRInterfaceType::GetInfo(GStrIdx strIdx) const { - size_t size = info.size(); - for (size_t i = 0; i < size; i++) { - if (info[i].first == strIdx) { - return info[i].second; +static uint32 GetInfoFromStrIdx(const std::vector &info, const GStrIdx &strIdx) { + for (MIRInfoPair infoPair : info) { + if (infoPair.first == strIdx) { + return infoPair.second; } } - ASSERT(false, "should not be here"); return 0; } +uint32 MIRInterfaceType::GetInfo(GStrIdx strIdx) const { + return GetInfoFromStrIdx(info, strIdx); +} + +// return class id or superclass id accroding to input string +uint32 MIRInterfaceType::GetInfo(const std::string &infoStr) const { + GStrIdx stridx = GlobalTables::GetStrTable().GetStrIdxFromName(infoStr); + return GetInfo(stridx); +} size_t MIRInterfaceType::GetSize() const { if (parentsTyIdx.empty()) { return MIRStructType::GetSize(); @@ -867,6 +865,31 @@ static void DumpInterfaces(std::vector interfaces, int indent) { } } +size_t MIRStructType::GetSize() const { + if (typeKind == kTypeUnion) { + size_t maxSize = GetElemType(0)->GetSize(); + for (size_t i = 1; i < fields.size(); i++) { + size_t size = GetElemType(i)->GetSize(); + if (size == 0) { + return 0; + } + if (maxSize < size) { + maxSize = size; + } + } + return maxSize; + } + size_t size = 0; + for (size_t i = 0; i < fields.size(); i++) { + size_t fieldSize = GetElemType(i)->GetSize(); + if (fieldSize == 0) { + return 0; + } + size += fieldSize; + } + return size; +} + void MIRStructType::DumpFieldsAndMethods(int indent, bool hasMethod) const { DumpFields(fields, indent); bool hasField = !fields.empty(); @@ -898,19 +921,16 @@ void MIRStructType::Dump(int indent, bool dontUseName) const { LogInfo::MapleLogger() << "}>"; } -static uint32 GetInfoFromStrIdx(const std::vector &info, const GStrIdx &strIdx) { - for (MIRInfoPair infoPair : info) { - if (infoPair.first == strIdx) { - return infoPair.second; - } - } - return 0; -} - uint32 MIRClassType::GetInfo(GStrIdx strIdx) const { return GetInfoFromStrIdx(info, strIdx); } +// return class id or superclass id accroding to input string +uint32 MIRClassType::GetInfo(const std::string &infoStr) const { + GStrIdx stridx = GlobalTables::GetStrTable().GetStrIdxFromName(infoStr); + return GetInfo(stridx); +} + bool MIRClassType::IsFinal() const { uint32 attrStrIdx = GetInfo(GlobalTables::GetStrTable().GetOrCreateStrIdxFromName("INFO_attribute_string")); CHECK(attrStrIdx < GlobalTables::GetStrTable().StringTableSize(), "out of range of vector"); diff --git a/src/maple_ir/src/parser.cpp b/src/maple_ir/src/parser.cpp index 8d61e39c8ceb19652adfdca177fa8e8b69d5c089..89b566b754b7385a99026f048e254c6ef75dbd6a 100644 --- a/src/maple_ir/src/parser.cpp +++ b/src/maple_ir/src/parser.cpp @@ -580,7 +580,7 @@ bool MIRParser::ParsePragma(MIRStructType &type) { } } lexer.NextToken(); - type.AddPragmaVec(p); + type.PushbackPragma(p); return true; } @@ -632,7 +632,7 @@ bool MIRParser::ParseFields(MIRStructType &type) { tk = lexer.NextToken(); if (type.GetKind() == kTypeClass || type.GetKind() == kTypeClassIncomplete || type.GetKind() == kTypeInterface || type.GetKind() == kTypeInterfaceIncomplete) { - type.AddStaticValue(elem); + type.PushbackStaticValue(elem); } else { Error("parsing staticvalue error "); return false; @@ -660,8 +660,8 @@ bool MIRParser::ParseFields(MIRStructType &type) { uint32 infoVal = (tk == kTkIntconst) ? lexer.GetTheIntVal() : GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(lexer.GetName()).GetIdx(); - type.AddInfo(MIRInfoPair(strIdx, infoVal)); - type.AddIsStringInfo(tk != kTkIntconst); + type.PushbackMIRInfo(MIRInfoPair(strIdx, infoVal)); + type.PushbackIsString(tk != kTkIntconst); notaType = true; lexer.NextToken(); } else { @@ -788,7 +788,7 @@ bool MIRParser::ParseFields(MIRStructType &type) { TyIdx tyidx = mod.GetTypeNameTab()->GetTyIdxFromGStrIdx(strIdx); if (tyidx == 0) { MIRInterfaceType interfaceType(kTypeInterfaceIncomplete); - interfaceType.GetNameStrIdx() = strIdx; + interfaceType.SetNameStrIdx(strIdx); tyidx = GlobalTables::GetTypeTable().GetOrCreateMIRType(&interfaceType); mod.AddClass(tyidx); mod.AddExternStructType(tyidx); @@ -857,7 +857,7 @@ bool MIRParser::ParseClassType(TyIdx &styidx) { } } MIRClassType classType(tkind); - classType.GetParentTyIdx() = parentTypeIdx; + classType.SetParentTyIdx(parentTypeIdx); if (!ParseFields(classType)) { return false; } @@ -1105,14 +1105,14 @@ bool MIRParser::ParseDefinedTypename(TyIdx &definedTyIdx, MIRTypeKind kind) { if (definedTyIdx == 0) { if (kind == kTypeInterface || kind == kTypeInterfaceIncomplete) { MIRInterfaceType interfaceType(kTypeInterfaceIncomplete); - interfaceType.GetNameStrIdx() = strIdx; + interfaceType.SetNameStrIdx(strIdx); definedTyIdx = GlobalTables::GetTypeTable().GetOrCreateMIRType(&interfaceType); mod.AddClass(definedTyIdx); mod.AddExternStructType(definedTyIdx); mod.GetTypeNameTab()->SetGStrIdxToTyIdx(strIdx, definedTyIdx); } else if (kind == kTypeClass || kind == kTypeClassIncomplete || IsClassInterfaceTypeName(nameStr)) { MIRClassType classType(kTypeClassIncomplete); - classType.GetNameStrIdx() = strIdx; + classType.SetNameStrIdx(strIdx); definedTyIdx = GlobalTables::GetTypeTable().GetOrCreateMIRType(&classType); mod.AddClass(definedTyIdx); mod.AddExternStructType(definedTyIdx); @@ -1384,7 +1384,7 @@ void MIRParser::FixupForwardReferencedTypeByMap() { MIRClassType *classType = static_cast(type); std::map::iterator it = typeDefIdxMap.find(classType->GetParentTyIdx()); if (it != typeDefIdxMap.end()) { - classType->GetParentTyIdx() = it->second; + classType->SetParentTyIdx(it->second); } for (size_t j = 0; j < classType->GetInterfaceImplemented().size(); j++) { std::map::iterator it2 = typeDefIdxMap.find(classType->GetNthInterfaceImplemented(j)); diff --git a/src/maple_me/include/alias_class.h b/src/maple_me/include/alias_class.h index 94588a094fb7ed4a3b1321329e9d6e5dc77a54e3..7d25132dce89b4a4f29baff60073801c06956651 100644 --- a/src/maple_me/include/alias_class.h +++ b/src/maple_me/include/alias_class.h @@ -65,17 +65,17 @@ class AliasElem { nextLevNotAllDefsSeen = allDefsSeen; } - const MapleSet *GetClassSet() const { + const MapleSet *GetClassSet() const { return classSet; } - void AddClassToSet(uint id) { + void AddClassToSet(unsigned int id) { classSet->emplace(id); } - const MapleSet *GetAssignSet() const { + const MapleSet *GetAssignSet() const { return assignSet; } - void AddAssignToSet(uint id) { + void AddAssignToSet(unsigned int id) { assignSet->emplace(id); } @@ -84,8 +84,8 @@ class AliasElem { OriginalSt &ost; bool notAllDefsSeen; // applied to current level; unused for lev -1 bool nextLevNotAllDefsSeen; // remember that next level's elements need to be made notAllDefsSeen - MapleSet *classSet; // points to the set of members of its class; nullptr for single-member classes - MapleSet *assignSet; // points to the set of members that have assignments among themselves + MapleSet *classSet; // points to the set of members of its class; nullptr for single-member classes + MapleSet *assignSet; // points to the set of members that have assignments among themselves }; class AliasClass : public AnalysisResult { @@ -101,7 +101,7 @@ class AliasClass : public AnalysisResult { osym2Elem(ssatb.GetOriginalStTableSize(), nullptr, acAlloc.Adapter()), id2Elem(acAlloc.Adapter()), notAllDefsSeenClassSetRoots(acAlloc.Adapter()), - globalsAffectedByCalls(std::less(), acAlloc.Adapter()), + globalsAffectedByCalls(std::less(), acAlloc.Adapter()), globalsMayAffectedByClinitCheck(acAlloc.Adapter()), lessThrowAlias(lessThrowAliasParam), finalFieldAlias(finalFieldHasAlias), @@ -144,9 +144,9 @@ class AliasClass : public AnalysisResult { void DumpAssignSets(); void UnionAllPointedTos(); void ApplyUnionForPointedTos(); - void CollectRootIDOfNextLevelNodes(const OriginalSt &ost, std::set &rootIDOfNADSs); + void CollectRootIDOfNextLevelNodes(const OriginalSt &ost, std::set &rootIDOfNADSs); void UnionForNotAllDefsSeen(); - void CollectAliasGroups(std::map> &aliasGroups); + void CollectAliasGroups(std::map> &aliasGroups); bool AliasAccordingToType(TyIdx tyidxA, TyIdx tyidxB); bool AliasAccordingToFieldID(const OriginalSt &ostA, const OriginalSt &ostB); void ReconstructAliasGroups(); @@ -170,7 +170,7 @@ class AliasClass : public AnalysisResult { MapleVector osym2Elem; // index is OStIdx MapleVector id2Elem; // index is the id MapleVector notAllDefsSeenClassSetRoots; // root of the not_all_defs_seen class sets - MapleSet globalsAffectedByCalls; // set of class ids of globals + MapleSet globalsAffectedByCalls; // set of class ids of globals // aliased at calls; needed only when wholeProgramScope is true MapleSet globalsMayAffectedByClinitCheck; bool lessThrowAlias; @@ -187,7 +187,7 @@ class AliasClass : public AnalysisResult { AliasElem *CreateAliasElemsExpr(BaseNode &expr); void SetNotAllDefsSeenForMustDefs(const StmtNode &callas); void SetPtrOpndNextLevNADS(const BaseNode &opnd, AliasElem *ae, bool hasNoPrivateDefEffect); - void SetPtrOpndsNextLevNADS(uint start, uint end, MapleVector &opnds, bool hasNoPrivateDefEffect); + void SetPtrOpndsNextLevNADS(unsigned int start, unsigned int end, MapleVector &opnds, bool hasNoPrivateDefEffect); void ApplyUnionForDassignCopy(const AliasElem &lhsAe, const AliasElem *rhsAe, const BaseNode &rhs); AliasElem *FindOrCreateDummyNADSAe(); void CollectMayDefForMustDefs(const StmtNode &stmt, std::set &mayDefOsts); @@ -217,7 +217,7 @@ class AliasClass : public AnalysisResult { void InsertMayDefUseIntrncall(StmtNode &stmt, BBId bbid); void InsertMayDefUseClinitCheck(IntrinsiccallNode &stmt, BBId bbid); virtual BB *GetBB(BBId id) = 0; - void ProcessIdsAliasWithRoot(const std::set &idsAliasWithRoot, std::vector &newGroups); + void ProcessIdsAliasWithRoot(const std::set &idsAliasWithRoot, std::vector &newGroups); void UpdateNextLevelNodes(std::vector &nextLevelOsts, const AliasElem &aliasElem); void UnionNodes(std::vector &nextLevelOsts); int GetOffset(const Klass &super, Klass &base) const; diff --git a/src/maple_me/include/me_cfg.h b/src/maple_me/include/me_cfg.h index baf0ca24481b62200140b22e65053d8c487c690e..080bf87abcde27a96f5258b20290c611a61b9768 100644 --- a/src/maple_me/include/me_cfg.h +++ b/src/maple_me/include/me_cfg.h @@ -53,6 +53,12 @@ class MeCFG { private: MeFunction &func; bool hasDoWhile = false; + + std::string ConstructFileNameToDump(const std::string &prefix) const; + void DumpToFileInStrs(std::ofstream &cfgFile) const; + void ConvertPhiList2IdentityAssigns(BB &meBB) const; + void ConvertMevarPhiList2IdentityAssigns(BB &meBB) const; + void ConvertMeregphiList2IdentityAssigns(BB &meBB) const; }; } // namespace maple #endif // MAPLE_ME_INCLUDE_ME_CFG_H diff --git a/src/maple_me/include/union_find.h b/src/maple_me/include/union_find.h index 36591f2015b338f3105c49b902297ca87e853586..f72ac1939238bbc3414a66c39f0c1ae9a2c116e2 100644 --- a/src/maple_me/include/union_find.h +++ b/src/maple_me/include/union_find.h @@ -39,8 +39,8 @@ class UnionFind { ~UnionFind() { // for the root id's, the sum of their size should be population size #if DEBUG - uint sum = 0; - for (uint i = 0; i < num; i++) + unsigned int sum = 0; + for (unsigned int i = 0; i < num; i++) if (id[i] == i) { // it is a root sum += sz[i]; @@ -50,19 +50,19 @@ class UnionFind { } void Reinit() { - for (uint i = 0; i < num; i++) { + for (unsigned int i = 0; i < num; i++) { id[i] = i; sz[i] = 1; } } - uint NewMember() { + unsigned int NewMember() { id.push_back(num); // new member is its own root sz.push_back(1); return ++num; } - uint Root(uint i) { + unsigned int Root(unsigned int i) { while (id[i] != i) { id[i] = id[id[i]]; // this compresses the path i = id[i]; @@ -70,13 +70,13 @@ class UnionFind { return i; } - bool Find(uint p, uint q) { + bool Find(unsigned int p, unsigned int q) { return Root(p) == Root(q); } - void Union(uint p, uint q) { - uint i = Root(p); - uint j = Root(q); + void Union(unsigned int p, unsigned int q) { + unsigned int i = Root(p); + unsigned int j = Root(q); if (i == j) { return; } @@ -90,26 +90,26 @@ class UnionFind { } } - uint GetElementsNumber(int i) const { + unsigned int GetElementsNumber(int i) const { ASSERT(i < sz.size(), "index out of range"); return sz[i]; } - bool SingleMemberClass(uint p) { - uint i = Root(p); + bool SingleMemberClass(unsigned int p) { + unsigned int i = Root(p); ASSERT(i < sz.size(), "index out of range"); return sz[i] == 1; } private: MapleAllocator ufAlloc; - uint num; // the population size; can continue to increase - MapleVector id; // array index is id of each population member; + unsigned int num; // the population size; can continue to increase + MapleVector id; // array index is id of each population member; // value is id of the root member of its class; // the member is a root if its value is itself; // as its root changes, will keep updating so as to // maintain a flat tree - MapleVector sz; // gives number of elements in the tree rooted there + MapleVector sz; // gives number of elements in the tree rooted there }; } // namespace maple #endif // MAPLE_ME_INCLUDE_UNION_FIND_H diff --git a/src/maple_me/src/alias_class.cpp b/src/maple_me/src/alias_class.cpp index 93b80a7866f40354409b7b4ee0d3035e82c8e9d7..2808ae2df404e0a50880806cecccc054ece953c4 100644 --- a/src/maple_me/src/alias_class.cpp +++ b/src/maple_me/src/alias_class.cpp @@ -186,9 +186,10 @@ void AliasClass::SetPtrOpndNextLevNADS(const BaseNode &opnd, AliasElem *ae, bool } // Set ae of the pointer-type opnds of a call as next_level_not_all_defines_seen -void AliasClass::SetPtrOpndsNextLevNADS(uint start, uint end, MapleVector &opnds, +void AliasClass::SetPtrOpndsNextLevNADS(unsigned int start, unsigned int end, + MapleVector &opnds, bool hasNoPrivateDefEffect) { - for (uint i = start; i < end; i++) { + for (unsigned int i = start; i < end; i++) { BaseNode *opnd = opnds[i]; SetPtrOpndNextLevNADS(*opnd, CreateAliasElemsExpr(*opnd), hasNoPrivateDefEffect); } @@ -273,12 +274,13 @@ void AliasClass::ApplyUnionForCopies(StmtNode &stmt) { void AliasClass::CreateAssignSets() { // iterate through all the alias elems for (AliasElem *aliasElem : id2Elem) { - uint id = aliasElem->GetClassID(); - uint rootID = unionFind.Root(id); + unsigned int id = aliasElem->GetClassID(); + unsigned int rootID = unionFind.Root(id); if (unionFind.GetElementsNumber(rootID) > 1) { // only root id's have assignset if (id2Elem[rootID]->GetAssignSet() == nullptr) { - id2Elem[rootID]->assignSet = acMemPool.New>(std::less(), acAlloc.Adapter()); + id2Elem[rootID]->assignSet = acMemPool.New>(std::less(), + acAlloc.Adapter()); } id2Elem[rootID]->AddAssignToSet(id); } @@ -298,7 +300,7 @@ void AliasClass::DumpAssignSets() { LogInfo::MapleLogger() << '\n'; } else { LogInfo::MapleLogger() << "Members of assign set " << aliasElem->GetClassID() << ": "; - for (uint elemID : *(aliasElem->GetAssignSet())) { + for (unsigned int elemID : *(aliasElem->GetAssignSet())) { id2Elem[elemID]->Dump(mirModule); } LogInfo::MapleLogger() << '\n'; @@ -320,7 +322,7 @@ void AliasClass::UnionAllPointedTos() { } void AliasClass::UpdateNextLevelNodes(std::vector &nextLevelOsts, const AliasElem &aliasElem) { - for (uint elemID : *(aliasElem.GetAssignSet())) { + for (unsigned int elemID : *(aliasElem.GetAssignSet())) { for (OriginalSt *nextLevelNode : *(GetAliasAnalysisTable()->GetNextLevelNodes(id2Elem[elemID]->GetOriginalSt()))) { nextLevelOsts.push_back(nextLevelNode); } @@ -354,7 +356,8 @@ void AliasClass::ApplyUnionForPointedTos() { } } -void AliasClass::CollectRootIDOfNextLevelNodes(const OriginalSt &ost, std::set &rootIDOfNADSs) { +void AliasClass::CollectRootIDOfNextLevelNodes(const OriginalSt &ost, + std::set &rootIDOfNADSs) { for (OriginalSt *nextLevelNode : *(GetAliasAnalysisTable()->GetNextLevelNodes(ost))) { if (finalFieldAlias || !nextLevelNode->IsFinal()) { uint32 id = FindAliasElem(*nextLevelNode)->GetClassID(); @@ -364,7 +367,7 @@ void AliasClass::CollectRootIDOfNextLevelNodes(const OriginalSt &ost, std::set rootIDOfNADSs; + std::set rootIDOfNADSs; for (AliasElem *ae : id2Elem) { if (ae->GetAssignSet() == nullptr) { if (ae->IsNotAllDefsSeen() || ae->IsNextLevNotAllDefsSeen()) { @@ -372,10 +375,10 @@ void AliasClass::UnionForNotAllDefsSeen() { } continue; } - for (uint elemIdA : *(ae->GetAssignSet())) { + for (unsigned int elemIdA : *(ae->GetAssignSet())) { AliasElem *aeA = id2Elem[elemIdA]; if (aeA->IsNotAllDefsSeen() || aeA->IsNextLevNotAllDefsSeen()) { - for (uint elemIdB : *(ae->GetAssignSet())) { + for (unsigned int elemIdB : *(ae->GetAssignSet())) { CollectRootIDOfNextLevelNodes(id2Elem[elemIdB]->GetOriginalSt(), rootIDOfNADSs); } break; @@ -383,9 +386,9 @@ void AliasClass::UnionForNotAllDefsSeen() { } } if (!rootIDOfNADSs.empty()) { - uint elemIdA = *(rootIDOfNADSs.begin()); + unsigned int elemIdA = *(rootIDOfNADSs.begin()); rootIDOfNADSs.erase(rootIDOfNADSs.begin()); - for (uint elemIdB : rootIDOfNADSs) { + for (unsigned int elemIdB : rootIDOfNADSs) { unionFind.Union(elemIdA, elemIdB); } for (AliasElem *ae : id2Elem) { @@ -417,17 +420,17 @@ AliasElem *AliasClass::FindOrCreateDummyNADSAe() { // TBAA // Collect the alias groups. Each alias group is a map that maps the rootId to the ids aliasing with the root. -void AliasClass::CollectAliasGroups(std::map> &aliasGroups) { +void AliasClass::CollectAliasGroups(std::map> &aliasGroups) { // key is the root id. The set contains ids of aes that alias with the root. for (AliasElem *ae : id2Elem) { - uint id = ae->GetClassID(); - uint rootID = unionFind.Root(id); + unsigned int id = ae->GetClassID(); + unsigned int rootID = unionFind.Root(id); if (id == rootID) { continue; } if (aliasGroups.find(rootID) == aliasGroups.end()) { - std::set idsAliasWithRoot; + std::set idsAliasWithRoot; aliasGroups.insert(make_pair(rootID, idsAliasWithRoot)); } aliasGroups[rootID].insert(id); @@ -502,10 +505,11 @@ bool AliasClass::AliasAccordingToFieldID(const OriginalSt &ostA, const OriginalS return fldA == ostB.GetFieldID(); } -void AliasClass::ProcessIdsAliasWithRoot(const std::set &idsAliasWithRoot, std::vector &newGroups) { - for (uint idA : idsAliasWithRoot) { +void AliasClass::ProcessIdsAliasWithRoot(const std::set &idsAliasWithRoot, + std::vector &newGroups) { + for (unsigned int idA : idsAliasWithRoot) { bool unioned = false; - for (uint idB : newGroups) { + for (unsigned int idB : newGroups) { OriginalSt &ostA = id2Elem[idA]->GetOriginalSt(); OriginalSt &ostB = id2Elem[idB]->GetOriginalSt(); if (AliasAccordingToType(GetAliasAnalysisTable()->GetPrevLevelNode(ostA)->GetTyIdx(), @@ -524,14 +528,14 @@ void AliasClass::ProcessIdsAliasWithRoot(const std::set &idsAliasWithRoot, void AliasClass::ReconstructAliasGroups() { // map the root id to the set contains the ae-id that alias with the root. - std::map> aliasGroups; + std::map> aliasGroups; CollectAliasGroups(aliasGroups); unionFind.Reinit(); // kv.first is the root id. kv.second is the id the alias with the root. for (auto oneGroup : aliasGroups) { - std::vector newGroups; // contains one id of each new alias group. - uint rootId = oneGroup.first; - std::set idsAliasWithRoot = oneGroup.second; + std::vector newGroups; // contains one id of each new alias group. + unsigned int rootId = oneGroup.first; + std::set idsAliasWithRoot = oneGroup.second; newGroups.push_back(rootId); ProcessIdsAliasWithRoot(idsAliasWithRoot, newGroups); } @@ -548,11 +552,12 @@ void AliasClass::CollectNotAllDefsSeenAes() { void AliasClass::CreateClassSets() { // iterate through all the alias elems for (AliasElem *aliasElem : id2Elem) { - uint id = aliasElem->GetClassID(); - uint rootID = unionFind.Root(id); + unsigned int id = aliasElem->GetClassID(); + unsigned int rootID = unionFind.Root(id); if (unionFind.GetElementsNumber(rootID) > 1) { if (id2Elem[rootID]->GetClassSet() == nullptr) { - id2Elem[rootID]->classSet = acMemPool.New>(std::less(), acAlloc.Adapter()); + id2Elem[rootID]->classSet = acMemPool.New>(std::less(), + acAlloc.Adapter()); } aliasElem->classSet = id2Elem[rootID]->classSet; aliasElem->AddClassToSet(id); @@ -588,7 +593,7 @@ void AliasClass::DumpClassSets() { LogInfo::MapleLogger() << '\n'; } else { LogInfo::MapleLogger() << "Members of alias class " << aliaselem->GetClassID() << ": "; - for (uint elemID : *(aliaselem->GetClassSet())) { + for (unsigned int elemID : *(aliaselem->GetClassSet())) { id2Elem[elemID]->Dump(mirModule); } LogInfo::MapleLogger() << '\n'; @@ -615,7 +620,7 @@ void AliasClass::InsertMayUseExpr(BaseNode &expr) { // collect the mayUses caused by globalsAffectedByCalls. void AliasClass::CollectMayUseFromGlobalsAffectedByCalls(std::set &mayUseOsts) { - for (uint elemID : globalsAffectedByCalls) { + for (unsigned int elemID : globalsAffectedByCalls) { mayUseOsts.insert(&id2Elem[elemID]->GetOriginalSt()); } } @@ -627,7 +632,7 @@ void AliasClass::CollectMayUseFromNADS(std::set &mayUseOsts) { // single mayUse mayUseOsts.insert(¬AllDefsSeenAE->GetOriginalSt()); } else { - for (uint elemID : *(notAllDefsSeenAE->GetClassSet())) { + for (unsigned int elemID : *(notAllDefsSeenAE->GetClassSet())) { AliasElem *ae = id2Elem[elemID]; if (!OriginalStIsZeroLevAndAuto(ae->GetOriginalSt())) { mayUseOsts.insert(&ae->GetOriginalSt()); @@ -667,7 +672,7 @@ void AliasClass::CollectPtsToOfReturnOpnd(const OriginalSt &ost, std::setGetClassSet() == nullptr) { mayUseOsts.insert(&indAe->GetOriginalSt()); } else { - for (uint elemID : *(indAe->GetClassSet())) { + for (unsigned int elemID : *(indAe->GetClassSet())) { mayUseOsts.insert(&id2Elem[elemID]->GetOriginalSt()); } } @@ -687,7 +692,7 @@ void AliasClass::InsertReturnOpndMayUse(const StmtNode &stmt) { if (ae->GetAssignSet() == nullptr) { CollectPtsToOfReturnOpnd(ae->GetOriginalSt(), mayUseOsts); } else { - for (uint elemID : *(ae->GetAssignSet())) { + for (unsigned int elemID : *(ae->GetAssignSet())) { CollectPtsToOfReturnOpnd(id2Elem[elemID]->GetOriginalSt(), mayUseOsts); } } @@ -715,7 +720,7 @@ void AliasClass::CollectMayDefForDassign(const StmtNode &stmt, std::setGetSSAVar()->GetOrigIdx().idx); ASSERT(lhsAe != nullptr, "aliaselem of lhs should not be null"); if (lhsAe->GetClassSet() != nullptr) { - for (uint elemID : *(lhsAe->GetClassSet())) { + for (unsigned int elemID : *(lhsAe->GetClassSet())) { if (elemID != lhsAe->GetClassID()) { OriginalSt &ostOfAliasAE = id2Elem[elemID]->GetOriginalSt(); if (ostOfAliasAE.GetTyIdx() == lhsAe->GetOriginalSt().GetMIRSymbol()->GetTyIdx()) { @@ -777,7 +782,7 @@ void AliasClass::CollectMayDefForIassign(StmtNode &stmt, std::set & mayDefOsts.insert(&lhsAe->GetOriginalSt()); return; } - for (uint elemID : *(lhsAe->GetClassSet())) { + for (unsigned int elemID : *(lhsAe->GetClassSet())) { AliasElem *aliasElem = id2Elem[elemID]; OriginalSt &ostOfAliasAE = aliasElem->GetOriginalSt(); if (aliasElem != lhsAe && OriginalStIsZeroLevAndAuto(ostOfAliasAE)) { @@ -811,7 +816,7 @@ void AliasClass::InsertMayDefIassign(StmtNode &stmt, BBId bbID) { } void AliasClass::InsertMayDefUseSyncOps(StmtNode &stmt, BBId bbID) { - std::set aliasSet; + std::set aliasSet; // collect the full alias set first for (size_t i = 0; i < stmt.NumOpnds(); i++) { BaseNode *addrBase = stmt.Opnd(i); @@ -840,7 +845,7 @@ void AliasClass::InsertMayDefUseSyncOps(StmtNode &stmt, BBId bbID) { } // do the insertion according to aliasSet MayDefMayUsePart *theSSAPart = static_cast(ssaTab.GetStmtsSSAPart().SSAPartOf(stmt)); - for (uint elemid : aliasSet) { + for (unsigned int elemid : aliasSet) { AliasElem *aliasElem = id2Elem[elemid]; OriginalSt &ostOfAliasAE = aliasElem->GetOriginalSt(); if (!ostOfAliasAE.IsFinal() && !OriginalStIsZeroLevAndAuto(ostOfAliasAE)) { @@ -862,7 +867,7 @@ void AliasClass::CollectMayDefForMustDefs(const StmtNode &stmt, std::setGetClassSet() == nullptr || lhsAe->IsNotAllDefsSeen()) { continue; } - for (uint elemID : *(lhsAe->GetClassSet())) { + for (unsigned int elemID : *(lhsAe->GetClassSet())) { AliasElem *ae = id2Elem[elemID]; if (elemID != lhsAe->GetClassID() && ae->GetOriginalSt().GetTyIdx() == lhsAe->GetOriginalSt().GetMIRSymbol()->GetTyIdx()) { @@ -900,7 +905,7 @@ void AliasClass::CollectMayUseForCallOpnd(const StmtNode &stmt, std::setGetClassSet() == nullptr) { mayUseOsts.insert(&indAe->GetOriginalSt()); } else { - for (uint elemID : *(indAe->GetClassSet())) { + for (unsigned int elemID : *(indAe->GetClassSet())) { mayUseOsts.insert(&id2Elem[elemID]->GetOriginalSt()); } } diff --git a/src/maple_me/src/me_cfg.cpp b/src/maple_me/src/me_cfg.cpp index a826b8e4b7efd571a54f0bb78139782432f59dfb..7c88a915345b9940d02bb94f94cdf43af456f0fd 100644 --- a/src/maple_me/src/me_cfg.cpp +++ b/src/maple_me/src/me_cfg.cpp @@ -453,8 +453,7 @@ void MeCFG::FixMirCFG() { } -// used only after DSE because it looks at live field of VersionSt -void MeCFG::ConvertPhis2IdentityAssigns(BB &meBB) const { +void MeCFG::ConvertPhiList2IdentityAssigns(BB &meBB) const { auto phiIt = meBB.GetPhiList().begin(); while (phiIt != meBB.GetPhiList().end()) { if (!(*phiIt).second.GetResult()->IsLive()) { @@ -467,13 +466,13 @@ void MeCFG::ConvertPhis2IdentityAssigns(BB &meBB) const { const MIRSymbol *st = ost->GetMIRSymbol(); MIRType *type = GlobalTables::GetTypeTable().GetTypeFromTyIdx(st->GetTyIdx()); AddrofNode *dread = func.GetMIRModule().GetMIRBuilder()->CreateDread(*st, GetRegPrimType(type->GetPrimType())); - AddrofSSANode *dread2 = func.GetMirFunc()->GetCodeMemPool()->New(dread); + auto *dread2 = func.GetMirFunc()->GetCodeMemPool()->New(dread); dread2->SetSSAVar((*phiIt).second.GetPhiOpnd(0)); DassignNode *dassign = func.GetMIRModule().GetMIRBuilder()->CreateStmtDassign(*st, 0, dread2); func.GetMeSSATab()->GetStmtsSSAPart().SetSSAPartOf( *dassign, func.GetMeSSATab()->GetStmtsSSAPart().GetSSAPartMp()->New( &func.GetMeSSATab()->GetStmtsSSAPart().GetSSAPartAlloc())); - MayDefPartWithVersionSt *theSSAPart = + auto *theSSAPart = static_cast(func.GetMeSSATab()->GetStmtsSSAPart().SSAPartOf(*dassign)); theSSAPart->SetSSAVar(*((*phiIt).second.GetResult())); meBB.PrependStmtNode(dassign); @@ -481,6 +480,9 @@ void MeCFG::ConvertPhis2IdentityAssigns(BB &meBB) const { phiIt++; } meBB.ClearPhiList(); // delete all the phis +} + +void MeCFG::ConvertMevarPhiList2IdentityAssigns(BB &meBB) const { auto varPhiIt = meBB.GetMevarPhiList().begin(); while (varPhiIt != meBB.GetMevarPhiList().end()) { if (!(*varPhiIt).second->GetIsLive()) { @@ -490,7 +492,7 @@ void MeCFG::ConvertPhis2IdentityAssigns(BB &meBB) const { // replace phi with identify assignment as it only has 1 opnd const OriginalSt *ost = func.GetMeSSATab()->GetOriginalStFromID(varPhiIt->first); if (ost->IsSymbolOst() && ost->GetIndirectLev() == 0) { - DassignMeStmt *dassign = func.GetIRMap()->NewInPool(); + auto *dassign = func.GetIRMap()->NewInPool(); MeVarPhiNode *varPhi = varPhiIt->second; dassign->SetLHS(varPhi->GetLHS()); dassign->SetRHS(varPhi->GetOpnd(0)); @@ -501,6 +503,9 @@ void MeCFG::ConvertPhis2IdentityAssigns(BB &meBB) const { varPhiIt++; } meBB.GetMevarPhiList().clear(); // delete all the phis +} + +void MeCFG::ConvertMeregphiList2IdentityAssigns(BB &meBB) const { auto regPhiIt = meBB.GetMeregphiList().begin(); while (regPhiIt != meBB.GetMeregphiList().end()) { if (!(*regPhiIt).second->GetIsLive()) { @@ -510,7 +515,7 @@ void MeCFG::ConvertPhis2IdentityAssigns(BB &meBB) const { // replace phi with identify assignment as it only has 1 opnd const OriginalSt *ost = func.GetMeSSATab()->GetOriginalStFromID(regPhiIt->first); if (ost->IsSymbolOst() && ost->GetIndirectLev() == 0) { - RegassignMeStmt *regass = func.GetIRMap()->New(); + auto *regass = func.GetIRMap()->New(); MeRegPhiNode *regPhi = regPhiIt->second; regass->SetLHS(regPhi->GetLHS()); regass->SetRHS(regPhi->GetOpnd(0)); @@ -523,6 +528,13 @@ void MeCFG::ConvertPhis2IdentityAssigns(BB &meBB) const { meBB.GetMeregphiList().clear(); // delete all the phis } +// used only after DSE because it looks at live field of VersionSt +void MeCFG::ConvertPhis2IdentityAssigns(BB &meBB) const { + ConvertPhiList2IdentityAssigns(meBB); + ConvertMevarPhiList2IdentityAssigns(meBB); + ConvertMeregphiList2IdentityAssigns(meBB); +} + // analyse the CFG to find the BBs that are not reachable from function entries // and delete them void MeCFG::UnreachCodeAnalysis(bool updatePhi) { @@ -763,15 +775,7 @@ static bool ContainsConststr(const BaseNode &x) { return false; } -/* generate dot file for cfg */ -void MeCFG::DumpToFile(const std::string &prefix, bool dumpInStrs) const { - if (MeOption::noDot) { - return; - } - std::ofstream cfgFile; - std::streambuf *coutBuf = LogInfo::MapleLogger().rdbuf(); /* keep original cout buffer */ - std::streambuf *buf = cfgFile.rdbuf(); - LogInfo::MapleLogger().rdbuf(buf); +std::string MeCFG::ConstructFileNameToDump(const std::string &prefix) const { std::string fileName; if (!prefix.empty()) { fileName.append(prefix); @@ -785,6 +789,51 @@ void MeCFG::DumpToFile(const std::string &prefix, bool dumpInStrs) const { } ReplaceFilename(fileName); fileName.append(".dot"); + return fileName; +} + +void MeCFG::DumpToFileInStrs(std::ofstream &cfgFile) const { + const auto &eIt = func.valid_end(); + for (auto bIt = func.valid_begin(); bIt != eIt; ++bIt) { + auto *bb = *bIt; + if (bb->IsEmpty()) { + continue; + } + if (bb->GetKind() == kBBCondGoto) { + cfgFile << "BB" << bb->GetBBId().idx << "[shape=diamond,label= \" BB" << bb->GetBBId().idx << ":\n{ "; + } else { + cfgFile << "BB" << bb->GetBBId().idx << "[shape=box,label= \" BB" << bb->GetBBId().idx << ":\n{ "; + } + if (bb->GetBBLabel() != 0) { + cfgFile << "@" << func.GetMirFunc()->GetLabelName(bb->GetBBLabel()) << ":\n"; + } + for (auto phiIt = bb->GetPhiList().begin(); phiIt != bb->GetPhiList().end(); phiIt++) { + (*phiIt).second.Dump(&(func.GetMIRModule())); + } + for (auto &stmt : bb->GetStmtNodes()) { + // avoid printing content that may contain " as this needs to be quoted + if (stmt.GetOpCode() == OP_comment) { + continue; + } + if (ContainsConststr(stmt)) { + continue; + } + stmt.Dump(func.GetMIRModule(), 1); + } + cfgFile << "}\"];\n"; + } +} + +/* generate dot file for cfg */ +void MeCFG::DumpToFile(const std::string &prefix, bool dumpInStrs) const { + if (MeOption::noDot) { + return; + } + std::ofstream cfgFile; + std::streambuf *coutBuf = LogInfo::MapleLogger().rdbuf(); /* keep original cout buffer */ + std::streambuf *buf = cfgFile.rdbuf(); + LogInfo::MapleLogger().rdbuf(buf); + const std::string &fileName = ConstructFileNameToDump(prefix); cfgFile.open(fileName.c_str(), std::ios::trunc); cfgFile << "digraph {\n"; cfgFile << " # /*" << func.GetName().c_str() << " (red line is exception handler)*/\n"; @@ -817,35 +866,7 @@ void MeCFG::DumpToFile(const std::string &prefix, bool dumpInStrs) const { } /* dump instruction in each BB */ if (dumpInStrs) { - eIt = func.valid_end(); - for (auto bIt = func.valid_begin(); bIt != eIt; ++bIt) { - auto *bb = *bIt; - if (bb->IsEmpty()) { - continue; - } - if (bb->GetKind() == kBBCondGoto) { - cfgFile << "BB" << bb->GetBBId().idx << "[shape=diamond,label= \" BB" << bb->GetBBId().idx << ":\n{ "; - } else { - cfgFile << "BB" << bb->GetBBId().idx << "[shape=box,label= \" BB" << bb->GetBBId().idx << ":\n{ "; - } - if (bb->GetBBLabel() != 0) { - cfgFile << "@" << func.GetMirFunc()->GetLabelName(bb->GetBBLabel()) << ":\n"; - } - for (auto phiIt = bb->GetPhiList().begin(); phiIt != bb->GetPhiList().end(); phiIt++) { - (*phiIt).second.Dump(&(func.GetMIRModule())); - } - for (auto &stmt : bb->GetStmtNodes()) { - // avoid printing content that may contain " as this needs to be quoted - if (stmt.GetOpCode() == OP_comment) { - continue; - } - if (ContainsConststr(stmt)) { - continue; - } - stmt.Dump(func.GetMIRModule(), 1); - } - cfgFile << "}\"];\n"; - } + DumpToFileInStrs(cfgFile); } cfgFile << "}\n"; cfgFile.flush(); diff --git a/src/maple_phase/include/phase.h b/src/maple_phase/include/phase.h index c1fded6b4be94c0fc0d4860269ee19378a62b9ad..37c0647e5730a8eead2ec5d2ec13bfcae3c2e213 100644 --- a/src/maple_phase/include/phase.h +++ b/src/maple_phase/include/phase.h @@ -83,7 +83,7 @@ class Phase { virtual ~Phase(){}; private: - uint memPoolCount = 0; + unsigned int memPoolCount = 0; std::vector memPools; }; diff --git a/src/mempool/include/mempool.h b/src/mempool/include/mempool.h index c2aad9a1d32765d63e3a0e125911b2cfd7f032bf..82f32a8862e6cbddd5c37590562f746526cbe8ac 100644 --- a/src/mempool/include/mempool.h +++ b/src/mempool/include/mempool.h @@ -22,10 +22,15 @@ #include "mir_config.h" #include "mpl_logging.h" -namespace maple { +namespace maple { +#ifdef _WIN32 +#define FALSE 0 +#define TRUE 1 +#else constexpr bool FALSE = false; constexpr bool TRUE = true; +#endif // Class declaration class MemPool; diff --git a/src/mpl2mpl/include/class_hierarchy.h b/src/mpl2mpl/include/class_hierarchy.h index ff1126deb969593a293e6ca7bbc0a4112974300c..5a7bd575abc896ce307da7de8d195a79b7269d5d 100644 --- a/src/mpl2mpl/include/class_hierarchy.h +++ b/src/mpl2mpl/include/class_hierarchy.h @@ -83,7 +83,7 @@ class Klass { public: Klass(MIRStructType *type, MapleAllocator *alc); - ~Klass() {} + ~Klass() = default; // Return true if Klass represents an interface bool IsInterface() const { @@ -246,10 +246,10 @@ class Klass { } // Return a vector of possible functions - MapleVector *GetCandidates(GStrIdx mnameNoklassStridx) const; + MapleVector *GetCandidates(GStrIdx mnameNoklassStrIdx) const; // Return the unique method if there is only one target virtual function. // Return nullptr if there are multiple targets. - MIRFunction *GetUniqueMethod(GStrIdx mnameNoklassStridx) const; + MIRFunction *GetUniqueMethod(GStrIdx mnameNoklassStrIdx) const; void AddSuperKlass(Klass *superclass) { superKlasses.push_back(superclass); } @@ -322,11 +322,11 @@ class KlassHierarchy : public AnalysisResult { public: static bool traceFlag; KlassHierarchy(MIRModule *mirmodule, MemPool *memPool); - virtual ~KlassHierarchy() {} + virtual ~KlassHierarchy() = default; // Get a class. Return nullptr it does not exist. - Klass *GetKlassFromStrIdx(GStrIdx stridx) const; - Klass *GetKlassFromTyIdx(TyIdx tyidx) const; + Klass *GetKlassFromStrIdx(GStrIdx strIdx) const; + Klass *GetKlassFromTyIdx(TyIdx tyIdx) const; Klass *GetKlassFromFunc(const MIRFunction *func) const; Klass *GetKlassFromName(const std::string &name) const; Klass *GetKlassFromLiteral(const std::string &name) const; diff --git a/src/mpl2mpl/include/class_init.h b/src/mpl2mpl/include/class_init.h index 29719d91108c2803aa88206ab7ce9d63b88f27a1..2fb5d3ce35791f1b4987e9f66ee49449e322e498 100644 --- a/src/mpl2mpl/include/class_init.h +++ b/src/mpl2mpl/include/class_init.h @@ -24,7 +24,7 @@ static constexpr char kMCCPostClinitCheck[] = "MCC_PostClinitCheck"; class ClassInit : public FuncOptimizeImpl { public: ClassInit(MIRModule *mod, KlassHierarchy *kh, bool dump); - ~ClassInit() {} + ~ClassInit() = default; FuncOptimizeImpl *Clone() override { return new (std::nothrow) ClassInit(*this); @@ -44,7 +44,7 @@ class DoClassInit : public ModulePhase { public: explicit DoClassInit(ModulePhaseID id) : ModulePhase(id) {} - ~DoClassInit() {} + ~DoClassInit() = default; std::string PhaseName() const override { return "clinit"; diff --git a/src/mpl2mpl/include/gen_check_cast.h b/src/mpl2mpl/include/gen_check_cast.h index 977d2c7ec566e0ff53f29cdf05e676ed41568456..9136b9ac1710ff731137c77bf409f1b4e036a706 100644 --- a/src/mpl2mpl/include/gen_check_cast.h +++ b/src/mpl2mpl/include/gen_check_cast.h @@ -55,7 +55,7 @@ class DoCheckCastGeneration : public ModulePhase { public: explicit DoCheckCastGeneration(ModulePhaseID id) : ModulePhase(id) {} - ~DoCheckCastGeneration() {} + ~DoCheckCastGeneration() = default; std::string PhaseName() const override { return "gencheckcast"; diff --git a/src/mpl2mpl/include/java_intrn_lowering.h b/src/mpl2mpl/include/java_intrn_lowering.h index 4337ffff678fcf92bf68f61095a79cd1151305ac..9fccb8e065223d541d04ecdc7cee578e9ca07f5f 100644 --- a/src/mpl2mpl/include/java_intrn_lowering.h +++ b/src/mpl2mpl/include/java_intrn_lowering.h @@ -23,7 +23,7 @@ namespace maple { class JavaIntrnLowering : public FuncOptimizeImpl { public: JavaIntrnLowering(MIRModule *mod, KlassHierarchy *kh, bool dump); - ~JavaIntrnLowering() {} + ~JavaIntrnLowering() = default; FuncOptimizeImpl *Clone() override { return new JavaIntrnLowering(*this); @@ -40,7 +40,7 @@ class DoJavaIntrnLowering : public ModulePhase { public: explicit DoJavaIntrnLowering(ModulePhaseID id) : ModulePhase(id) {} - ~DoJavaIntrnLowering() {} + ~DoJavaIntrnLowering() = default; std::string PhaseName() const override { return "javaintrnlowering"; diff --git a/src/mpl2mpl/include/muid_replacement.h b/src/mpl2mpl/include/muid_replacement.h index f8b8aa56162b16d6ab2a3505c6fe94f26b2a3236..d22a4b8c6348e5dab2c5b9d2b8a165a2d08eb105 100644 --- a/src/mpl2mpl/include/muid_replacement.h +++ b/src/mpl2mpl/include/muid_replacement.h @@ -58,7 +58,7 @@ enum RangeIdx { class MUIDReplacement : public FuncOptimizeImpl { public: MUIDReplacement(MIRModule *mod, KlassHierarchy *kh, bool dump); - ~MUIDReplacement() {} + ~MUIDReplacement() = default; FuncOptimizeImpl *Clone() override { return new (std::nothrow) MUIDReplacement(*this); @@ -67,11 +67,11 @@ class MUIDReplacement : public FuncOptimizeImpl { void ProcessFunc(MIRFunction *func) override; static void SetMplMd5(MUID muid) { - kMplMuid = muid; + mplMuid = muid; } static MUID &GetMplMd5() { - return kMplMuid; + return mplMuid; } private: @@ -90,7 +90,7 @@ class MUIDReplacement : public FuncOptimizeImpl { MIRSymbol *funcMuidIdxTabSym = nullptr; MIRSymbol *rangeTabSym = nullptr; MIRSymbol *funcProfileTabSym = nullptr; - static MUID kMplMuid; + static MUID mplMuid; std::string mplMuidStr; using SymIdxPair = std::pair; std::map funcDefMap; @@ -111,7 +111,7 @@ class MUIDReplacement : public FuncOptimizeImpl { void GenericRangeTable(); uint32 FindIndexFromDefTable(const MIRSymbol &mirSymbol, bool isFunc); uint32 FindIndexFromUndefTable(const MIRSymbol &mirSymbol, bool isFunc); - void ReplaceAddroffuncConst(MIRConst *&entry, uint32 fieldId, bool isVtab); + void ReplaceAddroffuncConst(MIRConst *&entry, uint32 fieldID, bool isVtab); void ReplaceFuncTable(const std::string &name); void ReplaceAddrofConst(MIRConst *&entry); void ReplaceDataTable(const std::string &name); @@ -155,12 +155,12 @@ class MUIDReplacement : public FuncOptimizeImpl { #define __MRT_MAGIC_PASTE(x, y) __MRT_MAGIC_PASTE2(x, y) #define __MRT_MAGIC_PASTE2(x, y) x##y #define CLASS_PREFIX(classname) TO_STR(__MRT_MAGIC_PASTE(CLASSINFO_PREFIX, classname)), - const std::unordered_set kPreloadedClassInfo = { + const std::unordered_set preloadedClassInfo = { }; #undef CLASS_PREFIX #undef __MRT_MAGIC_PASTE2 #undef __MRT_MAGIC_PASTE - const std::unordered_set kReflectionList = { + const std::unordered_set reflectionList = { }; }; @@ -168,7 +168,7 @@ class DoMUIDReplacement : public ModulePhase { public: explicit DoMUIDReplacement(ModulePhaseID id) : ModulePhase(id) {} - ~DoMUIDReplacement() {} + ~DoMUIDReplacement() = default; std::string PhaseName() const override { return "MUIDReplacement"; diff --git a/src/mpl2mpl/include/native_stub_func.h b/src/mpl2mpl/include/native_stub_func.h index f4cd76a4966755e5c7f070f3dd0765a7a2eb0b43..4dd5ac59dac80475cb831838ee499d30d04918bd 100644 --- a/src/mpl2mpl/include/native_stub_func.h +++ b/src/mpl2mpl/include/native_stub_func.h @@ -38,16 +38,14 @@ static constexpr char kSetReliableUnwindContextFunc[] = "MCC_SetReliableUnwindCo class NativeFuncProperty { public: - NativeFuncProperty() { - jniType = kJniTypeNormal; - } + NativeFuncProperty() = default; ~NativeFuncProperty() = default; private: std::string javaFunc; std::string nativeFile; std::string nativeFunc; - int jniType; + int jniType = kJniTypeNormal; friend class GenericNativeStubFunc; }; @@ -55,7 +53,7 @@ class NativeFuncProperty { class GenericNativeStubFunc : public FuncOptimizeImpl { public: GenericNativeStubFunc(MIRModule *mod, KlassHierarchy *kh, bool dump); - ~GenericNativeStubFunc() {} + ~GenericNativeStubFunc() = default; void ProcessFunc(MIRFunction *func) override; void Finish() override; @@ -70,13 +68,6 @@ class GenericNativeStubFunc : public FuncOptimizeImpl { MIRAggConst *regTableConst = nullptr; MIRSymbol *regFuncSymbol = nullptr; MIRAggConst *regFuncTabConst = nullptr; - bool IsStaticBindingListMode() const; - inline bool ReturnsJstr(TyIdx retType) { - return (retType == jstrPointerTypeIdx); - } - - void InitStaticBindingMethodList(); - bool IsStaticBindingMethod(const std::string &methodName); MIRFunction *MRTPreNativeFunc = nullptr; MIRFunction *MRTPostNativeFunc = nullptr; MIRFunction *MRTDecodeRefFunc = nullptr; @@ -86,10 +77,16 @@ class GenericNativeStubFunc : public FuncOptimizeImpl { MIRFunction *MRTCallSlowNativeFunc[kSlownativeFuncnum] = { nullptr }; // for native func which args <=8, use x0-x7 MIRFunction *MRTCallSlowNativeExtFunc = nullptr; MIRFunction *MCCSetReliableUnwindContextFunc = nullptr; - const std::string kCallSlowNativeFuncs[kSlownativeFuncnum] = { + const std::string callSlowNativeFuncs[kSlownativeFuncnum] = { "MCC_CallSlowNative0", "MCC_CallSlowNative1", "MCC_CallSlowNative2", "MCC_CallSlowNative3", "MCC_CallSlowNative4", "MCC_CallSlowNative5", "MCC_CallSlowNative6", "MCC_CallSlowNative7", "MCC_CallSlowNative8" }; + bool IsStaticBindingListMode() const; + inline bool ReturnsJstr(TyIdx retType) { + return (retType == jstrPointerTypeIdx); + } + void InitStaticBindingMethodList(); + bool IsStaticBindingMethod(const std::string &methodName); MIRFunction &GetOrCreateDefaultNativeFunc(MIRFunction &stubFunc); void GenericRegisteredNativeFuncCall(MIRFunction &func, const MIRFunction &nativeFunc, MapleVector &args, const MIRSymbol *ret, bool needNativeCall, CallNode &prevNativeFuncCall, @@ -111,7 +108,7 @@ class DoGenericNativeStubFunc : public ModulePhase { public: explicit DoGenericNativeStubFunc(ModulePhaseID id) : ModulePhase(id) {} - ~DoGenericNativeStubFunc() {} + ~DoGenericNativeStubFunc() = default; std::string PhaseName() const override { return "GenNativeStubFunc"; diff --git a/src/mpl2mpl/include/reflection_analysis.h b/src/mpl2mpl/include/reflection_analysis.h index 4cb4aa727d5b9d4a001d481bb7e29925797b9732..0bf8e7006310f588e7ff2e668bbb83ac3c287036 100644 --- a/src/mpl2mpl/include/reflection_analysis.h +++ b/src/mpl2mpl/include/reflection_analysis.h @@ -20,7 +20,7 @@ namespace maple { // +1 is needed here because our field id starts with 0 pointing to the struct itself #define OBJ_KLASS_FIELDID (static_cast(ClassProperty::kShadow) + 1) #define METADATA_KLASS_FIELDID (static_cast(ClassProperty::kShadow) + 1) -static constexpr bool raDebug = false; +static constexpr bool kRADebug = false; static constexpr int64 kTBDValue = 0xABCD; static constexpr int kMaxOptimiseThreshold = 6; static constexpr uint32 kMethodFieldHashSize = 1022; @@ -174,7 +174,7 @@ static constexpr uint64 kMethodNotVirtual = 0x00000001; static constexpr uint64 kMethodFinalize = 0x00000002; static constexpr uint64 kMethodMetaCompact = 0x00000004; static constexpr uint64 kMethodAbstract = 0x00000010; -#define CaseCondition(ARRAYNAME, ELEM) \ +#define CASE_CONDITION(ARRAYNAME, ELEM) \ case kValueInt: \ ARRAYNAME += std::to_string(ELEM->GetI32Val()); \ oss.str(); \ @@ -216,9 +216,6 @@ static constexpr uint64 kMethodAbstract = 0x00000010; break; class ReflectionAnalysis : public AnalysisResult { public: - static void GenStrTab(MIRModule &mirmodule); - static uint32 FindOrInsertRepeatString(const std::string &str, bool isHot = false, uint8 hotType = kLayoutUnused); - static BaseNode *GenClassInfoAddr(BaseNode *obj, MIRBuilder &builder); ReflectionAnalysis(MIRModule *mod, MemPool *memPool, KlassHierarchy *kh, MIRBuilder &builder) : AnalysisResult(memPool), mirModule(mod), @@ -228,9 +225,10 @@ class ReflectionAnalysis : public AnalysisResult { classTab(allocator.Adapter()) { isLibcore = -1; } - - ~ReflectionAnalysis() {} - + ~ReflectionAnalysis() = default; + static void GenStrTab(MIRModule &mirmodule); + static uint32 FindOrInsertRepeatString(const std::string &str, bool isHot = false, uint8 hotType = kLayoutUnused); + static BaseNode *GenClassInfoAddr(BaseNode *obj, MIRBuilder &builder); static TyIdx GetClassMetaDataTyIdx() { return classMetadataTyIdx; } @@ -355,7 +353,7 @@ class DoReflectionAnalysis : public ModulePhase { public: explicit DoReflectionAnalysis(ModulePhaseID id) : ModulePhase(id) {} - ~DoReflectionAnalysis() {} + ~DoReflectionAnalysis() = default; AnalysisResult *Run(MIRModule *module, ModuleResultMgr *m) override; std::string PhaseName() const override { diff --git a/src/mpl2mpl/include/vtable_analysis.h b/src/mpl2mpl/include/vtable_analysis.h index 7e1283c25db26e8452227fc4ab820eec12ecd7f9..fccba681d4ff72eb3b2acac67afb7a06b6a4449c 100644 --- a/src/mpl2mpl/include/vtable_analysis.h +++ b/src/mpl2mpl/include/vtable_analysis.h @@ -31,7 +31,7 @@ static constexpr unsigned int kTabEntrySize = 8; class VtableAnalysis : public FuncOptimizeImpl { public: VtableAnalysis(MIRModule *mod, KlassHierarchy *kh, bool dump); - ~VtableAnalysis() {} + ~VtableAnalysis() = default; static std::string DecodeBaseNameWithType(const MIRFunction &func); void ProcessFunc(MIRFunction *func) override; FuncOptimizeImpl *Clone() override { @@ -63,7 +63,7 @@ class DoVtableAnalysis : public ModulePhase { public: explicit DoVtableAnalysis(ModulePhaseID id) : ModulePhase(id) {} - ~DoVtableAnalysis() {} + ~DoVtableAnalysis() = default; std::string PhaseName() const override { return "vtableanalysis"; diff --git a/src/mpl2mpl/include/vtable_impl.h b/src/mpl2mpl/include/vtable_impl.h index aecd7cea4e4fa527ef4230b8fc252604621b7191..90a60e6440959b3787266c659541b669d4264e22 100644 --- a/src/mpl2mpl/include/vtable_impl.h +++ b/src/mpl2mpl/include/vtable_impl.h @@ -19,7 +19,11 @@ namespace maple { static constexpr int kNumOfMCCParas = 5; -enum CallKind { kStaticCall = 0, kVirtualCall = 1, kSuperCall = 2}; +enum CallKind { + kStaticCall = 0, + kVirtualCall = 1, + kSuperCall = 2 +}; #ifdef USE_32BIT_REF static constexpr char kInterfaceMethod[] = "MCC_getFuncPtrFromItab"; @@ -30,7 +34,7 @@ static constexpr char kInterfaceMethod[] = "MCC_getFuncPtrFromItabSecondHash64"; class VtableImpl : public FuncOptimizeImpl { public: VtableImpl(MIRModule *mod, KlassHierarchy *kh, bool dump); - ~VtableImpl() {} + ~VtableImpl() = default; void ProcessFunc(MIRFunction *func) override; FuncOptimizeImpl *Clone() override { @@ -52,7 +56,7 @@ class DoVtableImpl : public ModulePhase { return "VtableImpl"; } - ~DoVtableImpl() {} + ~DoVtableImpl() = default; AnalysisResult *Run(MIRModule *mod, ModuleResultMgr *mrm) override { OPT_TEMPLATE(VtableImpl); diff --git a/src/mpl2mpl/src/class_hierarchy.cpp b/src/mpl2mpl/src/class_hierarchy.cpp index cb7eaabe5ad61ee9aa15b7085510799c08b5de7d..93dd1f697d1c80d090cbb7e6878cf79b8bddcf68 100644 --- a/src/mpl2mpl/src/class_hierarchy.cpp +++ b/src/mpl2mpl/src/class_hierarchy.cpp @@ -69,11 +69,11 @@ void Klass::DumpKlassMethods() const { for (MIRFunction * const &method : methods) { LogInfo::MapleLogger() << " \t" << method->GetName() << " , "; method->GetFuncSymbol()->GetAttrs().DumpAttributes(); - LogInfo::MapleLogger() << std::endl; + LogInfo::MapleLogger() << "\n"; } for (auto const &m2cPair : strIdx2CandidateMap) { LogInfo::MapleLogger() << " \t" << GlobalTables::GetStrTable().GetStringFromStrIdx(m2cPair.first) - << " , # of target:" << m2cPair.second->size() << std::endl; + << " , # of target:" << m2cPair.second->size() << "\n"; } } @@ -120,7 +120,7 @@ void Klass::DumpKlassSubKlasses() const { void Klass::Dump() const { // Dump detailed class info LogInfo::MapleLogger() << "class \" " << GetKlassName() << " \" @class_id " << structType->GetTypeIndex().GetIdx() - << std::endl; + << "\n"; DumpKlassSuperKlasses(); DumpKlassSubKlasses(); DumpKlassImplInterfaces(); @@ -132,9 +132,8 @@ MIRFunction *Klass::GetClosestMethod(GStrIdx funcnamewithtype) const { MapleVector *cands = GetCandidates(funcnamewithtype); if (cands != nullptr && !cands->empty()) { return cands->at(0); - } else { - return nullptr; } + return nullptr; } void Klass::DelMethod(const MIRFunction &func) { @@ -157,7 +156,7 @@ Klass *Klass::GetSuperKlass() const { case 1: return *superKlasses.begin(); default: - LogInfo::MapleLogger() << GetKlassName() << std::endl; + LogInfo::MapleLogger() << GetKlassName() << "\n"; CHECK_FATAL(false, "GetSuperKlass expects less than one super class"); return nullptr; } @@ -184,18 +183,18 @@ bool Klass::ImplementsKlass() const { return (!ctype->GetInterfaceImplemented().empty()); } -MapleVector *Klass::GetCandidates(GStrIdx mnameNoklassStridx) const { +MapleVector *Klass::GetCandidates(GStrIdx mnameNoklassStrIdx) const { MapleMap*>::const_iterator it; - it = strIdx2CandidateMap.find(mnameNoklassStridx); + it = strIdx2CandidateMap.find(mnameNoklassStrIdx); return ((it != strIdx2CandidateMap.end()) ? (it->second) : nullptr); } -MIRFunction *Klass::GetUniqueMethod(GStrIdx mnameNoklassStridx) const { +MIRFunction *Klass::GetUniqueMethod(GStrIdx mnameNoklassStrIdx) const { if (structType->IsIncomplete()) { return nullptr; } MapleMap*>::const_iterator it; - it = strIdx2CandidateMap.find(mnameNoklassStridx); + it = strIdx2CandidateMap.find(mnameNoklassStrIdx); if (it != strIdx2CandidateMap.end()) { MapleVector *fv = it->second; if (fv != nullptr && fv->size() == 1) { @@ -212,12 +211,12 @@ bool Klass::IsVirtualMethod(const MIRFunction &func) const { void Klass::CountVirtMethTopDown(const KlassHierarchy &kh) { MapleVector *vec, *pvec; - GStrIdx stridx; + GStrIdx strIdx; MapleVector *superAndImplClasses = alloc->GetMemPool()->New>(alloc->Adapter()); // Add default methods of interface. Add them first because they have lowest // priorities compared with methods defined in classes - for (TyIdx const &tyidx : GetMIRClassType()->GetInterfaceImplemented()) { - Klass *interface = kh.GetKlassFromTyIdx(tyidx); + for (TyIdx const &tyIdx : GetMIRClassType()->GetInterfaceImplemented()) { + Klass *interface = kh.GetKlassFromTyIdx(tyIdx); if (interface != nullptr) { superAndImplClasses->push_back(interface); } @@ -228,23 +227,23 @@ void Klass::CountVirtMethTopDown(const KlassHierarchy &kh) { } // Initialize strIdx2CandidateMap based on the superclass methods for (Klass * const &superAndImplClass : *superAndImplClasses) { - ASSERT(superAndImplClass, "Not a valid super class of interface"); + ASSERT(superAndImplClass != nullptr, "Not a valid super class of interface"); for (auto const &pair : superAndImplClass->strIdx2CandidateMap) { - stridx = pair.first; + strIdx = pair.first; pvec = pair.second; ASSERT(pvec->size() == 1, "Expect exactly one method definition from parent class"); - if (strIdx2CandidateMap.find(stridx) == strIdx2CandidateMap.end()) { + if (strIdx2CandidateMap.find(strIdx) == strIdx2CandidateMap.end()) { vec = alloc->GetMemPool()->New>(alloc->Adapter()); vec->push_back(pvec->at(0)); - strIdx2CandidateMap[stridx] = vec; + strIdx2CandidateMap[strIdx] = vec; } else { // Override the method coming from previous klass (must be an interface) - ASSERT(strIdx2CandidateMap[stridx]->size() == 1, "Expect exactly one method definition"); - ASSERT(kh.GetKlassFromStrIdx(strIdx2CandidateMap[stridx]->at(0)->GetBaseClassNameStrIdx())->IsInterface(), + ASSERT(strIdx2CandidateMap[strIdx]->size() == 1, "Expect exactly one method definition"); + ASSERT(kh.GetKlassFromStrIdx(strIdx2CandidateMap[strIdx]->at(0)->GetBaseClassNameStrIdx())->IsInterface(), "Override interface default methods"); // Interfaces implemented methods override, need to determine the inherit relation. // class method can override interface method, interface method can override its parent's methods - vec = strIdx2CandidateMap[stridx]; + vec = strIdx2CandidateMap[strIdx]; ASSERT(vec != nullptr, "nullptr check!"); ASSERT(vec->size() == 1, "Expect exactly one method definition from parent class"); Klass *parentKlass = kh.GetKlassFromFunc((*vec)[0]); @@ -263,11 +262,10 @@ void Klass::CountVirtMethTopDown(const KlassHierarchy &kh) { if (!IsVirtualMethod(*method)) { continue; } - - stridx = method->GetBaseFuncNameWithTypeStrIdx(); - if (strIdx2CandidateMap.find(stridx) != strIdx2CandidateMap.end()) { + strIdx = method->GetBaseFuncNameWithTypeStrIdx(); + if (strIdx2CandidateMap.find(strIdx) != strIdx2CandidateMap.end()) { // Override the method coming from parent - vec = strIdx2CandidateMap[stridx]; + vec = strIdx2CandidateMap[strIdx]; ASSERT(vec != nullptr, "nullptr check!"); ASSERT(vec->size() == 1, "Expect exactly one method definition from parent class"); (*vec)[0] = method; @@ -275,22 +273,22 @@ void Klass::CountVirtMethTopDown(const KlassHierarchy &kh) { // Newly declared and defined vec = alloc->GetMemPool()->New>(alloc->Adapter()); vec->push_back(method); - strIdx2CandidateMap[stridx] = vec; + strIdx2CandidateMap[strIdx] = vec; } } } void Klass::CountVirtMethBottomUp() { MapleVector *vec; - GStrIdx stridx; + GStrIdx strIdx; for (Klass * const &subKlass : subKlasses) { CHECK_FATAL(subKlass != nullptr, "nullptr check failed"); for (auto const &pair : subKlass->strIdx2CandidateMap) { - stridx = pair.first; - if (strIdx2CandidateMap.find(stridx) == strIdx2CandidateMap.end()) { + strIdx = pair.first; + if (strIdx2CandidateMap.find(strIdx) == strIdx2CandidateMap.end()) { continue; } - vec = strIdx2CandidateMap[stridx]; + vec = strIdx2CandidateMap[strIdx]; MapleVector *subv = pair.second; if (!vec->empty() && !subv->empty() && vec->at(0) == subv->at(0)) { // If this class and subclass share the same default implementation, @@ -312,14 +310,14 @@ const MIRFunction *Klass::HasMethod(const std::string &funcname) { return nullptr; } -Klass *KlassHierarchy::GetKlassFromStrIdx(GStrIdx stridx) const { - MapleMap::const_iterator it = strIdx2KlassMap.find(stridx); +Klass *KlassHierarchy::GetKlassFromStrIdx(GStrIdx strIdx) const { + MapleMap::const_iterator it = strIdx2KlassMap.find(strIdx); return ((it != strIdx2KlassMap.end()) ? (it->second) : nullptr); } -Klass *KlassHierarchy::GetKlassFromTyIdx(TyIdx tyidx) const { - MIRType *type = GlobalTables::GetTypeTable().GetTypeFromTyIdx(tyidx); - return (type ? GetKlassFromStrIdx(type->GetNameStrIdx()) : nullptr); +Klass *KlassHierarchy::GetKlassFromTyIdx(TyIdx tyIdx) const { + MIRType *type = GlobalTables::GetTypeTable().GetTypeFromTyIdx(tyIdx); + return (type != nullptr ? GetKlassFromStrIdx(type->GetNameStrIdx()) : nullptr); } Klass *KlassHierarchy::GetKlassFromFunc(const MIRFunction *func) const { @@ -469,17 +467,17 @@ Klass *KlassHierarchy::GetLCA(Klass *k1, Klass *k2) const { TyIdx KlassHierarchy::GetLCA(TyIdx ty1, TyIdx ty2) const { Klass *result = GetLCA(GetKlassFromTyIdx(ty1), GetKlassFromTyIdx(ty2)); - return (result ? result->GetTypeIdx() : TyIdx(0)); + return (result != nullptr ? result->GetTypeIdx() : TyIdx(0)); } GStrIdx KlassHierarchy::GetLCA(GStrIdx str1, GStrIdx str2) const { Klass *result = GetLCA(GetKlassFromStrIdx(str1), GetKlassFromStrIdx(str2)); - return (result ? result->GetKlassNameStrIdx() : GStrIdx(0)); + return (result != nullptr ? result->GetKlassNameStrIdx() : GStrIdx(0)); } const std::string &KlassHierarchy::GetLCA(const std::string &name1, const std::string &name2) const { Klass *result = GetLCA(GetKlassFromName(name1), GetKlassFromName(name2)); - return (result ? result->GetKlassName() : GlobalTables::GetStrTable().GetStringFromStrIdx(GStrIdx(0))); + return (result != nullptr ? result->GetKlassName() : GlobalTables::GetStrTable().GetStringFromStrIdx(GStrIdx(0))); } void KlassHierarchy::AddKlasses() { @@ -487,17 +485,17 @@ void KlassHierarchy::AddKlasses() { if (type == nullptr || (type->GetKind() != kTypeClass && type->GetKind() != kTypeInterface)) { continue; } - GStrIdx stridx = type->GetNameStrIdx(); - Klass *klass = GetKlassFromStrIdx(stridx); + GStrIdx strIdx = type->GetNameStrIdx(); + Klass *klass = GetKlassFromStrIdx(strIdx); if (klass != nullptr) { if (klass->GetKlassName().compare(NameMangler::kThrowClassStr) == 0) { klass->SetExceptionKlass(); } continue; } - MIRStructType *stype = static_cast(type); + auto *stype = static_cast(type); klass = GetMempool()->New(stype, &alloc); - strIdx2KlassMap[stridx] = klass; + strIdx2KlassMap[strIdx] = klass; } } @@ -517,7 +515,7 @@ void KlassHierarchy::AddKlassRelationAndMethods() { Klass *superKlass = nullptr; if (klass->IsInterface()) { MIRInterfaceType *itype = klass->GetMIRInterfaceType(); - ASSERT(itype, "null ptr check"); + ASSERT(itype != nullptr, "null ptr check"); // Java interface supports multiple inheritance for (TyIdx const &superTyIdx : itype->GetParentsTyIdx()) { superKlass = GetKlassFromTyIdx(superTyIdx); @@ -577,7 +575,7 @@ void KlassHierarchy::TagThrowableKlasses() { } for (auto const &pair : strIdx2KlassMap) { Klass *klass = pair.second; - ASSERT(klass, "unexpeced null klass"); + ASSERT(klass != nullptr, "unexpeced null klass"); if (!klass->IsInterface() && IsSuperKlass(throwable, klass)) { klass->SetExceptionKlass(); } @@ -645,7 +643,7 @@ void KlassHierarchy::TopologicalSortKlasses() { std::set inQueue; // Local variable, no need to use MapleSet for (auto const &pair : strIdx2KlassMap) { Klass *klass = pair.second; - ASSERT(klass, "klass can not be nullptr"); + ASSERT(klass != nullptr, "klass can not be nullptr"); if (!klass->HasSuperKlass() && !klass->ImplementsKlass()) { topoWorkList.push_back(klass); inQueue.insert(klass); @@ -775,8 +773,7 @@ KlassHierarchy::KlassHierarchy(MIRModule *mirmodule, MemPool *memPool) alloc(memPool), mirModule(mirmodule), strIdx2KlassMap(std::less(), alloc.Adapter()), - topoWorkList(alloc.Adapter()) { -} + topoWorkList(alloc.Adapter()) {} MIRType *WKTypes::javalangObject; MIRType *WKTypes::jlString; @@ -823,7 +820,7 @@ void WKTypes::Init() { // type of java.io.Serializable, Comparable or CharSequence bool WKTypes::Util::MayRefString(const BaseNode &n, MIRType &type) { if ((n.GetPrimType() == PTY_ref || n.GetPrimType() == PTY_ptr) && type.GetKind() == kTypePointer) { - MIRPtrType *pointType = static_cast(&type); + auto *pointType = static_cast(&type); MIRType *pointedType = pointType->GetPointedType(); if (pointedType == jlString || pointedType == javalangobjectSerializable || pointedType == javalangComparable || pointedType == javalangCharSequence || pointedType == javalangObject) { @@ -838,7 +835,7 @@ bool WKTypes::Util::MayRefString(const BaseNode &n, MIRType &type) { // java.lang.reflect.Constructor bool WKTypes::Util::MayRefMeta(const BaseNode &n, MIRType &type) { if ((n.GetPrimType() == PTY_ref || n.GetPrimType() == PTY_ptr) && type.GetKind() == kTypePointer) { - MIRPtrType *pointType = static_cast(&type); + auto *pointType = static_cast(&type); MIRType *pointedType = pointType->GetPointedType(); /* Definition of java.lang.Class: @@ -860,7 +857,6 @@ bool WKTypes::Util::MayRefMeta(const BaseNode &n, MIRType &type) { /* Definition of java.lang.reflect.Method: public final class Method extends Executable {...} - public abstract class Executable extends AccessibleObject implements Member, GenericDeclaration {...} public class AccessibleObject implements AnnotatedElement {...} @@ -912,7 +908,7 @@ bool WKTypes::Util::NotCyclicType(MIRType &type, std::set &workList) { if (type.GetKind() == kTypeScalar) { // primitive type return true; } else if (type.GetKind() == kTypePointer) { - MIRType *pointedType = static_cast(&type)->GetPointedType(); + auto *pointedType = static_cast(&type)->GetPointedType(); ASSERT(pointedType != nullptr, "null ptr check!"); return NotCyclicType(*pointedType, workList); } else if (type.GetKind() == kTypeJArray) { @@ -921,7 +917,7 @@ bool WKTypes::Util::NotCyclicType(MIRType &type, std::set &workList) { ASSERT(elemType != nullptr, "null ptr check!"); return NotCyclicType(*elemType, workList); } else if (type.GetKind() == kTypeClass) { - MIRClassType *classType = static_cast(&type); + auto *classType = static_cast(&type); if (!classType->IsFinal()) { // Not sure what actual class it refers to return false; } @@ -931,7 +927,7 @@ bool WKTypes::Util::NotCyclicType(MIRType &type, std::set &workList) { MIRType *parentType = GlobalTables::GetTypeTable().GetTypeFromTyIdx(classType->GetParentTyIdx()); while (parentType != nullptr) { CHECK_FATAL(parentType->GetKind() == kTypeClass, "parent class"); - MIRClassType *parentclass = static_cast(parentType); + auto *parentclass = static_cast(parentType); allFields.insert(allFields.end(), parentclass->GetFields().begin(), parentclass->GetFields().end()); // ignore static fields for now, they are not recycled anyway parentType = GlobalTables::GetTypeTable().GetTypeFromTyIdx(parentclass->GetParentTyIdx()); diff --git a/src/mpl2mpl/src/class_init.cpp b/src/mpl2mpl/src/class_init.cpp index cd002979bd2adff5ed1d1da55a3be57689602f6d..ef4a1ace07e837c9bb7f5d3bcac886761b31eb82 100644 --- a/src/mpl2mpl/src/class_init.cpp +++ b/src/mpl2mpl/src/class_init.cpp @@ -73,12 +73,12 @@ void ClassInit::ProcessFunc(MIRFunction *func) { } else { const std::string &funcName = func->GetName(); size_t pos = funcName.find(NameMangler::kNameSplitterStr); - constexpr size_t kPrePos = 2; - constexpr size_t kLigalPos = 2; + constexpr size_t prePos = 2; + constexpr size_t ligalPos = 2; while (pos != std::string::npos && - (pos >= kLigalPos && funcName[pos - 1] == '_' && funcName[pos - kPrePos] != '_')) { - constexpr size_t kNextPos = 3; - pos = funcName.find(NameMangler::kNameSplitterStr, pos + kNextPos); + (pos >= ligalPos && funcName[pos - 1] == '_' && funcName[pos - prePos] != '_')) { + constexpr size_t nextPos = 3; + pos = funcName.find(NameMangler::kNameSplitterStr, pos + nextPos); } selfClassName = funcName.substr(0, pos); } @@ -100,7 +100,7 @@ void ClassInit::ProcessFunc(MIRFunction *func) { BaseNode *classInfoNode = builder->CreateExprAddrof(0, *classInfo); if (trace) { LogInfo::MapleLogger() << "\t- low-cost clinit - insert check in static method " << func->GetName() - << "clasname " << className << std::endl; + << "clasname " << className << "\n"; } MapleVector args(builder->GetCurrentFuncCodeMpAllocator()->Adapter()); args.push_back(classInfoNode); @@ -115,7 +115,7 @@ void ClassInit::ProcessFunc(MIRFunction *func) { StmtNode *stmt = func->GetBody()->GetFirst(); while (stmt != nullptr) { if (stmt->GetOpCode() == OP_intrinsiccallwithtype) { - IntrinsiccallNode *intrinsicCall = static_cast(stmt); + auto *intrinsicCall = static_cast(stmt); if (intrinsicCall->GetIntrinsic() == INTRN_JAVA_CLINIT_CHECK) { // intrinsiccallwithtype <$LTest_3B> JAVA_CLINIT_CHECK () --> // intrinsiccall MPL_CLINIT_CHECK (addrof ptr $__cinf_LTest_3B) @@ -144,7 +144,7 @@ void ClassInit::ProcessFunc(MIRFunction *func) { func->GetBody()->ReplaceStmt1WithStmt2(stmt, mplIntrinsicCall); if (trace) { LogInfo::MapleLogger() << "\t- low-cost clinit - lower JAVA_CLINIT_CHECK " << className << " in " - << func->GetName() << "()" << std::endl; + << func->GetName() << "()\n"; } ASSERT(classInfo != nullptr, "null ptr check!"); GenClassInitCheckProfile(*func, *classInfo, mplIntrinsicCall); diff --git a/src/mpl2mpl/src/gen_check_cast.cpp b/src/mpl2mpl/src/gen_check_cast.cpp index 1f7f550cd4e0281fa3a9591d564eb443fa255daf..f2fb139ce667897c401be555c678dee96e4bd11b 100644 --- a/src/mpl2mpl/src/gen_check_cast.cpp +++ b/src/mpl2mpl/src/gen_check_cast.cpp @@ -59,7 +59,8 @@ MIRSymbol *CheckCastGenerator::GetOrCreateClassInfoSymbol(const std::string &cla GStrIdx gStrIdx = GlobalTables::GetStrTable().GetStrIdxFromName(className); MIRType *classType = GlobalTables::GetTypeTable().GetTypeFromTyIdx(GlobalTables::GetTypeNameTable().GetTyIdxFromGStrIdx(gStrIdx)); - MIRStorageClass sclass = (classType && static_cast(classType)->IsLocal()) ? kScGlobal : kScExtern; + MIRStorageClass sclass = (classType != nullptr && static_cast(classType)->IsLocal()) ? kScGlobal + : kScExtern; // Creating global symbol needs synchronization. classInfoSymbol = builder->CreateGlobalDecl(classInfoName.c_str(), *GlobalTables::GetTypeTable().GetPtr(), sclass); } @@ -69,7 +70,7 @@ MIRSymbol *CheckCastGenerator::GetOrCreateClassInfoSymbol(const std::string &cla void CheckCastGenerator::GenCheckCast(BaseNode &stmt) { // Handle the special case like (Type)null, we don't need a checkcast. if (stmt.GetOpCode() == OP_intrinsiccallwithtypeassigned) { - IntrinsiccallNode *callNode = static_cast(&stmt); + auto *callNode = static_cast(&stmt); ASSERT(callNode->GetNopndSize() == 1, "array size error"); BaseNode *opnd = callNode->Opnd(0); if (opnd->GetOpCode() == OP_constval) { @@ -90,14 +91,14 @@ void CheckCastGenerator::GenCheckCast(BaseNode &stmt) { } } // Do type check first. - IntrinsiccallNode *callNode = static_cast(&stmt); + auto *callNode = static_cast(&stmt); ASSERT(callNode->GetNopndSize() == 1, "array size error"); TyIdx checkTyidx = callNode->GetTyIdx(); MIRType *checkType = GlobalTables::GetTypeTable().GetTypeFromTyIdx(checkTyidx); Klass *checkKlass = klassHierarchy->GetKlassFromTyIdx(static_cast(checkType)->GetPointedTyIdx()); { - if (checkKlass && strcmp("", checkKlass->GetKlassName().c_str())) { + if (checkKlass != nullptr && strcmp("", checkKlass->GetKlassName().c_str())) { if (!strcmp(checkKlass->GetKlassName().c_str(), NameMangler::kJavaLangObjectStr)) { const size_t callNodeNopndSize1 = callNode->GetNopndSize(); CHECK_FATAL(callNodeNopndSize1 > 0, "container check"); @@ -121,15 +122,14 @@ void CheckCastGenerator::GenCheckCast(BaseNode &stmt) { BaseNode *cond = builder->CreateExprCompare(OP_ne, *GlobalTables::GetTypeTable().GetUInt1(), *GlobalTables::GetTypeTable().GetPtr(), callNode->GetNopndAt(0), nullPtr); - IfStmtNode *ifStmt = static_cast(builder->CreateStmtIf(cond)); + auto *ifStmt = static_cast(builder->CreateStmtIf(cond)); MIRType *mVoidPtr = GlobalTables::GetTypeTable().GetVoidPtr(); CHECK_FATAL(mVoidPtr != nullptr, "builder->GetVoidPtr() is null in CheckCastGenerator::GenCheckCast"); BaseNode *opnd = callNode->GetNopndAt(0); BaseNode *ireadExpr = GetObjectShadow(opnd); - BaseNode *innerCond = builder->CreateExprCompare(OP_ne, *GlobalTables::GetTypeTable().GetUInt1(), *GlobalTables::GetTypeTable().GetPtr(), valueExpr, ireadExpr); - IfStmtNode *innerIfStmt = static_cast(builder->CreateStmtIf(innerCond)); + auto *innerIfStmt = static_cast(builder->CreateStmtIf(innerCond)); MapleVector args(builder->GetCurrentFuncCodeMpAllocator()->Adapter()); args.push_back(valueExpr); args.push_back(opnd); @@ -143,7 +143,7 @@ void CheckCastGenerator::GenCheckCast(BaseNode &stmt) { GlobalTables::GetTypeTable().GetTypeFromTyIdx(static_cast(checkType)->GetPointedTyIdx()); if (pointedType->GetKind() == kTypeJArray) { // Java array. - MIRJarrayType *jarrayType = static_cast(pointedType); + auto *jarrayType = static_cast(pointedType); std::string arrayName = jarrayType->GetJavaName(); int dim = 0; while (arrayName[dim] == 'A') { @@ -182,7 +182,7 @@ void CheckCastGenerator::GenCheckCast(BaseNode &stmt) { if (kd == kTypeStructIncomplete || kd == kTypeClassIncomplete || kd == kTypeInterfaceIncomplete) { LogInfo::MapleLogger() << "Warining: CheckCastGenerator::GenCheckCast " << GlobalTables::GetStrTable().GetStringFromStrIdx(pointedType->GetNameStrIdx()) - << " INCOMPLETE " << std::endl; + << " INCOMPLETE \n"; } else { CHECK_FATAL(false, "unsupport kind"); } @@ -195,7 +195,6 @@ void CheckCastGenerator::GenCheckCast(BaseNode &stmt) { BaseNode *opnd = callNode->Opnd(0); ASSERT(opnd->GetOpCode() == OP_dread || opnd->GetOpCode() == OP_regread || opnd->GetOpCode() == OP_iread || opnd->GetOpCode() == OP_retype, "unknown calltype! check it!"); - MIRType *fromType = nullptr; if (opnd->GetOpCode() == OP_dread) { fromType = GlobalTables::GetTypeTable().GetTypeFromTyIdx( @@ -203,8 +202,8 @@ void CheckCastGenerator::GenCheckCast(BaseNode &stmt) { } else if (opnd->GetOpCode() == OP_retype) { fromType = GlobalTables::GetTypeTable().GetTypeFromTyIdx(static_cast(opnd)->GetTyIdx()); } else if (opnd->GetOpCode() == OP_iread) { - IreadNode *irnode = static_cast(opnd); - MIRPtrType *ptrType = static_cast(GlobalTables::GetTypeTable().GetTypeFromTyIdx(irnode->GetTyIdx())); + auto *irnode = static_cast(opnd); + auto *ptrType = static_cast(GlobalTables::GetTypeTable().GetTypeFromTyIdx(irnode->GetTyIdx())); if (irnode->GetFieldID() != 0) { MIRType *pointedType = GlobalTables::GetTypeTable().GetTypeFromTyIdx(ptrType->GetPointedTyIdx()); MIRStructType *structType = nullptr; @@ -214,13 +213,13 @@ void CheckCastGenerator::GenCheckCast(BaseNode &stmt) { // It's a Jarray type. Using it's parent's field info: java.lang.Object. structType = static_cast(pointedType)->GetParentType(); } - CHECK_FATAL(structType, "null ptr check"); + CHECK_FATAL(structType != nullptr, "null ptr check"); fromType = structType->GetFieldType(irnode->GetFieldID()); } else { fromType = GlobalTables::GetTypeTable().GetTypeFromTyIdx(ptrType->GetPointedTyIdx()); } } else if (opnd->GetOpCode() == OP_regread) { - RegreadNode *regReadNode = static_cast(opnd); + auto *regReadNode = static_cast(opnd); MIRPreg *mirPreg = currFunc->GetPregTab()->PregFromPregIdx(regReadNode->GetRegIdx()); CHECK_FATAL(mirPreg->GetPrimType() == PTY_ref || mirPreg->GetPrimType() == PTY_ptr, "must be reference or ptr type for preg"); @@ -237,8 +236,7 @@ void CheckCastGenerator::GenCheckCast(BaseNode &stmt) { ASSERT(GlobalTables::GetTypeTable().GetTypeFromTyIdx(callNode->GetTyIdx())->GetPrimType() == maple::PTY_ptr || GlobalTables::GetTypeTable().GetTypeFromTyIdx(callNode->GetTyIdx())->GetPrimType() == maple::PTY_ref, "unknown fromType! check it!"); - const size_t callNodeNretSize1 = callNode->GetReturnVec().size(); - CHECK_FATAL(callNodeNretSize1 > 0, "container check"); + CHECK_FATAL(!callNode->GetReturnVec().empty(), "container check"); CallReturnPair callReturnPair = callNode->GetReturnVec()[0]; StmtNode *assignReturnTypeNode = nullptr; if (!callReturnPair.second.IsReg()) { @@ -255,7 +253,7 @@ void CheckCastGenerator::GenAllCheckCast() { auto &stmtNodes = currFunc->GetBody()->GetStmtNodes(); for (auto &stmt : stmtNodes) { if (stmt.GetOpCode() == OP_intrinsiccallwithtypeassigned || stmt.GetOpCode() == OP_intrinsiccallwithtype) { - IntrinsiccallNode &callNode = static_cast(stmt); + auto &callNode = static_cast(stmt); if (callNode.GetIntrinsic() == INTRN_JAVA_CHECK_CAST) { GenCheckCast(stmt); if (stmt.GetOpCode() == OP_intrinsiccallwithtype) { diff --git a/src/mpl2mpl/src/java_eh_lower.cpp b/src/mpl2mpl/src/java_eh_lower.cpp index 9971de35b27235b35eb220569c115d4323b3d5b3..c1724fd2d45ad1b7e8ba42262488b9e2787fcc74 100644 --- a/src/mpl2mpl/src/java_eh_lower.cpp +++ b/src/mpl2mpl/src/java_eh_lower.cpp @@ -143,15 +143,16 @@ BlockNode *JavaEHLowerer::DoLowerBlock(BlockNode &block) { switch (stmt->GetOpCode()) { case OP_switch: { - SwitchNode *switchNode = static_cast(stmt); + auto *switchNode = static_cast(stmt); switchNode->SetSwitchOpnd(DoLowerExpr(*(switchNode->GetSwitchOpnd()), *newBlock)); newBlock->AddStatement(switchNode); break; } case OP_if: { - IfStmtNode *ifStmtNode = static_cast(stmt); + auto *ifStmtNode = static_cast(stmt); BlockNode *thenPart = ifStmtNode->GetThenPart(); BlockNode *elsePart = ifStmtNode->GetElsePart(); + ASSERT(ifStmtNode->Opnd() != nullptr, "null ptr check!"); ifStmtNode->SetOpnd(DoLowerExpr(*(ifStmtNode->Opnd()), *newBlock)); ifStmtNode->SetThenPart(DoLowerBlock(*thenPart)); if (elsePart != nullptr) { @@ -162,7 +163,7 @@ BlockNode *JavaEHLowerer::DoLowerBlock(BlockNode &block) { } case OP_while: case OP_dowhile: { - WhileStmtNode *whileStmtNode = static_cast(stmt); + auto *whileStmtNode = static_cast(stmt); BaseNode *testOpnd = whileStmtNode->Opnd(0); whileStmtNode->SetOpnd(DoLowerExpr(*testOpnd, *newBlock)); whileStmtNode->SetBody(DoLowerBlock(*(whileStmtNode->GetBody()))); @@ -170,7 +171,7 @@ BlockNode *JavaEHLowerer::DoLowerBlock(BlockNode &block) { break; } case OP_doloop: { - DoloopNode *doLoopNode = static_cast(stmt); + auto *doLoopNode = static_cast(stmt); doLoopNode->SetStartExpr(DoLowerExpr(*(doLoopNode->GetStartExpr()), *newBlock)); doLoopNode->SetContExpr(DoLowerExpr(*(doLoopNode->GetCondExpr()), *newBlock)); doLoopNode->SetIncrExpr(DoLowerExpr(*(doLoopNode->GetIncrExpr()), *newBlock)); @@ -179,17 +180,17 @@ BlockNode *JavaEHLowerer::DoLowerBlock(BlockNode &block) { break; } case OP_block: { - BlockNode *tmp = DoLowerBlock(*(static_cast(stmt))); - CHECK_FATAL(tmp, "null ptr check"); + auto *tmp = DoLowerBlock(*(static_cast(stmt))); + CHECK_FATAL(tmp != nullptr, "null ptr check"); newBlock->AddStatement(tmp); break; } case OP_throw: { - UnaryStmtNode *tstmt = static_cast(stmt); + auto *tstmt = static_cast(stmt); BaseNode *opnd0 = DoLowerExpr(*(tstmt->Opnd(0)), *newBlock); if (opnd0->GetOpCode() == OP_constval) { CHECK_FATAL(IsPrimitiveInteger(opnd0->GetPrimType()), "must be integer or something wrong"); - MIRIntConst *intConst = static_cast(static_cast(opnd0)->GetConstVal()); + auto *intConst = static_cast(static_cast(opnd0)->GetConstVal()); CHECK_FATAL(intConst->IsZero(), "can only be zero"); MIRFunction *func = GetMIRModule().GetMIRBuilder()->GetOrCreateFunction(strMCCThrowNullPointerException, TyIdx(PTY_void)); @@ -204,7 +205,7 @@ BlockNode *JavaEHLowerer::DoLowerBlock(BlockNode &block) { break; } case OP_intrinsiccall: { - IntrinsiccallNode *intrinCall = static_cast(stmt); + auto *intrinCall = static_cast(stmt); if (intrinCall->GetIntrinsic() == INTRN_MPL_BOUNDARY_CHECK) { DoLowerBoundaryCheck(*intrinCall, *newBlock); break; diff --git a/src/mpl2mpl/src/java_intrn_lowering.cpp b/src/mpl2mpl/src/java_intrn_lowering.cpp index c55c9c2ae8629d629630a58c8c43b14886f37be2..db129b87386861900d5e19f8dc2e25188a020910 100644 --- a/src/mpl2mpl/src/java_intrn_lowering.cpp +++ b/src/mpl2mpl/src/java_intrn_lowering.cpp @@ -40,14 +40,14 @@ void JavaIntrnLowering::ProcessStmt(StmtNode &stmt) { case OP_regassign: { BaseNode *rhs = nullptr; if (opcode == OP_dassign) { - DassignNode &dassign = static_cast(stmt); + auto &dassign = static_cast(stmt); rhs = dassign.GetRHS(); } else { - RegassignNode ®assign = static_cast(stmt); + auto ®assign = static_cast(stmt); rhs = regassign.GetRHS(); } if (rhs != nullptr && rhs->GetOpCode() == OP_intrinsicop) { - IntrinsicopNode *intrinNode = static_cast(rhs); + auto *intrinNode = static_cast(rhs); if (intrinNode->GetIntrinsic() == INTRN_JAVA_MERGE) { ProcessJavaIntrnMerge(stmt, *intrinNode); } @@ -150,11 +150,11 @@ void JavaIntrnLowering::ProcessJavaIntrnFillNewArray(IntrinsiccallNode &intrinCa if (!isReg) { retType = currFunc->GetLocalOrGlobalSymbol(retPair.first)->GetType(); } else { - PregIdx pregidx = retPair.second.GetPregIdx(); - MIRPreg *mirpreg = currFunc->GetPregTab()->PregFromPregIdx(pregidx); - CHECK_FATAL(mirpreg->GetPrimType() == PTY_ref || mirpreg->GetPrimType() == PTY_ptr, + PregIdx pregIdx = retPair.second.GetPregIdx(); + MIRPreg *mirPreg = currFunc->GetPregTab()->PregFromPregIdx(pregIdx); + CHECK_FATAL(mirPreg->GetPrimType() == PTY_ref || mirPreg->GetPrimType() == PTY_ptr, "Dst preg needs to be a pointer or reference type"); - retType = mirpreg->GetMIRType(); + retType = mirPreg->GetMIRType(); } CHECK_FATAL(retType->GetKind() == kTypePointer, "Return type of INTRN_JAVA_FILL_NEW_ARRAY should point to a Jarray"); MIRType *arrayType = static_cast(retType)->GetPointedType(); @@ -169,11 +169,11 @@ void JavaIntrnLowering::ProcessJavaIntrnFillNewArray(IntrinsiccallNode &intrinCa currFunc->GetBody()->ReplaceStmt1WithStmt2(&intrinCall, assignStmt); addrExpr = builder->CreateExprDread(*retSym); } else { - PregIdx pregidx = retPair.second.GetPregIdx(); - MIRPreg *mirpreg = currFunc->GetPregTab()->PregFromPregIdx(pregidx); - assignStmt = builder->CreateStmtRegassign(mirpreg->GetPrimType(), pregidx, newArrayNode); + PregIdx pregIdx = retPair.second.GetPregIdx(); + MIRPreg *mirPreg = currFunc->GetPregTab()->PregFromPregIdx(pregIdx); + assignStmt = builder->CreateStmtRegassign(mirPreg->GetPrimType(), pregIdx, newArrayNode); currFunc->GetBody()->ReplaceStmt1WithStmt2(&intrinCall, assignStmt); - addrExpr = builder->CreateExprRegread(mirpreg->GetPrimType(), pregidx); + addrExpr = builder->CreateExprRegread(mirPreg->GetPrimType(), pregIdx); } assignStmt->SetSrcPos(intrinCall.GetSrcPos()); StmtNode *stmt = assignStmt; diff --git a/src/mpl2mpl/src/muid_replacement.cpp b/src/mpl2mpl/src/muid_replacement.cpp index ce89d73eadb9edb9cad33e7a1ab79fb8a7ba01ab..2e26ae82491513bd77cd98af3fe299052113a730 100644 --- a/src/mpl2mpl/src/muid_replacement.cpp +++ b/src/mpl2mpl/src/muid_replacement.cpp @@ -27,7 +27,7 @@ // table.And then we can close these symbols to reduce the code size. namespace maple { -MUID MUIDReplacement::kMplMuid; +MUID MUIDReplacement::mplMuid; MUIDReplacement::MUIDReplacement(MIRModule *mod, KlassHierarchy *kh, bool dump) : FuncOptimizeImpl(mod, kh, dump), @@ -73,14 +73,14 @@ void MUIDReplacement::DumpMUIDFile(bool isFunc) { outFile << outName << " "; MIRSymbol *mirFunc = keyVal.second.first; outFile << mirFunc->GetName() << " "; - outFile << keyVal.first.ToStr() << std::endl; + outFile << keyVal.first.ToStr() << "\n"; } } else { for (auto const &keyVal : dataDefMap) { outFile << outName << " "; MIRSymbol *mirSymbol = keyVal.second.first; outFile << mirSymbol->GetName() << " "; - outFile << keyVal.first.ToStr() << std::endl; + outFile << keyVal.first.ToStr() << "\n"; } } } @@ -90,7 +90,7 @@ void MUIDReplacement::CollectFuncAndDataFromKlasses() { for (Klass *klass : klassHierarchy->GetTopoSortedKlasses()) { MIRStructType *sType = klass->GetMIRStructType(); // DefTable and UndefTable are placed where a class is defined - if (!sType || !sType->IsLocal()) { + if (sType == nullptr || !sType->IsLocal()) { continue; } // Collect FuncDefSet @@ -123,10 +123,10 @@ void MUIDReplacement::CollectFuncAndDataFromGlobalTab() { for (size_t i = 1; i < GlobalTables::GetGsymTable().GetSymbolTableSize(); i++) { // entry 0 is reserved as nullptr MIRSymbol *mirSymbol = GlobalTables::GetGsymTable().GetSymbolFromStidx(i); - CHECK_FATAL(mirSymbol, "Invalid global data symbol at index %u", i); + CHECK_FATAL(mirSymbol != nullptr, "Invalid global data symbol at index %u", i); if (mirSymbol->GetStorageClass() == kScGlobal) { if (mirSymbol->IsReflectionClassInfo()) { - if (mirSymbol->GetKonst()) { + if (mirSymbol->GetKonst() != nullptr) { // Use this to exclude forward-declared classinfo symbol AddDefData(mirSymbol); } @@ -143,7 +143,7 @@ void MUIDReplacement::CollectFuncAndDataFromGlobalTab() { void MUIDReplacement::CollectFuncAndDataFromFuncList() { // Iterate function bodies for (MIRFunction *mirFunc : GetMIRModule().GetFunctionList()) { - if (!mirFunc->GetBody()) { + if (mirFunc->GetBody() == nullptr) { continue; } StmtNode *stmt = mirFunc->GetBody()->GetFirst(); @@ -157,14 +157,14 @@ void MUIDReplacement::CollectFuncAndDataFromFuncList() { } case OP_dassign: { // epre in ME may have splitted a direct call into addroffunc and an indirect call - BaseNode *rhs = static_cast(stmt)->GetRHS(); + auto *rhs = static_cast(stmt)->GetRHS(); if (rhs != nullptr && rhs->GetOpCode() == OP_addroffunc) { puidx = static_cast(rhs)->GetPUIdx(); } break; } case OP_regassign: { - BaseNode *rhs = static_cast(stmt)->Opnd(); + auto *rhs = static_cast(stmt)->Opnd(); if (rhs != nullptr && rhs->GetOpCode() == OP_addroffunc) { puidx = static_cast(rhs)->GetPUIdx(); } @@ -175,7 +175,7 @@ void MUIDReplacement::CollectFuncAndDataFromFuncList() { } if (puidx != 0) { MIRFunction *undefMIRFunc = GlobalTables::GetFunctionTable().GetFunctionFromPuidx(puidx); - ASSERT(undefMIRFunc, "Invalid MIRFunction"); + ASSERT(undefMIRFunc != nullptr, "Invalid MIRFunction"); if (undefMIRFunc->GetBody() == nullptr && (undefMIRFunc->IsJava() || !undefMIRFunc->GetBaseClassName().empty())) { AddUndefFunc(undefMIRFunc); @@ -270,14 +270,14 @@ void MUIDReplacement::GenericFuncDefTable() { FieldVector fields; GlobalTables::GetTypeTable().PushIntoFieldVector(fields, "funcUnifiedAddr", *GlobalTables::GetTypeTable().GetCompactPtr()); - MIRStructType *funcDefTabEntryType = static_cast( + auto *funcDefTabEntryType = static_cast( GlobalTables::GetTypeTable().GetOrCreateStructType("MUIDFuncDefTabEntry", fields, parentFields, GetMIRModule())); FieldVector funcinffields; GlobalTables::GetTypeTable().PushIntoFieldVector(funcinffields, "funcSize", *GlobalTables::GetTypeTable().GetUInt32()); GlobalTables::GetTypeTable().PushIntoFieldVector(funcinffields, "funcName", *GlobalTables::GetTypeTable().GetUInt32()); - MIRStructType *funcInfTabEntryType = static_cast(GlobalTables::GetTypeTable().GetOrCreateStructType( + auto *funcInfTabEntryType = static_cast(GlobalTables::GetTypeTable().GetOrCreateStructType( "MUIDFuncInfTabEntry", funcinffields, parentFields, GetMIRModule())); FieldVector muidFields; #ifdef USE_64BIT_MUID @@ -287,7 +287,7 @@ void MUIDReplacement::GenericFuncDefTable() { GlobalTables::GetTypeTable().PushIntoFieldVector(muidFields, "muidLow", *GlobalTables::GetTypeTable().GetUInt64()); GlobalTables::GetTypeTable().PushIntoFieldVector(muidFields, "muidHigh", *GlobalTables::GetTypeTable().GetUInt64()); #endif // USE_64BIT_MUID - MIRStructType *funcDefMuidTabEntryType = + auto *funcDefMuidTabEntryType = static_cast(GlobalTables::GetTypeTable().GetOrCreateStructType( "MUIDFuncDefMuidTabEntry", muidFields, parentFields, GetMIRModule())); MIRArrayType &arrayType = *GlobalTables::GetTypeTable().GetOrCreateArrayType(*funcDefTabEntryType, arraySize); @@ -311,10 +311,10 @@ void MUIDReplacement::GenericFuncDefTable() { // With muidIdxTab, we can use index sorted by muid to find the index in funcDefTab and funcDefMuidTab // Use the left 1 bit of muidIdx to mark wether the function is weak or not. 1 is for weak MIRIntConst *indexConst = nullptr; - if (kReflectionList.find(mirFunc->GetName()) != kReflectionList.end()) { - constexpr uint32 kWeakFuncFlag = 0x80000000; // 0b10000000 00000000 00000000 00000000 + if (reflectionList.find(mirFunc->GetName()) != reflectionList.end()) { + constexpr uint32 weakFuncFlag = 0x80000000; // 0b10000000 00000000 00000000 00000000 indexConst = - GetMIRModule().GetMemPool()->New(kWeakFuncFlag | idx, *GlobalTables::GetTypeTable().GetUInt32()); + GetMIRModule().GetMemPool()->New(weakFuncFlag | idx, *GlobalTables::GetTypeTable().GetUInt32()); } else { indexConst = GetMIRModule().GetMemPool()->New(idx, *GlobalTables::GetTypeTable().GetUInt32()); } @@ -327,7 +327,7 @@ void MUIDReplacement::GenericFuncDefTable() { LogInfo::MapleLogger() << "funcDefMap, MUID: " << muid.ToStr() << ", Function Name: " << iter->second.first->GetName() << ", Offset in addr order: " << (idx - 1) - << ", Offset in muid order: " << iter->second.second << std::endl; + << ", Offset in muid order: " << iter->second.second << "\n"; } } // Create funcDefTab, funcInfoTab and funcMuidTab sorted by address, funcMuidIdxTab sorted by muid @@ -399,7 +399,7 @@ void MUIDReplacement::GenericDataDefTable() { FieldVector fields; GlobalTables::GetTypeTable().PushIntoFieldVector(fields, "dataUnifiedAddr", *GlobalTables::GetTypeTable().GetCompactPtr()); - MIRStructType *dataDefTabEntryType = static_cast( + auto *dataDefTabEntryType = static_cast( GlobalTables::GetTypeTable().GetOrCreateStructType("MUIDDataDefTabEntry", fields, parentFields, GetMIRModule())); FieldVector muidFields; #ifdef USE_64BIT_MUID // USE_64BIT_MUID @@ -409,7 +409,7 @@ void MUIDReplacement::GenericDataDefTable() { GlobalTables::GetTypeTable().PushIntoFieldVector(muidFields, "muidLow", *GlobalTables::GetTypeTable().GetUInt64()); GlobalTables::GetTypeTable().PushIntoFieldVector(muidFields, "muidHigh", *GlobalTables::GetTypeTable().GetUInt64()); #endif - MIRStructType *dataDefMuidTabEntryType = + auto *dataDefMuidTabEntryType = static_cast(GlobalTables::GetTypeTable().GetOrCreateStructType( std::string("MUIDDataDefMuidTabEntry"), muidFields, parentFields, GetMIRModule())); size_t arraySize = dataDefMap.size(); @@ -433,7 +433,7 @@ void MUIDReplacement::GenericDataDefTable() { mplMuidStr += muid.ToStr(); if (trace) { LogInfo::MapleLogger() << "dataDefMap, MUID: " << muid.ToStr() << ", Variable Name: " << mirSymbol->GetName() - << ", Offset: " << keyVal.second.second << std::endl; + << ", Offset: " << keyVal.second.second << "\n"; } } if (Options::dumpMuidFile) { @@ -479,7 +479,7 @@ void MUIDReplacement::GenericUnifiedUndefTable() { FieldVector fields; GlobalTables::GetTypeTable().PushIntoFieldVector(fields, "globalAddress", *GlobalTables::GetTypeTable().GetCompactPtr()); - MIRStructType *unifiedUndefTabEntryType = + auto *unifiedUndefTabEntryType = static_cast(GlobalTables::GetTypeTable().GetOrCreateStructType( std::string("MUIDUnifiedUndefTabEntry"), fields, parentFields, GetMIRModule())); FieldVector muidFields; @@ -490,7 +490,7 @@ void MUIDReplacement::GenericUnifiedUndefTable() { GlobalTables::GetTypeTable().PushIntoFieldVector(muidFields, "muidLow", *GlobalTables::GetTypeTable().GetUInt64()); GlobalTables::GetTypeTable().PushIntoFieldVector(muidFields, "muidHigh", *GlobalTables::GetTypeTable().GetUInt64()); #endif - MIRStructType *unifiedUndefMuidTabEntryType = + auto *unifiedUndefMuidTabEntryType = static_cast(GlobalTables::GetTypeTable().GetOrCreateStructType( "MUIDUnifiedUndefMuidTabEntry", muidFields, parentFields, GetMIRModule())); size_t arraySize = funcUndefMap.size(); @@ -505,7 +505,7 @@ void MUIDReplacement::GenericUnifiedUndefTable() { if (trace) { LogInfo::MapleLogger() << "funcUndefMap, MUID: " << muid.ToStr() << ", Function Name: " << keyVal.second.first->GetName() - << ", Offset: " << keyVal.second.second << std::endl; + << ", Offset: " << keyVal.second.second << "\n"; } MIRAggConst *entryConst = GetMIRModule().GetMemPool()->New(GetMIRModule(), *unifiedUndefTabEntryType); uint32 fieldID = 1; @@ -556,7 +556,7 @@ void MUIDReplacement::GenericUnifiedUndefTable() { mplMuidStr += muid.ToStr(); if (trace) { LogInfo::MapleLogger() << "dataUndefMap, MUID: " << muid.ToStr() << ", Variable Name: " << mirSymbol->GetName() - << ", Offset: " << keyVal.second.second << std::endl; + << ", Offset: " << keyVal.second.second << "\n"; } } if (!dataUndefTabConst->GetConstVec().empty()) { @@ -614,10 +614,21 @@ void MUIDReplacement::GenericRangeTable() { rangeTabConst->GetConstVec().push_back(entryConst); } // Please refer to mrt/compiler-rt/include/mpl_linker.h for the layout - std::vector workList = { funcDefTabSym, funcDefOrigTabSym, funcInfTabSym, funcUndefTabSym, - dataDefTabSym, dataDefOrigTabSym, dataUndefTabSym, funcDefMuidTabSym, - funcUndefMuidTabSym, dataDefMuidTabSym, dataUndefMuidTabSym, funcMuidIdxTabSym, - funcProfileTabSym }; + std::vector workList = { + funcDefTabSym, + funcDefOrigTabSym, + funcInfTabSym, + funcUndefTabSym, + dataDefTabSym, + dataDefOrigTabSym, + dataUndefTabSym, + funcDefMuidTabSym, + funcUndefMuidTabSym, + dataDefMuidTabSym, + dataUndefMuidTabSym, + funcMuidIdxTabSym, + funcProfileTabSym + }; for (MIRSymbol *mirSymbol : workList) { MIRAggConst *entryConst = GetMIRModule().GetMemPool()->New(GetMIRModule(), rangeTabEntryType); uint32 fieldID = 1; @@ -691,9 +702,9 @@ void MUIDReplacement::ReplaceFuncTable(const std::string &name) { if (tabSym->GetName().find(VTAB_PREFIX_STR) == 0) { isVtab = true; } - for (MIRConst *&oldTabEntry : static_cast(oldConst)->GetConstVec()) { + for (auto *&oldTabEntry : static_cast(oldConst)->GetConstVec()) { if (oldTabEntry->GetKind() == kConstAggConst) { - MIRAggConst *aggrC = static_cast(oldTabEntry); + auto *aggrC = static_cast(oldTabEntry); for (size_t i = 0; i < aggrC->GetConstVec().size(); i++) { ReplaceAddroffuncConst(aggrC->GetConstVecItem(i), i + 1, isVtab); } @@ -703,26 +714,26 @@ void MUIDReplacement::ReplaceFuncTable(const std::string &name) { } } -void MUIDReplacement::ReplaceAddroffuncConst(MIRConst *&entry, uint32 fieldId, bool isVtab = false) { +void MUIDReplacement::ReplaceAddroffuncConst(MIRConst *&entry, uint32 fieldID, bool isVtab = false) { if (entry->GetKind() != kConstAddrofFunc) { return; } MIRType &voidType = *GlobalTables::GetTypeTable().GetVoidPtr(); - MIRAddroffuncConst *funcAddr = static_cast(entry); + auto *funcAddr = static_cast(entry); MIRFunction *func = GlobalTables::GetFunctionTable().GetFunctionFromPuidx(funcAddr->GetValue()); ASSERT(func != nullptr, "Invalid MIRFunction"); uint64 offset = 0; MIRIntConst *constNode = nullptr; - constexpr uint64 kReservedBits = 2u; - if (func->GetBody()) { + constexpr uint64 reservedBits = 2u; + if (func->GetBody() != nullptr) { ASSERT(func->GetFuncSymbol() != nullptr, "null ptr check!"); offset = FindIndexFromDefTable(*(func->GetFuncSymbol()), true); // Left shifting is needed because in itable 0 and 1 are reserved. // 0 marks no entry and 1 marks a conflict. // The second least significant bit is set to 1, indicating // this is an index into the funcDefTab - constexpr uint64 kIdxIntoFuncDefTabFlag = 2u; - constNode = GetMIRModule().GetMemPool()->New(((offset + 1) << kReservedBits) + kIdxIntoFuncDefTabFlag, + constexpr uint64 idxIntoFuncDefTabFlag = 2u; + constNode = GetMIRModule().GetMemPool()->New(((offset + 1) << reservedBits) + idxIntoFuncDefTabFlag, voidType); } else if (isVtab && func->IsAbstract()) { MIRType &type = *GlobalTables::GetTypeTable().GetVoidPtr(); @@ -732,10 +743,10 @@ void MUIDReplacement::ReplaceAddroffuncConst(MIRConst *&entry, uint32 fieldId, b offset = FindIndexFromUndefTable(*(func->GetFuncSymbol()), true); // The second least significant bit is set to 0, indicating // this is an index into the funcUndefTab - constNode = GetMIRModule().GetMemPool()->New((offset + 1) << kReservedBits, voidType); + constNode = GetMIRModule().GetMemPool()->New((offset + 1) << reservedBits, voidType); } - if (fieldId != 0xffffffff) { - constNode->SetFieldID(fieldId); + if (fieldID != 0xffffffff) { + constNode->SetFieldID(fieldID); } entry = constNode; } @@ -745,14 +756,14 @@ void MUIDReplacement::ReplaceDataTable(const std::string &name) { if (tabSym == nullptr) { return; } - MIRAggConst *oldConst = static_cast(tabSym->GetKonst()); + auto *oldConst = static_cast(tabSym->GetKonst()); if (oldConst == nullptr) { return; } for (MIRConst *&oldTabEntry : oldConst->GetConstVec()) { ASSERT(oldTabEntry != nullptr, "null ptr check!"); if (oldTabEntry->GetKind() == kConstAggConst) { - MIRAggConst *aggrC = static_cast(oldTabEntry); + auto *aggrC = static_cast(oldTabEntry); for (size_t i = 0; i < aggrC->GetConstVec().size(); i++) { ASSERT(aggrC->GetConstVecItem(i) != nullptr, "null ptr check!"); ReplaceAddrofConst(aggrC->GetConstVecItem(i)); @@ -769,7 +780,7 @@ void MUIDReplacement::ReplaceAddrofConst(MIRConst *&entry) { return; } MIRType &voidType = *GlobalTables::GetTypeTable().GetVoidPtr(); - MIRAddrofConst *addr = static_cast(entry); + auto *addr = static_cast(entry); MIRSymbol *addrSym = GlobalTables::GetGsymTable().GetSymbolFromStidx(addr->GetSymbolIndex().Idx()); ASSERT(addrSym != nullptr, "Invalid MIRSymbol"); if (!addrSym->IsReflectionClassInfo() && !addrSym->IsStatic()) { @@ -818,7 +829,7 @@ void MUIDReplacement::ReplaceDirectInvokeOrAddroffunc(MIRFunction ¤tFunc, AddrofNode *baseExpr = nullptr; uint32 index = 0; MIRArrayType *arrayType = nullptr; - if (calleeFunc->GetBody()) { + if (calleeFunc->GetBody() != nullptr) { // Local function is accessed through funcDefTab // Add a comment to store the original function name std::string commentLabel = NameMangler::kMarkMuidFuncDefStr + calleeFunc->GetName(); @@ -943,20 +954,20 @@ void MUIDReplacement::ReplaceDreadStmt(MIRFunction *currentFunc, StmtNode *stmt) } switch (stmt->GetOpCode()) { case OP_if: { - IfStmtNode *inode = static_cast(stmt); + auto *inode = static_cast(stmt); inode->SetOpnd(ReplaceDreadExpr(currentFunc, stmt, inode->Opnd(0)), 0); ReplaceDreadStmt(currentFunc, inode->GetThenPart()); ReplaceDreadStmt(currentFunc, inode->GetElsePart()); break; } case OP_while: { - WhileStmtNode *wnode = static_cast(stmt); + auto *wnode = static_cast(stmt); wnode->SetOpnd(ReplaceDreadExpr(currentFunc, stmt, wnode->Opnd(0)), 0); ReplaceDreadStmt(currentFunc, wnode->GetBody()); break; } case OP_block: { - BlockNode *bnode = static_cast(stmt); + auto *bnode = static_cast(stmt); for (auto &s : bnode->GetStmtNodes()) { ReplaceDreadStmt(currentFunc, &s); } @@ -1017,7 +1028,7 @@ BaseNode *MUIDReplacement::ReplaceDread(MIRFunction ¤tFunc, StmtNode *stmt if (opnd == nullptr || (opnd->GetOpCode() != OP_dread && opnd->GetOpCode() != OP_addrof)) { return opnd; } - DreadNode *dreadNode = static_cast(opnd); + auto *dreadNode = static_cast(opnd); MIRSymbol *mirSymbol = currentFunc.GetLocalOrGlobalSymbol(dreadNode->GetStIdx()); ASSERT(mirSymbol != nullptr, "null ptr check!"); if (!mirSymbol->IsStatic()) { @@ -1072,7 +1083,7 @@ void MUIDReplacement::ProcessFunc(MIRFunction *func) { ReplaceDirectInvokeOrAddroffunc(*func, *stmt); } else if (stmt->GetOpCode() == OP_dassign) { ReplaceDirectInvokeOrAddroffunc(*func, *stmt); - DassignNode *dassignNode = static_cast(stmt); + auto *dassignNode = static_cast(stmt); ReplaceDassign(*func, *dassignNode); } else if (stmt->GetOpCode() == OP_regassign) { ReplaceDirectInvokeOrAddroffunc(*func, *stmt); @@ -1104,7 +1115,7 @@ void MUIDReplacement::GenericGlobalRootList() { if (type->GetKind() != kTypePointer) { continue; } - MIRPtrType *pointType = static_cast(type); + auto *pointType = static_cast(type); MIRType *pointedType = pointType->GetPointedType(); if (!(pointedType->GetKind() == kTypeClass)) { continue; diff --git a/src/mpl2mpl/src/native_stub_func.cpp b/src/mpl2mpl/src/native_stub_func.cpp index 4546dd62d252ffca909461baff0ed66c09240244..d57d736c81361b3764b89b063d7423e0e1812d8d 100644 --- a/src/mpl2mpl/src/native_stub_func.cpp +++ b/src/mpl2mpl/src/native_stub_func.cpp @@ -48,7 +48,7 @@ MIRFunction &GenericNativeStubFunc::GetOrCreateDefaultNativeFunc(MIRFunction &st MIRFunction *nativeFunc = builder->GetOrCreateFunction(nativeName.c_str(), stubFunc.GetReturnTyIdx()); ASSERT(nativeFunc != nullptr, "null ptr check!"); nativeFunc->GetSrcPosition().SetMplLineNum(stubFunc.GetSrcPosition().MplLineNum()); - if (!nativeFunc->GetBody()) { + if (nativeFunc->GetBody() == nullptr) { builder->SetCurrentFunction(nativeFunc); nativeFunc->SetAttr(FUNCATTR_weak); nativeFunc->SetBody(nativeFunc->GetCodeMempool()->New()); @@ -112,7 +112,7 @@ void GenericNativeStubFunc::ProcessFunc(MIRFunction *func) { } SetCurrentFunction(*func); if (trace) { - LogInfo::MapleLogger(kLlErr) << "Create stub func: " << func->GetName() << std::endl; + LogInfo::MapleLogger(kLlErr) << "Create stub func: " << func->GetName() << "\n"; } if (func->GetBody()) { func->GetBody()->ResetBlock(); @@ -128,7 +128,7 @@ void GenericNativeStubFunc::ProcessFunc(MIRFunction *func) { GStrIdx classObjSymStrIdx = GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(CLASSINFO_PREFIX_STR + func->GetBaseClassName()); MIRSymbol *classObjSymbol = GlobalTables::GetGsymTable().GetSymbolFromStrIdx(classObjSymStrIdx); - ASSERT(classObjSymbol, "Classinfo for %s is not found", func->GetBaseClassName().c_str()); + ASSERT(classObjSymbol != nullptr, "Classinfo for %s is not found", func->GetBaseClassName().c_str()); // Generate MonitorEnter if this is a synchronized method if (func->GetAttr(FUNCATTR_synchronized)) { BaseNode *monitor = nullptr; @@ -348,7 +348,7 @@ void GenericNativeStubFunc::GenericRegisteredNativeFuncCall(MIRFunction &func, c AddrofNode *regFuncExpr = builder->CreateExprAddrof(0, *regFuncSymbol); ArrayNode *arrayExpr = builder->CreateExprArray(regArrayType, regFuncExpr, builder->CreateIntConst(loc - 1, PTY_i32)); arrayExpr->SetBoundsCheck(false); - MIRType *elemType = static_cast(regArrayType).GetElemType(); + auto *elemType = static_cast(regArrayType).GetElemType(); BaseNode *ireadExpr = builder->CreateExprIread(*elemType, *GlobalTables::GetTypeTable().GetOrCreatePointerType(*elemType), 0, arrayExpr); // assign registered func ptr to a preg. @@ -372,7 +372,7 @@ void GenericNativeStubFunc::GenericRegisteredNativeFuncCall(MIRFunction &func, c builder->CreateExprCompare(OP_eq, *GlobalTables::GetTypeTable().GetUInt1(), *GlobalTables::GetTypeTable().GetPtr(), readFuncptrshift, builder->CreateIntConst(kInvalidCode, PTY_ptr)); - IfStmtNode *ifStmt = static_cast(builder->CreateStmtIf(checkRegExpr)); + auto *ifStmt = static_cast(builder->CreateStmtIf(checkRegExpr)); // get find_native_func function MIRType *voidPointerType = GlobalTables::GetTypeTable().GetVoidPtr(); // set parameter of find_native_func @@ -412,7 +412,7 @@ void GenericNativeStubFunc::GenericRegisteredNativeFuncCall(MIRFunction &func, c BaseNode *checkStubReturnExpr = builder->CreateExprCompare(OP_eq, *GlobalTables::GetTypeTable().GetUInt1(), *GlobalTables::GetTypeTable().GetPtr(), readFuncPtr, readDummyFuncPtr); - IfStmtNode *subIfStmt = static_cast(builder->CreateStmtIf(checkStubReturnExpr)); + auto *subIfStmt = static_cast(builder->CreateStmtIf(checkStubReturnExpr)); // Assign with address of strong/weak symbol auto *nativeFuncAddr = builder->CreateExprAddroffunc(nativeFunc.GetPuidx()); funcptrAssign = builder->CreateStmtRegassign(PTY_ptr, funcptrPreg, nativeFuncAddr); @@ -445,8 +445,7 @@ void GenericNativeStubFunc::GenericRegisteredNativeFuncCall(MIRFunction &func, c ifStmt->GetThenPart()->AddStatement(callGetExceptFunc); BlockNode *elseBlock = func.GetCodeMempool()->New(); ifStmt->SetElsePart(elseBlock); - constexpr uint32 kNumOfOpnds = 3u; - ifStmt->SetNumOpnds(kNumOfOpnds); + ifStmt->SetNumOpnds(kOperandNumTernary); wrapperCall = CreateNativeWrapperCallNode(func, readFuncPtr, args, ret); elseBlock->AddStatement(wrapperCall); func.GetBody()->AddStatement(ifStmt); @@ -516,8 +515,8 @@ StmtNode *GenericNativeStubFunc::CreateNativeWrapperCallNode(MIRFunction &func, auto isFast = (func.GetAttr(FUNCATTR_fast_native) || func.GetAttr(FUNCATTR_critical_native)); // Do not need native wrapper for critical natives // if num_of_args < 8 - constexpr size_t kNumOfArgs = 8; - if (func.GetAttr(FUNCATTR_critical_native) && args.size() < kNumOfArgs) { + constexpr size_t numOfArgs = 8; + if (func.GetAttr(FUNCATTR_critical_native) && args.size() < numOfArgs) { IcallNode *icall = func.GetCodeMempool()->New(GetMIRModule(), OP_icallassigned); CallReturnVector nrets(func.GetCodeMempoolAllocator()->Adapter()); if (ret != nullptr) { @@ -538,7 +537,7 @@ StmtNode *GenericNativeStubFunc::CreateNativeWrapperCallNode(MIRFunction &func, } // If num of args > 8 - if (args.size() > kNumOfArgs) { + if (args.size() > numOfArgs) { wrapperFunc = isFast ? MRTCallFastNativeExtFunc : MRTCallSlowNativeExtFunc; } else if (isFast) { wrapperFunc = MRTCallFastNativeFunc; @@ -577,7 +576,7 @@ void GenericNativeStubFunc::GenericHelperFuncDecl() { // MRT_PendingException MRTCheckThrowPendingExceptionFunc = builder->GetOrCreateFunction(kCheckThrowPendingExceptionFunc, voidType->GetTypeIndex()); - CHECK_FATAL(MRTCheckThrowPendingExceptionFunc, + CHECK_FATAL(MRTCheckThrowPendingExceptionFunc != nullptr, "MRTCheckThrowPendingExceptionFunc is null in GenericNativeStubFunc::GenericHelperFuncDecl"); MRTCheckThrowPendingExceptionFunc->SetAttr(FUNCATTR_nosideeffect); MRTCheckThrowPendingExceptionFunc->SetBody(nullptr); @@ -585,31 +584,32 @@ void GenericNativeStubFunc::GenericHelperFuncDecl() { ArgVector preArgs(GetMIRModule().GetMPAllocator().Adapter()); preArgs.push_back(ArgPair("caller", refType)); MRTPreNativeFunc = builder->CreateFunction(kPreNativeFunc, *voidPointerType, preArgs); - CHECK_FATAL(MRTPreNativeFunc, "MRTPreNativeFunc is null in GenericNativeStubFunc::GenericHelperFuncDecl"); + CHECK_FATAL(MRTPreNativeFunc != nullptr, "MRTPreNativeFunc is null in GenericNativeStubFunc::GenericHelperFuncDecl"); MRTPreNativeFunc->SetBody(nullptr); // MRT_PostNativeCall ArgVector postArgs(GetMIRModule().GetMPAllocator().Adapter()); postArgs.push_back(ArgPair("env", voidPointerType)); MRTPostNativeFunc = builder->CreateFunction(kPostNativeFunc, *voidType, postArgs); - CHECK_FATAL(MRTPostNativeFunc, "MRTPostNativeFunc is null in GenericNativeStubFunc::GenericHelperFuncDecl"); + CHECK_FATAL(MRTPostNativeFunc != nullptr, "MRTPostNativeFunc is null in GenericNativeStubFunc::GenericHelperFuncDecl"); MRTPostNativeFunc->SetBody(nullptr); // MRT_DecodeReference ArgVector decodeArgs(GetMIRModule().GetMPAllocator().Adapter()); decodeArgs.push_back(ArgPair("obj", refType)); MRTDecodeRefFunc = builder->CreateFunction(kDecodeRefFunc, *refType, decodeArgs); - CHECK_FATAL(MRTDecodeRefFunc, "MRTDecodeRefFunc is null in GenericNativeStubFunc::GenericHelperFuncDecl"); + CHECK_FATAL(MRTDecodeRefFunc != nullptr, "MRTDecodeRefFunc is null in GenericNativeStubFunc::GenericHelperFuncDecl"); MRTDecodeRefFunc->SetAttr(FUNCATTR_nosideeffect); MRTDecodeRefFunc->SetBody(nullptr); // MCC_CallFastNative ArgVector callArgs(GetMIRModule().GetMPAllocator().Adapter()); callArgs.push_back(ArgPair("func", voidPointerType)); MRTCallFastNativeFunc = builder->CreateFunction(kCallFastNativeFunc, *voidPointerType, callArgs); - CHECK_FATAL(MRTCallFastNativeFunc, "MRTCallFastNativeFunc is null in GenericNativeStubFunc::GenericHelperFuncDecl"); + CHECK_FATAL(MRTCallFastNativeFunc != nullptr, + "MRTCallFastNativeFunc is null in GenericNativeStubFunc::GenericHelperFuncDecl"); MRTCallFastNativeFunc->SetBody(nullptr); // MCC_CallSlowNative for (int i = 0; i < kSlownativeFuncnum; i++) { - MRTCallSlowNativeFunc[i] = builder->CreateFunction(kCallSlowNativeFuncs[i], *voidPointerType, callArgs); - CHECK_FATAL(MRTCallSlowNativeFunc[i], + MRTCallSlowNativeFunc[i] = builder->CreateFunction(callSlowNativeFuncs[i], *voidPointerType, callArgs); + CHECK_FATAL(MRTCallSlowNativeFunc[i] != nullptr, "MRTCallSlowNativeFunc is null in GenericNativeStubFunc::GenericHelperFuncDecl"); MRTCallSlowNativeFunc[i]->SetBody(nullptr); } @@ -628,7 +628,7 @@ void GenericNativeStubFunc::GenericHelperFuncDecl() { // MCC_SetReliableUnwindContext MCCSetReliableUnwindContextFunc = builder->GetOrCreateFunction(kSetReliableUnwindContextFunc, voidType->GetTypeIndex()); - CHECK_FATAL(MCCSetReliableUnwindContextFunc, + CHECK_FATAL(MCCSetReliableUnwindContextFunc != nullptr, "MCCSetReliableUnwindContextFunc is null in GenericNativeStubFunc::GenericHelperFuncDecl"); MCCSetReliableUnwindContextFunc->SetAttr(FUNCATTR_nosideeffect); MCCSetReliableUnwindContextFunc->SetBody(nullptr); diff --git a/src/mpl2mpl/src/reflection_analysis.cpp b/src/mpl2mpl/src/reflection_analysis.cpp index 10d79d4d8898bd09c7662775f12d9396559636b9..721fdb94be869ac7ec351cfb72f41fcc76d57d31 100644 --- a/src/mpl2mpl/src/reflection_analysis.cpp +++ b/src/mpl2mpl/src/reflection_analysis.cpp @@ -26,6 +26,7 @@ #include "name_mangler.h" #include "itab_util.h" #include "string_utils.h" +#include "metadata_layout.h" // Reflection metadata // This file is used to generate the classmetadata and classhashmetadata. @@ -34,7 +35,6 @@ // and we generates these data according to the structure which defined in // the reflection_analysis.h && metadata_layout.h and then add their address // to mirbuilder. -using namespace NameMangler; namespace maple { std::string ReflectionAnalysis::strTab = std::string(1, '\0'); @@ -50,7 +50,7 @@ int ReflectionAnalysis::GetDeflateStringIdx(const std::string &subStr) { static uint32 FirstFindOrInsertRepeatString(const std::string &str, bool isHot, uint8 hotType) { uint32 index = 0; - constexpr int kLengthShift = 2; + constexpr uint32 lengthShift = 2u; auto it = ReflectionAnalysis::GetStr2IdxMap().find(str); if (it != ReflectionAnalysis::GetStr2IdxMap().end()) { index = it->second; @@ -58,20 +58,20 @@ static uint32 FirstFindOrInsertRepeatString(const std::string &str, bool isHot, if (isHot) { if (hotType == kLayoutBootHot) { uint32 length = ReflectionAnalysis::GetStrTabStartHot().length(); - index = (length << kLengthShift) | (kLayoutBootHot + kCStringShift); // Use the LSB to indicate hotness. + index = (length << lengthShift) | (kLayoutBootHot + kCStringShift); // Use the LSB to indicate hotness. ReflectionAnalysis::AddStrTabStartHot(str + '\0'); } else if (hotType == kLayoutBothHot) { uint32 length = ReflectionAnalysis::GetStrTabBothHot().length(); - index = (length << kLengthShift) | (kLayoutBothHot + kCStringShift); // Use the LSB to indicate hotness. + index = (length << lengthShift) | (kLayoutBothHot + kCStringShift); // Use the LSB to indicate hotness. ReflectionAnalysis::AddStrTabBothHot(str + '\0'); } else { uint32 length = ReflectionAnalysis::GetStrTabRunHot().length(); - index = (length << kLengthShift) | (kLayoutRunHot + kCStringShift); // Use the LSB to indicate hotness. + index = (length << lengthShift) | (kLayoutRunHot + kCStringShift); // Use the LSB to indicate hotness. ReflectionAnalysis::AddStrTabRunHot(str + '\0'); } } else { uint32 length = ReflectionAnalysis::GetStrTab().length(); - index = length << kLengthShift; + index = length << lengthShift; ReflectionAnalysis::AddStrTab(str + '\0'); } ReflectionAnalysis::SetStr2IdxMap(str, index); @@ -96,7 +96,7 @@ uint32 ReflectionAnalysis::FindOrInsertRepeatString(const std::string &str, bool BaseNode *ReflectionAnalysis::GenClassInfoAddr(BaseNode *obj, MIRBuilder &builder) { GenMetadataType(builder.GetMirModule()); - MIRClassType *objectType = static_cast(WKTypes::Util::GetJavaLangObjectType()); + auto *objectType = static_cast(WKTypes::Util::GetJavaLangObjectType()); BaseNode *classinfoAddress = nullptr; if (objectType != nullptr && objectType->GetKind() != kTypeClassIncomplete) { classinfoAddress = builder.CreateExprIread(*GlobalTables::GetTypeTable().GetRef(), @@ -104,7 +104,7 @@ BaseNode *ReflectionAnalysis::GenClassInfoAddr(BaseNode *obj, MIRBuilder &builde OBJ_KLASS_FIELDID, obj); } else { // If java.lang.Object type is not defined, fall back to use the classinfo struct to retrieve the first field. - MIRStructType *classMetadataType = static_cast( + auto *classMetadataType = static_cast( GlobalTables::GetTypeTable().GetTypeFromTyIdx(ReflectionAnalysis::classMetadataTyIdx)); classinfoAddress = builder.CreateExprIread(*GlobalTables::GetTypeTable().GetRef(), *GlobalTables::GetTypeTable().GetOrCreatePointerType(*classMetadataType), @@ -113,7 +113,7 @@ BaseNode *ReflectionAnalysis::GenClassInfoAddr(BaseNode *obj, MIRBuilder &builde return classinfoAddress; } -const char *ReflectionAnalysis::klassPtrName = kShadowClassName; +const char *ReflectionAnalysis::klassPtrName = NameMangler::kShadowClassName; TyIdx ReflectionAnalysis::classMetadataTyIdx = TyIdx(0); TyIdx ReflectionAnalysis::classMetadataRoTyIdx = TyIdx(0); TyIdx ReflectionAnalysis::methodsInfoTyIdx = TyIdx(0); @@ -179,7 +179,7 @@ uint32 GetFieldModifier(FieldAttrs fa) { uint32 GetClassAccessFlags(MIRClassType &classType) { int32 accessFlag = 0; - for (MIRPragma *prag : classType.GetPragmVec()) { + for (MIRPragma *prag : classType.GetPragmaVec()) { if (prag->GetKind() == kPragmaClass) { MapleVector elemVector = prag->GetElementVector(); for (MIRPragmaElement *elem : elemVector) { @@ -268,7 +268,7 @@ int ReflectionAnalysis::SolveAnnotation(MIRClassType &classType, MIRFunction &fu return GetDeflateStringIdx(subStr); } -uint32 ReflectionAnalysis::GetTypeNameIdxFromType(MIRType &type, const Klass &klass, const std::string &fieldname) { +uint32 ReflectionAnalysis::GetTypeNameIdxFromType(MIRType &type, const Klass &klass, const std::string &fieldName) { uint32 typeNameIdx = 0; switch (type.GetKind()) { case kTypeScalar: { @@ -277,7 +277,7 @@ uint32 ReflectionAnalysis::GetTypeNameIdxFromType(MIRType &type, const Klass &kl break; } case kTypePointer: { - MIRType *ptype = static_cast(&type)->GetPointedType(); + auto *ptype = static_cast(&type)->GetPointedType(); if (ptype->GetKind() == kTypeArray || ptype->GetKind() == kTypeJArray) { CHECK_FATAL(static_cast(ptype) != nullptr, "null ptr check"); std::string javaName = static_cast(ptype)->GetJavaName(); @@ -293,12 +293,12 @@ uint32 ReflectionAnalysis::GetTypeNameIdxFromType(MIRType &type, const Klass &kl typeNameIdx = FindOrInsertReflectString(klassJavaDescriptor); } else { CHECK_FATAL(false, "In class %s: field %s 's type is UNKNOWN", klass.GetKlassName().c_str(), - fieldname.c_str()); + fieldName.c_str()); } break; } default: { - CHECK_FATAL(false, "In class %s: field %s 's type is UNKNOWN", klass.GetKlassName().c_str(), fieldname.c_str()); + CHECK_FATAL(false, "In class %s: field %s 's type is UNKNOWN", klass.GetKlassName().c_str(), fieldName.c_str()); } } return typeNameIdx; @@ -339,8 +339,7 @@ void ReflectionAnalysis::ConvertMethodSig(std::string &signature) { size_t signatureSize = signature.size(); for (size_t i = 1; i < signatureSize; i++) { if (signature[i] == 'L') { - while (signature[++i] != ';') // eg. Ljava/io/InputStream; so we do not check the boundary. - ; + while (signature[++i] != ';') {} // eg. Ljava/io/InputStream; so we do not check the boundary. } else if (signature[i] == 'A') { signature[i] = '['; } @@ -409,28 +408,28 @@ uint16 GetFieldHash(std::vector> &fieldV, FieldPair } static void DelimeterConvert(std::string &str) { - constexpr size_t kNextPos = 2; + constexpr size_t nextPos = 2; size_t loc = str.find("`"); while (loc != std::string::npos) { str.replace(loc, 1, "``"); - loc = str.find("`", loc + kNextPos); + loc = str.find("`", loc + nextPos); } loc = str.find("!"); while (loc != std::string::npos) { str.replace(loc, 1, "`!"); - loc = str.find("!", loc + kNextPos); + loc = str.find("!", loc + nextPos); } loc = str.find("|"); while (loc != std::string::npos) { str.replace(loc, 1, "`|"); - loc = str.find("|", loc + kNextPos); + loc = str.find("|", loc + nextPos); } } bool ReflectionAnalysis::RootClassDefined() { if (isLibcore < 0) { // Check whether this module defines root classes including Class/Object/Fields/Methods. - Klass *objectKlass = klassh->GetKlassFromLiteral(kJavaLangObjectStr); + Klass *objectKlass = klassh->GetKlassFromLiteral(NameMangler::kJavaLangObjectStr); isLibcore = 0; if (objectKlass != nullptr && objectKlass->GetMIRStructType()->IsLocal()) { isLibcore = 1; @@ -451,7 +450,7 @@ MIRSymbol *ReflectionAnalysis::GetOrCreateSymbol(const std::string &name, TyIdx if (StringUtils::StartsWith(name, CLASSINFO_PREFIX_STR)) { std::string className = name.substr(strlen(CLASSINFO_PREFIX_STR)); Klass *klass = klassh->GetKlassFromName(className); - if (klass && !klass->GetMIRStructType()->IsLocal()) { + if (klass != nullptr && !klass->GetMIRStructType()->IsLocal()) { st->SetStorageClass(kScExtern); } } @@ -459,8 +458,8 @@ MIRSymbol *ReflectionAnalysis::GetOrCreateSymbol(const std::string &name, TyIdx } MIRSymbol *ReflectionAnalysis::GetSymbol(const std::string &name, TyIdx tyIdx) { - const GStrIdx stridx = GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(name); - MIRSymbol *st = GetSymbol(stridx, tyIdx); + const GStrIdx strIdx = GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(name); + MIRSymbol *st = GetSymbol(strIdx, tyIdx); return st; } @@ -503,15 +502,15 @@ bool ReflectionAnalysis::VtableFunc(const MIRFunction &func) const { } bool RtRetentionPolicyCheck(const MIRSymbol &clInfo) { - GStrIdx stridx; - MIRClassType *annoType = + GStrIdx strIdx; + auto *annoType = static_cast(GlobalTables::GetTypeTable().GetTypeFromTyIdx(clInfo.GetTyIdx())); - for (MIRPragma *p : annoType->GetPragmVec()) { + for (MIRPragma *p : annoType->GetPragmaVec()) { if (GlobalTables::GetStrTable().GetStringFromStrIdx( GlobalTables::GetTypeTable().GetTypeFromTyIdx(p->GetTyIdx())->GetNameStrIdx()) == (kJavaLangAnnotationRetentionStr)) { - stridx.SetIdx(p->GetElementVector()[0]->GetU64Val()); - std::string retentionType = GlobalTables::GetStrTable().GetStringFromStrIdx(stridx); + strIdx.SetIdx(p->GetElementVector()[0]->GetU64Val()); + std::string retentionType = GlobalTables::GetStrTable().GetStringFromStrIdx(strIdx); if (retentionType != "RUNTIME") { return false; } else { @@ -532,7 +531,7 @@ int16 ReflectionAnalysis::GetMethodInVtabIndex(const Klass &klass, const MIRFunc MIRAggConst *vtableConst = static_cast(vtableSymbol->GetKonst()); for (MIRConstPtr &node : vtableConst->GetConstVec()) { if (node->GetKind() == kConstAddrofFunc) { - MIRAddroffuncConst *addr = static_cast(node); + auto *addr = static_cast(node); MIRFunction *vtableFunc = GlobalTables::GetFunctionTable().GetFunctionFromPuidx(addr->GetValue()); // NOTE: In VtableAnalysis::AddMethodToTable, a abstract method will not // be added to the vtable if there is already an abstract method of the @@ -653,7 +652,7 @@ struct HashCodeComparator { MIRSymbol *ReflectionAnalysis::GenMethodsMetaData(const Klass &klass) { MIRModule &module = *mirModule; MIRClassType *classType = klass.GetMIRClassType(); - if (!classType || classType->GetMethods().empty()) { + if (classType == nullptr || classType->GetMethods().empty()) { return nullptr; } size_t arraySize = classType->GetMethods().size(); @@ -768,11 +767,11 @@ static void ConvertFieldName(std::string &fieldname, bool staticfield) { // Convert field name to java define name. if (staticfield) { // Remove class name prefix. - size_t pos1 = fieldname.find(kClassNameSplitterStr); + size_t pos1 = fieldname.find(NameMangler::kClassNameSplitterStr); CHECK_FATAL(pos1 != fieldname.npos, "fieldname not found"); - int fieldLength = strlen(kClassNameSplitterStr); + int fieldLength = strlen(NameMangler::kClassNameSplitterStr); fieldname = fieldname.substr(pos1 + fieldLength); - size_t pos2 = fieldname.find(kNameSplitterStr); + size_t pos2 = fieldname.find(NameMangler::kNameSplitterStr); if (pos2 != fieldname.npos) { fieldname = fieldname.substr(0, pos2); } @@ -922,7 +921,7 @@ void ReflectionAnalysis::ConvertMapleClassName(const std::string &mplClassName, std::string ReflectionAnalysis::GetAnnotationValue(MapleVector subelemVector, GStrIdx typestridx) { std::string annoArray, tmp; - GStrIdx stridx; + GStrIdx strIdx; annoArray += '['; annoArray += std::to_string(subelemVector.size()); annoArray += '!'; @@ -947,17 +946,17 @@ std::string ReflectionAnalysis::GetAnnotationValue(MapleVectorGetFloatVal(); annoArray += oss3.str(); } else if (arrayElem->GetType() == kValueString || arrayElem->GetType() == kValueEnum) { - stridx.SetIdx(arrayElem->GetU64Val()); - std::string t = GlobalTables::GetStrTable().GetStringFromStrIdx(stridx); + strIdx.SetIdx(arrayElem->GetU64Val()); + std::string t = GlobalTables::GetStrTable().GetStringFromStrIdx(strIdx); DelimeterConvert(t); ReflectionAnalysis::CompressHighFrequencyStr(t); annoArray += t; } else if (arrayElem->GetType() == kValueBoolean || arrayElem->GetType() == kValueChar) { annoArray += std::to_string(arrayElem->GetU64Val()); } else if (arrayElem->GetType() == kValueType) { - stridx.SetIdx(arrayElem->GetU64Val()); + strIdx.SetIdx(arrayElem->GetU64Val()); std::string javaDsp; - ConvertMapleClassName(GlobalTables::GetStrTable().GetStringFromStrIdx(stridx), javaDsp); + ConvertMapleClassName(GlobalTables::GetStrTable().GetStringFromStrIdx(strIdx), javaDsp); annoArray += javaDsp; } else if (arrayElem->GetType() == kValueAnnotation) { annoArray += GetAnnotationValue(arrayElem->GetSubElemVec(), arrayElem->GetTypeStrIdx()); @@ -967,8 +966,8 @@ std::string ReflectionAnalysis::GetAnnotationValue(MapleVectorGetU64Val()); annoArray += '!'; annoArray += GlobalTables::GetStrTable().GetStringFromStrIdx(arrayElem->GetNameStrIdx()); - stridx.SetIdx(arrayElem->GetU64Val()); - annoArray += GlobalTables::GetStrTable().GetStringFromStrIdx(stridx); + strIdx.SetIdx(arrayElem->GetU64Val()); + annoArray += GlobalTables::GetStrTable().GetStringFromStrIdx(strIdx); annoArray += '!'; } } @@ -978,7 +977,7 @@ std::string ReflectionAnalysis::GetAnnotationValue(MapleVector subelemVector, bool isSN) { std::string annoArray; - GStrIdx stridx; + GStrIdx strIdx; annoArray += '['; annoArray += std::to_string(subelemVector.size()); annoArray += '!'; @@ -1023,8 +1022,8 @@ std::string ReflectionAnalysis::GetArrayValue(MapleVector sub oss3 << type << std::setiosflags(std::ios::scientific) << std::setprecision(7) << arrayElem->GetFloatVal(); annoArray += oss3.str(); } else if (arrayElem->GetType() == kValueString || arrayElem->GetType() == kValueEnum) { - stridx.SetIdx(arrayElem->GetU64Val()); - std::string t = GlobalTables::GetStrTable().GetStringFromStrIdx(stridx); + strIdx.SetIdx(arrayElem->GetU64Val()); + std::string t = GlobalTables::GetStrTable().GetStringFromStrIdx(strIdx); DelimeterConvert(t); ReflectionAnalysis::CompressHighFrequencyStr(t); if (arrayElem->GetType() == kValueString && isSN && t.size() > kMaxOptimiseThreshold) { @@ -1036,17 +1035,17 @@ std::string ReflectionAnalysis::GetArrayValue(MapleVector sub oss3 << type << arrayElem->GetU64Val(); annoArray += oss3.str(); } else if (arrayElem->GetType() == kValueType) { - stridx.SetIdx(arrayElem->GetU64Val()); + strIdx.SetIdx(arrayElem->GetU64Val()); std::string javaDspInner; - ConvertMapleClassName(GlobalTables::GetStrTable().GetStringFromStrIdx(stridx), javaDspInner); + ConvertMapleClassName(GlobalTables::GetStrTable().GetStringFromStrIdx(strIdx), javaDspInner); annoArray += javaDspInner; } else { oss3 << type << arrayElem->GetU64Val(); annoArray += oss3.str(); annoArray += '!'; annoArray += GlobalTables::GetStrTable().GetStringFromStrIdx(arrayElem->GetNameStrIdx()); - stridx.SetIdx(arrayElem->GetU64Val()); - annoArray += GlobalTables::GetStrTable().GetStringFromStrIdx(stridx); + strIdx.SetIdx(arrayElem->GetU64Val()); + annoArray += GlobalTables::GetStrTable().GetStringFromStrIdx(strIdx); annoArray += '!'; } } @@ -1113,7 +1112,7 @@ uint32 ReflectionAnalysis::FindOrInsertReflectString(const std::string &str) { MIRSymbol *ReflectionAnalysis::GetClinitFuncSymbol(const Klass &klass) { MIRClassType *classType = klass.GetMIRClassType(); - if (!classType || classType->GetMethods().empty()) { + if (classType == nullptr || classType->GetMethods().empty()) { return nullptr; } MIRSymbol *clinitFuncSymbol = nullptr; @@ -1144,9 +1143,9 @@ void ReflectionAnalysis::GenClassMetaData(Klass &klass) { std::string klassJavaDescriptor; NameMangler::DecodeMapleNameToJavaDescriptor(klassName, klassJavaDescriptor); int64 hashIndex = GetHashIndex(klassJavaDescriptor); - if (raDebug) { + if (kRADebug) { LogInfo::MapleLogger(kLlErr) << "========= Gen Class: " << klassJavaDescriptor - << " (" << hashIndex << ") ========" << std::endl; + << " (" << hashIndex << ") ========\n"; } MIRStructType &classMetadataROType = static_cast(*GlobalTables::GetTypeTable().GetTypeFromTyIdx(classMetadataRoTyIdx)); @@ -1158,9 +1157,9 @@ void ReflectionAnalysis::GenClassMetaData(Klass &klass) { // @iFields: All instance fields. int numOfFields = 0; bool hasAdded = false; - if (klass.GetKlassName() == NameMangler::GetInternalNameLiteral(kJavaLangObjectStr)) { + if (klass.GetKlassName() == NameMangler::GetInternalNameLiteral(NameMangler::kJavaLangObjectStr)) { const GStrIdx stridx = GlobalTables::GetStrTable().GetOrCreateStrIdxFromName( - kFieldsInfoPrefixStr + NameMangler::GetInternalNameLiteral(kJavaLangObjectStr)); + NameMangler::kFieldsInfoPrefixStr + NameMangler::GetInternalNameLiteral(NameMangler::kJavaLangObjectStr)); MIRSymbol *fieldsSt = GlobalTables::GetGsymTable().GetSymbolFromStrIdx(stridx); if (fieldsSt != nullptr) { mirBuilder.AddAddrofFieldConst(classMetadataROType, *newconst, fieldID++, *fieldsSt); @@ -1199,7 +1198,7 @@ void ReflectionAnalysis::GenClassMetaData(Klass &klass) { missingSuper = true; MIRType *type = GlobalTables::GetTypeTable().GetTypeFromTyIdx(kTyIdx); LogInfo::MapleLogger() << "Error: Interface " << static_cast(type)->GetName() << " is not found" - << std::endl; + << "\n"; } std::list::iterator it = std::find(superClassList.begin(), superClassList.end(), interface); if (it == superClassList.end()) { @@ -1207,7 +1206,7 @@ void ReflectionAnalysis::GenClassMetaData(Klass &klass) { } } if (missingSuper) { - LogInfo::MapleLogger(kLlErr) << "Error: Missing interface for " << klass.GetKlassName() << std::endl; + LogInfo::MapleLogger(kLlErr) << "Error: Missing interface for " << klass.GetKlassName() << "\n"; CHECK_FATAL(0, "Missing interface"); } size_t superClassSize = superClassList.size(); @@ -1300,27 +1299,25 @@ void ReflectionAnalysis::GenClassMetaData(Klass &klass) { // @gctib MIRSymbol *gctibSt = GetOrCreateSymbol(GCTIB_PREFIX_STR + klass.GetKlassName(), GlobalTables::GetTypeTable().GetVoidPtr()->GetTypeIndex(), false); - if (klass.GetKlassName() != NameMangler::GetInternalNameLiteral(kJavaLangObjectStr)) { + if (klass.GetKlassName() != NameMangler::GetInternalNameLiteral(NameMangler::kJavaLangObjectStr)) { // Direct access to gctib is only possible within a .so, for most classes. gctibSt->SetStorageClass(kScFstatic); } mirBuilder.AddAddrofFieldConst(classMetadataType, *newconst, fieldID++, *gctibSt); // @classinfo ro. mirBuilder.AddAddrofFieldConst(classMetadataType, *newconst, fieldID++, *classMetadataROSymbolType); + // Set default value to class initialization state. - // If this class and its parents do not have clinit, we do not clinit-check for this class. if (klassh->NeedClinitCheckRecursively(klass)) { - MIRType *ptrType = GlobalTables::GetTypeTable().GetPtr(); - MIRSymbol *classInitProtectRegion = mirBuilder.GetOrCreateSymbol( - ptrType->GetTypeIndex(), kClassInitProtectRegionStr, kStVar, kScExtern, nullptr, kScopeGlobal, true); - classInitProtectRegion->SetAttr(ATTR_extern); - mirBuilder.AddAddrofFieldConst(classMetadataType, *newconst, fieldID++, *classInitProtectRegion); + mirBuilder.AddIntFieldConst(classMetadataType, *newconst, fieldID++, kSEGVAddrForClassUninitialized); } else { + // If this class and its parents do not have method, we do not do clinit-check for this class, + // thus the class initialization state is modified to "Initialized", i.e., some readable address. MIRType *clinitState = GlobalTables::GetTypeTable().GetUInt64(); - // The class initialization state is modified to classStateInitialized. MIRSymbol *classInfo = mirBuilder.GetOrCreateGlobalDecl(kClassStateInitializedStr, *clinitState); mirBuilder.AddAddrofFieldConst(classMetadataType, *newconst, fieldID++, *classInfo); } + // Finally generate class metadata here. MIRSymbol *classSt = GetOrCreateSymbol(CLASSINFO_PREFIX_STR + klass.GetKlassName(), classMetadataTyIdx, true); classSt->SetKonst(newconst); @@ -1353,7 +1350,7 @@ void ReflectionAnalysis::GeneAnnotation(std::map &idxNumMap, std::stri std::map *paramnumArray, int *paramIndex) { int annoNum = 0; std::string cmpString = ""; - for (MIRPragma *prag : classType.GetPragmVec()) { + for (MIRPragma *prag : classType.GetPragmaVec()) { if (paragKind == kPragmaVar) { cmpString = NameMangler::DecodeName(GlobalTables::GetStrTable().GetStringFromStrIdx(prag->GetStrIdx())); } else { @@ -1382,7 +1379,7 @@ void ReflectionAnalysis::GeneAnnotation(std::map &idxNumMap, std::stri annoArr += klassJavaDescriptor; annoArr += "!"; if (paramnumArray != nullptr) { - CHECK_FATAL(paramIndex, "null ptr check"); + CHECK_FATAL(paramIndex != nullptr, "null ptr check"); (*paramnumArray)[(*paramIndex)++] = prag->GetParamNum(); } for (MIRPragmaElement *elem : elemVector) { @@ -1399,7 +1396,7 @@ void ReflectionAnalysis::GeneAnnotation(std::map &idxNumMap, std::stri annoArr += "!"; MapleVector subelemVector = elem->GetSubElemVec(); switch (elem->GetType()) { - CaseCondition(annoArr, elem) case kValueAnnotation : annoArr += + CASE_CONDITION(annoArr, elem) case kValueAnnotation : annoArr += GetAnnotationValue(subelemVector, elem->GetTypeStrIdx()); break; case kValueArray: @@ -1453,17 +1450,17 @@ bool ReflectionAnalysis::IsAnonymousClass(const std::string &annotationString) { } TyIdx ReflectionAnalysis::GenMetaStructType(MIRModule &mirModule, MIRStructType &metatype, const std::string &str) { - const GStrIdx stridx = GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(str); - TyIdx tyidx = GlobalTables::GetTypeTable().GetOrCreateMIRType(&metatype); + const GStrIdx strIdx = GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(str); + TyIdx tyIdx = GlobalTables::GetTypeTable().GetOrCreateMIRType(&metatype); // Global? - mirModule.GetTypeNameTab()->SetGStrIdxToTyIdx(stridx, tyidx); - mirModule.PushbackTypeDefOrder(stridx); + mirModule.GetTypeNameTab()->SetGStrIdxToTyIdx(strIdx, tyIdx); + mirModule.PushbackTypeDefOrder(strIdx); const size_t globalTypeTableSize = GlobalTables::GetTypeTable().GetTypeTable().size(); - CHECK_FATAL(globalTypeTableSize > tyidx.GetIdx(), "null ptr check"); - if (GlobalTables::GetTypeTable().GetTypeTable()[tyidx.GetIdx()]->GetNameStrIdx() == 0) { - GlobalTables::GetTypeTable().GetTypeFromTyIdx(tyidx)->GetNameStrIdx() = stridx; + CHECK_FATAL(globalTypeTableSize > tyIdx.GetIdx(), "null ptr check"); + if (GlobalTables::GetTypeTable().GetTypeTable()[tyIdx.GetIdx()]->GetNameStrIdx() == 0) { + GlobalTables::GetTypeTable().GetTypeFromTyIdx(tyIdx)->SetNameStrIdx(strIdx); } - return tyidx; + return tyIdx; } MIRType *ReflectionAnalysis::GetRefFieldType(MIRBuilder &mirbuilder) { @@ -1503,7 +1500,7 @@ void ReflectionAnalysis::GenMetadataType(MIRModule &mirModule) { GlobalTables::GetTypeTable().AddFieldToStructType(classMetadataType, kGctibStr, *typeVoidPtr); GlobalTables::GetTypeTable().AddFieldToStructType(classMetadataType, kClassinforoStr, *typeVoidPtr); GlobalTables::GetTypeTable().AddFieldToStructType(classMetadataType, kClinitbridgeStr, *typeVoidPtr); - classMetadataTyIdx = GenMetaStructType(mirModule, classMetadataType, kClassMetadataTypeName); + classMetadataTyIdx = GenMetaStructType(mirModule, classMetadataType, NameMangler::kClassMetadataTypeName); MIRStructType classMetadataROType(kTypeStruct); GlobalTables::GetTypeTable().AddFieldToStructType(classMetadataROType, kClassnameStr, *typeVoidPtr); GlobalTables::GetTypeTable().AddFieldToStructType(classMetadataROType, kIfieldsStr, *typeVoidPtr); @@ -1583,8 +1580,8 @@ void ReflectionAnalysis::GenClassHashMetaData() { MIRType *type = GlobalTables::GetTypeTable().GetVoidPtr(); MIRModule &module = *mirModule; CHECK_FATAL(type != nullptr, "type is null in ReflectionAnalysis::GenClassHashMetaData"); - if (raDebug) { - LogInfo::MapleLogger(kLlErr) << "========= HASH TABLE ========" << std::endl; + if (kRADebug) { + LogInfo::MapleLogger(kLlErr) << "========= HASH TABLE ========\n"; } if (classTab.empty()) { return; @@ -1643,8 +1640,8 @@ void ReflectionAnalysis::GenStrTab(MIRModule &mirModule) { } void ReflectionAnalysis::MarkWeakMethods() { - GStrIdx classNames[] = { GetOrCreateGStrIdxFromName(kJavaLangClassStr), - GetOrCreateGStrIdxFromName(kJavaLangObjectStr), + GStrIdx classNames[] = { GetOrCreateGStrIdxFromName(NameMangler::kJavaLangClassStr), + GetOrCreateGStrIdxFromName(NameMangler::kJavaLangObjectStr), GetOrCreateGStrIdxFromName(kReflectionReferencePrefixStr) }; for (GStrIdx nameIdx : classNames) { Klass *klass = klassh->GetKlassFromStrIdx(nameIdx); @@ -1668,8 +1665,8 @@ void ReflectionAnalysis::Run() { MarkWeakMethods(); GenMetadataType(*mirModule); const MapleVector &klasses = klassh->GetTopoSortedKlasses(); - if (raDebug) { - LogInfo::MapleLogger(kLlErr) << "========= Gen Class: Total " << klasses.size() << " ========" << std::endl; + if (kRADebug) { + LogInfo::MapleLogger(kLlErr) << "========= Gen Class: Total " << klasses.size() << " ========\n"; } // Cluster classname together in reflection string table to improve the locality. for (Klass *klass : klasses) { @@ -1690,7 +1687,7 @@ void ReflectionAnalysis::Run() { AnalysisResult *DoReflectionAnalysis::Run(MIRModule *module, ModuleResultMgr *mrm) { MemPool *memPool = mempoolctrler.NewMemPool("ReflectionAnalysis mempool"); - KlassHierarchy *kh = static_cast(mrm->GetAnalysisResult(MoPhase_CHA, module)); + auto *kh = static_cast(mrm->GetAnalysisResult(MoPhase_CHA, module)); maple::MIRBuilder mirBuilder(module); ReflectionAnalysis *rv = memPool->New(module, memPool, kh, mirBuilder); if (rv == nullptr) { diff --git a/src/mpl2mpl/src/vtable_analysis.cpp b/src/mpl2mpl/src/vtable_analysis.cpp index 17821d468991b76f551416aecd713a44bb9994c5..91e11d3048e60ff7b2d45988e048e06c58c8bc16 100644 --- a/src/mpl2mpl/src/vtable_analysis.cpp +++ b/src/mpl2mpl/src/vtable_analysis.cpp @@ -68,12 +68,12 @@ bool VtableAnalysis::CheckOverrideForCrossPackage(const MIRFunction &baseMethod, void VtableAnalysis::AddMethodToTable(MethodPtrVector &methodTable, MethodPair &methodpair) { MIRFunction *method = builder->GetFunctionFromStidx(methodpair.first); ASSERT(method != nullptr, "null ptr check!"); - GStrIdx stridx = method->GetBaseFuncNameWithTypeStrIdx(); + GStrIdx strIdx = method->GetBaseFuncNameWithTypeStrIdx(); for (size_t i = 0; i < methodTable.size(); i++) { MIRFunction *currFunc = builder->GetFunctionFromStidx(methodTable[i]->first); ASSERT(currFunc != nullptr, "null ptr check!"); - GStrIdx currStridx = currFunc->GetBaseFuncNameWithTypeStrIdx(); - if (stridx == currStridx) { + GStrIdx currStrIdx = currFunc->GetBaseFuncNameWithTypeStrIdx(); + if (strIdx == currStrIdx) { if (CheckOverrideForCrossPackage(*currFunc, *method)) { // only update when it's not an abstract method if (!method->IsAbstract()) { @@ -113,7 +113,7 @@ void VtableAnalysis::GenVtableList(const Klass &klass) { // vtable from implemented interfaces, need to merge in. both default or none-default // Note, all interface methods are also virtual methods, need to be in vtable too. for (TyIdx const &tyIdx : curType->GetInterfaceImplemented()) { - MIRInterfaceType *iType = static_cast(GlobalTables::GetTypeTable().GetTypeFromTyIdx(tyIdx)); + auto *iType = static_cast(GlobalTables::GetTypeTable().GetTypeFromTyIdx(tyIdx)); for (MethodPair *methodPair : iType->GetVTableMethods()) { MIRFunction *method = builder->GetFunctionFromStidx(methodPair->first); GStrIdx strIdx = method->GetBaseFuncNameWithTypeStrIdx(); @@ -153,6 +153,7 @@ void VtableAnalysis::GenVtableList(const Klass &klass) { // Create initial cached vtable mapping for (size_t i = 0; i < curType->GetVTableMethods().size(); i++) { MIRFunction *curMethod = builder->GetFunctionFromStidx(curType->GetVTableMethods()[i]->first); + ASSERT(curMethod != nullptr, "null ptr check!"); puidxToVtabIndex[curMethod->GetPuidx()] = i; } } @@ -164,6 +165,7 @@ void VtableAnalysis::GenVtableDefinition(const Klass &klass) { ASSERT(newconst != nullptr, "null ptr check!"); for (MethodPair *methodPair : curType->GetVTableMethods()) { MIRFunction *vtabMethod = builder->GetFunctionFromStidx(methodPair->first); + ASSERT(vtabMethod != nullptr, "null ptr check!"); AddroffuncNode *addrofFuncNode = builder->CreateExprAddroffunc(vtabMethod->GetPuidx(), GetMIRModule().GetMemPool()); MIRConst *constNode = GetMIRModule().GetMemPool()->New(addrofFuncNode->GetPUIdx(), *voidPtrType); newconst->GetConstVec().push_back(constNode); @@ -221,8 +223,8 @@ void VtableAnalysis::GenItableDefinition(const Klass &klass) { break; } } - CHECK_FATAL(vtabMethod, "Interface method %s is not implemented in class %s", interfaceMethod->GetName().c_str(), - klass.GetKlassName().c_str()); + CHECK_FATAL(vtabMethod != nullptr, "Interface method %s is not implemented in class %s", + interfaceMethod->GetName().c_str(), klass.GetKlassName().c_str()); if (!vtabMethod->IsAbstract()) { itabContainsMethod = true; if (!firstItabVec[hashCode] && !firstConflictFlag[hashCode]) { @@ -334,10 +336,11 @@ void VtableAnalysis::GenTableSymbol(const std::string &prefix, const std::string } void VtableAnalysis ::DumpVtableList(const Klass *klass) const { - LogInfo::MapleLogger() << "=========" << klass->GetKlassName() << "========" << std::endl; + LogInfo::MapleLogger() << "=========" << klass->GetKlassName() << "========\n"; for (MethodPair *vtableMethod : klass->GetMIRStructType()->GetVTableMethods()) { MIRFunction *method = builder->GetFunctionFromStidx(vtableMethod->first); - LogInfo::MapleLogger() << method->GetName() << std::endl; + ASSERT(method != nullptr, "null ptr check!"); + LogInfo::MapleLogger() << method->GetName() << "\n"; } } @@ -391,9 +394,9 @@ void VtableAnalysis::ReplaceSuperclassInvoke(CallNode &stmt) { } } } - if (!cands || cands->size() == 0) { + if (cands == nullptr || cands->size() == 0) { if (klass->IsClass() || klass->IsInterface()) { - LogInfo::MapleLogger() << "warning: func " << callee->GetName() << " is not found in SuperInvoke!" << std::endl; + LogInfo::MapleLogger() << "warning: func " << callee->GetName() << " is not found in SuperInvoke!\n"; stmt.SetOpCode(OP_callassigned); return; } @@ -402,7 +405,7 @@ void VtableAnalysis::ReplaceSuperclassInvoke(CallNode &stmt) { "Dependency Error: function %s cannot be found in %s or any of its superclasses/interfaces", callee->GetBaseFuncNameWithType().c_str(), klass->GetKlassName().c_str()); MIRFunction *actualMIRFunc = cands->at(0); - CHECK_FATAL(actualMIRFunc, "Can not find the implementation of %s", callee->GetName().c_str()); + CHECK_FATAL(actualMIRFunc != nullptr, "Can not find the implementation of %s", callee->GetName().c_str()); stmt.SetOpCode(OP_callassigned); stmt.SetPUIdx(actualMIRFunc->GetPuidx()); GetMIRModule().addSuperCall(actualMIRFunc->GetName()); @@ -421,7 +424,7 @@ void VtableAnalysis::ReplacePolymorphicInvoke(CallNode &stmt) { BaseNode *VtableAnalysis::GenVtabItabBaseAddr(BaseNode *obj, bool isVirtual) { ASSERT(builder != nullptr, "null ptr check!"); BaseNode *classInfoAddress = ReflectionAnalysis::GenClassInfoAddr(obj, *builder); - MIRStructType *classMetadataType = static_cast( + auto *classMetadataType = static_cast( GlobalTables::GetTypeTable().GetTypeFromTyIdx(ReflectionAnalysis::GetClassMetaDataTyIdx())); return builder->CreateExprIread(*voidPtrType, *GlobalTables::GetTypeTable().GetOrCreatePointerType(*classMetadataType), (isVirtual ? KLASS_VTAB_FIELDID : KLASS_ITAB_FIELDID), classInfoAddress); @@ -432,7 +435,7 @@ void VtableAnalysis::ReplaceVirtualInvoke(CallNode &stmt) { MIRFunction *callee = GlobalTables::GetFunctionTable().GetFunctionFromPuidx(stmt.GetPUIdx()); ASSERT(callee != nullptr, "null ptr check!"); CHECK_FATAL(callee->GetParamSize() != 0, "container check"); - MIRPtrType *firstFormalArgType = static_cast(callee->GetNthParamType(0)); + auto *firstFormalArgType = static_cast(callee->GetNthParamType(0)); MIRType *pointedType = GlobalTables::GetTypeTable().GetTypeFromTyIdx(firstFormalArgType->GetPointedTyIdx()); MIRStructType *structType = nullptr; if (pointedType->GetKind() == kTypeJArray) { @@ -451,6 +454,7 @@ void VtableAnalysis::ReplaceVirtualInvoke(CallNode &stmt) { ASSERT(structType != nullptr, "null ptr check!"); for (size_t id1 = 0; id1 < structType->GetVTableMethods().size(); id1++) { MIRFunction *vtableMethod = builder->GetFunctionFromStidx(structType->GetVTableMethods()[id1]->first); + ASSERT(vtableMethod != nullptr, "null ptr check!"); if (calleeStridx == vtableMethod->GetBaseFuncNameWithTypeStrIdx()) { entryOffset = id1; puidxToVtabIndex[callee->GetPuidx()] = id1; @@ -479,6 +483,7 @@ void VtableAnalysis::ReplaceInterfaceInvoke(CallNode &stmt) { CHECK_FATAL(stmt.GetNopnd().empty() == false, "container check"); BaseNode *tabBaseAddress = GenVtabItabBaseAddr(stmt.GetNopndAt(0), false); MemPool *currentFuncMp = builder->GetCurrentFuncCodeMp(); + ASSERT(currentFuncMp != nullptr, "null ptr check!"); ResolveFuncNode *resolveNode = currentFuncMp->New( OP_resolveinterfacefunc, GlobalTables::GetTypeTable().GetCompactPtr()->GetPrimType(), stmt.GetPUIdx(), tabBaseAddress, builder->GetConstUInt32(0)); diff --git a/src/mpl2mpl/src/vtable_impl.cpp b/src/mpl2mpl/src/vtable_impl.cpp index 95cf3c3c4848d6bc8867abc8abf2ba75068a738f..5ac571d71f24eb9d2607e7fcecbed01d744ae81b 100644 --- a/src/mpl2mpl/src/vtable_impl.cpp +++ b/src/mpl2mpl/src/vtable_impl.cpp @@ -20,11 +20,12 @@ // This phase is mainly to lower interfacecall into icall namespace maple { -VtableImpl::VtableImpl(MIRModule *mod, KlassHierarchy *kh, bool dump) : FuncOptimizeImpl(mod, kh, dump) { +VtableImpl::VtableImpl(MIRModule *mod, KlassHierarchy *kh, bool dump) + : FuncOptimizeImpl(mod, kh, dump), + mirModule(mod) { + klassHierarchy = kh; mccItabFunc = builder->GetOrCreateFunction(kInterfaceMethod, TyIdx(PTY_ptr)); mccItabFunc->SetAttr(FUNCATTR_nosideeffect); - mirModule = mod; - klassHierarchy = kh; } void VtableImpl::ProcessFunc(MIRFunction *func) { @@ -39,7 +40,7 @@ void VtableImpl::ProcessFunc(MIRFunction *func) { Opcode opcode = stmt->GetOpCode(); switch (opcode) { case OP_regassign: { - RegassignNode *regassign = static_cast(stmt); + auto *regassign = static_cast(stmt); BaseNode *rhs = regassign->Opnd(); ASSERT(rhs != nullptr, "null ptr check!"); if (rhs->GetOpCode() == maple::OP_resolveinterfacefunc) { @@ -49,7 +50,7 @@ void VtableImpl::ProcessFunc(MIRFunction *func) { } case OP_interfaceicallassigned: case OP_virtualicallassigned: { - CallNode *callNode = static_cast(stmt); + auto *callNode = static_cast(stmt); MIRFunction *callee = GlobalTables::GetFunctionTable().GetFunctionFromPuidx(callNode->GetPUIdx()); MemPool *currentFuncCodeMempool = builder->GetCurrentFuncCodeMp(); IcallNode *icallNode = @@ -67,7 +68,7 @@ void VtableImpl::ProcessFunc(MIRFunction *func) { // Fall-through } case OP_icallassigned: { - IcallNode *icall = static_cast(stmt); + auto *icall = static_cast(stmt); BaseNode *firstParm = icall->GetNopndAt(0); ASSERT(firstParm != nullptr, "null ptr check!"); if (firstParm->GetOpCode() == maple::OP_resolveinterfacefunc) { @@ -138,14 +139,14 @@ void VtableImpl::ReplaceResolveInterface(StmtNode &stmt, const ResolveFuncNode & BaseNode *checkExpr = builder->CreateExprCompare(OP_eq, *GlobalTables::GetTypeTable().GetUInt1(), *compactPtrType, builder->CreateExprRegread(compactPtrPrim, pregFuncPtr), builder->CreateIntConst(0, compactPtrPrim)); - IfStmtNode *ifStmt = static_cast(builder->CreateStmtIf(checkExpr)); + auto *ifStmt = static_cast(builder->CreateStmtIf(checkExpr)); ifStmt->GetThenPart()->AddStatement(mccCallStmt); currFunc->GetBody()->InsertBefore(&stmt, ifStmt); if (stmt.GetOpCode() == OP_regassign) { - RegassignNode *regAssign = static_cast(&stmt); + auto *regAssign = static_cast(&stmt); regAssign->SetOpnd(builder->CreateExprRegread(compactPtrPrim, pregFuncPtr)); } else { - IcallNode *icall = static_cast(&stmt); + auto *icall = static_cast(&stmt); const size_t nopndSize = icall->GetNopndSize(); CHECK_FATAL(nopndSize > 0, "container check"); icall->SetNOpndAt(0, builder->CreateExprRegread(compactPtrPrim, pregFuncPtr));