ByteCodeExprGen.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580
  1. //===--- ByteCodeExprGen.cpp - Code generator for expressions ---*- C++ -*-===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. #include "ByteCodeExprGen.h"
  9. #include "ByteCodeEmitter.h"
  10. #include "ByteCodeGenError.h"
  11. #include "Context.h"
  12. #include "Function.h"
  13. #include "PrimType.h"
  14. #include "Program.h"
  15. #include "State.h"
  16. using namespace clang;
  17. using namespace clang::interp;
  18. using APSInt = llvm::APSInt;
  19. template <typename T> using Expected = llvm::Expected<T>;
  20. template <typename T> using Optional = llvm::Optional<T>;
  21. namespace clang {
  22. namespace interp {
  23. /// Scope used to handle temporaries in toplevel variable declarations.
  24. template <class Emitter> class DeclScope final : public LocalScope<Emitter> {
  25. public:
  26. DeclScope(ByteCodeExprGen<Emitter> *Ctx, const VarDecl *VD)
  27. : LocalScope<Emitter>(Ctx), Scope(Ctx->P, VD) {}
  28. void addExtended(const Scope::Local &Local) override {
  29. return this->addLocal(Local);
  30. }
  31. private:
  32. Program::DeclScope Scope;
  33. };
  34. /// Scope used to handle initialization methods.
  35. template <class Emitter> class OptionScope {
  36. public:
  37. using InitFnRef = typename ByteCodeExprGen<Emitter>::InitFnRef;
  38. using ChainedInitFnRef = std::function<bool(InitFnRef)>;
  39. /// Root constructor, compiling or discarding primitives.
  40. OptionScope(ByteCodeExprGen<Emitter> *Ctx, bool NewDiscardResult)
  41. : Ctx(Ctx), OldDiscardResult(Ctx->DiscardResult),
  42. OldInitFn(std::move(Ctx->InitFn)) {
  43. Ctx->DiscardResult = NewDiscardResult;
  44. Ctx->InitFn = llvm::Optional<InitFnRef>{};
  45. }
  46. /// Root constructor, setting up compilation state.
  47. OptionScope(ByteCodeExprGen<Emitter> *Ctx, InitFnRef NewInitFn)
  48. : Ctx(Ctx), OldDiscardResult(Ctx->DiscardResult),
  49. OldInitFn(std::move(Ctx->InitFn)) {
  50. Ctx->DiscardResult = true;
  51. Ctx->InitFn = NewInitFn;
  52. }
  53. /// Extends the chain of initialisation pointers.
  54. OptionScope(ByteCodeExprGen<Emitter> *Ctx, ChainedInitFnRef NewInitFn)
  55. : Ctx(Ctx), OldDiscardResult(Ctx->DiscardResult),
  56. OldInitFn(std::move(Ctx->InitFn)) {
  57. assert(OldInitFn && "missing initializer");
  58. Ctx->InitFn = [this, NewInitFn] { return NewInitFn(*OldInitFn); };
  59. }
  60. ~OptionScope() {
  61. Ctx->DiscardResult = OldDiscardResult;
  62. Ctx->InitFn = std::move(OldInitFn);
  63. }
  64. private:
  65. /// Parent context.
  66. ByteCodeExprGen<Emitter> *Ctx;
  67. /// Old discard flag to restore.
  68. bool OldDiscardResult;
  69. /// Old pointer emitter to restore.
  70. llvm::Optional<InitFnRef> OldInitFn;
  71. };
  72. } // namespace interp
  73. } // namespace clang
  74. template <class Emitter>
  75. bool ByteCodeExprGen<Emitter>::VisitCastExpr(const CastExpr *CE) {
  76. auto *SubExpr = CE->getSubExpr();
  77. switch (CE->getCastKind()) {
  78. case CK_LValueToRValue: {
  79. return dereference(
  80. CE->getSubExpr(), DerefKind::Read,
  81. [](PrimType) {
  82. // Value loaded - nothing to do here.
  83. return true;
  84. },
  85. [this, CE](PrimType T) {
  86. // Pointer on stack - dereference it.
  87. if (!this->emitLoadPop(T, CE))
  88. return false;
  89. return DiscardResult ? this->emitPop(T, CE) : true;
  90. });
  91. }
  92. case CK_ArrayToPointerDecay:
  93. case CK_AtomicToNonAtomic:
  94. case CK_ConstructorConversion:
  95. case CK_FunctionToPointerDecay:
  96. case CK_NonAtomicToAtomic:
  97. case CK_NoOp:
  98. case CK_UserDefinedConversion:
  99. return this->Visit(SubExpr);
  100. case CK_ToVoid:
  101. return discard(SubExpr);
  102. default: {
  103. // TODO: implement other casts.
  104. return this->bail(CE);
  105. }
  106. }
  107. }
  108. template <class Emitter>
  109. bool ByteCodeExprGen<Emitter>::VisitIntegerLiteral(const IntegerLiteral *LE) {
  110. if (DiscardResult)
  111. return true;
  112. auto Val = LE->getValue();
  113. QualType LitTy = LE->getType();
  114. if (Optional<PrimType> T = classify(LitTy))
  115. return emitConst(*T, getIntWidth(LitTy), LE->getValue(), LE);
  116. return this->bail(LE);
  117. }
  118. template <class Emitter>
  119. bool ByteCodeExprGen<Emitter>::VisitParenExpr(const ParenExpr *PE) {
  120. return this->Visit(PE->getSubExpr());
  121. }
  122. template <class Emitter>
  123. bool ByteCodeExprGen<Emitter>::VisitBinaryOperator(const BinaryOperator *BO) {
  124. const Expr *LHS = BO->getLHS();
  125. const Expr *RHS = BO->getRHS();
  126. // Deal with operations which have composite or void types.
  127. switch (BO->getOpcode()) {
  128. case BO_Comma:
  129. if (!discard(LHS))
  130. return false;
  131. if (!this->Visit(RHS))
  132. return false;
  133. return true;
  134. default:
  135. break;
  136. }
  137. // Typecheck the args.
  138. Optional<PrimType> LT = classify(LHS->getType());
  139. Optional<PrimType> RT = classify(RHS->getType());
  140. if (!LT || !RT) {
  141. return this->bail(BO);
  142. }
  143. if (Optional<PrimType> T = classify(BO->getType())) {
  144. if (!visit(LHS))
  145. return false;
  146. if (!visit(RHS))
  147. return false;
  148. auto Discard = [this, T, BO](bool Result) {
  149. if (!Result)
  150. return false;
  151. return DiscardResult ? this->emitPop(*T, BO) : true;
  152. };
  153. switch (BO->getOpcode()) {
  154. case BO_EQ:
  155. return Discard(this->emitEQ(*LT, BO));
  156. case BO_NE:
  157. return Discard(this->emitNE(*LT, BO));
  158. case BO_LT:
  159. return Discard(this->emitLT(*LT, BO));
  160. case BO_LE:
  161. return Discard(this->emitLE(*LT, BO));
  162. case BO_GT:
  163. return Discard(this->emitGT(*LT, BO));
  164. case BO_GE:
  165. return Discard(this->emitGE(*LT, BO));
  166. case BO_Sub:
  167. return Discard(this->emitSub(*T, BO));
  168. case BO_Add:
  169. return Discard(this->emitAdd(*T, BO));
  170. case BO_Mul:
  171. return Discard(this->emitMul(*T, BO));
  172. default:
  173. return this->bail(BO);
  174. }
  175. }
  176. return this->bail(BO);
  177. }
  178. template <class Emitter>
  179. bool ByteCodeExprGen<Emitter>::discard(const Expr *E) {
  180. OptionScope<Emitter> Scope(this, /*NewDiscardResult=*/true);
  181. return this->Visit(E);
  182. }
  183. template <class Emitter>
  184. bool ByteCodeExprGen<Emitter>::visit(const Expr *E) {
  185. OptionScope<Emitter> Scope(this, /*NewDiscardResult=*/false);
  186. return this->Visit(E);
  187. }
  188. template <class Emitter>
  189. bool ByteCodeExprGen<Emitter>::visitBool(const Expr *E) {
  190. if (Optional<PrimType> T = classify(E->getType())) {
  191. return visit(E);
  192. } else {
  193. return this->bail(E);
  194. }
  195. }
  196. template <class Emitter>
  197. bool ByteCodeExprGen<Emitter>::visitZeroInitializer(PrimType T, const Expr *E) {
  198. switch (T) {
  199. case PT_Bool:
  200. return this->emitZeroBool(E);
  201. case PT_Sint8:
  202. return this->emitZeroSint8(E);
  203. case PT_Uint8:
  204. return this->emitZeroUint8(E);
  205. case PT_Sint16:
  206. return this->emitZeroSint16(E);
  207. case PT_Uint16:
  208. return this->emitZeroUint16(E);
  209. case PT_Sint32:
  210. return this->emitZeroSint32(E);
  211. case PT_Uint32:
  212. return this->emitZeroUint32(E);
  213. case PT_Sint64:
  214. return this->emitZeroSint64(E);
  215. case PT_Uint64:
  216. return this->emitZeroUint64(E);
  217. case PT_Ptr:
  218. return this->emitNullPtr(E);
  219. }
  220. llvm_unreachable("unknown primitive type");
  221. }
  222. template <class Emitter>
  223. bool ByteCodeExprGen<Emitter>::dereference(
  224. const Expr *LV, DerefKind AK, llvm::function_ref<bool(PrimType)> Direct,
  225. llvm::function_ref<bool(PrimType)> Indirect) {
  226. if (Optional<PrimType> T = classify(LV->getType())) {
  227. if (!LV->refersToBitField()) {
  228. // Only primitive, non bit-field types can be dereferenced directly.
  229. if (auto *DE = dyn_cast<DeclRefExpr>(LV)) {
  230. if (!DE->getDecl()->getType()->isReferenceType()) {
  231. if (auto *PD = dyn_cast<ParmVarDecl>(DE->getDecl()))
  232. return dereferenceParam(LV, *T, PD, AK, Direct, Indirect);
  233. if (auto *VD = dyn_cast<VarDecl>(DE->getDecl()))
  234. return dereferenceVar(LV, *T, VD, AK, Direct, Indirect);
  235. }
  236. }
  237. }
  238. if (!visit(LV))
  239. return false;
  240. return Indirect(*T);
  241. }
  242. return false;
  243. }
  244. template <class Emitter>
  245. bool ByteCodeExprGen<Emitter>::dereferenceParam(
  246. const Expr *LV, PrimType T, const ParmVarDecl *PD, DerefKind AK,
  247. llvm::function_ref<bool(PrimType)> Direct,
  248. llvm::function_ref<bool(PrimType)> Indirect) {
  249. auto It = this->Params.find(PD);
  250. if (It != this->Params.end()) {
  251. unsigned Idx = It->second;
  252. switch (AK) {
  253. case DerefKind::Read:
  254. return DiscardResult ? true : this->emitGetParam(T, Idx, LV);
  255. case DerefKind::Write:
  256. if (!Direct(T))
  257. return false;
  258. if (!this->emitSetParam(T, Idx, LV))
  259. return false;
  260. return DiscardResult ? true : this->emitGetPtrParam(Idx, LV);
  261. case DerefKind::ReadWrite:
  262. if (!this->emitGetParam(T, Idx, LV))
  263. return false;
  264. if (!Direct(T))
  265. return false;
  266. if (!this->emitSetParam(T, Idx, LV))
  267. return false;
  268. return DiscardResult ? true : this->emitGetPtrParam(Idx, LV);
  269. }
  270. return true;
  271. }
  272. // If the param is a pointer, we can dereference a dummy value.
  273. if (!DiscardResult && T == PT_Ptr && AK == DerefKind::Read) {
  274. if (auto Idx = P.getOrCreateDummy(PD))
  275. return this->emitGetPtrGlobal(*Idx, PD);
  276. return false;
  277. }
  278. // Value cannot be produced - try to emit pointer and do stuff with it.
  279. return visit(LV) && Indirect(T);
  280. }
  281. template <class Emitter>
  282. bool ByteCodeExprGen<Emitter>::dereferenceVar(
  283. const Expr *LV, PrimType T, const VarDecl *VD, DerefKind AK,
  284. llvm::function_ref<bool(PrimType)> Direct,
  285. llvm::function_ref<bool(PrimType)> Indirect) {
  286. auto It = Locals.find(VD);
  287. if (It != Locals.end()) {
  288. const auto &L = It->second;
  289. switch (AK) {
  290. case DerefKind::Read:
  291. if (!this->emitGetLocal(T, L.Offset, LV))
  292. return false;
  293. return DiscardResult ? this->emitPop(T, LV) : true;
  294. case DerefKind::Write:
  295. if (!Direct(T))
  296. return false;
  297. if (!this->emitSetLocal(T, L.Offset, LV))
  298. return false;
  299. return DiscardResult ? true : this->emitGetPtrLocal(L.Offset, LV);
  300. case DerefKind::ReadWrite:
  301. if (!this->emitGetLocal(T, L.Offset, LV))
  302. return false;
  303. if (!Direct(T))
  304. return false;
  305. if (!this->emitSetLocal(T, L.Offset, LV))
  306. return false;
  307. return DiscardResult ? true : this->emitGetPtrLocal(L.Offset, LV);
  308. }
  309. } else if (auto Idx = getGlobalIdx(VD)) {
  310. switch (AK) {
  311. case DerefKind::Read:
  312. if (!this->emitGetGlobal(T, *Idx, LV))
  313. return false;
  314. return DiscardResult ? this->emitPop(T, LV) : true;
  315. case DerefKind::Write:
  316. if (!Direct(T))
  317. return false;
  318. if (!this->emitSetGlobal(T, *Idx, LV))
  319. return false;
  320. return DiscardResult ? true : this->emitGetPtrGlobal(*Idx, LV);
  321. case DerefKind::ReadWrite:
  322. if (!this->emitGetGlobal(T, *Idx, LV))
  323. return false;
  324. if (!Direct(T))
  325. return false;
  326. if (!this->emitSetGlobal(T, *Idx, LV))
  327. return false;
  328. return DiscardResult ? true : this->emitGetPtrGlobal(*Idx, LV);
  329. }
  330. }
  331. // If the declaration is a constant value, emit it here even
  332. // though the declaration was not evaluated in the current scope.
  333. // The access mode can only be read in this case.
  334. if (!DiscardResult && AK == DerefKind::Read) {
  335. if (VD->hasLocalStorage() && VD->hasInit() && !VD->isConstexpr()) {
  336. QualType VT = VD->getType();
  337. if (VT.isConstQualified() && VT->isFundamentalType())
  338. return this->Visit(VD->getInit());
  339. }
  340. }
  341. // Value cannot be produced - try to emit pointer.
  342. return visit(LV) && Indirect(T);
  343. }
  344. template <class Emitter>
  345. bool ByteCodeExprGen<Emitter>::emitConst(PrimType T, unsigned NumBits,
  346. const APInt &Value, const Expr *E) {
  347. switch (T) {
  348. case PT_Sint8:
  349. return this->emitConstSint8(Value.getSExtValue(), E);
  350. case PT_Uint8:
  351. return this->emitConstUint8(Value.getZExtValue(), E);
  352. case PT_Sint16:
  353. return this->emitConstSint16(Value.getSExtValue(), E);
  354. case PT_Uint16:
  355. return this->emitConstUint16(Value.getZExtValue(), E);
  356. case PT_Sint32:
  357. return this->emitConstSint32(Value.getSExtValue(), E);
  358. case PT_Uint32:
  359. return this->emitConstUint32(Value.getZExtValue(), E);
  360. case PT_Sint64:
  361. return this->emitConstSint64(Value.getSExtValue(), E);
  362. case PT_Uint64:
  363. return this->emitConstUint64(Value.getZExtValue(), E);
  364. case PT_Bool:
  365. return this->emitConstBool(Value.getBoolValue(), E);
  366. case PT_Ptr:
  367. llvm_unreachable("Invalid integral type");
  368. break;
  369. }
  370. llvm_unreachable("unknown primitive type");
  371. }
  372. template <class Emitter>
  373. unsigned ByteCodeExprGen<Emitter>::allocateLocalPrimitive(DeclTy &&Src,
  374. PrimType Ty,
  375. bool IsConst,
  376. bool IsExtended) {
  377. Descriptor *D = P.createDescriptor(Src, Ty, IsConst, Src.is<const Expr *>());
  378. Scope::Local Local = this->createLocal(D);
  379. if (auto *VD = dyn_cast_or_null<ValueDecl>(Src.dyn_cast<const Decl *>()))
  380. Locals.insert({VD, Local});
  381. VarScope->add(Local, IsExtended);
  382. return Local.Offset;
  383. }
  384. template <class Emitter>
  385. llvm::Optional<unsigned>
  386. ByteCodeExprGen<Emitter>::allocateLocal(DeclTy &&Src, bool IsExtended) {
  387. QualType Ty;
  388. const ValueDecl *Key = nullptr;
  389. bool IsTemporary = false;
  390. if (auto *VD = dyn_cast_or_null<ValueDecl>(Src.dyn_cast<const Decl *>())) {
  391. Key = VD;
  392. Ty = VD->getType();
  393. }
  394. if (auto *E = Src.dyn_cast<const Expr *>()) {
  395. IsTemporary = true;
  396. Ty = E->getType();
  397. }
  398. Descriptor *D = P.createDescriptor(Src, Ty.getTypePtr(),
  399. Ty.isConstQualified(), IsTemporary);
  400. if (!D)
  401. return {};
  402. Scope::Local Local = this->createLocal(D);
  403. if (Key)
  404. Locals.insert({Key, Local});
  405. VarScope->add(Local, IsExtended);
  406. return Local.Offset;
  407. }
  408. template <class Emitter>
  409. bool ByteCodeExprGen<Emitter>::visitInitializer(
  410. const Expr *Init, InitFnRef InitFn) {
  411. OptionScope<Emitter> Scope(this, InitFn);
  412. return this->Visit(Init);
  413. }
  414. template <class Emitter>
  415. bool ByteCodeExprGen<Emitter>::getPtrVarDecl(const VarDecl *VD, const Expr *E) {
  416. // Generate a pointer to the local, loading refs.
  417. if (Optional<unsigned> Idx = getGlobalIdx(VD)) {
  418. if (VD->getType()->isReferenceType())
  419. return this->emitGetGlobalPtr(*Idx, E);
  420. else
  421. return this->emitGetPtrGlobal(*Idx, E);
  422. }
  423. return this->bail(VD);
  424. }
  425. template <class Emitter>
  426. llvm::Optional<unsigned>
  427. ByteCodeExprGen<Emitter>::getGlobalIdx(const VarDecl *VD) {
  428. if (VD->isConstexpr()) {
  429. // Constexpr decl - it must have already been defined.
  430. return P.getGlobal(VD);
  431. }
  432. if (!VD->hasLocalStorage()) {
  433. // Not constexpr, but a global var - can have pointer taken.
  434. Program::DeclScope Scope(P, VD);
  435. return P.getOrCreateGlobal(VD);
  436. }
  437. return {};
  438. }
  439. template <class Emitter>
  440. const RecordType *ByteCodeExprGen<Emitter>::getRecordTy(QualType Ty) {
  441. if (auto *PT = dyn_cast<PointerType>(Ty))
  442. return PT->getPointeeType()->getAs<RecordType>();
  443. else
  444. return Ty->getAs<RecordType>();
  445. }
  446. template <class Emitter>
  447. Record *ByteCodeExprGen<Emitter>::getRecord(QualType Ty) {
  448. if (auto *RecordTy = getRecordTy(Ty)) {
  449. return getRecord(RecordTy->getDecl());
  450. }
  451. return nullptr;
  452. }
  453. template <class Emitter>
  454. Record *ByteCodeExprGen<Emitter>::getRecord(const RecordDecl *RD) {
  455. return P.getOrCreateRecord(RD);
  456. }
  457. template <class Emitter>
  458. bool ByteCodeExprGen<Emitter>::visitExpr(const Expr *Exp) {
  459. ExprScope<Emitter> RootScope(this);
  460. if (!visit(Exp))
  461. return false;
  462. if (Optional<PrimType> T = classify(Exp))
  463. return this->emitRet(*T, Exp);
  464. else
  465. return this->emitRetValue(Exp);
  466. }
  467. template <class Emitter>
  468. bool ByteCodeExprGen<Emitter>::visitDecl(const VarDecl *VD) {
  469. const Expr *Init = VD->getInit();
  470. if (Optional<unsigned> I = P.createGlobal(VD)) {
  471. if (Optional<PrimType> T = classify(VD->getType())) {
  472. {
  473. // Primitive declarations - compute the value and set it.
  474. DeclScope<Emitter> LocalScope(this, VD);
  475. if (!visit(Init))
  476. return false;
  477. }
  478. // If the declaration is global, save the value for later use.
  479. if (!this->emitDup(*T, VD))
  480. return false;
  481. if (!this->emitInitGlobal(*T, *I, VD))
  482. return false;
  483. return this->emitRet(*T, VD);
  484. } else {
  485. {
  486. // Composite declarations - allocate storage and initialize it.
  487. DeclScope<Emitter> LocalScope(this, VD);
  488. if (!visitGlobalInitializer(Init, *I))
  489. return false;
  490. }
  491. // Return a pointer to the global.
  492. if (!this->emitGetPtrGlobal(*I, VD))
  493. return false;
  494. return this->emitRetValue(VD);
  495. }
  496. }
  497. return this->bail(VD);
  498. }
  499. template <class Emitter>
  500. void ByteCodeExprGen<Emitter>::emitCleanup() {
  501. for (VariableScope<Emitter> *C = VarScope; C; C = C->getParent())
  502. C->emitDestruction();
  503. }
  504. namespace clang {
  505. namespace interp {
  506. template class ByteCodeExprGen<ByteCodeEmitter>;
  507. template class ByteCodeExprGen<EvalEmitter>;
  508. } // namespace interp
  509. } // namespace clang