--- include/ir/IR.h +++ include/ir/IR.h @@ -93,6 +93,7 @@ class Type { public: - enum class Kind { Void, Int32, PtrInt32 }; + enum class Kind { Void, Int1, Int32, PtrInt32 }; explicit Type(Kind k); // 使用静态共享对象获取类型。 // 同一类型可直接比较返回值是否相等,例如: // Type::GetInt32Type() == Type::GetInt32Type() static const std::shared_ptr& GetVoidType(); + static const std::shared_ptr& GetInt1Type(); static const std::shared_ptr& GetInt32Type(); static const std::shared_ptr& GetPtrInt32Type(); Kind GetKind() const; bool IsVoid() const; + bool IsInt1() const; bool IsInt32() const; bool IsPtrInt32() const; @@ -118,6 +119,7 @@ const std::string& GetName() const; void SetName(std::string n); bool IsVoid() const; + bool IsInt1() const; bool IsInt32() const; bool IsPtrInt32() const; bool IsConstant() const; @@ -153,7 +155,9 @@ // 后续还需要扩展更多指令类型。 -// enum class Opcode { Add, Sub, Mul, Alloca, Load, Store, Ret }; -enum class Opcode { Add, Sub, Mul, Div, Mod, Neg, Alloca, Load, Store, Ret }; +enum class Opcode { Add, Sub, Mul, Div, Mod, Neg, Alloca, Load, Store, Ret, Cmp, Zext, Br, CondBr }; + +enum class CmpOp { Eq, Ne, Lt, Gt, Le, Ge }; // User 是所有“会使用其他 Value 作为输入”的 IR 对象的抽象基类。 @@ -231,6 +235,33 @@ Value* GetPtr() const; }; +class CmpInst : public Instruction { + public: + CmpInst(CmpOp cmp_op, Value* lhs, Value* rhs, std::string name); + CmpOp GetCmpOp() const; + Value* GetLhs() const; + Value* GetRhs() const; + private: + CmpOp cmp_op_; +}; + +class ZextInst : public Instruction { + public: + ZextInst(std::shared_ptr dest_ty, Value* val, std::string name); + Value* GetValue() const; +}; + +class BranchInst : public Instruction { + public: + BranchInst(BasicBlock* dest); + BasicBlock* GetDest() const; +}; + +class CondBranchInst : public Instruction { + public: + CondBranchInst(Value* cond, BasicBlock* true_bb, BasicBlock* false_bb); + Value* GetCond() const; + BasicBlock* GetTrueBlock() const; + BasicBlock* GetFalseBlock() const; +}; + // BasicBlock 已纳入 Value 体系,便于后续向更完整 IR 类图靠拢。 @@ -315,6 +346,10 @@ LoadInst* CreateLoad(Value* ptr, const std::string& name); StoreInst* CreateStore(Value* val, Value* ptr); ReturnInst* CreateRet(Value* v); + CmpInst* CreateCmp(CmpOp op, Value* lhs, Value* rhs, const std::string& name); + ZextInst* CreateZext(Value* val, const std::string& name); + BranchInst* CreateBr(BasicBlock* dest); + CondBranchInst* CreateCondBr(Value* cond, BasicBlock* true_bb, BasicBlock* false_bb); private: