Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,15 @@ private void addProvider(Provider provider) {
}
methodMap.put(funcName, new NativeJassFunction(funcName, provider, method));
}
} else {
methodMap.put(method.getName(), new NativeJassFunction(method.getName(), provider, method));
} else if (method.getDeclaringClass() != Object.class) {
// Two providers with a method of the same name would make the later one win silently
// (FrameProvider once shadowed ConversionProvider's ConvertOriginFrameType, whose handles keep
// their identity). Overloads within one provider stay as they were.
NativeJassFunction previous = methodMap.put(method.getName(), new NativeJassFunction(method.getName(), provider, method));
if (previous != null && previous.getProvider() != provider) {
throw new Error("Trying to add multiple implementations of <" + method.getName() + ">: "
+ previous.getProvider().getClass().getSimpleName() + " and " + provider.getClass().getSimpleName());
}
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,6 @@ static class FrameHandle {
}


public IlConstHandle ConvertOriginFrameType(ILconstInt i) {
return new IlConstHandle("frameType", i.getVal());
}

public IlConstHandle BlzGetFrameByName(ILconstString name, ILconstInt createContext) {
return new IlConstHandle("framehandle", new FrameHandle());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,12 +76,10 @@ public boolean checkProg(WurstModel root, Collection<CompilationUnit> toCheck) {

/**
* Lets a model which was checked completely by another checker report to this one, so that errors
* found while translating it reach this checker's gui. What a check of the whole model would clear
* and the model's own attributes do not hold, the compile time interpreter's caches, is cleared.
* found while translating it reach this checker's gui.
*/
public void adoptCheckedModel(WurstModel root) {
attachErrorHandler(root);
GlobalCaches.clearInterpreterCaches();
}

private void clearGlobalCaches(WurstModel root, Collection<CompilationUnit> toCheck) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,6 @@
import de.peeeq.wurstscript.translation.imtranslation.JassKeyOfLowering;
import de.peeeq.wurstscript.translation.imtranslation.JassKeyedMapLowering;
import de.peeeq.wurstscript.types.TypesHelper;
import de.peeeq.wurstscript.validation.GlobalCaches;
import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap;
import org.eclipse.jdt.annotation.Nullable;

import java.io.File;
Expand All @@ -31,9 +29,6 @@
import java.util.Optional;
import java.util.stream.Collectors;

import static de.peeeq.wurstscript.translation.imoptimizer.SideEffectFreeNatives.isFunctionPure;
import static de.peeeq.wurstscript.validation.GlobalCaches.LOCAL_STATE_CACHE;
import static de.peeeq.wurstscript.validation.GlobalCaches.LOCAL_STATE_NOARG_CACHE;

public class ILInterpreter implements AbstractInterpreter, AutoCloseable {
private ImProg prog;
Expand Down Expand Up @@ -506,9 +501,6 @@ private static boolean isTypeReal(ImType t) {
}


// Cap per-function cache size to avoid unbounded growth
private static final int MAX_CACHE_PER_FUNC = 2048;

private static final LocalState EMPTY_LOCAL_STATE = new LocalState();

/**
Expand Down Expand Up @@ -589,35 +581,13 @@ private static ILconst keyedMapValueOfInt(ProgramState globalState, ILconst stor
+ valueType + ".");
}

/**
* Calls a native through the provider which implements it. Results are not memoised: the natives are
* cheaper than hashing and comparing their arguments, and the ones whose identity matters (the
* conversions, Player) keep their own handles.
*/
private static LocalState runBuiltinFunction(ProgramState globalState, ImFunction f, ILconst... args) {
// Delegate to the array overload to avoid double-allocations.
return runBuiltinFunction(globalState, f, args, /*isVarargs*/ true);
}

private static LocalState runBuiltinFunction(ProgramState globalState, ImFunction f, ILconst[] args, boolean isVarargs) {
// Cache purity + name once
final String fname = f.getName();
final boolean pure = isFunctionPure(fname);

if (pure && args.length == 0) {
LocalState cachedNoArg = LOCAL_STATE_NOARG_CACHE.get(f);
if (cachedNoArg != null) {
return cachedNoArg;
}
}

GlobalCaches.ArgumentKey key = null;
Object2ObjectOpenHashMap<GlobalCaches.ArgumentKey, LocalState> perFn = null;
if (pure) {
key = GlobalCaches.ArgumentKey.forLookup(args);
perFn = LOCAL_STATE_CACHE.get(f);
if (perFn != null) {
final LocalState cached = perFn.get(key);
if (cached != null) {
return cached;
}
}
}

// Build error text lazily (only if we actually get exceptions)
StringBuilder errors = null;
Expand All @@ -626,23 +596,7 @@ private static LocalState runBuiltinFunction(ProgramState globalState, ImFunctio
NativesProvider cachedProvider = globalState.getCachedNativeProvider(fname);
if (cachedProvider != null) {
try {
final LocalState localState = new LocalState(cachedProvider.invoke(fname, args));
if (pure) {
if (args.length == 0) {
LOCAL_STATE_NOARG_CACHE.put(f, localState);
return localState;
}
if (perFn == null) {
perFn = new Object2ObjectOpenHashMap<>(16);
LOCAL_STATE_CACHE.put(f, perFn);
}
perFn.put(key, localState);
if (perFn.size() > MAX_CACHE_PER_FUNC) {
final GlobalCaches.ArgumentKey eldest = perFn.keySet().iterator().next();
perFn.remove(eldest);
}
}
return localState;
return new LocalState(cachedProvider.invoke(fname, args));
Comment thread
Frotty marked this conversation as resolved.
Resolved
} catch (NoSuchNativeException e) {
// Provider mapping changed or function not available in this provider instance anymore.
// Fall through to full scan and refresh cache.
Expand All @@ -659,31 +613,9 @@ private static LocalState runBuiltinFunction(ProgramState globalState, ImFunctio

for (NativesProvider natives : globalState.getNativeProviders()) {
try {
// Invoke native; TODO: cache method handles per name elsewhere.
final LocalState localState = new LocalState(natives.invoke(fname, args));
globalState.cacheNativeProvider(fname, natives);

if (pure) {
if (args.length == 0) {
LOCAL_STATE_NOARG_CACHE.put(f, localState);
return localState;
}
// insert into per-function cache with bounded size
if (perFn == null) {
perFn = new Object2ObjectOpenHashMap<>(16);
LOCAL_STATE_CACHE.put(f, perFn);
}
perFn.put(key, localState);
if (perFn.size() > MAX_CACHE_PER_FUNC) {
// evict eldest (insertion order) to bound memory
// Object2ObjectOpenHashMap maintains insertion order
final GlobalCaches.ArgumentKey eldest = perFn.keySet().iterator().next();
perFn.remove(eldest);
}
}

return localState;

} catch (NoSuchNativeException e) {
if (errors == null) errors = new StringBuilder(128);
errors.append('\n').append(e.getMessage());
Expand All @@ -705,12 +637,6 @@ private static LocalState runBuiltinFunction(ProgramState globalState, ImFunctio
return new LocalState(returnValue);
}

/** Zero-allocation combined hash for ILconst[] (order-sensitive). */
private static int fastHashArgs(ILconst[] args) {
return Arrays.hashCode(args);
}


private static boolean isCompiletimeNative(ImFunction f) {
if (f.getTrace() instanceof HasModifier) {
HasModifier f2 = (HasModifier) f.getTrace();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -262,7 +262,7 @@ public ILconstObject allocate(ImClassType clazz, Element trace) {
int objId = !idSpace.freeObjectIds.isEmpty() ? idSpace.freeObjectIds.pop() : ++idSpace.objectIdCounter;
ILconstObject res = new ILconstObject(clazz, objId, trace);
idSpace.indexToObject.put(objId, res);
WLogger.trace("alloc objId=" + objId + " type=" + clazz + " trace=" + trace);
WLogger.trace(() -> "alloc objId=" + objId + " type=" + clazz + " trace=" + trace);
return res;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,9 @@

import de.peeeq.wurstscript.ast.Element;
import de.peeeq.wurstscript.attributes.HasAnnotation;
import de.peeeq.wurstscript.intermediatelang.ILconst;
import de.peeeq.wurstscript.intermediatelang.interpreter.LocalState;
import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap;

import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Collection;
import java.util.IdentityHashMap;
import java.util.Map;
Expand Down Expand Up @@ -60,43 +57,6 @@ public String toString() {
}

private static final CacheStats lookupStats = new CacheStats("LookupCache");
private static final CacheStats localStateStats = new CacheStats("LocalStateCache");

// Optimized ArgumentKey that minimizes allocation overhead
public static final class ArgumentKey {
private final ILconst[] args;
private final int hash;
private static final ArgumentKey EMPTY = new ArgumentKey(new ILconst[0]);

// Reuse instances when possible via a small pool for common sizes
private static final ThreadLocal<ArgumentKey[]> POOL =
ThreadLocal.withInitial(() -> new ArgumentKey[4]);

private ArgumentKey(ILconst[] args) {
this.args = args;
this.hash = Arrays.hashCode(args);
}

// Factory method that reuses instances for lookup
public static ArgumentKey forLookup(ILconst[] args) {
if (args.length == 0) {
return EMPTY;
}
return new ArgumentKey(args);
}

@Override
public int hashCode() {
return hash;
}

@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof ArgumentKey that)) return false;
return hash == that.hash && Arrays.equals(args, that.args);
}
}

public enum Mode {TEST_ISOLATED, DEV_PERSISTENT}

Expand All @@ -113,50 +73,14 @@ public static Mode mode() {
private GlobalCaches() {
}

// Wrapped caches with statistics
public static final Object2ObjectOpenHashMap<Object, Object2ObjectOpenHashMap<ArgumentKey, LocalState>> LOCAL_STATE_CACHE =
new Object2ObjectOpenHashMap<Object, Object2ObjectOpenHashMap<ArgumentKey, LocalState>>() {
@Override
public Object2ObjectOpenHashMap<ArgumentKey, LocalState> get(Object key) {
Object2ObjectOpenHashMap<ArgumentKey, LocalState> result = super.get(key);
if (result != null) {
localStateStats.recordHit();
} else {
localStateStats.recordMiss();
}
return result;
}

@Override
public void clear() {
localStateStats.recordEviction(size());
super.clear();
}
};

// Fast path for pure builtin calls without arguments: avoid ArgumentKey hashing entirely.
public static final Object2ObjectOpenHashMap<Object, LocalState> LOCAL_STATE_NOARG_CACHE =
new Object2ObjectOpenHashMap<>();


/**
* Call this between tests (and after each compile)
*/
public static void clearAll() {
clearInterpreterCaches();
lookupCache.clear();
HasAnnotation.clearCaches();
}

/**
* The results the interpreter cached for native functions. They are keyed by the functions of one
* compilation's IM program, which nothing may keep alive after that compilation.
*/
public static void clearInterpreterCaches() {
LOCAL_STATE_CACHE.clear();
LOCAL_STATE_NOARG_CACHE.clear();
}

/**
* Clears lookup entries whose query element belongs to one of the changed roots.
* This keeps editor validation from throwing away hot lookup data for unchanged files.
Expand Down Expand Up @@ -240,26 +164,17 @@ public void clear() {
public static void printStats() {
System.out.println("=== GlobalCaches Statistics ===");
System.out.println(lookupStats);
System.out.println(localStateStats);
System.out.println("Current sizes: lookup=" + lookupCache.size() +
", localState=" + LOCAL_STATE_CACHE.size());
System.out.println("Current sizes: lookup=" + lookupCache.size());
System.out.println("==============================");
}

public static void resetStats() {
lookupStats.hits.set(0);
lookupStats.misses.set(0);
lookupStats.evictions.set(0);
localStateStats.hits.set(0);
localStateStats.misses.set(0);
localStateStats.evictions.set(0);
}

public static CacheStats getLookupStats() {
return lookupStats;
}

public static CacheStats getLocalStateStats() {
return localStateStats;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -534,6 +534,9 @@ public void conversionNativesAsMeasured() {
" return b ? \"true\" : \"false\"",
"init",
" measured(\"same value, same handle\", bs(ConvertUnitType(1) == UNIT_TYPE_DEAD) + \",\" + bs(ConvertUnitEvent(5) == ConvertUnitEvent(5)) + \",\" + bs(ConvertUnitType(999) != null), \"true,true,true\")",
// every conversion keeps its handle, the frame types too, which a second provider once made afresh
" measured(\"same origin frame type, same handle\", bs(ConvertOriginFrameType(3) == ConvertOriginFrameType(3)) + \",\""
+ " + bs(GetHandleId(ConvertOriginFrameType(3)) == GetHandleId(ConvertOriginFrameType(3))), \"true,true\")",
" let ids = I2S(GetHandleId(UNIT_TYPE_DEAD)) + \",\" + I2S(GetHandleId(UNIT_STATE_MANA)) + \",\" + I2S(GetHandleId(FRAMEPOINT_CENTER)) + \",\" + I2S(GetHandleId(PLAYER_STATE_RESOURCE_GOLD)) + \",\" + I2S(GetHandleId(UNIT_RF_HP)) + \",\" + I2S(GetHandleId(ConvertUnitType(999)))",
" measured(\"GetHandleId of conversions\", ids, \"1,2,4,1,1969778787,999\")",
" measured(\"GetHandleId of a unit\", bs(GetHandleId(CreateUnit(Player(0), 'hfoo', 0.0, 0.0, 0.0)) >= 0x100000), \"true\")",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1508,9 +1508,7 @@ public void aCompilationDoesNotCheckAModelThatIsAlreadyChecked() throws IOExcept
ModelManagerImpl manager = new ModelManagerImpl(projectFolder, new BufferManager());
manager.buildProject();

GlobalCaches.LOCAL_STATE_NOARG_CACHE.put("left over from an earlier compilation", null);
assertEquals(checksWhenCompiling(projectFolder, manager), 0, "nothing changed since the build");
assertTrue(GlobalCaches.LOCAL_STATE_NOARG_CACHE.isEmpty(), "the interpreter caches of the last compilation go");

ModelManager.Changes changes = manager.syncCompilationUnitContent(fileA, packageA + "// changed\n");
manager.reconcile(changes);
Expand Down
Loading