// PassManager.h
#pragma once

#include <vector>
#include <memory>
#include <typeindex> // For std::type_index
#include <unordered_map>
#include "SysYIRPass.h"
#include "IR.h" // 假设你的IR.h定义了Module, Function等

namespace sysy {

class PassManager {
public:
	PassManager() = default;

	// 添加一个FunctionPass
	void addPass(std::unique_ptr<FunctionPass> pass) {
		functionPasses.push_back(std::move(pass));
	}

	// 添加一个ModulePass
	void addPass(std::unique_ptr<ModulePass> pass) {
		modulePasses.push_back(std::move(pass));
	}

	// 添加一个AnalysisPass
	template<typename T, typename... Args>
	T* addAnalysisPass(Args&&... args) {
		static_assert(std::is_base_of<AnalysisPass, T>::value, "T must derive from AnalysisPass");
		auto analysis = std::make_unique<T>(std::forward<Args>(args)...);
		T* rawPtr = analysis.get();
		analysisPasses[std::type_index(typeid(T))] = std::move(analysis);
		return rawPtr;
	}

	// 获取分析结果（用于其他Pass访问）
	template<typename T>
	T* getAnalysis() {
		static_assert(std::is_base_of<AnalysisPass, T>::value, "T must derive from AnalysisPass");
		auto it = analysisPasses.find(std::type_index(typeid(T)));
		if (it != analysisPasses.end()) {
			return static_cast<T*>(it->second.get());
		}
		return nullptr; // 或者抛出异常
	}

	// 运行所有注册的遍
	void run(Module& M);

private:
	std::vector<std::unique_ptr<FunctionPass>> functionPasses;
	std::vector<std::unique_ptr<ModulePass>> modulePasses;
	std::unordered_map<std::type_index, std::unique_ptr<AnalysisPass>> analysisPasses;
	// 未来可以添加AnalysisPass的缓存机制
};

} // namespace sysy