text
stringlengths
5
1.04M
/* * Copyright (C) 1999 Lars Knoll (knoll@kde.org) * (C) 1999 Antti Koivisto (koivisto@kde.org) * (C) 2001 Dirk Mueller (mueller@kde.org) * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2010 Apple Inc. All rights reserved. * (C) 2006 Alexey Proskuryakov (ap@nypop.com) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. * */ #include "config.h" #include "core/html/HTMLOptGroupElement.h" #include "core/HTMLNames.h" #include "core/dom/NodeComputedStyle.h" #include "core/dom/Text.h" #include "core/editing/htmlediting.h" #include "core/html/HTMLContentElement.h" #include "core/html/HTMLDivElement.h" #include "core/html/HTMLSelectElement.h" #include "core/html/shadow/ShadowElementNames.h" #include "wtf/StdLibExtras.h" #include "wtf/text/CharacterNames.h" namespace blink { using namespace HTMLNames; inline HTMLOptGroupElement::HTMLOptGroupElement(Document& document) : HTMLElement(optgroupTag, document) { setHasCustomStyleCallbacks(); } PassRefPtrWillBeRawPtr<HTMLOptGroupElement> HTMLOptGroupElement::create(Document& document) { RefPtrWillBeRawPtr<HTMLOptGroupElement> optGroupElement = adoptRefWillBeNoop(new HTMLOptGroupElement(document)); optGroupElement->ensureUserAgentShadowRoot(); return optGroupElement.release(); } bool HTMLOptGroupElement::isDisabledFormControl() const { return fastHasAttribute(disabledAttr); } void HTMLOptGroupElement::childrenChanged(const ChildrenChange& change) { recalcSelectOptions(); HTMLElement::childrenChanged(change); } void HTMLOptGroupElement::parseAttribute(const QualifiedName& name, const AtomicString& value) { HTMLElement::parseAttribute(name, value); recalcSelectOptions(); if (name == disabledAttr) { pseudoStateChanged(CSSSelector::PseudoDisabled); pseudoStateChanged(CSSSelector::PseudoEnabled); } else if (name == labelAttr) { updateGroupLabel(); } } void HTMLOptGroupElement::recalcSelectOptions() { if (HTMLSelectElement* select = Traversal<HTMLSelectElement>::firstAncestor(*this)) select->setRecalcListItems(); } void HTMLOptGroupElement::attach(const AttachContext& context) { if (context.resolvedStyle) { ASSERT(!m_style || m_style == context.resolvedStyle); m_style = context.resolvedStyle; } HTMLElement::attach(context); } void HTMLOptGroupElement::detach(const AttachContext& context) { m_style.clear(); HTMLElement::detach(context); } bool HTMLOptGroupElement::supportsFocus() const { RefPtrWillBeRawPtr<HTMLSelectElement> select = ownerSelectElement(); if (select && select->usesMenuList()) return false; return HTMLElement::supportsFocus(); } void HTMLOptGroupElement::updateNonComputedStyle() { m_style = originalStyleForLayoutObject(); if (layoutObject()) { if (HTMLSelectElement* select = ownerSelectElement()) select->updateListOnLayoutObject(); } } ComputedStyle* HTMLOptGroupElement::nonLayoutObjectComputedStyle() const { return m_style.get(); } PassRefPtr<ComputedStyle> HTMLOptGroupElement::customStyleForLayoutObject() { updateNonComputedStyle(); return m_style; } String HTMLOptGroupElement::groupLabelText() const { String itemText = getAttribute(labelAttr); // In WinIE, leading and trailing whitespace is ignored in options and optgroups. We match this behavior. itemText = itemText.stripWhiteSpace(); // We want to collapse our whitespace too. This will match other browsers. itemText = itemText.simplifyWhiteSpace(); return itemText; } HTMLSelectElement* HTMLOptGroupElement::ownerSelectElement() const { return Traversal<HTMLSelectElement>::firstAncestor(*this); } void HTMLOptGroupElement::accessKeyAction(bool) { HTMLSelectElement* select = ownerSelectElement(); // send to the parent to bring focus to the list box if (select && !select->focused()) select->accessKeyAction(false); } void HTMLOptGroupElement::didAddUserAgentShadowRoot(ShadowRoot& root) { DEFINE_STATIC_LOCAL(AtomicString, labelPadding, ("0 2px 1px 2px", AtomicString::ConstructFromLiteral)); DEFINE_STATIC_LOCAL(AtomicString, labelMinHeight, ("1.2em", AtomicString::ConstructFromLiteral)); RefPtrWillBeRawPtr<HTMLDivElement> label = HTMLDivElement::create(document()); label->setAttribute(roleAttr, AtomicString("group", AtomicString::ConstructFromLiteral)); label->setAttribute(aria_labelAttr, AtomicString()); label->setInlineStyleProperty(CSSPropertyPadding, labelPadding); label->setInlineStyleProperty(CSSPropertyMinHeight, labelMinHeight); label->setIdAttribute(ShadowElementNames::optGroupLabel()); root.appendChild(label); RefPtrWillBeRawPtr<HTMLContentElement> content = HTMLContentElement::create(document()); content->setAttribute(selectAttr, "option,optgroup,hr"); root.appendChild(content); } void HTMLOptGroupElement::updateGroupLabel() { const String& labelText = groupLabelText(); HTMLDivElement& label = optGroupLabelElement(); label.setTextContent(labelText); label.setAttribute(aria_labelAttr, AtomicString(labelText)); } HTMLDivElement& HTMLOptGroupElement::optGroupLabelElement() const { return *toHTMLDivElement(userAgentShadowRoot()->getElementById(ShadowElementNames::optGroupLabel())); } } // namespace
#include "InjectOpenGLIntrinsics.h" #include "CodeGen_GPU_Dev.h" #include "FuseGPUThreadLoops.h" #include "IRMutator.h" #include "IROperator.h" #include "Scope.h" #include "Substitute.h" namespace Halide { namespace Internal { using std::string; using std::vector; /** Normalizes image loads/stores and produces glsl_texture_load/stores. */ class InjectOpenGLIntrinsics : public IRMutator { public: InjectOpenGLIntrinsics() : inside_kernel_loop(false) { } Scope<int> scope; bool inside_kernel_loop; private: using IRMutator::visit; Expr visit(const Call *call) override { if (call->is_intrinsic(Call::image_load)) { vector<Expr> call_args = call->args; // // Create // glsl_texture_load("name", // name.buffer, // (x - x_min + 0.5)/x_extent, // (y - y_min + 0.5)/y_extent, // c) // from // image_load("name", // name.buffer, // x - x_min, x_extent, // y - y_min, y_extent, // c - c_min, c_extent // ) // vector<Expr> args(5); args[0] = call_args[0]; // "name" args[1] = call_args[1]; // name.buffer // Normalize first two coordinates. for (size_t i = 0; i < 2; i++) { int to_index = 2 + i; int from_index = 2 + i * 2; args[to_index] = (Cast::make(Float(32), mutate(call_args[from_index])) + 0.5f) / mutate(call_args[from_index + 1]); } // Confirm that user explicitly specified constant value for min // value of c dimension for ImageParams accessed by GLSL-based filters. if (call->param.defined()) { bool const_min_constraint = call->param.min_constraint(2).defined() && is_const(call->param.min_constraint(2)); user_assert(const_min_constraint) << "GLSL: Requires minimum for c-dimension set to constant " << "for ImageParam '" << args[0] << "'. " << "Call set_min(2, min) or set_bounds(2, min, extent) to set.\n"; } Expr c_coordinate = mutate(call_args[2 + 2 * 2]); args[4] = c_coordinate; return Call::make(call->type, Call::glsl_texture_load, vector<Expr>(&args[0], &args[5]), Call::Intrinsic, FunctionPtr(), 0, call->image, call->param); } else if (call->is_intrinsic(Call::image_store)) { user_assert(call->args.size() == 6) << "GLSL stores require three coordinates.\n"; // Create // gl_texture_store(name, name.buffer, x, y, c, value) // out of // image_store(name, name.buffer, x, y, c, value) vector<Expr> args(call->args); args[5] = mutate(call->args[5]); // mutate value return Call::make(call->type, Call::glsl_texture_store, args, Call::Intrinsic); } else { return IRMutator::visit(call); } } }; Stmt inject_opengl_intrinsics(const Stmt &s) { InjectOpenGLIntrinsics gl; return gl.mutate(s); } } // namespace Internal } // namespace Halide
#include <iostream> #include <vector> #include <cmath> #include <algorithm> using namespace std; /* Código de: https://iq.opengenus.org/strassens-matrix-multiplication-algorithm/ Código para resolver una multiplicación de matrices utilizando el algorítmo de multiplicación de matrices de Strassen, utilizando la técnica de diseño Divide y Venceras. */ /* * Método para obtener la siguiente potencia de 2 * @param k: número al que se esta elevando 2 actualmente * @return siguiente potencia de 2 */ int nextpowerof2(int k) { return pow(2, int(ceil(log2(k)))); } /* * Utilizada para mostrar la matriz final * @param matrix: conjunto de vectores que foroman la matriz resultante * @param m: número de filas de la matriz * @param n: número de columnas de la matriz */ void display(vector< vector<int>> &matrix, int m, int n) { for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (j != 0) { cout << "\t"; } cout << matrix[i][j]; } cout << endl; } } /* Operación de suma para submatrices*/ void add(vector<vector<int>> &A, vector<vector<int>> &B, vector<vector<int>> &C, int size) { int i, j; for (i = 0; i < size; i++) { for (j = 0; j < size; j++) { C[i][j] = A[i][j] + B[i][j]; } } } /* Operación de resta para submatrices*/ void sub(vector<vector<int>> &A, vector<vector<int>> &B, vector<vector<int>> &C, int size) { int i, j; for (i = 0; i < size; i++) { for (j = 0; j < size; j++) { C[i][j] = A[i][j] - B[i][j]; } } } /* Crea submatrices a partir de las matrices originales y agrupa los resultados en la matriz resultante */ void STRASSEN_algorithmA(vector<vector<int>> &A, vector<vector<int>> &B, vector<vector<int>> &C, int size) { //base case if (size == 1) { C[0][0] = A[0][0] * B[0][0]; return; } else { int new_size = size / 2; vector<int> z(new_size); vector<vector<int>> a11(new_size, z), a12(new_size, z), a21(new_size, z), a22(new_size, z), b11(new_size, z), b12(new_size, z), b21(new_size, z), b22(new_size, z), c11(new_size, z), c12(new_size, z), c21(new_size, z), c22(new_size, z), p1(new_size, z), p2(new_size, z), p3(new_size, z), p4(new_size, z), p5(new_size, z), p6(new_size, z), p7(new_size, z), aResult(new_size, z), bResult(new_size, z); int i, j; //dividing the matrices into sub-matrices: for (i = 0; i < new_size; i++) { for (j = 0; j < new_size; j++) { a11[i][j] = A[i][j]; a12[i][j] = A[i][j + new_size]; a21[i][j] = A[i + new_size][j]; a22[i][j] = A[i + new_size][j + new_size]; b11[i][j] = B[i][j]; b12[i][j] = B[i][j + new_size]; b21[i][j] = B[i + new_size][j]; b22[i][j] = B[i + new_size][j + new_size]; } } // Calculating p1 to p7: add(a11, a22, aResult, new_size); // a11 + a22 add(b11, b22, bResult, new_size); // b11 + b22 STRASSEN_algorithmA(aResult, bResult, p1, new_size); // p1 = (a11+a22) * (b11+b22) add(a21, a22, aResult, new_size); // a21 + a22 STRASSEN_algorithmA(aResult, b11, p2, new_size); // p2 = (a21+a22) * (b11) sub(b12, b22, bResult, new_size); // b12 - b22 STRASSEN_algorithmA(a11, bResult, p3, new_size); // p3 = (a11) * (b12 - b22) sub(b21, b11, bResult, new_size); // b21 - b11 STRASSEN_algorithmA(a22, bResult, p4, new_size); // p4 = (a22) * (b21 - b11) add(a11, a12, aResult, new_size); // a11 + a12 STRASSEN_algorithmA(aResult, b22, p5, new_size); // p5 = (a11+a12) * (b22) sub(a21, a11, aResult, new_size); // a21 - a11 add(b11, b12, bResult, new_size); // b11 + b12 STRASSEN_algorithmA(aResult, bResult, p6, new_size); // p6 = (a21-a11) * (b11+b12) sub(a12, a22, aResult, new_size); // a12 - a22 add(b21, b22, bResult, new_size); // b21 + b22 STRASSEN_algorithmA(aResult, bResult, p7, new_size); // p7 = (a12-a22) * (b21+b22) // calculating c21, c21, c11 e c22: add(p3, p5, c12, new_size); // c12 = p3 + p5 add(p2, p4, c21, new_size); // c21 = p2 + p4 add(p1, p4, aResult, new_size); // p1 + p4 add(aResult, p7, bResult, new_size); // p1 + p4 + p7 sub(bResult, p5, c11, new_size); // c11 = p1 + p4 - p5 + p7 add(p1, p3, aResult, new_size); // p1 + p3 add(aResult, p6, bResult, new_size); // p1 + p3 + p6 sub(bResult, p2, c22, new_size); // c22 = p1 + p3 - p2 + p6 // Grouping the results obtained in a single matrix: for (i = 0; i < new_size; i++) { for (j = 0; j < new_size; j++) { C[i][j] = c11[i][j]; C[i][j + new_size] = c12[i][j]; C[i + new_size][j] = c21[i][j]; C[i + new_size][j + new_size] = c22[i][j]; } } } } /* Revisa el tamaño de las matrices a utilizar y las ajusta si es necesario * Define los parametros de la matriz resultante para invocar el método en el que se * asginaran los valores */ void STRASSEN_algorithm(vector<vector<int>> &A, vector<vector<int>> &B, int m, int n, int a, int b) { /* Check to see if these matrices are already square and have dimensions of a power of 2. If not, * the matrices must be resized and padded with zeroes to meet this criteria. */ int k = max({m, n, a, b}); int s = nextpowerof2(k); vector<int> z(s); vector<vector<int>> Aa(s, z), Bb(s, z), Cc(s, z); for (unsigned int i = 0; i < m; i++) { for (unsigned int j = 0; j < n; j++) { Aa[i][j] = A[i][j]; } } for (unsigned int i = 0; i < a; i++) { for (unsigned int j = 0; j < b; j++) { Bb[i][j] = B[i][j]; } } STRASSEN_algorithmA(Aa, Bb, Cc, s); vector<int> temp1(b); vector<vector<int>> C(m, temp1); for (unsigned int i = 0; i < m; i++) { for (unsigned int j = 0; j < b; j++) { C[i][j] = Cc[i][j]; } } display(C, m, b); } /* Revisa el tamaño de la matriz resultante para asegurar que haya sido una multiplicación exitosa */ bool check(int n, int a) { if (n == a) return true; else return false; } int main() { int m, n, a, b; cout << "Matrix Multiplication using Strassen algorithm" << endl; cout << "Enter rows and columns of first matrix" << endl; cin >> m >> n; cout << "enter values into first matrix" << endl; vector<vector<int>> A; //first matrix input for (int i = 0; i < m; i++) { vector<int> temp; for (int j = 0; j < n; j++) { int i; cin >> i; temp.push_back(i); } A.push_back(temp); } cout << "Enter rows and columns of second matrix" << endl; cin >> a >> b; cout << "enter values into second matrix" << endl; vector<vector<int>> B; //second matrix input for (int i = 0; i < a; i++) { vector<int> temp; for (int j = 0; j < b; j++) { int i; cin >> i; temp.push_back(i); } B.push_back(temp); } bool k = check(n, a); if (k) { STRASSEN_algorithm(A, B, m, n, a, b); } else { cout << "martrix multiplication not possible"; } cout<<"\nLa complejidad de este algoritmo es O(n^Log7) que se aproxima a O(n^2.8074)"<<endl; return 0; }
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> // Common file #include <ext/pb_ds/tree_policy.hpp> // Including tree_order_statistics_node_update using namespace __gnu_pbds; using namespace std; #pragma GCC optimize("O3") #pragma GCC optimization ("unroll-loops") #pragma region using ll = long long; using db = long double; // or double, if TL is tight using str = string; // yay python! using pi = pair<int,int>; using pl = pair<ll,ll>; using pd = pair<db,db>; using vi = vector<int>; using vb = vector<bool>; using vl = vector<ll>; using vd = vector<db>; using vs = vector<str>; using vpi = vector<pi>; using vpl = vector<pl>; using vpd = vector<pd>; #define tcT template<class T #define tcTU tcT, class U // ^ lol this makes everything look weird but I'll try it tcT> using V = vector<T>; tcT, size_t SZ> using AR = array<T,SZ>; tcT> using PR = pair<T,T>; // pairs #define mp make_pair #define f first #define s second // vectors // oops size(x), rbegin(x), rend(x) need C++17 #define sz(x) (int)x.size() #define bg(x) x.begin() #define en(x) x.end() #define all(x) bg(x), end(x) #define rall(x) x.rbegin(), x.rend() #define sor(x) sort(all(x)) #define rsz resize #define ins insert #define ft front() #define bk back() #define pb push_back #define eb emplace_back #define pf push_front #define lb lower_bound #define ub upper_bound tcT> int lwb(V<T>& a, const T& b) { return int(lb(all(a),b)-bg(a)); } // loops #define FOR(i,a,b) for (int i = (a); i < (b); ++i) #define F0R(i,a) FOR(i,0,a) #define ROF(i,a,b) for (int i = (b)-1; i >= (a); --i) #define R0F(i,a) ROF(i,0,a) #define trav(a,x) for (auto& a: x) const int MOD = 1e9+7; // 998244353; const ll INF = 1e18; // not too close to LLONG_MAX const char nl = '\n'; const db PI = acos((db)-1); const int dx[4] = {1,0,-1,0}, dy[4] = {0,1,0,-1}; // for every grid problem!! mt19937 rng((uint32_t)chrono::steady_clock::now().time_since_epoch().count()); template<class T> using pqg = priority_queue<T,vector<T>,greater<T>>; template<class T> using ost = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>; //order statistic tree! // bitwise ops // also see https://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html constexpr int pct(int x) { return __builtin_popcount(x); } // # of bits set constexpr int bits(int x) { // assert(x >= 0); // make C++11 compatible until USACO updates ... return x == 0 ? 0 : 31-__builtin_clz(x); } // floor(log2(x)) constexpr int p2(int x) { return 1<<x; } constexpr int msk2(int x) { return p2(x)-1; } ll cdiv(ll a, ll b) { return a/b+((a^b)>0&&a%b); } // divide a by b rounded up ll fdiv(ll a, ll b) { return a/b-((a^b)<0&&a%b); } // divide a by b rounded down tcT> bool ckmin(T& a, const T& b) { return b < a ? a = b, 1 : 0; } // set a = min(a,b) tcT> bool ckmax(T& a, const T& b) { return a < b ? a = b, 1 : 0; } tcTU> T fstTrue(T lo, T hi, U f) { hi ++; assert(lo <= hi); // assuming f is increasing while (lo < hi) { // find first index such that f is true T mid = lo+(hi-lo)/2; f(mid) ? hi = mid : lo = mid+1; } return lo; } tcTU> T lstTrue(T lo, T hi, U f) { lo --; assert(lo <= hi); // assuming f is decreasing while (lo < hi) { // find first index such that f is true T mid = lo+(hi-lo+1)/2; f(mid) ? lo = mid : hi = mid-1; } return lo; } tcT> void remDup(vector<T>& v) { // sort and remove duplicates sort(all(v)); v.erase(unique(all(v)),end(v)); } tcTU> void erase(T& t, const U& u) { // don't erase auto it = t.find(u); assert(it != end(t)); t.erase(it); } // element that doesn't exist from (multi)set // INPUT #define tcTUU tcT, class ...U tcT> void re(complex<T>& c); tcTU> void re(pair<T,U>& p); tcT> void re(V<T>& v); tcT, size_t SZ> void re(AR<T,SZ>& a); tcT> void re(T& x) { cin >> x; } void re(double& d) { str t; re(t); d = stod(t); } void re(long double& d) { str t; re(t); d = stold(t); } tcTUU> void re(T& t, U&... u) { re(t); re(u...); } tcT> void re(complex<T>& c) { T a,b; re(a,b); c = {a,b}; } tcTU> void re(pair<T,U>& p) { re(p.f,p.s); } tcT> void re(V<T>& x) { trav(a,x) re(a); } tcT, size_t SZ> void re(AR<T,SZ>& x) { trav(a,x) re(a); } tcT> void rv(int n, V<T>& x) { x.rsz(n); re(x); } // TO_STRING #define ts to_string str ts(char c) { return str(1,c); } str ts(const char* s) { return (str)s; } str ts(str s) { return s; } str ts(bool b) { // #ifdef LOCAL // return b ? "true" : "false"; // #else return ts((int)b); // #endif } tcT> str ts(complex<T> c) { stringstream ss; ss << c; return ss.str(); } str ts(V<bool> v) { str res = "{"; F0R(i,sz(v)) res += char('0'+v[i]); res += "}"; return res; } template<size_t SZ> str ts(bitset<SZ> b) { str res = ""; F0R(i,SZ) res += char('0'+b[i]); return res; } tcTU> str ts(pair<T,U> p); tcT> str ts(T v) { // containers with begin(), end() #ifdef LOCAL bool fst = 1; str res = "{"; for (const auto& x: v) { if (!fst) res += ", "; fst = 0; res += ts(x); } res += "}"; return res; #else bool fst = 1; str res = ""; for (const auto& x: v) { if (!fst) res += " "; fst = 0; res += ts(x); } return res; #endif } tcTU> str ts(pair<T,U> p) { #ifdef LOCAL return "("+ts(p.f)+", "+ts(p.s)+")"; #else return ts(p.f)+" "+ts(p.s); #endif } // OUTPUT tcT> void pr(T x) { cout << ts(x); } tcTUU> void pr(const T& t, const U&... u) { pr(t); pr(u...); } void ps() { pr("\n"); } // print w/ spaces tcTUU> void ps(const T& t, const U&... u) { pr(t); if (sizeof...(u)) pr(" "); ps(u...); } // DEBUG void DBG() { cerr << "]" << endl; } tcTUU> void DBG(const T& t, const U&... u) { cerr << ts(t); if (sizeof...(u)) cerr << ", "; DBG(u...); } #ifdef LOCAL // compile with -DLOCAL, chk -> fake assert #define dbg(...) cerr << "Line(" << __LINE__ << ") -> [" << #__VA_ARGS__ << "]: [", DBG(__VA_ARGS__) #define chk(...) if (!(__VA_ARGS__)) cerr << "Line(" << __LINE__ << ") -> function(" \ << __FUNCTION__ << ") -> CHK FAILED: (" << #__VA_ARGS__ << ")" << "\n", exit(0); #else #define dbg(...) 0 #define chk(...) 0 #endif void setPrec() { cout << fixed << setprecision(15); } void unsyncIO() { cin.tie(0)->sync_with_stdio(0); } // FILE I/O void setIn(str s) { freopen(s.c_str(),"r",stdin); } void setOut(str s) { freopen(s.c_str(),"w",stdout); } void setIO(str s = "") { unsyncIO(); setPrec(); // cin.exceptions(cin.failbit); // throws exception when do smth illegal // ex. try to read letter into int if (sz(s)) setIn(s+".in"), setOut(s+".out"); // for USACO } #pragma endregion const int MX = 2e5+5; // make sure to intialize ALL GLOBAL VARS between tcs! int N, M; char mat[51][51]; bool vis[51][51]; // void ff(int x, int y) { // vis[x][y] = true; // F0R(i, 4) { // int nx = x + dx[i]; // int ny = y + dy[i]; // if(!vis[nx][ny] && dx[]) ff(nx, ny); // } // }a int main() { // clock_t start = clock(); setIO(); re(N, M); vpi wL; F0R(i, N) { F0R(j, M) { re(mat[i][j]); } } bool ret = true; F0R(i, N) F0R(j, M) { F0R(k, 4) { int nx = i + dx[k]; int ny = j + dy[k]; if(nx < 0 || nx >= N || ny < 0 || ny >= M) continue; if(mat[nx][ny] == 'P' && mat[i][j] == 'W') { ret = false; break; } } } ret ? pr("Yes") : pr("No"); // cerr << "Total Time: " << (double)(clock() - start)/ CLOCKS_PER_SEC; } /* stuff you should look for * int overflow, array bounds * special cases (n=1?) * do smth instead of nothing and stay organized * WRITE STUFF DOWN * DON'T GET STUCK ON ONE APPROACH */
//===- Simulation.cpp - Handshake MLIR Operations -----------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file contains functions used to execute a restricted form of the // standard dialect, and the handshake dialect. // //===----------------------------------------------------------------------===// #include <list> #include "mlir/Dialect/StandardOps/IR/Ops.h" #include "circt/Dialect/Handshake/HandshakeOps.h" #include "circt/Dialect/Handshake/Simulation.h" #define DEBUG_TYPE "runner" #define INDEX_WIDTH 32 using namespace llvm; using namespace circt; STATISTIC(instructionsExecuted, "Instructions Executed"); STATISTIC(simulatedTime, "Simulated Time"); void executeOp(mlir::ConstantIndexOp op, std::vector<Any> &in, std::vector<Any> &out) { auto attr = op->getAttrOfType<mlir::IntegerAttr>("value"); out[0] = attr.getValue().sextOrTrunc(INDEX_WIDTH); } void executeOp(mlir::ConstantIntOp op, std::vector<Any> &in, std::vector<Any> &out) { auto attr = op->getAttrOfType<mlir::IntegerAttr>("value"); out[0] = attr.getValue(); } void executeOp(mlir::AddIOp op, std::vector<Any> &in, std::vector<Any> &out) { out[0] = any_cast<APInt>(in[0]) + any_cast<APInt>(in[1]); } void executeOp(mlir::AddFOp op, std::vector<Any> &in, std::vector<Any> &out) { out[0] = any_cast<APFloat>(in[0]) + any_cast<APFloat>(in[1]); } void executeOp(mlir::CmpIOp op, std::vector<Any> &in, std::vector<Any> &out) { APInt in0 = any_cast<APInt>(in[0]); APInt in1 = any_cast<APInt>(in[1]); APInt out0(1, mlir::applyCmpPredicate(op.getPredicate(), in0, in1)); out[0] = out0; } void executeOp(mlir::CmpFOp op, std::vector<Any> &in, std::vector<Any> &out) { APFloat in0 = any_cast<APFloat>(in[0]); APFloat in1 = any_cast<APFloat>(in[1]); APInt out0(1, mlir::applyCmpPredicate(op.getPredicate(), in0, in1)); out[0] = out0; } void executeOp(mlir::SubIOp op, std::vector<Any> &in, std::vector<Any> &out) { out[0] = any_cast<APInt>(in[0]) - any_cast<APInt>(in[1]); } void executeOp(mlir::SubFOp op, std::vector<Any> &in, std::vector<Any> &out) { out[0] = any_cast<APFloat>(in[0]) + any_cast<APFloat>(in[1]); } void executeOp(mlir::MulIOp op, std::vector<Any> &in, std::vector<Any> &out) { out[0] = any_cast<APInt>(in[0]) * any_cast<APInt>(in[1]); } void executeOp(mlir::MulFOp op, std::vector<Any> &in, std::vector<Any> &out) { out[0] = any_cast<APFloat>(in[0]) * any_cast<APFloat>(in[1]); } void executeOp(mlir::SignedDivIOp op, std::vector<Any> &in, std::vector<Any> &out) { assert(any_cast<APInt>(in[1]).getZExtValue() && "Division By Zero!"); out[0] = any_cast<APInt>(in[0]).sdiv(any_cast<APInt>(in[1])); } void executeOp(mlir::UnsignedDivIOp op, std::vector<Any> &in, std::vector<Any> &out) { assert(any_cast<APInt>(in[1]).getZExtValue() && "Division By Zero!"); out[0] = any_cast<APInt>(in[0]).udiv(any_cast<APInt>(in[1])); } void executeOp(mlir::DivFOp op, std::vector<Any> &in, std::vector<Any> &out) { out[0] = any_cast<APFloat>(in[0]) / any_cast<APFloat>(in[1]); } void executeOp(mlir::IndexCastOp op, std::vector<Any> &in, std::vector<Any> &out) { out[0] = in[0]; } void executeOp(mlir::SignExtendIOp op, std::vector<Any> &in, std::vector<Any> &out) { int64_t width = op.getType().getIntOrFloatBitWidth(); out[0] = any_cast<APInt>(in[0]).sext(width); } void executeOp(mlir::ZeroExtendIOp op, std::vector<Any> &in, std::vector<Any> &out) { int64_t width = op.getType().getIntOrFloatBitWidth(); out[0] = any_cast<APInt>(in[0]).zext(width); } // Allocate a new matrix with dimensions given by the type, in the // given store. Return the pseuddo-pointer to the new matrix in the // store (i.e. the first dimension index) unsigned allocateMemRef(mlir::MemRefType type, std::vector<Any> &in, std::vector<std::vector<Any>> &store, std::vector<double> &storeTimes) { ArrayRef<int64_t> shape = type.getShape(); int64_t allocationSize = 1; unsigned count = 0; for (int64_t dim : shape) { if (dim > 0) allocationSize *= dim; else { assert(count < in.size()); allocationSize *= any_cast<APInt>(in[count++]).getSExtValue(); } } unsigned ptr = store.size(); store.resize(ptr + 1); storeTimes.resize(ptr + 1); store[ptr].resize(allocationSize); storeTimes[ptr] = 0.0; mlir::Type elementType = type.getElementType(); int64_t width = elementType.getIntOrFloatBitWidth(); for (int i = 0; i < allocationSize; i++) { if (elementType.isa<mlir::IntegerType>()) { store[ptr][i] = APInt(width, 0); } else if (elementType.isa<mlir::FloatType>()) { store[ptr][i] = APFloat(0.0); } else { llvm_unreachable("Unknown result type!\n"); } } return ptr; } void executeOp(mlir::LoadOp op, std::vector<Any> &in, std::vector<Any> &out, std::vector<std::vector<Any>> &store) { ArrayRef<int64_t> shape = op.getMemRefType().getShape(); unsigned address = 0; for (unsigned i = 0; i < shape.size(); i++) { address = address * shape[i] + any_cast<APInt>(in[i + 1]).getZExtValue(); } unsigned ptr = any_cast<unsigned>(in[0]); assert(ptr < store.size()); auto &ref = store[ptr]; assert(address < ref.size()); // LLVM_DEBUG(dbgs() << "Load " << ref[address] << " from " << ptr << "[" << // address << "]\n"); Any result = ref[address]; out[0] = result; } void executeOp(mlir::StoreOp op, std::vector<Any> &in, std::vector<Any> &out, std::vector<std::vector<Any>> &store) { ArrayRef<int64_t> shape = op.getMemRefType().getShape(); unsigned address = 0; for (unsigned i = 0; i < shape.size(); i++) { address = address * shape[i] + any_cast<APInt>(in[i + 2]).getZExtValue(); } unsigned ptr = any_cast<unsigned>(in[1]); assert(ptr < store.size()); auto &ref = store[ptr]; // LLVM_DEBUG(dbgs() << "Store " << in[0] << " to " << ptr << "[" << address // << "]\n"); assert(address < ref.size()); ref[address] = in[0]; } void debugArg(const std::string &head, mlir::Value op, const APInt &value, double time) { LLVM_DEBUG(dbgs() << " " << head << ": " << op << " = " << value << " (APInt<" << value.getBitWidth() << ">) @" << time << "\n"); } void debugArg(const std::string &head, mlir::Value op, const APFloat &value, double time) { LLVM_DEBUG(dbgs() << " " << head << ": " << op << " = "; value.print(dbgs()); dbgs() << " (" << "float" << ") @" << time << "\n"); } void debugArg(const std::string &head, mlir::Value op, const Any &value, double time) { if (any_isa<APInt>(value)) { debugArg(head, op, any_cast<APInt>(value), time); } else if (any_isa<APFloat>(value)) { debugArg(head, op, any_cast<APFloat>(value), time); } else if (any_isa<unsigned>(value)) { // Represents an allocated buffer. LLVM_DEBUG(dbgs() << " " << head << ": " << op << " = Buffer " << any_cast<unsigned>(value) << "\n"); } else { llvm_unreachable("unknown type"); } } Any readValueWithType(mlir::Type type, std::string in) { std::stringstream arg(in); if (type.isIndex()) { int64_t x; arg >> x; int64_t width = INDEX_WIDTH; APInt aparg(width, x); return aparg; } else if (type.isa<mlir::IntegerType>()) { int64_t x; arg >> x; int64_t width = type.getIntOrFloatBitWidth(); APInt aparg(width, x); return aparg; // } else if (type.isF16()) { // half x; // arg >> x; // APFloat aparg(x); // return aparg; } else if (type.isF32()) { float x; arg >> x; APFloat aparg(x); return aparg; } else if (type.isF64()) { double x; arg >> x; APFloat aparg(x); return aparg; } else { assert(0 && "unknown argument type!\n"); } } std::string printAnyValueWithType(mlir::Type type, Any &value) { std::stringstream out; if (type.isa<mlir::IntegerType>() || type.isa<mlir::IndexType>()) { out << any_cast<APInt>(value).getSExtValue(); return out.str(); } else if (type.isa<mlir::FloatType>()) { out << any_cast<APFloat>(value).convertToDouble(); return out.str(); } else if (type.isa<mlir::NoneType>()) { return "none"; } else { llvm_unreachable("Unknown result type!"); } } void scheduleIfNeeded(std::list<mlir::Operation *> &readyList, llvm::DenseMap<mlir::Value, Any> &valueMap, mlir::Operation *op) { if (std::find(readyList.begin(), readyList.end(), op) == readyList.end()) { readyList.push_back(op); } } void scheduleUses(std::list<mlir::Operation *> &readyList, llvm::DenseMap<mlir::Value, Any> &valueMap, mlir::Value value) { for (auto &use : value.getUses()) { scheduleIfNeeded(readyList, valueMap, use.getOwner()); } } bool executeStdOp(mlir::Operation &op, std::vector<Any> &inValues, std::vector<Any> &outValues) { if (auto stdOp = dyn_cast<mlir::ConstantIndexOp>(op)) executeOp(stdOp, inValues, outValues); else if (auto stdOp = dyn_cast<mlir::ConstantIntOp>(op)) executeOp(stdOp, inValues, outValues); else if (auto stdOp = dyn_cast<mlir::AddIOp>(op)) executeOp(stdOp, inValues, outValues); else if (auto stdOp = dyn_cast<mlir::AddFOp>(op)) executeOp(stdOp, inValues, outValues); else if (auto stdOp = dyn_cast<mlir::SubIOp>(op)) executeOp(stdOp, inValues, outValues); else if (auto stdOp = dyn_cast<mlir::SubFOp>(op)) executeOp(stdOp, inValues, outValues); else if (auto stdOp = dyn_cast<mlir::CmpIOp>(op)) executeOp(stdOp, inValues, outValues); else if (auto stdOp = dyn_cast<mlir::CmpFOp>(op)) executeOp(stdOp, inValues, outValues); else if (auto stdOp = dyn_cast<mlir::MulIOp>(op)) executeOp(stdOp, inValues, outValues); else if (auto stdOp = dyn_cast<mlir::MulFOp>(op)) executeOp(stdOp, inValues, outValues); else if (auto stdOp = dyn_cast<mlir::UnsignedDivIOp>(op)) executeOp(stdOp, inValues, outValues); else if (auto stdOp = dyn_cast<mlir::SignedDivIOp>(op)) executeOp(stdOp, inValues, outValues); else if (auto stdOp = dyn_cast<mlir::DivFOp>(op)) executeOp(stdOp, inValues, outValues); else if (auto stdOp = dyn_cast<mlir::IndexCastOp>(op)) executeOp(stdOp, inValues, outValues); else if (auto stdOp = dyn_cast<mlir::SignExtendIOp>(op)) executeOp(stdOp, inValues, outValues); else if (auto stdOp = dyn_cast<mlir::ZeroExtendIOp>(op)) executeOp(stdOp, inValues, outValues); else return false; return true; } void executeFunction(mlir::FuncOp &toplevel, llvm::DenseMap<mlir::Value, Any> &valueMap, llvm::DenseMap<mlir::Value, double> &timeMap, std::vector<Any> &results, std::vector<double> &resultTimes, std::vector<std::vector<Any>> &store, std::vector<double> &storeTimes) { mlir::Block &entryBlock = toplevel.getBody().front(); // An iterator which walks over the instructions. mlir::Block::iterator instIter = entryBlock.begin(); // Main executive loop. Start at the first instruction of the entry // block. Fetch and execute instructions until we hit a terminator. while (true) { mlir::Operation &op = *instIter; int64_t i = 0; std::vector<Any> inValues(op.getNumOperands()); std::vector<Any> outValues(op.getNumResults()); LLVM_DEBUG(dbgs() << "OP: " << op.getName() << "\n"); double time = 0.0; for (mlir::Value in : op.getOperands()) { inValues[i] = valueMap[in]; time = std::max(time, timeMap[in]); LLVM_DEBUG(debugArg("IN", in, inValues[i], timeMap[in])); i++; } if (executeStdOp(op, inValues, outValues)) { } else if (auto allocOp = dyn_cast<mlir::AllocOp>(op)) { outValues[0] = allocateMemRef(allocOp.getType(), inValues, store, storeTimes); unsigned ptr = any_cast<unsigned>(outValues[0]); storeTimes[ptr] = time; } else if (auto loadOp = dyn_cast<mlir::LoadOp>(op)) { executeOp(loadOp, inValues, outValues, store); unsigned ptr = any_cast<unsigned>(inValues[0]); double storeTime = storeTimes[ptr]; LLVM_DEBUG(dbgs() << "STORE: " << storeTime << "\n"); time = std::max(time, storeTime); storeTimes[ptr] = time; } else if (auto storeOp = dyn_cast<mlir::StoreOp>(op)) { executeOp(storeOp, inValues, outValues, store); unsigned ptr = any_cast<unsigned>(inValues[1]); double storeTime = storeTimes[ptr]; LLVM_DEBUG(dbgs() << "STORE: " << storeTime << "\n"); time = std::max(time, storeTime); storeTimes[ptr] = time; } else if (auto branchOp = dyn_cast<mlir::BranchOp>(op)) { mlir::Block *dest = branchOp.getDest(); unsigned arg = 0; for (mlir::Value out : dest->getArguments()) { LLVM_DEBUG(debugArg("ARG", out, inValues[arg], time)); valueMap[out] = inValues[arg]; timeMap[out] = time; arg++; } instIter = dest->begin(); continue; } else if (auto condBranchOp = dyn_cast<mlir::CondBranchOp>(op)) { APInt condition = any_cast<APInt>(inValues[0]); mlir::Block *dest; std::vector<Any> inArgs; double time = 0.0; if (condition != 0) { dest = condBranchOp.getTrueDest(); inArgs.resize(condBranchOp.getNumTrueOperands()); for (mlir::Value in : condBranchOp.getTrueOperands()) { inArgs[i] = valueMap[in]; time = std::max(time, timeMap[in]); LLVM_DEBUG(debugArg("IN", in, inArgs[i], timeMap[in])); i++; } } else { dest = condBranchOp.getFalseDest(); inArgs.resize(condBranchOp.getNumFalseOperands()); for (mlir::Value in : condBranchOp.getFalseOperands()) { inArgs[i] = valueMap[in]; time = std::max(time, timeMap[in]); LLVM_DEBUG(debugArg("IN", in, inArgs[i], timeMap[in])); i++; } } int64_t arg = 0; for (mlir::Value out : dest->getArguments()) { LLVM_DEBUG(debugArg("ARG", out, inArgs[arg], time)); valueMap[out] = inArgs[arg]; timeMap[out] = time; arg++; } instIter = dest->begin(); continue; } else if (auto returnOp = dyn_cast<mlir::ReturnOp>(op)) { for (unsigned i = 0; i < results.size(); i++) { results[i] = inValues[i]; resultTimes[i] = timeMap[returnOp.getOperand(i)]; } return; } else if (auto callOp = dyn_cast<mlir::CallOpInterface>(op)) { // implement function calls. mlir::Operation *calledOp = callOp.resolveCallable(); if (auto funcOp = dyn_cast<mlir::FuncOp>(calledOp)) { mlir::FunctionType ftype = funcOp.getType(); unsigned inputs = ftype.getNumInputs(); unsigned outputs = ftype.getNumResults(); llvm::DenseMap<mlir::Value, Any> newValueMap; llvm::DenseMap<mlir::Value, double> newTimeMap; std::vector<Any> results(outputs); std::vector<double> resultTimes(outputs); std::vector<std::vector<Any>> store; std::vector<double> storeTimes; mlir::Block &entryBlock = funcOp.getBody().front(); mlir::Block::BlockArgListType blockArgs = entryBlock.getArguments(); for (unsigned i = 0; i < inputs; i++) { newValueMap[blockArgs[i]] = inValues[i]; newTimeMap[blockArgs[i]] = timeMap[op.getOperand(i)]; } executeFunction(funcOp, newValueMap, newTimeMap, results, resultTimes, store, storeTimes); i = 0; for (mlir::Value out : op.getResults()) { valueMap[out] = results[i]; timeMap[out] = resultTimes[i]; i++; } instIter++; continue; } else { llvm_unreachable("Callable was not a Function!\n"); } } else { llvm_unreachable("Unknown operation!\n"); } i = 0; for (mlir::Value out : op.getResults()) { LLVM_DEBUG(debugArg("OUT", out, outValues[i], time)); valueMap[out] = outValues[i]; timeMap[out] = time + 1; i++; } instIter++; instructionsExecuted++; } } void executeHandshakeFunction(handshake::FuncOp &toplevel, llvm::DenseMap<mlir::Value, Any> &valueMap, llvm::DenseMap<mlir::Value, double> &timeMap, std::vector<Any> &results, std::vector<double> &resultTimes, std::vector<std::vector<Any>> &store, std::vector<double> &storeTimes) { mlir::Block &entryBlock = toplevel.getBody().front(); // The arguments of the entry block. mlir::Block::BlockArgListType blockArgs = entryBlock.getArguments(); // A list of operations which might be ready to execute. std::list<mlir::Operation *> readyList; // A map of memory ops llvm::DenseMap<unsigned, unsigned> memoryMap; // Pre-allocate memory toplevel.walk([&](Operation *op) { if (auto handshakeMemoryOp = dyn_cast<handshake::MemoryOpInterface>(op)) if (!handshakeMemoryOp.allocateMemory(memoryMap, store, storeTimes)) llvm_unreachable("Memory op does not have unique ID!\n"); }); for (unsigned i = 0; i < blockArgs.size(); i++) scheduleUses(readyList, valueMap, blockArgs[i]); #define EXTRA_DEBUG while (true) { #ifdef EXTRA_DEBUG LLVM_DEBUG( for (auto t : readyList) { dbgs() << "READY: " << *t << "\n"; } dbgs() << "Live: " << valueMap.size() << "\n"; for (auto t : valueMap) { debugArg("Value:", t.first, t.second, 0.0); // dbgs() << "Value: " << *(t.first) << " " << t.second << // "\n"; }); #endif assert(readyList.size() > 0); mlir::Operation &op = *readyList.front(); readyList.pop_front(); /* for(mlir::Value out : op.getResults()) { if(valueMap.count(out) != 0) { LLVM_DEBUG(dbgs() << "OP: " << op << "\n"); for(auto t : valueMap) { dbgs() << "Value: " << *(t.first) << " " << t.second << "\n"; } assert(false); } }*/ // Execute handshake ops through ExecutableOpInterface if (auto handshakeOp = dyn_cast<handshake::ExecutableOpInterface>(op)) { std::vector<mlir::Value> scheduleList; if (!handshakeOp.tryExecute(valueMap, memoryMap, timeMap, store, scheduleList)) readyList.push_back(&op); for (mlir::Value out : scheduleList) scheduleUses(readyList, valueMap, out); continue; } int64_t i = 0; std::vector<Any> inValues(op.getNumOperands()); std::vector<Any> outValues(op.getNumResults()); bool reschedule = false; LLVM_DEBUG(dbgs() << "OP: (" << op.getNumOperands() << "->" << op.getNumResults() << ")" << op << "\n"); double time; for (mlir::Value in : op.getOperands()) { if (valueMap.count(in) == 0) { reschedule = true; continue; } inValues[i] = valueMap[in]; time = std::max(time, timeMap[in]); LLVM_DEBUG(debugArg("IN", in, inValues[i], timeMap[in])); i++; } if (reschedule) { LLVM_DEBUG(dbgs() << "Rescheduling data...\n"); readyList.push_back(&op); continue; } // Consume the inputs. for (mlir::Value in : op.getOperands()) { valueMap.erase(in); } if (executeStdOp(op, inValues, outValues)) { } else if (auto returnOp = dyn_cast<handshake::ReturnOp>(op)) { for (unsigned i = 0; i < results.size(); i++) { results[i] = inValues[i]; resultTimes[i] = timeMap[returnOp.getOperand(i)]; } return; //} else { // implement function calls. } else { llvm_unreachable("Unknown operation!\n"); } i = 0; for (mlir::Value out : op.getResults()) { LLVM_DEBUG(debugArg("OUT", out, outValues[i], time)); assert(outValues[i].hasValue()); valueMap[out] = outValues[i]; timeMap[out] = time + 1; scheduleUses(readyList, valueMap, out); i++; } instructionsExecuted++; } } bool simulate(StringRef toplevelFunction, ArrayRef<std::string> inputArgs, mlir::OwningModuleRef &module, mlir::MLIRContext &context) { // The store associates each allocation in the program // (represented by a int) with a vector of values which can be // accessed by it. Currently values are assumed to be an integer. std::vector<std::vector<Any>> store; std::vector<double> storeTimes; // The valueMap associates each SSA statement in the program // (represented by a Value*) with it's corresponding value. // Currently the value is assumed to be an integer. llvm::DenseMap<mlir::Value, Any> valueMap; // The timeMap associates each value with the time it was created. llvm::DenseMap<mlir::Value, double> timeMap; // We need three things in a function-type independent way. // The type signature of the function. mlir::FunctionType ftype; // The arguments of the entry block. mlir::Block::BlockArgListType blockArgs; // The number of inputs to the function in the IR. unsigned inputs; unsigned outputs; // The number of 'real' inputs. This avoids the dummy input // associated with the handshake control logic for handshake // functions. unsigned realInputs; unsigned realOutputs; if (mlir::FuncOp toplevel = module->lookupSymbol<mlir::FuncOp>(toplevelFunction)) { ftype = toplevel.getType(); mlir::Block &entryBlock = toplevel.getBody().front(); blockArgs = entryBlock.getArguments(); // Get the primary inputs of toplevel off the command line. inputs = ftype.getNumInputs(); realInputs = inputs; outputs = ftype.getNumResults(); realOutputs = outputs; } else if (handshake::FuncOp toplevel = module->lookupSymbol<handshake::FuncOp>(toplevelFunction)) { ftype = toplevel.getType(); mlir::Block &entryBlock = toplevel.getBody().front(); blockArgs = entryBlock.getArguments(); // Get the primary inputs of toplevel off the command line. inputs = ftype.getNumInputs(); realInputs = inputs - 1; outputs = ftype.getNumResults(); realOutputs = outputs - 1; if (inputs == 0) { errs() << "Function " << toplevelFunction << " is expected to have " << "at least one dummy argument.\n"; return 1; } if (outputs == 0) { errs() << "Function " << toplevelFunction << " is expected to have " << "at least one dummy result.\n"; return 1; } // Implicit none argument APInt apnonearg(1, 0); valueMap[blockArgs[blockArgs.size() - 1]] = apnonearg; } else { llvm_unreachable("Function not supported.\n"); } if (inputArgs.size() != realInputs) { errs() << "Toplevel function " << toplevelFunction << " has " << realInputs << " actual arguments, but " << inputArgs.size() << " arguments were provided on the command line.\n"; return 1; } for (unsigned i = 0; i < realInputs; i++) { mlir::Type type = ftype.getInput(i); if (type.isa<mlir::MemRefType>()) { // We require this memref type to be fully specified. auto memreftype = type.dyn_cast<mlir::MemRefType>(); std::vector<Any> nothing; std::string x; unsigned buffer = allocateMemRef(memreftype, nothing, store, storeTimes); valueMap[blockArgs[i]] = buffer; timeMap[blockArgs[i]] = 0.0; int64_t i = 0; std::stringstream arg(inputArgs[i]); while (!arg.eof()) { getline(arg, x, ','); store[buffer][i++] = readValueWithType(memreftype.getElementType(), x); } } else { Any value = readValueWithType(type, inputArgs[i]); valueMap[blockArgs[i]] = value; timeMap[blockArgs[i]] = 0.0; } } std::vector<Any> results(realOutputs); std::vector<double> resultTimes(realOutputs); if (mlir::FuncOp toplevel = module->lookupSymbol<mlir::FuncOp>(toplevelFunction)) { executeFunction(toplevel, valueMap, timeMap, results, resultTimes, store, storeTimes); } else if (handshake::FuncOp toplevel = module->lookupSymbol<handshake::FuncOp>(toplevelFunction)) { executeHandshakeFunction(toplevel, valueMap, timeMap, results, resultTimes, store, storeTimes); } double time = 0.0; for (unsigned i = 0; i < results.size(); i++) { mlir::Type t = ftype.getResult(i); outs() << printAnyValueWithType(t, results[i]) << " "; time = std::max(resultTimes[i], time); } // Go back through the arguments and output any memrefs. for (unsigned i = 0; i < realInputs; i++) { mlir::Type type = ftype.getInput(i); if (type.isa<mlir::MemRefType>()) { // We require this memref type to be fully specified. auto memreftype = type.dyn_cast<mlir::MemRefType>(); unsigned buffer = any_cast<unsigned>(valueMap[blockArgs[i]]); auto elementType = memreftype.getElementType(); for (int j = 0; j < memreftype.getNumElements(); j++) { if (j != 0) outs() << ","; outs() << printAnyValueWithType(elementType, store[buffer][j]); } outs() << " "; } } outs() << "\n"; simulatedTime += (int)time; return 0; }
#include "stdafx.h" #include "StackTrace.h" #include "MapFile.h" #include "MapFileEntry.h" //----------------------------------------------------------------------------- #define MAX_DEPTH 32 //----------------------------------------------------------------------------- namespace dev { static long getCaller( int index ) { #if defined(_DEBUG) && defined(_MSC_VER) && defined(_M_IX86) long caller = 0; __asm { mov ebx, ebp mov ecx, index inc ecx xor eax, eax StackTrace_getCaller_next: mov eax, [ebx+4] mov ebx, [ebx] dec ecx jnz StackTrace_getCaller_next mov caller, eax } return caller; #else return 0; #endif } int StackTrace::printStackTrace( MapFile** _map, int maps, int initLevel, int maxDepth, char* buffer, int bufferSize ) { if ( maxDepth > MAX_DEPTH ) maxDepth = MAX_DEPTH; // list callers long callersAddr[MAX_DEPTH]; int callers = 0; int i; for ( i = initLevel ; i < maxDepth ; ++i ) { long addr = getCaller( i ); callersAddr[callers++] = addr; // end tracing here if the entry is not in a map file int entry = -1; for ( int j = 0 ; j < maps ; ++j ) { entry = _map[j]->findEntry( addr ); if ( -1 != entry ) break; } if ( -1 == entry ) break; } // output call stack if ( bufferSize > 0 ) *buffer = 0; int needed = 0; for ( i = initLevel ; i < callers ; ++i ) { long addr = callersAddr[callers-i-1]; // find entry info int entry = -1; const MapFile* entryMap = 0; for ( int j = 0 ; j < maps ; ++j ) { entry = _map[j]->findEntry( addr ); if ( -1 != entry ) { entryMap = _map[j]; break; } } // format entry to tempory buf char buf[MapFileEntry::MAX_NAME+MAX_DEPTH+20]; // name + margin + hex number buf[0] = 0; for ( int k = initLevel-1 ; k < i ; ++k ) strcat( buf, " " ); if ( !entryMap ) sprintf( buf+strlen(buf), "0x%x\n", addr ); else sprintf( buf+strlen(buf), "%s (%x)\n", entryMap->getEntry(entry).name(), addr ); // append temporary buf to output buffer if space left needed += strlen( buf ); if ( needed < bufferSize ) strcat( buffer, buf ); } // terminate output buffer if ( needed < bufferSize ) buffer[needed] = 0; else if ( bufferSize > 0 ) buffer[bufferSize-1] = 0; return needed; } } // dev /* * Copyright (c) 2001 Jani Kajala * * Permission to use, copy, modify, distribute and sell this * software and its documentation for any purpose is hereby * granted without fee, provided that the above copyright notice * appear in all copies and that both that copyright notice and * this permission notice appear in supporting documentation. * Jani Kajala makes no representations about the suitability * of this software for any purpose. It is provided "as is" * without express or implied warranty. */
// ObjectTalk Scripting Language // Copyright (c) 1993-2022 Johan A. Goossens. All rights reserved. // // This work is licensed under the terms of the MIT license. // For a copy, see <https://opensource.org/licenses/MIT>. // // Include files // #include <algorithm> #include <cmath> #include <cstdlib> #include <ctime> #include "ot/numbers.h" #include "ot/function.h" #include "controller.h" #include "heightmap.h" // // OtHeightMapClass::~OtHeightMapClass // OtHeightMapClass::~OtHeightMapClass() { if (heightmap) { delete [] heightmap; } } // // packHeight // static inline void packHeight(void* dst, const float* src) { float* d = (float*) dst; d[0] = 0.299 * src[0] + 0.587 * src[1] + 0.114 * src[2]; } // // OtHeightMapClass::init // OtObject OtHeightMapClass::init(size_t count, OtObject* parameters) { switch (count) { case 2: scale = parameters[1]->operator float(); case 1: loadMap(parameters[0]->operator std::string()); case 0: break; default: OtExcept("[HeightMap] constructor expects up to 2 arguments (not %ld)", count); } return nullptr; } // // OtHeightMapClass::loadMap // OtObject OtHeightMapClass::loadMap(const std::string& file) { // delete old heightmap if required if (heightmap) { delete [] heightmap; } // load height map static bx::DefaultAllocator allocator; static bx::FileReader reader; if (!bx::open(&reader, file.c_str())) { OtExcept("Can't open heightmap [%s]", file.c_str()); } uint32_t size = (uint32_t) bx::getSize(&reader); void* data = BX_ALLOC(&allocator, size); bx::read(&reader, data, size, bx::ErrorAssert{}); bx::close(&reader); bimg::ImageContainer* image = bimg::imageParse(&allocator, data, size); if (!image) { OtExcept("Can't process heightmap in [%s]", file.c_str()); } // allocate heightmap width = image->m_width; height = image->m_height; heightmap = new float[width * height]; // convert image to height map bimg::imageConvert( (void*) heightmap, sizeof(float) * 8, packHeight, image->m_data, bimg::getBitsPerPixel(image->m_format), bimg::getUnpack(image->m_format), uint32_t(width), uint32_t(height), 1, bimg::getBitsPerPixel(image->m_format) * width / 8, sizeof(float) * width); // free image resources BX_FREE(&allocator, data); bimg::imageFree(image); // notify observers notify(); return shared(); } // // OtHeightMapClass::setScale // OtObject OtHeightMapClass::setScale(float s) { scale = s; notify(); return shared(); } // // OtHeightMapClass::setOffset // OtObject OtHeightMapClass::setOffset(float o) { offset = o; notify(); return shared(); } // // OtHeightMapClass::getHeightAbs // float OtHeightMapClass::getHeightAbs(int x, int y) { x = std::clamp(x, 0, width - 1); y = std::clamp(y, 0, height - 1); return heightmap[y * width + x] * scale + offset; } // // OtHeightMapClass::getHeight // float OtHeightMapClass::getHeight(float x, float y) { x *= width - 1; y *= height - 1; int x1 = std::floor(x); int y1 = std::floor(y); int x2 = x1 + 1; int y2 = y1 + 1; auto h11 = getHeightAbs(x1, y1); auto h21 = getHeightAbs(x2, y1); auto h12 = getHeightAbs(x1, y2); auto h22 = getHeightAbs(x2, y2); auto hx1 = std::lerp(h11, h21, x - x1); auto hx2 = std::lerp(h12, h22, x - x1); return std::lerp(hx1, hx2, y - y1); } // // OtHeightMapClass::getNormal // glm::vec3 OtHeightMapClass::getNormal(float x, float y) { int ix = int(x * width); int iy = int(y * height); return glm::normalize(glm::vec3( getHeightAbs(ix - 1, iy) - getHeightAbs(ix + 1, iy), 2.0, getHeightAbs(ix, iy - 1) - getHeightAbs(ix, iy + 1))); } // // OtHeightMapClass::renderGUI // void OtHeightMapClass::renderGUI() { bool changed = false; if (ImGui::SliderFloat("Scale", &scale, 1.0f, 100.0f)) { changed = true; } if (ImGui::SliderFloat("Ofsset", &offset, -50.0f, 50.0f)) { changed = true; } if (changed) { notify(); } } // // OtHeightMapClass::getMeta // OtType OtHeightMapClass::getMeta() { static OtType type = nullptr; if (!type) { type = OtTypeClass::create<OtHeightMapClass>("HeightMap", OtGuiClass::getMeta()); type->set("__init__", OtFunctionClass::create(&OtHeightMapClass::init)); type->set("loadMap", OtFunctionClass::create(&OtHeightMapClass::loadMap)); type->set("setScale", OtFunctionClass::create(&OtHeightMapClass::setScale)); type->set("setOffset", OtFunctionClass::create(&OtHeightMapClass::setOffset)); type->set("getHeight", OtFunctionClass::create(&OtHeightMapClass::getHeight)); } return type; } // // OtHeightMapClass::create // OtHeightMap OtHeightMapClass::create() { OtHeightMap heightmap = std::make_shared<OtHeightMapClass>(); heightmap->setType(getMeta()); return heightmap; }
Given the array nums, for each nums[i] find out how many numbers in the array are smaller than it. That is, for each nums[i] you have to count the number of valid j's such that j != i and nums[j] < nums[i]. Return the answer in an array. Example 1: Input: nums = [8,1,2,2,3] Output: [4,0,1,1,3] Explanation: For nums[0]=8 there exist four smaller numbers than it (1, 2, 2 and 3). For nums[1]=1 does not exist any smaller number than it. For nums[2]=2 there exist one smaller number than it (1). For nums[3]=2 there exist one smaller number than it (1). For nums[4]=3 there exist three smaller numbers than it (1, 2 and 2). Example 2: Input: nums = [6,5,4,8] Output: [2,1,0,3] Example 3: Input: nums = [7,7,7,7] Output: [0,0,0,0] Constraints: 2 <= nums.length <= 500 0 <= nums[i] <= 100 // Brute Force class Solution { public: vector<int> smallerNumbersThanCurrent(vector<int>& nums) { vector<int> res; int n=nums.size(); for(int i=0;i<n;i++){ int cnt=0; for(int j=0;j<n;j++){ if(i!=j && nums[j]<nums[i]) cnt++; } res.push_back(cnt); } return res; } }; // Optimized // Store the count in a bucket and take the running sum. class Solution { public: vector<int> smallerNumbersThanCurrent(vector<int>& nums) { vector<int> res; vector<int> freq(101, 0); int n=nums.size(); for(auto &x :nums) freq[x]++; for(int i=1;i<101;i++){ freq[i]+=freq[i-1]; } for(int i=0;i<n;i++){ if(nums[i]==0){ res.push_back(0); } else { res.push_back(freq[nums[i]-1]); } } return res; } };
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2013-2019 Regents of the University of California. * * This file is part of ndn-cxx library (NDN C++ library with eXperimental eXtensions). * * ndn-cxx library is free software: you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later version. * * ndn-cxx library is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * * You should have received copies of the GNU General Public License and GNU Lesser * General Public License along with ndn-cxx, e.g., in COPYING.md file. If not, see * <http://www.gnu.org/licenses/>. * * See AUTHORS.md for complete list of ndn-cxx authors and contributors. */ #ifndef NDN_CXX_LP_FIELDS_HPP #define NDN_CXX_LP_FIELDS_HPP #include "ndn-cxx/lp/field-decl.hpp" #include "ndn-cxx/lp/cache-policy.hpp" #include "ndn-cxx/lp/nack-header.hpp" #include "ndn-cxx/lp/prefix-announcement-header.hpp" #include <boost/mpl/set.hpp> namespace ndn { namespace lp { typedef FieldDecl<field_location_tags::Header, Sequence, tlv::Sequence> SequenceField; BOOST_CONCEPT_ASSERT((Field<SequenceField>)); typedef FieldDecl<field_location_tags::Header, uint64_t, tlv::FragIndex, false, NonNegativeIntegerTag, NonNegativeIntegerTag> FragIndexField; BOOST_CONCEPT_ASSERT((Field<FragIndexField>)); typedef FieldDecl<field_location_tags::Header, uint64_t, tlv::FragCount, false, NonNegativeIntegerTag, NonNegativeIntegerTag> FragCountField; BOOST_CONCEPT_ASSERT((Field<FragCountField>)); typedef FieldDecl<field_location_tags::Header, std::pair<Buffer::const_iterator, Buffer::const_iterator>, tlv::PitToken> PitTokenField; BOOST_CONCEPT_ASSERT((Field<PitTokenField>)); typedef FieldDecl<field_location_tags::Header, NackHeader, tlv::Nack> NackField; BOOST_CONCEPT_ASSERT((Field<NackField>)); typedef FieldDecl<field_location_tags::Header, uint64_t, tlv::NextHopFaceId, false, NonNegativeIntegerTag, NonNegativeIntegerTag> NextHopFaceIdField; BOOST_CONCEPT_ASSERT((Field<NextHopFaceIdField>)); typedef FieldDecl<field_location_tags::Header, CachePolicy, tlv::CachePolicy> CachePolicyField; BOOST_CONCEPT_ASSERT((Field<CachePolicyField>)); typedef FieldDecl<field_location_tags::Header, uint64_t, tlv::IncomingFaceId, false, NonNegativeIntegerTag, NonNegativeIntegerTag> IncomingFaceIdField; BOOST_CONCEPT_ASSERT((Field<IncomingFaceIdField>)); typedef FieldDecl<field_location_tags::Header, uint64_t, tlv::CongestionMark, false, NonNegativeIntegerTag, NonNegativeIntegerTag> CongestionMarkField; BOOST_CONCEPT_ASSERT((Field<CongestionMarkField>)); typedef FieldDecl<field_location_tags::Header, Sequence, tlv::Ack, true> AckField; BOOST_CONCEPT_ASSERT((Field<AckField>)); typedef FieldDecl<field_location_tags::Header, Sequence, tlv::TxSequence> TxSequenceField; BOOST_CONCEPT_ASSERT((Field<TxSequenceField>)); typedef FieldDecl<field_location_tags::Header, EmptyValue, tlv::NonDiscovery> NonDiscoveryField; BOOST_CONCEPT_ASSERT((Field<NonDiscoveryField>)); typedef FieldDecl<field_location_tags::Header, PrefixAnnouncementHeader, tlv::PrefixAnnouncement> PrefixAnnouncementField; BOOST_CONCEPT_ASSERT((Field<PrefixAnnouncementField>)); /** \brief Declare the Fragment field. * * The fragment (i.e. payload) is the bytes between two provided iterators. During encoding, * these bytes are copied from the Buffer into the LpPacket. */ typedef FieldDecl<field_location_tags::Fragment, std::pair<Buffer::const_iterator, Buffer::const_iterator>, tlv::Fragment> FragmentField; BOOST_CONCEPT_ASSERT((Field<FragmentField>)); /** \brief Set of all field declarations. */ typedef boost::mpl::set< FragmentField, SequenceField, FragIndexField, FragCountField, PitTokenField, NackField, NextHopFaceIdField, IncomingFaceIdField, CachePolicyField, CongestionMarkField, AckField, TxSequenceField, NonDiscoveryField, PrefixAnnouncementField > FieldSet; } // namespace lp } // namespace ndn #endif // NDN_CXX_LP_FIELDS_HPP
/* * motion_gateway_rpi.cpp * * Created on: 3 mai 2014 * Author: essoussi */ #include "GatewayManager.h" #include <iostream> #include <cstring> #include <cstdlib> int main (int argc, char* argv[]) { uint32_t ErrorGateWayCode = 0; /** Instanciate the gateway manager */ GatewayManager_c gatewayManager = GatewayManager_c::getInstance(); /** Connect to web server */ ErrorGateWayCode = gatewayManager.init_connection(); if (ErrorGateWayCode != 0 ) { std::cerr << "[ERROR]" << strerror(ErrorGateWayCode) << std::endl; return EXIT_FAILURE; } else { std::cout << "[INFO] connected to server " << std::endl; } /** @TODO : add here the read from UART and write on socket */ gatewayManager.write_server((const uint8_t*)"\nHey salut\n\n"); return 0; }
// // VulkanConvolution.hpp // MNN // // Created by MNN on 2019/01/31. // Copyright © 2018, Alibaba Group Holding Limited // #ifndef VulkanConvolution_hpp #define VulkanConvolution_hpp #include "VulkanBasicExecution.hpp" #include "core/ConvolutionCommon.hpp" namespace MNN { class VulkanConvolutionCommon : public VulkanBasicExecution { public: VulkanConvolutionCommon(const Op* op, Backend* bn); virtual ~VulkanConvolutionCommon(); virtual ErrorCode onEncode(const std::vector<Tensor*>& inputs, const std::vector<Tensor*>& outputs, const VulkanCommandPool::Buffer* cmdBuffer) override; struct ConvolutionParameter { ivec2 pad; ivec2 kernelSize; ivec2 stride; ivec2 dilate; ivec4 inputSize; ivec4 outputSize; int batch; int group; }; static void writeParameter(ConvolutionParameter* dest, const Convolution2DCommon* common, const Tensor* input, const Tensor* output); static std::string getPostTreatMacro(const Convolution2DCommon* common); class BufferToImageCopy { public: BufferToImageCopy(const VulkanBackend* bn) { mBackend = bn; std::vector<VkDescriptorType> types{VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER}; mPipeline = mBackend->getPipeline("glsl_buffer2Image2D_comp", types); mSets.reset(mPipeline->createSet()); mConstBuffer = std::make_shared<VulkanBuffer>(bn->getMemoryPool(), true, 2 * sizeof(int), nullptr, VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT); } void encode(const VulkanImage* image, VkBuffer buffer, size_t bufferSize, const VulkanCommandPool::Buffer* cmdBuffer) { int localX = 16; int localY = 16; int localZ = 1; int* dim = (int*)mConstBuffer->map(); dim[0] = image->width(); dim[1] = image->height(); mConstBuffer->unmap(); cmdBuffer->barrierImageIfNeeded(image, VK_IMAGE_LAYOUT_GENERAL); mSets->writeImage(image->view(), mBackend->getCommonSampler()->get(), VK_IMAGE_LAYOUT_GENERAL, 0); mSets->writeBuffer(buffer, 1, bufferSize); mSets->writeBuffer(mConstBuffer->buffer(), 2, mConstBuffer->size()); mPipeline->bind(cmdBuffer->get(), mSets->get()); cmdBuffer->barrierSource(buffer, 0, bufferSize); vkCmdDispatch(cmdBuffer->get(), UP_DIV(image->width(), localX), UP_DIV(image->height(), localY), UP_DIV(image->depth(), localZ)); } private: const VulkanBackend* mBackend; const VulkanPipeline* mPipeline; std::shared_ptr<VulkanPipeline::DescriptorSet> mSets; std::shared_ptr<VulkanBuffer> mConstBuffer; }; static int gImage2ColLocal; protected: virtual ErrorCode onEncodeConvolution(const Convolution2DCommon* common, const std::vector<Tensor*>& inputs, const std::vector<Tensor*>& outputs, const VulkanCommandPool::Buffer* cmdBuffer, const VulkanBuffer* constConvBuffer, const VulkanImage* biasBuffer) = 0; private: std::shared_ptr<VulkanImage> mBias; const Convolution2DCommon* mCommon; std::shared_ptr<VulkanBuffer> mConvCons; }; class VulkanConvolutionDepthwise : public VulkanConvolutionCommon { public: VulkanConvolutionDepthwise(const float* weightData, size_t weightSize, const Op* op, Backend* bn); virtual ~VulkanConvolutionDepthwise(); virtual ErrorCode onEncodeConvolution(const Convolution2DCommon* common, const std::vector<Tensor*>& inputs, const std::vector<Tensor*>& outputs, const VulkanCommandPool::Buffer* cmdBuffer, const VulkanBuffer* constConvBuffer, const VulkanImage* biasBuffer) override; private: std::shared_ptr<VulkanImage> mKernel; const VulkanPipeline* mConvPipeline; std::shared_ptr<VulkanPipeline::DescriptorSet> mConvSet; const VulkanSampler* mSampler; int mLocalX = 0; int mLocalY = 0; }; } // namespace MNN #endif /* VulkanConvolution_hpp */
/////////////////////////////////////////////////////////////////////////////////////////////////// /// /// Ivy Engine /// /// Copyright 2010-2011, Brandon Light /// All rights reserved. /// /////////////////////////////////////////////////////////////////////////////////////////////////// #include "IvyInput.h" #include "IvyUtils.h" #ifdef _WIN32 #include <XInput.h> #endif // _WIN32 #include <iostream> #ifndef _WIN32 #define STUB_INPUT 1 #endif // _WIN32 /////////////////////////////////////////////////////////////////////////////////////////////////// /// IvyGetGamepadState /// /// @brief /// /// @return /// N/A /////////////////////////////////////////////////////////////////////////////////////////////////// VOID IvyGetGamepadStates( IvyGamepadState* pGamepadStates, UINT numGamepads) { static const UINT MaxGamepadsSupported = 4; static const SHORT AnalogDeadZone = 6000; static const FLOAT MaxSignedShort = (FLOAT) 0x7FFF; UINT gamepadQueryCount = IVY_MIN(numGamepads, MaxGamepadsSupported); #ifndef STUB_INPUT for (DWORD i=0; i < gamepadQueryCount; i++ ) { XINPUT_STATE state; memset(&state, 0, sizeof(XINPUT_STATE)); //ZeroMemory( &state, sizeof(XINPUT_STATE) ); // Simply get the state of the controller from XInput. DWORD dwResult = XInputGetState( i, &state ); memset(&pGamepadStates[i], 0, sizeof(IvyGamepadState)); if( dwResult == ERROR_SUCCESS ) { // Controller is connected pGamepadStates[i].ButtonPressed[IvyGamepadButtons::ButtonA] = (state.Gamepad.wButtons & XINPUT_GAMEPAD_A); pGamepadStates[i].ButtonPressed[IvyGamepadButtons::ButtonB] = (state.Gamepad.wButtons & XINPUT_GAMEPAD_B); pGamepadStates[i].ButtonPressed[IvyGamepadButtons::ButtonX] = (state.Gamepad.wButtons & XINPUT_GAMEPAD_X); pGamepadStates[i].ButtonPressed[IvyGamepadButtons::ButtonY] = (state.Gamepad.wButtons & XINPUT_GAMEPAD_Y); if (!(-AnalogDeadZone < state.Gamepad.sThumbLX && state.Gamepad.sThumbLX < AnalogDeadZone)) { pGamepadStates[i].ThumbLX = state.Gamepad.sThumbLX / MaxSignedShort; } if (!(-AnalogDeadZone < state.Gamepad.sThumbLY && state.Gamepad.sThumbLY < AnalogDeadZone)) { pGamepadStates[i].ThumbLY = state.Gamepad.sThumbLY / MaxSignedShort; } if (!(-AnalogDeadZone < state.Gamepad.sThumbRX && state.Gamepad.sThumbRX < AnalogDeadZone)) { pGamepadStates[i].ThumbRX = state.Gamepad.sThumbRX / MaxSignedShort; } if (!(-AnalogDeadZone < state.Gamepad.sThumbRY && state.Gamepad.sThumbRY < AnalogDeadZone)) { pGamepadStates[i].ThumbRY = state.Gamepad.sThumbRY / MaxSignedShort; } } else { // no controller connected ///@todo Signal Error } } #endif // STUB_INPUT }
/****************************************************************************** @File OGLES3ColourGrading.cpp @Title Colour grading @Version @Copyright Copyright (c) Imagination Technologies Limited. @Platform Independent @Description Demonstrates how to colour grade your render. ******************************************************************************/ #include "PVRShell.h" #include "OGLES3Tools.h" /****************************************************************************** Constants ******************************************************************************/ const char* const c_pszMaskTexture = "MaskTexture.pvr"; const char* const c_pszBackgroundTexture = "Background.pvr"; // Our colour lookup tables const char* const c_pszLUTs[] = { "identity.pvr", "bw.pvr", "cooler.pvr", "warmer.pvr", "sepia.pvr", "inverted.pvr", "highcontrast.pvr", "bluewhitegradient.pvr" }; // Shader source const char* const c_szFragShaderSrcFile = "FragShader.fsh"; const char* const c_szVertShaderSrcFile = "VertShader.vsh"; const char* const c_szSceneFragShaderSrcFile = "SceneFragShader.fsh"; const char* const c_szSceneVertShaderSrcFile = "SceneVertShader.vsh"; const char* const c_szBackgroundFragShaderSrcFile = "BackgroundFragShader.fsh"; // POD scene files const char c_szSceneFile[] = "Mask.pod"; // Camera constants. Used for making the projection matrix const float CAM_FOV = PVRT_PI / 6; const float CAM_NEAR = 4.0f; const float CAM_FAR = 5000.0f; // Index to bind the attributes to vertex shaders const int VERTEX_ARRAY = 0; const int TEXCOORD_ARRAY = 1; const int NORMAL_ARRAY = 2; // Look up table enumeration enum ELUTs { eIdentity, eBW, eCooler, eWarmer, eSepia, eInverted, eHighContrast, eBlueWhiteGradient, eLast, // The range to cycle through eA = eBW, eB = eBlueWhiteGradient }; const char* const c_pszLUTNames[] = { "Identity", "Black and white", "Cooler", "Warmer", "Sepia", "Inverted", "High Contrast", "Blue White Gradient" }; /*!**************************************************************************** Class implementing the PVRShell functions. ******************************************************************************/ class OGLES3ColourGrading : public PVRShell { // Print3D object CPVRTPrint3D m_Print3D; // Texture handle GLuint m_uiMaskTexture; GLuint m_uiBackgroundTexture; GLuint m_uiLUTs[eLast]; int m_iCurrentLUT; // VBO handle GLuint m_ui32FullScreenRectVBO; // Stride for vertex data unsigned int m_ui32VertexStride; // 3D Model CPVRTModelPOD m_Mask; GLuint* m_puiMaskVBO; GLuint* m_puiMaskIBO; GLuint m_ui32BackgroundVBO; // Projection and view matrices PVRTMat4 m_mViewProjection; // Shaders GLuint m_uiPostVertShader; GLuint m_uiPostFragShader; struct { GLuint uiId; } m_PostShaderProgram; GLuint m_uiBackgroundFragShader; struct { GLuint uiId; } m_BackgroundShaderProgram; GLuint m_uiSceneVertShader; GLuint m_uiSceneFragShader; struct { GLuint uiId; GLuint uiMVPMatrixLoc; GLuint uiLightDirLoc; GLuint uiMaterialBiasLoc; GLuint uiMaterialScaleLoc; } m_SceneShaderProgram; // Render contexts, etc GLint m_i32OriginalFbo; // Texture IDs used by the app GLuint m_uiTextureToRenderTo; // Handle for our FBO and the depth buffer that it requires GLuint m_uiFBO; // Handle for our multi-sampled FBO and the depth buffer that it requires GLuint m_uiFBOMultisampled; GLuint m_uiDepthBufferMultisampled; GLuint m_uiColourBufferMultisampled; // Start time unsigned long m_ulStartTime; public: // PVRShell functions virtual bool InitApplication(); virtual bool InitView(); virtual bool ReleaseView(); virtual bool QuitApplication(); virtual bool RenderScene(); private: bool LoadShaders(CPVRTString& ErrorStr); bool CreateFBO(); void LoadVbos(const bool bRotated); void DrawMesh(const int i32NodeIndex); }; /*!**************************************************************************** @Function InitApplication @Return bool true if no error occurred @Description Code in InitApplication() will be called by PVRShell once per run, before the rendering context is created. Used to initialize variables that are not dependent on it (e.g. external modules, loading meshes, etc.) If the rendering context is lost, InitApplication() will not be called again. ******************************************************************************/ bool OGLES3ColourGrading::InitApplication() { // Get and set the read path for content files CPVRTResourceFile::SetReadPath((char*)PVRShellGet(prefReadPath)); // Get and set the load/release functions for loading external files. // In the majority of cases the PVRShell will return NULL function pointers implying that // nothing special is required to load external files. CPVRTResourceFile::SetLoadReleaseFunctions(PVRShellGet(prefLoadFileFunc), PVRShellGet(prefReleaseFileFunc)); // Load the scene if(m_Mask.ReadFromFile(c_szSceneFile) != PVR_SUCCESS) { PVRShellSet(prefExitMessage, "ERROR: Couldn't load the .pod file\n"); return false; } // Initialise some variables m_puiMaskVBO = m_puiMaskIBO = 0; m_iCurrentLUT = eA; return true; } /*!**************************************************************************** @Function QuitApplication @Return bool true if no error occurred @Description Code in QuitApplication() will be called by PVRShell once per run, just before exiting the program. If the rendering context is lost, QuitApplication() will not be called. ******************************************************************************/ bool OGLES3ColourGrading::QuitApplication() { // Free the memory allocated for the scene m_Mask.Destroy(); delete[] m_puiMaskVBO; m_puiMaskVBO = 0; delete[] m_puiMaskIBO; m_puiMaskIBO = 0; return true; } /*!**************************************************************************** @Function LoadEffects @Output ErrorStr A description of an error, if one occurs. @Return bool true if no error occurred @Description Loads and parses the bundled PFX and generates the various effect objects. ******************************************************************************/ bool OGLES3ColourGrading::LoadShaders(CPVRTString& ErrorStr) { // Load and compile the shaders from files. if(PVRTShaderLoadFromFile(NULL, c_szVertShaderSrcFile, GL_VERTEX_SHADER, GL_SGX_BINARY_IMG, &m_uiPostVertShader, &ErrorStr) != PVR_SUCCESS) { return false; } if(PVRTShaderLoadFromFile(NULL, c_szFragShaderSrcFile, GL_FRAGMENT_SHADER, GL_SGX_BINARY_IMG, &m_uiPostFragShader, &ErrorStr) != PVR_SUCCESS) { return false; } // Setup and link the shader program const char* aszAttribs[] = { "inVertex", "inTexCoord" }; if(PVRTCreateProgram(&m_PostShaderProgram.uiId, m_uiPostVertShader, m_uiPostFragShader, aszAttribs, 2, &ErrorStr) != PVR_SUCCESS) { return false; } // Set the sampler variables to their respective texture unit glUniform1i(glGetUniformLocation(m_PostShaderProgram.uiId, "sTexture"), 0); glUniform1i(glGetUniformLocation(m_PostShaderProgram.uiId, "sColourLUT"), 1); // Background shader if(PVRTShaderLoadFromFile(NULL, c_szBackgroundFragShaderSrcFile, GL_FRAGMENT_SHADER, GL_SGX_BINARY_IMG, &m_uiBackgroundFragShader, &ErrorStr) != PVR_SUCCESS) { return false; } // Set up and link the shader program re-using the vertex shader from the main shader program const char* aszBackgroundAttribs[] = { "inVertex", "inTexCoord" }; if(PVRTCreateProgram(&m_BackgroundShaderProgram.uiId, m_uiPostVertShader, m_uiBackgroundFragShader, aszBackgroundAttribs, 2, &ErrorStr) != PVR_SUCCESS) { return false; } // Set the sampler2D variable to the first texture unit glUniform1i(glGetUniformLocation(m_BackgroundShaderProgram.uiId, "sTexture"), 0); // Scene shaders - Used for rendering the mask if(PVRTShaderLoadFromFile(NULL, c_szSceneVertShaderSrcFile, GL_VERTEX_SHADER, GL_SGX_BINARY_IMG, &m_uiSceneVertShader, &ErrorStr) != PVR_SUCCESS) { return false; } if(PVRTShaderLoadFromFile(NULL, c_szSceneFragShaderSrcFile, GL_FRAGMENT_SHADER, GL_SGX_BINARY_IMG, &m_uiSceneFragShader, &ErrorStr) != PVR_SUCCESS) { return false; } // Setup and link the shader program const char* aszSceneAttribs[] = { "inVertex", "inTexCoord", "inNormal" }; if (PVRTCreateProgram(&m_SceneShaderProgram.uiId, m_uiSceneVertShader, m_uiSceneFragShader, aszSceneAttribs, 3, &ErrorStr) != PVR_SUCCESS) { return false; } // Set the sampler2D variable to the first texture unit glUniform1i(glGetUniformLocation(m_SceneShaderProgram.uiId, "sTexture"), 0); // Store the location of uniforms for later use m_SceneShaderProgram.uiMVPMatrixLoc = glGetUniformLocation(m_SceneShaderProgram.uiId, "MVPMatrix"); m_SceneShaderProgram.uiLightDirLoc = glGetUniformLocation(m_SceneShaderProgram.uiId, "LightDirection"); m_SceneShaderProgram.uiMaterialBiasLoc = glGetUniformLocation(m_SceneShaderProgram.uiId, "MaterialBias"); m_SceneShaderProgram.uiMaterialScaleLoc = glGetUniformLocation(m_SceneShaderProgram.uiId, "MaterialScale"); // Set default shader material uniforms float fSpecularConcentration = 0.6f; // a value from 0 to 1 (wider, concentrated) float fSpecularIntensity = 0.3f; // a value from 0 to 1 // Specular bias glUniform1f(m_SceneShaderProgram.uiMaterialBiasLoc, fSpecularConcentration); // Specular intensity scale glUniform1f(m_SceneShaderProgram.uiMaterialScaleLoc, fSpecularIntensity / (1.0f - fSpecularConcentration)); return true; } /*!**************************************************************************** @Function LoadVbos @Description Loads the mesh data required for this training course into vertex buffer objects ******************************************************************************/ void OGLES3ColourGrading::LoadVbos(const bool bRotated) { if(!m_puiMaskVBO) m_puiMaskVBO = new GLuint[m_Mask.nNumMesh]; if(!m_puiMaskIBO) m_puiMaskIBO = new GLuint[m_Mask.nNumMesh]; /* Load vertex data of all meshes in the scene into VBOs The meshes have been exported with the "Interleave Vectors" option, so all data is interleaved in the buffer at pMesh->pInterleaved. Interleaving data improves the memory access pattern and cache efficiency, thus it can be read faster by the hardware. */ glGenBuffers(m_Mask.nNumMesh, m_puiMaskVBO); for(unsigned int i = 0; i < m_Mask.nNumMesh; ++i) { // Load vertex data into buffer object SPODMesh& Mesh = m_Mask.pMesh[i]; unsigned int uiSize = Mesh.nNumVertex * Mesh.sVertex.nStride; glBindBuffer(GL_ARRAY_BUFFER, m_puiMaskVBO[i]); glBufferData(GL_ARRAY_BUFFER, uiSize, Mesh.pInterleaved, GL_STATIC_DRAW); // Load index data into buffer object if available m_puiMaskIBO[i] = 0; if (Mesh.sFaces.pData) { glGenBuffers(1, &m_puiMaskIBO[i]); uiSize = PVRTModelPODCountIndices(Mesh) * sizeof(GLshort); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_puiMaskIBO[i]); glBufferData(GL_ELEMENT_ARRAY_BUFFER, uiSize, Mesh.sFaces.pData, GL_STATIC_DRAW); } } // Create VBO for the fullscreen rect that we'll be rendering our FBO to // Interleaved vertex data GLfloat afVertices[] = { // Left quad -1.0f, 1.0f, 0.0f, 1.0f, // Pos 0.0f, 1.0f, // UVs -1.0f, -1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.5f, 1.0f, 0.0f, -1.0f, 0.0f, 1.0f, 0.5f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f, 0.0f, 1.0f, 1.0f, 0.0f, }; if(bRotated) // If we're rotated then pre-process the fullscreen rect's geometry to compensate { for(unsigned int i = 0; i < 6; ++i) { float fTmp = afVertices[i * 6 + 1]; afVertices[i * 6 + 1] = afVertices[i * 6]; afVertices[i * 6] = fTmp; fTmp = afVertices[i * 6 + 5]; afVertices[i * 6 + 5] = afVertices[i * 6 + 4]; afVertices[i * 6 + 4] = fTmp; } } glGenBuffers(1, &m_ui32FullScreenRectVBO); m_ui32VertexStride = 6 * sizeof(GLfloat); // 4 floats for the pos, 2 for the UVs // Bind the VBO glBindBuffer(GL_ARRAY_BUFFER, m_ui32FullScreenRectVBO); // Set the buffer's data glBufferData(GL_ARRAY_BUFFER, 6 * m_ui32VertexStride, afVertices, GL_STATIC_DRAW); // Create the VBO for the background GLfloat afBackgroundVertices[] = { // Left quad -1.0f, 1.0f, 0.0f, 1.0f, // Pos 0.0f, 1.0f, // UVs -1.0f, -1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f, 0.0f, 1.0f, 1.0f, 0.0f, }; if(bRotated) // If we're rotated then pre-process the background geometry { for(unsigned int i = 0; i < 4; ++i) { float fTmp = afBackgroundVertices[i * 6 + 1]; afBackgroundVertices[i * 6 + 1] = -afBackgroundVertices[i * 6]; afBackgroundVertices[i * 6] = -fTmp; } } glGenBuffers(1, &m_ui32BackgroundVBO); // Bind the VBO glBindBuffer(GL_ARRAY_BUFFER, m_ui32BackgroundVBO); // Set the buffer's data glBufferData(GL_ARRAY_BUFFER, 4 * m_ui32VertexStride, afBackgroundVertices, GL_STATIC_DRAW); // Unbind our buffers glBindBuffer(GL_ARRAY_BUFFER, 0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); } bool OGLES3ColourGrading::CreateFBO() { GLenum drawBuffers[] = { GL_COLOR_ATTACHMENT0 }; // Query the max amount of samples that are supported, we are going to use the max GLint samples; glGetIntegerv(GL_MAX_SAMPLES, &samples); // Get the currently bound frame buffer object. On most platforms this just gives 0. glGetIntegerv(GL_FRAMEBUFFER_BINDING, &m_i32OriginalFbo); // Create a texture for rendering to glGenTextures(1, &m_uiTextureToRenderTo); glBindTexture(GL_TEXTURE_2D, m_uiTextureToRenderTo); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB8, PVRShellGet(prefWidth), PVRShellGet(prefHeight), 0, GL_RGB, GL_UNSIGNED_BYTE, 0); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); // Create the object that will allow us to render to the aforementioned texture glGenFramebuffers(1, &m_uiFBO); glBindFramebuffer(GL_FRAMEBUFFER, m_uiFBO); glDrawBuffers(1, drawBuffers); glReadBuffer(GL_COLOR_ATTACHMENT0); // Attach the texture to the FBO glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, m_uiTextureToRenderTo, 0); // Check that our FBO creation was successful GLuint uStatus = glCheckFramebufferStatus(GL_FRAMEBUFFER); if(uStatus != GL_FRAMEBUFFER_COMPLETE) { PVRShellSet(prefExitMessage, "ERROR: Failed to initialise FBO"); return false; } // Create and initialize the multi-sampled FBO. // Create the object that will allow us to render to the aforementioned texture glGenFramebuffers(1, &m_uiFBOMultisampled); glBindFramebuffer(GL_FRAMEBUFFER, m_uiFBOMultisampled); glDrawBuffers(1, drawBuffers); glReadBuffer(GL_COLOR_ATTACHMENT0); // Generate and bind a render buffer which will become a multisampled depth buffer shared between our two FBOs glGenRenderbuffers(1, &m_uiDepthBufferMultisampled); glBindRenderbuffer(GL_RENDERBUFFER, m_uiDepthBufferMultisampled); glRenderbufferStorageMultisample(GL_RENDERBUFFER, samples, GL_DEPTH_COMPONENT24, PVRShellGet(prefWidth), PVRShellGet(prefHeight)); glGenRenderbuffers(1, &m_uiColourBufferMultisampled); glBindRenderbuffer(GL_RENDERBUFFER, m_uiColourBufferMultisampled); glRenderbufferStorageMultisample(GL_RENDERBUFFER, samples, GL_RGB8, PVRShellGet(prefWidth), PVRShellGet(prefHeight)); glBindRenderbuffer(GL_RENDERBUFFER, 0); // Attach the multisampled depth buffer we created earlier to our FBO. glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, m_uiDepthBufferMultisampled); // Attach the multisampled colour renderbuffer to the FBO glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, m_uiColourBufferMultisampled); // Check that our FBO creation was successful uStatus = glCheckFramebufferStatus(GL_FRAMEBUFFER); if(uStatus != GL_FRAMEBUFFER_COMPLETE) { PVRShellSet(prefExitMessage, "ERROR: Failed to initialise multisampled FBO"); return false; } // Unbind the frame buffer object so rendering returns back to the backbuffer glBindFramebuffer(GL_FRAMEBUFFER, m_i32OriginalFbo); return true; } /*!**************************************************************************** @Function InitView @Return bool true if no error occurred @Description Code in InitView() will be called by PVRShell upon initialization or after a change in the rendering context. Used to initialize variables that are dependent on the rendering context (e.g. textures, vertex buffers, etc.) ******************************************************************************/ bool OGLES3ColourGrading::InitView() { // Initialize the textures used by Print3D. bool bRotate = PVRShellGet(prefIsRotated) && PVRShellGet(prefFullScreen); if(m_Print3D.SetTextures(0, PVRShellGet(prefWidth), PVRShellGet(prefHeight), bRotate) != PVR_SUCCESS) { PVRShellSet(prefExitMessage, "ERROR: Cannot initialise Print3D\n"); return false; } // Create the texture if(PVRTTextureLoadFromPVR(c_pszMaskTexture, &m_uiMaskTexture) != PVR_SUCCESS) { PVRShellSet(prefExitMessage, "ERROR: Failed to load mask texture\n"); return false; } if(PVRTTextureLoadFromPVR(c_pszBackgroundTexture, &m_uiBackgroundTexture) != PVR_SUCCESS) { PVRShellSet(prefExitMessage, "ERROR: Failed to load background texture\n"); return false; } // Load our 3D texture look up tables for(unsigned int i = 0; i < eLast; ++i) { if(PVRTTextureLoadFromPVR(c_pszLUTs[i], &m_uiLUTs[i]) != PVR_SUCCESS) { PVRShellSet(prefExitMessage, "ERROR: Failed to load a 3D texture\n"); return false; } glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); } // Load the effects CPVRTString ErrorStr; if(!LoadShaders(ErrorStr)) { PVRShellSet(prefExitMessage, ErrorStr.c_str()); return false; } // Create FBOs if(!CreateFBO()) { PVRShellSet(prefExitMessage, "Failed to create FBO"); return false; } // Initialise VBO data LoadVbos(bRotate); // Calculate the projection and view matrices float fAspect = PVRShellGet(prefWidth) / (float)PVRShellGet(prefHeight); m_mViewProjection = PVRTMat4::PerspectiveFovRH(CAM_FOV, fAspect, CAM_NEAR, CAM_FAR, PVRTMat4::OGL, bRotate); m_mViewProjection *= PVRTMat4::LookAtRH(PVRTVec3(0.f, 0.f, 150.f), PVRTVec3(0.f), PVRTVec3(0.f, 1.f, 0.f)); // Enable backface culling and depth test glEnable(GL_CULL_FACE); glEnable(GL_DEPTH_TEST); // Set the clear colour glClearColor(1.0f, 0.0f, 0.0f, 1.0f); // Store initial time m_ulStartTime = PVRShellGetTime(); return true; } /*!**************************************************************************** @Function ReleaseView @Return bool true if no error occurred @Description Code in ReleaseView() will be called by PVRShell when the application quits or before a change in the rendering context. ******************************************************************************/ bool OGLES3ColourGrading::ReleaseView() { // Frees the texture glDeleteTextures(1, &m_uiMaskTexture); glDeleteTextures(1, &m_uiBackgroundTexture); glDeleteTextures(eLast, m_uiLUTs); glDeleteTextures(1, &m_uiTextureToRenderTo); // Release Vertex buffer object. glDeleteBuffers(1, &m_ui32FullScreenRectVBO); glDeleteBuffers(1, &m_ui32BackgroundVBO); // Release effects glDeleteShader(m_uiPostVertShader); glDeleteShader(m_uiPostFragShader); glDeleteShader(m_uiBackgroundFragShader); glDeleteShader(m_uiSceneVertShader); glDeleteShader(m_uiSceneFragShader); glDeleteProgram(m_PostShaderProgram.uiId); glDeleteProgram(m_BackgroundShaderProgram.uiId); glDeleteProgram(m_SceneShaderProgram.uiId); // Tidy up the FBOs and renderbuffers // Delete frame buffer objects glDeleteFramebuffers(1, &m_uiFBO); glDeleteFramebuffers(1, &m_uiFBOMultisampled); // Delete our depth buffer glDeleteRenderbuffers(1, &m_uiDepthBufferMultisampled); glDeleteRenderbuffers(1, &m_uiColourBufferMultisampled); // Delete buffer objects glDeleteBuffers(m_Mask.nNumMesh, m_puiMaskVBO); glDeleteBuffers(m_Mask.nNumMesh, m_puiMaskIBO); // Release Print3D Textures m_Print3D.ReleaseTextures(); return true; } /*!**************************************************************************** @Function RenderScene @Return bool true if no error occurred @Description Main rendering loop function of the program. The shell will call this function every frame. eglSwapBuffers() will be performed by PVRShell automatically. PVRShell will also manage important OS events. Will also manage relevant OS events. The user has access to these events through an abstraction layer provided by PVRShell. ******************************************************************************/ bool OGLES3ColourGrading::RenderScene() { // Clears the colour buffer glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); unsigned long ulTime = PVRShellGetTime() - m_ulStartTime; // Process input to switch between tone mapping operators if(PVRShellIsKeyPressed(PVRShellKeyNameRIGHT)) { ++m_iCurrentLUT; if(m_iCurrentLUT > eB) m_iCurrentLUT = eA; } else if(PVRShellIsKeyPressed(PVRShellKeyNameLEFT)) { --m_iCurrentLUT; if(m_iCurrentLUT < eA) m_iCurrentLUT = eB; } // Render to our texture { // Bind our FBO glBindFramebuffer(GL_FRAMEBUFFER, m_uiFBOMultisampled); // Clear the colour and depth buffer of our FBO surface glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glDisable(GL_CULL_FACE); glDisable(GL_DEPTH_TEST); // Bind the VBO glBindBuffer(GL_ARRAY_BUFFER, m_ui32BackgroundVBO); // Use shader program glUseProgram(m_BackgroundShaderProgram.uiId); // Enable the vertex attribute arrays glEnableVertexAttribArray(VERTEX_ARRAY); glEnableVertexAttribArray(TEXCOORD_ARRAY); // Set the vertex attribute offsets glVertexAttribPointer(VERTEX_ARRAY, 4, GL_FLOAT, GL_FALSE, m_ui32VertexStride, 0); glVertexAttribPointer(TEXCOORD_ARRAY, 2, GL_FLOAT, GL_FALSE, m_ui32VertexStride, (void*) (4 * sizeof(GLfloat))); // Bind texture glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, m_uiBackgroundTexture); // Draw a screen-aligned quad. // Draws a non-indexed triangle array glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); // Safely disable the vertex attribute arrays glDisableVertexAttribArray(VERTEX_ARRAY); glDisableVertexAttribArray(TEXCOORD_ARRAY); glEnable(GL_CULL_FACE); glEnable(GL_DEPTH_TEST); // Use shader program glUseProgram(m_SceneShaderProgram.uiId); // Rotate the model matrix PVRTMat4 mModel = PVRTMat4::RotationY(ulTime * 0.0015f); // Calculate model view projection matrix PVRTMat4 mMVP = m_mViewProjection * mModel; // Feeds Projection Model View matrix to the shaders glUniformMatrix4fv(m_SceneShaderProgram.uiMVPMatrixLoc, 1, GL_FALSE, mMVP.ptr()); PVRTVec3 vMsLightDir = (PVRTVec3(1, 1, 1) * PVRTMat3(mModel)).normalized(); glUniform3fv(m_SceneShaderProgram.uiLightDirLoc, 1, vMsLightDir.ptr()); glBindTexture(GL_TEXTURE_2D, m_uiMaskTexture); // Now that the uniforms are set, call another function to actually draw the mesh. DrawMesh(0); // Unbind the VBO glBindBuffer(GL_ARRAY_BUFFER, 0); // Give the drivers a hint that we don't want the depth and stencil information stored for future use. const GLenum attachments[] = { GL_DEPTH_ATTACHMENT, GL_STENCIL_ATTACHMENT }; glInvalidateFramebuffer(GL_FRAMEBUFFER, 2, attachments); // Blit and resolve the multisampled render buffer to the non-multisampled FBO glBindFramebuffer(GL_READ_FRAMEBUFFER, m_uiFBOMultisampled); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, m_uiFBO); glBlitFramebuffer(0, 0, PVRShellGet(prefWidth), PVRShellGet(prefHeight), 0, 0, PVRShellGet(prefWidth), PVRShellGet(prefHeight), GL_COLOR_BUFFER_BIT, GL_NEAREST); // We are done with rendering to our FBO so switch back to the back buffer. glBindFramebuffer(GL_FRAMEBUFFER, m_i32OriginalFbo); } glDisable(GL_CULL_FACE); glDisable(GL_DEPTH_TEST); // Use shader program glUseProgram(m_PostShaderProgram.uiId); // Bind the VBO glBindBuffer(GL_ARRAY_BUFFER, m_ui32FullScreenRectVBO); // Enable the vertex attribute arrays glEnableVertexAttribArray(VERTEX_ARRAY); glEnableVertexAttribArray(TEXCOORD_ARRAY); // Set the vertex attribute offsets glVertexAttribPointer(VERTEX_ARRAY, 4, GL_FLOAT, GL_FALSE, m_ui32VertexStride, 0); glVertexAttribPointer(TEXCOORD_ARRAY, 2, GL_FLOAT, GL_FALSE, m_ui32VertexStride, (void*) (4 * sizeof(GLfloat))); // Bind texture glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, m_uiTextureToRenderTo); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_3D, m_uiLUTs[m_iCurrentLUT]); // Draw a screen-aligned quad. // Draw the left-hand side that shows the scene with the colour grading applied glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); // Draw the right-hande side showing the scene how it looks without glBindTexture(GL_TEXTURE_3D, m_uiLUTs[eIdentity]); glDrawArrays(GL_TRIANGLE_STRIP, 2, 4); // Safely disable the vertex attribute arrays glDisableVertexAttribArray(VERTEX_ARRAY); glDisableVertexAttribArray(TEXCOORD_ARRAY); // Unbind the VBO glBindBuffer(GL_ARRAY_BUFFER, 0); // Render title m_Print3D.DisplayDefaultTitle("Colour grading using 3D textures", c_pszLUTNames[m_iCurrentLUT], ePVRTPrint3DSDKLogo); m_Print3D.Flush(); return true; } /*!**************************************************************************** @Function DrawMesh @Input i32NodeIndex Node index of the mesh to draw @Description Draws a SPODMesh after the model view matrix has been set and the material prepared. ******************************************************************************/ void OGLES3ColourGrading::DrawMesh(const int i32NodeIndex) { int i32MeshIndex = m_Mask.pNode[i32NodeIndex].nIdx; SPODMesh* pMesh = &m_Mask.pMesh[i32MeshIndex]; // bind the VBO for the mesh glBindBuffer(GL_ARRAY_BUFFER, m_puiMaskVBO[i32MeshIndex]); // bind the index buffer, won't hurt if the handle is 0 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_puiMaskIBO[i32MeshIndex]); // Enable the vertex attribute arrays glEnableVertexAttribArray(VERTEX_ARRAY); glEnableVertexAttribArray(NORMAL_ARRAY); glEnableVertexAttribArray(TEXCOORD_ARRAY); // Set the vertex attribute offsets glVertexAttribPointer(VERTEX_ARRAY, 3, GL_FLOAT, GL_FALSE, pMesh->sVertex.nStride, pMesh->sVertex.pData); glVertexAttribPointer(NORMAL_ARRAY, 3, GL_FLOAT, GL_FALSE, pMesh->sNormals.nStride, pMesh->sNormals.pData); glVertexAttribPointer(TEXCOORD_ARRAY, 2, GL_FLOAT, GL_FALSE, pMesh->psUVW[0].nStride, pMesh->psUVW[0].pData); // Indexed Triangle list glDrawElements(GL_TRIANGLES, pMesh->nNumFaces*3, GL_UNSIGNED_SHORT, 0); // Safely disable the vertex attribute arrays glDisableVertexAttribArray(VERTEX_ARRAY); glDisableVertexAttribArray(NORMAL_ARRAY); glDisableVertexAttribArray(TEXCOORD_ARRAY); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); } /*!**************************************************************************** @Function NewDemo @Return PVRShell* The demo supplied by the user @Description This function must be implemented by the user of the shell. The user should return its PVRShell object defining the behaviour of the application. ******************************************************************************/ PVRShell* NewDemo() { return new OGLES3ColourGrading(); } /****************************************************************************** End of file (OGLES3ColourGrading.cpp) ******************************************************************************/
/* 14:扫雷游戏地雷数计算 查看 提交 统计 提问 总时间限制: 1000ms 内存限制: 65536kB 描述 扫雷游戏是一款十分经典的单机小游戏。它的精髓在于,通过已翻开格子所提示的周围格地雷数,来判断未翻开格子里是否是地雷。 现在给出n行m列的雷区中的地雷分布,要求计算出每个非地雷格的周围格地雷数。 注:每个格子周围格有八个:上、下、左、右、左上、右上、左下、右下。 输入 第一行包含两个整数n和m,分别表示雷区的行数和列数。1 <= n <= 100, 1 <= m <= 100。 接下来n行,每行m个字符,‘*’表示相应格子中是地雷,‘?’表示相应格子中无地雷。字符之间无任何分隔符。 输出 n行,每行m个字符,描述整个雷区。若相应格中是地雷,则用‘*’表示,否则用相应的周围格地雷数表示。字符之间无任何分隔符。 样例输入 3 3 *?? ??? ?*? 样例输出 *10 221 1*1 */ #include<iostream> using namespace std; string a[1001]; int n,m; int count(int x,int y) { int ct=0; for(int i=x-1;i<=x+1;++i) for(int j=y-1;j<=y+1;++j) { if (i>=0 && i<n && j>=0 && j<m) if (a[i][j]=='*') ct++; } return ct; } int main() { cin>>n>>m; for(int i=0;i<n;++i) cin>>a[i]; for(int i=0;i<n;++i) { for(int j=0;j<m;++j) if(a[i][j]=='*') cout<<"*"; else cout<<count(i,j); cout<<endl; } return 0; }
#include "LightInspector.hpp" #include "imgui/imgui.h" namespace CpuRasterizer { void LightInspector::on_gui(DirectionalLight& light) { if (ImGui::CollapsingHeader("Light", ImGuiTreeNodeFlags_DefaultOpen)) { if (ImGui::InputFloat("distance", &distance)) { light.distance = distance; } else { distance = light.distance; } if (ImGui::InputFloat("near", &n)) { light.frustum_param.ortho_param.near = n; light.update_projection(); } else { n = light.frustum_param.ortho_param.near; } if (ImGui::InputFloat("far", &f)) { light.frustum_param.ortho_param. far = f; light.update_projection(); } else { f = light.frustum_param.ortho_param.far; } if (ImGui::InputFloat("light", &l)) { light.frustum_param.ortho_param.left = l; light.update_projection(); } else { l = light.frustum_param.ortho_param.left; } if (ImGui::InputFloat("right", &r)) { light.frustum_param.ortho_param.right = r; light.update_projection(); } else { r = light.frustum_param.ortho_param.right; } if (ImGui::InputFloat("bottom", &b)) { light.frustum_param.ortho_param.bottom = b; light.update_projection(); } else { b = light.frustum_param.ortho_param.bottom; } if (ImGui::InputFloat("top", &t)) { light.frustum_param.ortho_param.top = t; light.update_projection(); } else { t = light.frustum_param.ortho_param.top; } if (ImGui::SliderFloat("Yaw", &light.yaw, -180.0f, 180.0f)) { light.update_rotation(); } if (ImGui::SliderFloat("Pitch", &light.pitch, -180.0f, 180.0f)) { light.update_rotation(); } ImGui::SliderFloat("Intensity", &light.intensity, 0.0f, 10.0f); if (ImGui::ColorEdit3("Ambient", ambient)) { light.ambient = tinymath::Color(ambient[0], ambient[1], ambient[2], ambient[3]); } else { ambient[0] = light.ambient.r; ambient[1] = light.ambient.g; ambient[2] = light.ambient.b; ambient[3] = light.ambient.a; } if (ImGui::ColorEdit3("Diffuse", diffuse)) { light.diffuse = tinymath::Color(diffuse[0], diffuse[1], diffuse[2], diffuse[3]); } else { diffuse[0] = light.diffuse.r; diffuse[1] = light.diffuse.g; diffuse[2] = light.diffuse.b; diffuse[3] = light.diffuse.a; } if (ImGui::ColorEdit3("Specular", specular)) { light.specular = tinymath::Color(specular[0], specular[1], specular[2], specular[3]); } else { specular[0] = light.specular.r; specular[1] = light.specular.g; specular[2] = light.specular.b; specular[3] = light.specular.a; } } } }
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* #include "pch.h" #include "Scenario12_DisableCookies.xaml.h" using namespace SDKTemplate; using namespace concurrency; using namespace HttpFilters; using namespace Platform; using namespace Windows::Foundation; using namespace Windows::Foundation::Collections; using namespace Windows::Globalization::DateTimeFormatting; using namespace Windows::UI::Core; using namespace Windows::UI::Popups; using namespace Windows::UI::Xaml; using namespace Windows::UI::Xaml::Controls; using namespace Windows::UI::Xaml::Navigation; using namespace Windows::Web::Http; using namespace Windows::Web::Http::Filters; Scenario12::Scenario12() { InitializeComponent(); } /// <summary> /// Invoked when this page is about to be displayed in a Frame. /// </summary> /// <param name="e">Event data that describes how this page was reached. The Parameter /// property is typically used to configure the page.</param> void Scenario12::OnNavigatedTo(NavigationEventArgs^ e) { // A pointer back to the main page. This is needed if you want to call methods in MainPage such // as NotifyUser() rootPage = MainPage::Current; filter = ref new HttpBaseProtocolFilter(); httpClient = ref new HttpClient(filter); cancellationTokenSource = cancellation_token_source(); } void Scenario12::OnNavigatedFrom(NavigationEventArgs^ e) { // If the navigation is external to the app do not clean up. // This can occur on Phone when suspending the app. if (e->NavigationMode == NavigationMode::Forward && e->Uri == nullptr) { return; } Page::OnNavigatedFrom(e); } void Scenario12::SendInitialGetButton_Click(Object^ sender, RoutedEventArgs^ e) { Uri^ resourceAddress; // The value of 'AddressField' is set by the user and is therefore untrusted input. If we can't create a // valid, absolute URI, we'll notify the user about the incorrect input. if (!rootPage->TryGetUri(AddressField->Text, &resourceAddress)) { rootPage->NotifyUser("Invalid URI.", NotifyType::ErrorMessage); return; } Helpers::ScenarioStarted(SendInitialGetButton, CancelButton, OutputField); rootPage->NotifyUser("In progress", NotifyType::StatusMessage); create_task(httpClient->GetAsync(resourceAddress), cancellationTokenSource.get_token()).then( [=](task<HttpResponseMessage^> previousTask) { try { HttpResponseMessage^ response = previousTask.get(); HttpCookieCollection^ cookieCollection = filter->CookieManager->GetCookies(resourceAddress); OutputField->Text = cookieCollection->Size + " cookies found.\r\n"; for (HttpCookie^ cookie : cookieCollection) { OutputField->Text += "--------------------\r\n"; OutputField->Text += "Name: " + cookie->Name + "\r\n"; OutputField->Text += "Domain: " + cookie->Domain + "\r\n"; OutputField->Text += "Path: " + cookie->Path + "\r\n"; OutputField->Text += "Value: " + cookie->Value + "\r\n"; String^ expirationTimeString = ""; if (cookie->Expires) { DateTimeFormatter^ dateFormatter = ref new DateTimeFormatter("shortdate longtime"); expirationTimeString = dateFormatter->Format(cookie->Expires->Value); } OutputField->Text += "Expires: " + expirationTimeString + "\r\n"; OutputField->Text += "Secure: " + cookie->Secure + "\r\n"; OutputField->Text += "HttpOnly: " + cookie->HttpOnly + "\r\n"; } rootPage->NotifyUser("Completed", NotifyType::StatusMessage); SendNextRequestButton->IsEnabled = true; } catch (const task_canceled&) { rootPage->NotifyUser("Request canceled.", NotifyType::ErrorMessage); } catch (Exception^ ex) { rootPage->NotifyUser("Error: " + ex->Message, NotifyType::ErrorMessage); } Helpers::ScenarioCompleted(SendInitialGetButton, CancelButton); }, task_continuation_context::use_current()); } void Scenario12::SendNextRequestButton_Click(Object^ sender, RoutedEventArgs^ e) { Uri^ resourceAddress; // The value of 'AddressField' is set by the user and is therefore untrusted input. If we can't create a // valid, absolute URI, we'll notify the user about the incorrect input. if (!rootPage->TryGetUri(AddressField->Text, &resourceAddress)) { rootPage->NotifyUser("Invalid URI.", NotifyType::ErrorMessage); return; } Helpers::ScenarioStarted(SendNextRequestButton, CancelButton, OutputField); rootPage->NotifyUser("In progress", NotifyType::StatusMessage); if (CookieUsageBehaviorToggle->IsOn) { filter->CookieUsageBehavior = HttpCookieUsageBehavior::Default; } else { // Disable cookie handling - this will do two things: no cookies are attached to outgoing request, and // cookies contained in incoming server responses are not added to the CookieManager of the HttpBaseProtocolFilter. filter->CookieUsageBehavior = HttpCookieUsageBehavior::NoCookies; } create_task(httpClient->GetAsync(resourceAddress), cancellationTokenSource.get_token()).then( [=](HttpResponseMessage^ response) { return Helpers::DisplayTextResultAsync(response, OutputField, cancellationTokenSource.get_token()); }, task_continuation_context::use_current()).then([=](task<HttpResponseMessage^> previousTask) { try { HttpResponseMessage^ response = previousTask.get(); rootPage->NotifyUser( "Completed. Response came from " + response->Source.ToString() + ".", NotifyType::StatusMessage); } catch (const task_canceled&) { rootPage->NotifyUser("Request canceled.", NotifyType::ErrorMessage); } catch (Exception^ ex) { rootPage->NotifyUser("Error: " + ex->Message, NotifyType::ErrorMessage); } Helpers::ScenarioCompleted(SendNextRequestButton, CancelButton); }, task_continuation_context::use_current()); } void Scenario12::Cancel_Click(Object^ sender, RoutedEventArgs^ e) { cancellationTokenSource.cancel(); // Re-create the CancellationTokenSource. cancellationTokenSource = cancellation_token_source(); }
// Copyright 1998-2016 Epic Games, Inc. All Rights Reserved. #include "DetailCustomizationsPrivatePCH.h" #include "InputStructCustomization.h" #include "InputSettingsDetails.h" #include "GameFramework/PlayerInput.h" #define LOCTEXT_NAMESPACE "InputStructCustomization" /////////////////////////////////// // FInputAxisConfigCustomization // /////////////////////////////////// TSharedRef<IPropertyTypeCustomization> FInputAxisConfigCustomization::MakeInstance() { return MakeShareable( new FInputAxisConfigCustomization ); } void FInputAxisConfigCustomization::CustomizeHeader( TSharedRef<class IPropertyHandle> InStructPropertyHandle, class FDetailWidgetRow& HeaderRow, IPropertyTypeCustomizationUtils& StructCustomizationUtils ) { FString AxisKeyName; InStructPropertyHandle->GetChildHandle(GET_MEMBER_NAME_CHECKED(FInputAxisConfigEntry, AxisKeyName))->GetValue(AxisKeyName); HeaderRow.NameContent() [ InStructPropertyHandle->CreatePropertyNameWidget(FText::FromString(AxisKeyName)) ]; } void FInputAxisConfigCustomization::CustomizeChildren( TSharedRef<class IPropertyHandle> InStructPropertyHandle, class IDetailChildrenBuilder& StructBuilder, IPropertyTypeCustomizationUtils& StructCustomizationUtils ) { TSharedPtr<IPropertyHandle> AxisProperties = InStructPropertyHandle->GetChildHandle(GET_MEMBER_NAME_CHECKED(FInputAxisConfigEntry, AxisProperties)); uint32 NumChildren; AxisProperties->GetNumChildren( NumChildren ); for( uint32 ChildIndex = 0; ChildIndex < NumChildren; ++ChildIndex ) { StructBuilder.AddChildProperty( AxisProperties->GetChildHandle(ChildIndex).ToSharedRef() ); } } ////////////////////////////////////// // FInputActionMappingCustomization // ////////////////////////////////////// TSharedRef<IPropertyTypeCustomization> FInputActionMappingCustomization::MakeInstance() { return MakeShareable( new FInputActionMappingCustomization ); } void FInputActionMappingCustomization::CustomizeHeader( TSharedRef<class IPropertyHandle> InStructPropertyHandle, class FDetailWidgetRow& HeaderRow, IPropertyTypeCustomizationUtils& StructCustomizationUtils ) { ActionMappingHandle = InStructPropertyHandle; } void FInputActionMappingCustomization::CustomizeChildren( TSharedRef<class IPropertyHandle> InStructPropertyHandle, class IDetailChildrenBuilder& StructBuilder, IPropertyTypeCustomizationUtils& StructCustomizationUtils ) { TSharedPtr<IPropertyHandle> KeyHandle = InStructPropertyHandle->GetChildHandle(GET_MEMBER_NAME_CHECKED(FInputActionKeyMapping, Key)); TSharedPtr<IPropertyHandle> ShiftHandle = InStructPropertyHandle->GetChildHandle(GET_MEMBER_NAME_CHECKED(FInputActionKeyMapping, bShift)); TSharedPtr<IPropertyHandle> CtrlHandle = InStructPropertyHandle->GetChildHandle(GET_MEMBER_NAME_CHECKED(FInputActionKeyMapping, bCtrl)); TSharedPtr<IPropertyHandle> AltHandle = InStructPropertyHandle->GetChildHandle(GET_MEMBER_NAME_CHECKED(FInputActionKeyMapping, bAlt)); TSharedPtr<IPropertyHandle> CmdHandle = InStructPropertyHandle->GetChildHandle(GET_MEMBER_NAME_CHECKED(FInputActionKeyMapping, bCmd)); TSharedRef<SWidget> RemoveButton = PropertyCustomizationHelpers::MakeDeleteButton(FSimpleDelegate::CreateSP(this, &FInputActionMappingCustomization::RemoveActionMappingButton_OnClick), LOCTEXT("RemoveActionMappingToolTip", "Removes Action Mapping")); StructBuilder.AddChildContent( LOCTEXT("KeySearchStr", "Key") ) [ SNew(SHorizontalBox) + SHorizontalBox::Slot() .Padding(InputConstants::PropertyPadding) .AutoWidth() [ SNew( SBox ) .WidthOverride( InputConstants::TextBoxWidth ) [ StructBuilder.GenerateStructValueWidget( KeyHandle.ToSharedRef() ) ] ] + SHorizontalBox::Slot() .Padding(InputConstants::PropertyPadding) .HAlign(HAlign_Center) .VAlign(VAlign_Center) .AutoWidth() [ ShiftHandle->CreatePropertyNameWidget() ] + SHorizontalBox::Slot() .Padding(InputConstants::PropertyPadding) .HAlign(HAlign_Center) .VAlign(VAlign_Center) .AutoWidth() [ ShiftHandle->CreatePropertyValueWidget() ] + SHorizontalBox::Slot() .Padding(InputConstants::PropertyPadding) .HAlign(HAlign_Center) .VAlign(VAlign_Center) .AutoWidth() [ CtrlHandle->CreatePropertyNameWidget() ] + SHorizontalBox::Slot() .Padding(InputConstants::PropertyPadding) .HAlign(HAlign_Center) .VAlign(VAlign_Center) .AutoWidth() [ CtrlHandle->CreatePropertyValueWidget() ] + SHorizontalBox::Slot() .Padding(InputConstants::PropertyPadding) .HAlign(HAlign_Center) .VAlign(VAlign_Center) .AutoWidth() [ AltHandle->CreatePropertyNameWidget() ] + SHorizontalBox::Slot() .Padding(InputConstants::PropertyPadding) .HAlign(HAlign_Center) .VAlign(VAlign_Center) .AutoWidth() [ AltHandle->CreatePropertyValueWidget() ] + SHorizontalBox::Slot() .Padding(InputConstants::PropertyPadding) .HAlign(HAlign_Center) .VAlign(VAlign_Center) .AutoWidth() [ CmdHandle->CreatePropertyNameWidget() ] + SHorizontalBox::Slot() .Padding(InputConstants::PropertyPadding) .HAlign(HAlign_Center) .VAlign(VAlign_Center) .AutoWidth() [ CmdHandle->CreatePropertyValueWidget() ] + SHorizontalBox::Slot() .Padding(InputConstants::PropertyPadding) .HAlign(HAlign_Center) .VAlign(VAlign_Center) .AutoWidth() [ RemoveButton ] ]; } void FInputActionMappingCustomization::RemoveActionMappingButton_OnClick() { if( ActionMappingHandle->IsValidHandle() ) { const TSharedPtr<IPropertyHandle> ParentHandle = ActionMappingHandle->GetParentHandle(); const TSharedPtr<IPropertyHandleArray> ParentArrayHandle = ParentHandle->AsArray(); ParentArrayHandle->DeleteItem( ActionMappingHandle->GetIndexInArray() ); } } ////////////////////////////////////// // FInputAxisMappingCustomization // ////////////////////////////////////// TSharedRef<IPropertyTypeCustomization> FInputAxisMappingCustomization::MakeInstance() { return MakeShareable( new FInputAxisMappingCustomization ); } void FInputAxisMappingCustomization::CustomizeHeader( TSharedRef<class IPropertyHandle> InStructPropertyHandle, class FDetailWidgetRow& HeaderRow, IPropertyTypeCustomizationUtils& StructCustomizationUtils ) { AxisMappingHandle = InStructPropertyHandle; } void FInputAxisMappingCustomization::CustomizeChildren( TSharedRef<class IPropertyHandle> InStructPropertyHandle, class IDetailChildrenBuilder& StructBuilder, IPropertyTypeCustomizationUtils& StructCustomizationUtils ) { TSharedPtr<IPropertyHandle> KeyHandle = InStructPropertyHandle->GetChildHandle(GET_MEMBER_NAME_CHECKED(FInputAxisKeyMapping, Key)); TSharedPtr<IPropertyHandle> ScaleHandle = InStructPropertyHandle->GetChildHandle(GET_MEMBER_NAME_CHECKED(FInputAxisKeyMapping, Scale)); TSharedRef<SWidget> RemoveButton = PropertyCustomizationHelpers::MakeDeleteButton( FSimpleDelegate::CreateSP( this, &FInputAxisMappingCustomization::RemoveAxisMappingButton_OnClick), LOCTEXT("RemoveAxisMappingToolTip", "Removes Axis Mapping") ); StructBuilder.AddChildContent( LOCTEXT("KeySearchStr", "Key") ) [ SNew(SHorizontalBox) + SHorizontalBox::Slot() .Padding(InputConstants::PropertyPadding) .AutoWidth() [ SNew( SBox ) .WidthOverride( InputConstants::TextBoxWidth ) [ StructBuilder.GenerateStructValueWidget( KeyHandle.ToSharedRef() ) ] ] +SHorizontalBox::Slot() .Padding(InputConstants::PropertyPadding) .HAlign(HAlign_Center) .VAlign(VAlign_Center) .AutoWidth() [ ScaleHandle->CreatePropertyNameWidget() ] +SHorizontalBox::Slot() .Padding(InputConstants::PropertyPadding) .HAlign(HAlign_Left) .VAlign(VAlign_Center) .AutoWidth() [ SNew(SBox) .WidthOverride(InputConstants::ScaleBoxWidth) [ ScaleHandle->CreatePropertyValueWidget() ] ] +SHorizontalBox::Slot() .Padding(InputConstants::PropertyPadding) .HAlign(HAlign_Center) .VAlign(VAlign_Center) .AutoWidth() [ RemoveButton ] ]; } void FInputAxisMappingCustomization::RemoveAxisMappingButton_OnClick() { if( AxisMappingHandle->IsValidHandle() ) { const TSharedPtr<IPropertyHandle> ParentHandle = AxisMappingHandle->GetParentHandle(); const TSharedPtr<IPropertyHandleArray> ParentArrayHandle = ParentHandle->AsArray(); ParentArrayHandle->DeleteItem( AxisMappingHandle->GetIndexInArray() ); } } #undef LOCTEXT_NAMESPACE
#pragma once #include "Game.hpp" #include <string> class GameObject { public: GameObject(const char* textureSheet, SDL_Renderer* rend, int x, int y); ~GameObject(); void update(); void render(); private: int xpos; int ypos; SDL_Texture* objTexture; SDL_Rect srcRect; SDL_Rect destRect; SDL_Renderer* renderer; };
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <decaf/util/concurrent/Mutex.h> #include <decaf/internal/util/concurrent/MutexImpl.h> #include <decaf/internal/util/concurrent/ConditionImpl.h> #include <decaf/lang/Integer.h> #include <list> using namespace decaf; using namespace decaf::internal; using namespace decaf::internal::util; using namespace decaf::internal::util::concurrent; using namespace decaf::util; using namespace decaf::util::concurrent; using namespace decaf::lang; using namespace decaf::lang::exceptions; //////////////////////////////////////////////////////////////////////////////// namespace decaf{ namespace util{ namespace concurrent{ class MutexProperties { private: MutexProperties( const MutexProperties& ); MutexProperties& operator= ( const MutexProperties& ); public: MutexProperties( const std::string& name ) : mutex( NULL ), condition( NULL ), name( name ) { if( this->name.empty() ) { this->name = std::string( "Mutex-" ) + Integer::toString( ++id ); } } // The Platform Mutex object and an associated Condition Object // for use in the wait / notify pattern. MutexHandle* mutex; ConditionHandle* condition; std::string name; static unsigned int id; }; unsigned int MutexProperties::id = 0; }}} //////////////////////////////////////////////////////////////////////////////// Mutex::Mutex() : Synchronizable(), properties( NULL ) { this->properties = new MutexProperties(""); // Allocate the OS Mutex Implementation. this->properties->mutex = MutexImpl::create(); this->properties->condition = ConditionImpl::create( this->properties->mutex ); } //////////////////////////////////////////////////////////////////////////////// Mutex::Mutex( const std::string& name ) : Synchronizable(), properties( NULL ) { this->properties = new MutexProperties( name ); // Allocate the OS Mutex Implementation. this->properties->mutex = MutexImpl::create(); this->properties->condition = ConditionImpl::create( this->properties->mutex ); } //////////////////////////////////////////////////////////////////////////////// Mutex::~Mutex() { unlock(); ConditionImpl::destroy( this->properties->condition ); MutexImpl::destroy( this->properties->mutex ); delete this->properties; } //////////////////////////////////////////////////////////////////////////////// std::string Mutex::getName() const { return this->properties->name; } //////////////////////////////////////////////////////////////////////////////// std::string Mutex::toString() const { return this->properties->name; } //////////////////////////////////////////////////////////////////////////////// void Mutex::lock() { MutexImpl::lock( this->properties->mutex ); } //////////////////////////////////////////////////////////////////////////////// bool Mutex::tryLock() { return MutexImpl::trylock( this->properties->mutex ); } //////////////////////////////////////////////////////////////////////////////// void Mutex::unlock() { MutexImpl::unlock( this->properties->mutex ); } //////////////////////////////////////////////////////////////////////////////// void Mutex::wait() { ConditionImpl::wait( this->properties->condition ); } //////////////////////////////////////////////////////////////////////////////// void Mutex::wait( long long millisecs ) { wait( millisecs, 0 ); } //////////////////////////////////////////////////////////////////////////////// void Mutex::wait( long long millisecs, int nanos ) { if( millisecs < 0 ) { throw IllegalArgumentException( __FILE__, __LINE__, "Milliseconds value cannot be negative." ); } if( nanos < 0 || nanos > 999999 ) { throw IllegalArgumentException( __FILE__, __LINE__, "Nanoseconds value must be in the range [0..999999]." ); } ConditionImpl::wait( this->properties->condition, millisecs, nanos ); } //////////////////////////////////////////////////////////////////////////////// void Mutex::notify() { ConditionImpl::notify( this->properties->condition ); } //////////////////////////////////////////////////////////////////////////////// void Mutex::notifyAll() { ConditionImpl::notifyAll( this->properties->condition ); }
/****************************************************************************** * The MIT License (MIT) * * Copyright (c) 2019-2021 Baldur Karlsson * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. ******************************************************************************/ #include "FindReplace.h" #include <QKeyEvent> #include <QLineEdit> #include "Widgets/Extended/RDLineEdit.h" #include "ui_FindReplace.h" FindReplace::FindReplace(QWidget *parent) : QFrame(parent), ui(new Ui::FindReplace) { ui->setupUi(this); ui->searchContext->setCurrentIndex(FindReplace::File); // default to just find setReplaceMode(false); setDirection(FindReplace::Down); RDLineEdit *edit = new RDLineEdit(this); ui->findText->setLineEdit(edit); ui->findText->setAutoCompletion(false); ui->replaceText->setAutoCompletion(false); QObject::connect(edit, &RDLineEdit::keyPress, [this](QKeyEvent *event) { if(event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter) { SearchDirection dir = m_direction; if(event->modifiers() & Qt::ShiftModifier) m_direction = SearchDirection::Up; else m_direction = SearchDirection::Down; addHistory(ui->findText); emit performFind(); m_direction = dir; } }); QObject::connect(ui->replaceText->lineEdit(), &QLineEdit::returnPressed, this, &FindReplace::on_replace_clicked); } FindReplace::~FindReplace() { delete ui; } bool FindReplace::replaceMode() { return ui->replaceMode->isChecked(); } FindReplace::SearchContext FindReplace::context() { return (FindReplace::SearchContext)ui->searchContext->currentIndex(); } FindReplace::SearchDirection FindReplace::direction() { return m_direction; } bool FindReplace::matchCase() { return ui->matchCase->isChecked(); } bool FindReplace::matchWord() { return ui->matchWord->isChecked(); } bool FindReplace::regexp() { return ui->regexp->isChecked(); } void FindReplace::setFindText(QString text) { ui->findText->setCurrentText(text); } QString FindReplace::findText() { return ui->findText->currentText(); } void FindReplace::setReplaceText(QString text) { ui->replaceText->setCurrentText(text); } QString FindReplace::replaceText() { return ui->replaceText->currentText(); } void FindReplace::allowUserModeChange(bool allow) { ui->modeChangeFrame->setVisible(allow); } void FindReplace::setReplaceMode(bool replacing) { ui->replaceLabel->setVisible(replacing); ui->replaceText->setVisible(replacing); ui->replace->setVisible(replacing); ui->replaceAll->setVisible(replacing); ui->findMode->setChecked(!replacing); ui->replaceMode->setChecked(replacing); setWindowTitle(replacing ? tr("Find && Replace") : tr("Find")); } void FindReplace::setDirection(SearchDirection dir) { m_direction = dir; } void FindReplace::takeFocus() { ui->findText->setFocus(); ui->findText->lineEdit()->selectAll(); } void FindReplace::keyPressEvent(QKeyEvent *event) { if(event->key() == Qt::Key_F3) { SearchDirection dir = m_direction; if(event->modifiers() & Qt::ShiftModifier) m_direction = SearchDirection::Up; else m_direction = SearchDirection::Down; emit performFind(); m_direction = dir; } else { emit keyPress(event); } } void FindReplace::addHistory(QComboBox *combo) { QString text = combo->currentText(); for(int i = 0; i < combo->count(); i++) { if(combo->itemText(i) == text) { // remove the item so we can bump it up to the top of the list combo->removeItem(i); break; } } combo->insertItem(0, text); combo->setCurrentText(text); } void FindReplace::on_findPrev_clicked() { setDirection(FindReplace::Up); addHistory(ui->findText); emit performFind(); } void FindReplace::on_find_clicked() { setDirection(FindReplace::Down); addHistory(ui->findText); emit performFind(); } void FindReplace::on_findAll_clicked() { addHistory(ui->findText); emit performFindAll(); } void FindReplace::on_replace_clicked() { addHistory(ui->findText); addHistory(ui->replaceText); emit performReplace(); } void FindReplace::on_replaceAll_clicked() { addHistory(ui->findText); addHistory(ui->replaceText); emit performReplaceAll(); } void FindReplace::on_findMode_clicked() { setReplaceMode(false); } void FindReplace::on_replaceMode_clicked() { setReplaceMode(true); }
//***************************************************************************** // Copyright 2017-2020 Intel Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //***************************************************************************** #include "gtest/gtest.h" #include "ngraph/file_util.hpp" #include "ngraph/frontend/onnx_import/default_opset.hpp" #include "ngraph/frontend/onnx_import/onnx.hpp" #include "ngraph/opsets/opset0.hpp" #include "ngraph/pass/manager.hpp" #include "ngraph/pass/opset0_downgrade.hpp" #include "ngraph/provenance.hpp" #include "util/test_control.hpp" #include "util/type_prop.hpp" using namespace ngraph; using namespace ngraph::onnx_import; static std::string s_manifest = "${MANIFEST}"; NGRAPH_TEST(onnx_${BACKEND_NAME}, provenance_tag_text) { const auto function = onnx_import::import_onnx_model( file_util::path_join(SERIALIZED_ZOO, "onnx/provenance_tag_add.prototxt")); const auto ng_nodes = function->get_ordered_ops(); for (const auto ng_node : ng_nodes) { for (const auto tag : ng_node->get_provenance_tags()) { EXPECT_HAS_SUBSTRING(tag, "ONNX"); } } } // the NodeToCheck parameter of this template is used to find a node in the whole subgraph // that a particular unit test is supposed to check against the expected provenance tag template <typename NodeToCheck> void test_provenance_tags(const std::shared_ptr<Function> function, const std::string& expected_provenance_tag) { int node_count = 0; for (const auto ng_node : function->get_ordered_ops()) { if (as_type_ptr<NodeToCheck>(ng_node)) { ++node_count; const auto tags = ng_node->get_provenance_tags(); ASSERT_TRUE(tags.size() > 0) << "Node " << ng_node->get_friendly_name() << " should have at least one provenance tag."; EXPECT_TRUE(tags.find(expected_provenance_tag) != tags.end()); } } EXPECT_TRUE(node_count > 0) << "Expected type of node doesn't exist in graph."; } NGRAPH_TEST(onnx_${BACKEND_NAME}, provenance_only_output) { // the Add node in the model does not have a name, // only its output name should be found in the provenance tags const auto function = onnx_import::import_onnx_model( file_util::path_join(SERIALIZED_ZOO, "onnx/provenance_only_outputs.prototxt")); test_provenance_tags<default_opset::Add>(function, "<ONNX Add (-> output_of_add)>"); } NGRAPH_TEST(onnx_${BACKEND_NAME}, provenance_node_name_and_outputs) { const auto function = onnx_import::import_onnx_model( file_util::path_join(SERIALIZED_ZOO, "onnx/provenance_node_name_and_outputs.prototxt")); test_provenance_tags<default_opset::Add>(function, "<ONNX Add (Add_node -> output_of_add)>"); } NGRAPH_TEST(onnx_${BACKEND_NAME}, provenance_multiple_outputs_op) { const auto function = onnx_import::import_onnx_model( file_util::path_join(SERIALIZED_ZOO, "onnx/provenance_multiple_outputs_op.prototxt")); test_provenance_tags<default_opset::TopK>(function, "<ONNX TopK (TOPK -> values, indices)>"); } NGRAPH_TEST(onnx_${BACKEND_NAME}, provenance_tagging_constants) { const auto function = onnx_import::import_onnx_model( file_util::path_join(SERIALIZED_ZOO, "onnx/provenance_input_tags.prototxt")); test_provenance_tags<default_opset::Constant>(function, "<ONNX Input (initializer_of_A) Shape:{1}>"); } NGRAPH_TEST(onnx_${BACKEND_NAME}, provenance_tagging_parameters) { const auto function = onnx_import::import_onnx_model( file_util::path_join(SERIALIZED_ZOO, "onnx/provenance_input_tags.prototxt")); test_provenance_tags<default_opset::Parameter>(function, "<ONNX Input (input_B) Shape:{}>"); } NGRAPH_TEST(onnx_${BACKEND_NAME}, provenance_tag_downgrade_pass) { set_provenance_enabled(true); const auto function = onnx_import::import_onnx_model( file_util::path_join(SERIALIZED_ZOO, "onnx/provenance_downgrade_topk.prototxt")); ngraph::pass::Manager pass_manager; pass_manager.register_pass<pass::Opset0Downgrade>(); pass_manager.run_passes(function); test_provenance_tags<op::v0::TopK>(function, "<ONNX TopK (TOPK -> values, indices)>"); test_provenance_tags<op::v0::TopK>(function, "<Opset0_Downgrade (v1 TopK)>"); }
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "athena/test/base/sample_activity.h" #include "athena/input/public/accelerator_manager.h" #include "ui/gfx/image/image_skia.h" #include "ui/views/background.h" #include "ui/views/view.h" #include "ui/views/widget/widget.h" namespace athena { namespace test { SampleActivity::SampleActivity(SkColor color, SkColor contents_color, const base::string16& title) : color_(color), contents_color_(contents_color), title_(title), contents_view_(nullptr), current_state_(ACTIVITY_UNLOADED) { } SampleActivity::~SampleActivity() { } athena::ActivityViewModel* SampleActivity::GetActivityViewModel() { return this; } void SampleActivity::SetCurrentState(Activity::ActivityState state) { current_state_ = state; } Activity::ActivityState SampleActivity::GetCurrentState() { return current_state_; } bool SampleActivity::IsVisible() { return contents_view_ && contents_view_->IsDrawn(); } Activity::ActivityMediaState SampleActivity::GetMediaState() { return Activity::ACTIVITY_MEDIA_STATE_NONE; } aura::Window* SampleActivity::GetWindow() { return !contents_view_ ? nullptr : contents_view_->GetWidget()->GetNativeWindow(); } content::WebContents* SampleActivity::GetWebContents() { return nullptr; } void SampleActivity::Init() { accelerator_manager_ = AcceleratorManager::CreateForFocusManager( GetContentsView()->GetWidget()->GetFocusManager()); } SkColor SampleActivity::GetRepresentativeColor() const { return color_; } base::string16 SampleActivity::GetTitle() const { return title_; } gfx::ImageSkia SampleActivity::GetIcon() const { return gfx::ImageSkia(); } void SampleActivity::SetActivityView(ActivityView* view) { } bool SampleActivity::UsesFrame() const { return true; } views::View* SampleActivity::GetContentsView() { if (!contents_view_) { contents_view_ = new views::View; contents_view_->set_background( views::Background::CreateSolidBackground(contents_color_)); } return contents_view_; } gfx::ImageSkia SampleActivity::GetOverviewModeImage() { return gfx::ImageSkia(); } void SampleActivity::PrepareContentsForOverview() { } void SampleActivity::ResetContentsView() { } } // namespace test } // namespace athena
// struct node { // int data; // struct node* left; // struct node* right; // } // inorder(root->left) // display(root->data) // inorder(root->right)
#include "../core/global.h" #include "../core/config_parser.h" #include "../core/fileutils.h" #include "../core/timer.h" #include "../core/datetime.h" #include "../core/makedir.h" #include "../dataio/sgf.h" #include "../search/asyncbot.h" #include "../program/setup.h" #include "../program/playutils.h" #include "../program/play.h" #include "../command/commandline.h" #include "../main.h" using namespace std; static const vector<string> knownCommands = { //Basic GTP commands "protocol_version", "name", "version", "known_command", "list_commands", "quit", //GTP extension - specify "boardsize X:Y" or "boardsize X Y" for non-square sizes //rectangular_boardsize is an alias for boardsize, intended to make it more evident that we have such support "boardsize", "rectangular_boardsize", "clear_board", "set_position", "komi", //GTP extension - get KataGo's current komi setting "get_komi", "play", "undo", //GTP extension - specify rules "kata-get-rules", "kata-set-rule", "kata-set-rules", //Get or change a few limited params dynamically "kata-get-param", "kata-set-param", "kata-list-params", "kgs-rules", "genmove", "genmove_debug", //Prints additional info to stderr "search_debug", //Prints additional info to stderr, doesn't actually make the move //Clears neural net cached evaluations and bot search tree, allows fresh randomization "clear_cache", "showboard", "fixed_handicap", "place_free_handicap", "set_free_handicap", "time_settings", "kgs-time_settings", "time_left", //KataGo extensions for time settings "kata-list_time_settings", "kata-time_settings", "final_score", "final_status_list", "loadsgf", "printsgf", //GTP extensions for board analysis // "genmove_analyze", "lz-genmove_analyze", "kata-genmove_analyze", // "analyze", "lz-analyze", "kata-analyze", //Display raw neural net evaluations "kata-raw-nn", //Misc other stuff "cputime", "gomill-cpu_time", //Some debug commands "kata-debug-print-tc", //Stop any ongoing ponder or analyze "stop", }; static bool tryParseLoc(const string& s, const Board& b, Loc& loc) { return Location::tryOfString(s,b,loc); } //Filter out all double newlines, since double newline terminates GTP command responses static string filterDoubleNewlines(const string& s) { string filtered; for(int i = 0; i<s.length(); i++) { if(i > 0 && s[i-1] == '\n' && s[i] == '\n') continue; filtered += s[i]; } return filtered; } static bool timeIsValid(const double& time) { if(isnan(time) || time < 0.0 || time > TimeControls::MAX_USER_INPUT_TIME) return false; return true; } static bool timeIsValidAllowNegative(const double& time) { if(isnan(time) || time < -TimeControls::MAX_USER_INPUT_TIME || time > TimeControls::MAX_USER_INPUT_TIME) return false; return true; } static double parseTime(const vector<string>& args, int argIdx, const string& description) { double time = 0.0; if(args.size() <= argIdx || !Global::tryStringToDouble(args[argIdx],time)) throw StringError("Expected float for " + description + " as argument " + Global::intToString(argIdx)); if(!timeIsValid(time)) throw StringError(description + " is an invalid value: " + args[argIdx]); return time; } static double parseTimeAllowNegative(const vector<string>& args, int argIdx, const string& description) { double time = 0.0; if(args.size() <= argIdx || !Global::tryStringToDouble(args[argIdx],time)) throw StringError("Expected float for " + description + " as argument " + Global::intToString(argIdx)); if(!timeIsValidAllowNegative(time)) throw StringError(description + " is an invalid value: " + args[argIdx]); return time; } static int parseByoYomiStones(const vector<string>& args, int argIdx) { int byoYomiStones = 0; if(args.size() <= argIdx || !Global::tryStringToInt(args[argIdx],byoYomiStones)) throw StringError("Expected int for byo-yomi overtime stones as argument " + Global::intToString(argIdx)); if(byoYomiStones < 0 || byoYomiStones > 1000000) throw StringError("byo-yomi overtime stones is an invalid value: " + args[argIdx]); return byoYomiStones; } static int parseByoYomiPeriods(const vector<string>& args, int argIdx) { int byoYomiPeriods = 0; if(args.size() <= argIdx || !Global::tryStringToInt(args[argIdx],byoYomiPeriods)) throw StringError("Expected int for byo-yomi overtime periods as argument " + Global::intToString(argIdx)); if(byoYomiPeriods < 0 || byoYomiPeriods > 1000000) throw StringError("byo-yomi overtime periods is an invalid value: " + args[argIdx]); return byoYomiPeriods; } //Assumes that stones are worth 15 points area and 14 points territory, and that 7 komi is fair static double initialBlackAdvantage(const BoardHistory& hist) { BoardHistory histCopy = hist; histCopy.setAssumeMultipleStartingBlackMovesAreHandicap(true); int handicapStones = histCopy.computeNumHandicapStones(); if(handicapStones <= 1) return 7.0 - hist.rules.komi; //Subtract one since white gets the first move afterward int extraBlackStones = handicapStones - 1; double stoneValue = hist.rules.scoringRule == Rules::SCORING_AREA ? 15.0 : 14.0; double whiteHandicapBonus = 0.0; if(hist.rules.whiteHandicapBonusRule == Rules::WHB_N) whiteHandicapBonus += handicapStones; else if(hist.rules.whiteHandicapBonusRule == Rules::WHB_N_MINUS_ONE) whiteHandicapBonus += handicapStones-1; return stoneValue * extraBlackStones + (7.0 - hist.rules.komi - whiteHandicapBonus); } static double getBoardSizeScaling(const Board& board) { return pow(19.0 * 19.0 / (double)(board.x_size * board.y_size), 0.75); } static double getPointsThresholdForHandicapGame(double boardSizeScaling) { return std::max(4.0 / boardSizeScaling, 2.0); } static bool noWhiteStonesOnBoard(const Board& board) { for(int y = 0; y < board.y_size; y++) { for(int x = 0; x < board.x_size; x++) { Loc loc = Location::getLoc(x,y,board.x_size); if(board.colors[loc] == P_WHITE) return false; } } return true; } static void updateDynamicPDAHelper( const Board& board, const BoardHistory& hist, const double dynamicPlayoutDoublingAdvantageCapPerOppLead, const vector<double>& recentWinLossValues, double& desiredDynamicPDAForWhite ) { (void)board; if(dynamicPlayoutDoublingAdvantageCapPerOppLead <= 0.0) { desiredDynamicPDAForWhite = 0.0; } else { double boardSizeScaling = getBoardSizeScaling(board); double pdaScalingStartPoints = getPointsThresholdForHandicapGame(boardSizeScaling); double initialBlackAdvantageInPoints = initialBlackAdvantage(hist); Player disadvantagedPla = initialBlackAdvantageInPoints >= 0 ? P_WHITE : P_BLACK; double initialAdvantageInPoints = abs(initialBlackAdvantageInPoints); if(initialAdvantageInPoints < pdaScalingStartPoints || board.x_size <= 7 || board.y_size <= 7) { desiredDynamicPDAForWhite = 0.0; } else { double desiredDynamicPDAForDisadvantagedPla = (disadvantagedPla == P_WHITE) ? desiredDynamicPDAForWhite : -desiredDynamicPDAForWhite; //What increment to adjust desiredPDA at. //Power of 2 to avoid any rounding issues. const double increment = 0.125; //Hard cap of 2.75 in this parameter, since more extreme values start to reach into values without good training. //Scale mildly with board size - small board a given point lead counts as "more". double pdaCap = std::min( 2.75, dynamicPlayoutDoublingAdvantageCapPerOppLead * (initialAdvantageInPoints - pdaScalingStartPoints) * boardSizeScaling ); pdaCap = round(pdaCap / increment) * increment; //No history, or literally no white stones on board? Then this is a new game or a newly set position if(recentWinLossValues.size() <= 0 || noWhiteStonesOnBoard(board)) { //Just use the cap desiredDynamicPDAForDisadvantagedPla = pdaCap; } else { double winLossValue = recentWinLossValues[recentWinLossValues.size()-1]; //Convert to perspective of disadvantagedPla if(disadvantagedPla == P_BLACK) winLossValue = -winLossValue; //Keep winLossValue between 5% and 25%, subject to available caps. if(winLossValue < -0.9) desiredDynamicPDAForDisadvantagedPla = desiredDynamicPDAForDisadvantagedPla + 0.125; else if(winLossValue > -0.5) desiredDynamicPDAForDisadvantagedPla = desiredDynamicPDAForDisadvantagedPla - 0.125; desiredDynamicPDAForDisadvantagedPla = std::max(desiredDynamicPDAForDisadvantagedPla, 0.0); desiredDynamicPDAForDisadvantagedPla = std::min(desiredDynamicPDAForDisadvantagedPla, pdaCap); } desiredDynamicPDAForWhite = (disadvantagedPla == P_WHITE) ? desiredDynamicPDAForDisadvantagedPla : -desiredDynamicPDAForDisadvantagedPla; } } } static bool shouldResign( const Board& board, const BoardHistory& hist, Player pla, const vector<double>& recentWinLossValues, double lead, const double resignThreshold, const int resignConsecTurns, const double resignMinScoreDifference ) { double initialBlackAdvantageInPoints = initialBlackAdvantage(hist); int minTurnForResignation = 0; double noResignationWhenWhiteScoreAbove = board.x_size * board.y_size; if(initialBlackAdvantageInPoints > 0.9 && pla == P_WHITE) { //Play at least some moves no matter what minTurnForResignation = 1 + board.x_size * board.y_size / 5; //In a handicap game, also only resign if the lead difference is well behind schedule assuming //that we're supposed to catch up over many moves. double numTurnsToCatchUp = 0.60 * board.x_size * board.y_size - minTurnForResignation; double numTurnsSpent = (double)(hist.moveHistory.size()) - minTurnForResignation; if(numTurnsToCatchUp <= 1.0) numTurnsToCatchUp = 1.0; if(numTurnsSpent <= 0.0) numTurnsSpent = 0.0; if(numTurnsSpent > numTurnsToCatchUp) numTurnsSpent = numTurnsToCatchUp; double resignScore = -initialBlackAdvantageInPoints * ((numTurnsToCatchUp - numTurnsSpent) / numTurnsToCatchUp); resignScore -= 5.0; //Always require at least a 5 point buffer resignScore -= initialBlackAdvantageInPoints * 0.15; //And also require a 15% of the initial handicap noResignationWhenWhiteScoreAbove = resignScore; } if(hist.moveHistory.size() < minTurnForResignation) return false; if(pla == P_WHITE && lead > noResignationWhenWhiteScoreAbove) return false; if(resignConsecTurns > recentWinLossValues.size()) return false; //Don't resign close games. if((pla == P_WHITE && lead > -resignMinScoreDifference) || (pla == P_BLACK && lead < resignMinScoreDifference)) return false; for(int i = 0; i<resignConsecTurns; i++) { double winLossValue = recentWinLossValues[recentWinLossValues.size()-1-i]; Player resignPlayerThisTurn = C_EMPTY; if(winLossValue < resignThreshold) resignPlayerThisTurn = P_WHITE; else if(winLossValue > -resignThreshold) resignPlayerThisTurn = P_BLACK; if(resignPlayerThisTurn != pla) return false; } return true; } struct GTPEngine { GTPEngine(const GTPEngine&) = delete; GTPEngine& operator=(const GTPEngine&) = delete; const string nnModelFile; const bool assumeMultipleStartingBlackMovesAreHandicap; const int analysisPVLen; const bool preventEncore; const double dynamicPlayoutDoublingAdvantageCapPerOppLead; double staticPlayoutDoublingAdvantage; bool staticPDATakesPrecedence; double normalAvoidRepeatedPatternUtility; double handicapAvoidRepeatedPatternUtility; double genmoveWideRootNoise; double analysisWideRootNoise; bool genmoveAntiMirror; bool analysisAntiMirror; NNEvaluator* nnEval; AsyncBot* bot; Rules currentRules; //Should always be the same as the rules in bot, if bot is not NULL. //Stores the params we want to be using during genmoves or analysis SearchParams params; TimeControls bTimeControls; TimeControls wTimeControls; //This move history doesn't get cleared upon consecutive moves by the same side, and is used //for undo, whereas the one in search does. Board initialBoard; Player initialPla; vector<Move> moveHistory; vector<double> recentWinLossValues; double lastSearchFactor; double desiredDynamicPDAForWhite; bool avoidMYTDaggerHack; std::unique_ptr<PatternBonusTable> patternBonusTable; Player perspective; double genmoveTimeSum; GTPEngine( const string& modelFile, SearchParams initialParams, Rules initialRules, bool assumeMultiBlackHandicap, bool prevtEncore, double dynamicPDACapPerOppLead, double staticPDA, bool staticPDAPrecedence, double normAvoidRepeatedPatternUtility, double hcapAvoidRepeatedPatternUtility, bool avoidDagger, double genmoveWRN, double analysisWRN, bool genmoveAntiMir, bool analysisAntiMir, Player persp, int pvLen, std::unique_ptr<PatternBonusTable>&& pbTable ) :nnModelFile(modelFile), assumeMultipleStartingBlackMovesAreHandicap(assumeMultiBlackHandicap), analysisPVLen(pvLen), preventEncore(prevtEncore), dynamicPlayoutDoublingAdvantageCapPerOppLead(dynamicPDACapPerOppLead), staticPlayoutDoublingAdvantage(staticPDA), staticPDATakesPrecedence(staticPDAPrecedence), normalAvoidRepeatedPatternUtility(normAvoidRepeatedPatternUtility), handicapAvoidRepeatedPatternUtility(hcapAvoidRepeatedPatternUtility), genmoveWideRootNoise(genmoveWRN), analysisWideRootNoise(analysisWRN), genmoveAntiMirror(genmoveAntiMir), analysisAntiMirror(analysisAntiMir), nnEval(NULL), bot(NULL), currentRules(initialRules), params(initialParams), bTimeControls(), wTimeControls(), initialBoard(), initialPla(P_BLACK), moveHistory(), recentWinLossValues(), lastSearchFactor(1.0), desiredDynamicPDAForWhite(0.0), avoidMYTDaggerHack(avoidDagger), patternBonusTable(std::move(pbTable)), perspective(persp), genmoveTimeSum(0.0) { } ~GTPEngine() { stopAndWait(); delete bot; delete nnEval; } void stopAndWait() { bot->stopAndWait(); } Rules getCurrentRules() { return currentRules; } void clearStatsForNewGame() { //Currently nothing } //Specify -1 for the sizes for a default void setOrResetBoardSize(ConfigParser& cfg, Logger& logger, Rand& seedRand, int boardXSize, int boardYSize, bool loggingToStderr) { if(nnEval != NULL && boardXSize == nnEval->getNNXLen() && boardYSize == nnEval->getNNYLen()) return; if(nnEval != NULL) { assert(bot != NULL); bot->stopAndWait(); delete bot; delete nnEval; bot = NULL; nnEval = NULL; logger.write("Cleaned up old neural net and bot"); } bool wasDefault = false; if(boardXSize == -1 || boardYSize == -1) { boardXSize = Board::DEFAULT_LEN; boardYSize = Board::DEFAULT_LEN; wasDefault = true; } const int maxConcurrentEvals = params.numThreads * 2 + 16; // * 2 + 16 just to give plenty of headroom const int expectedConcurrentEvals = params.numThreads; const int defaultMaxBatchSize = std::max(8,((params.numThreads+3)/4)*4); const bool defaultRequireExactNNLen = true; const string expectedSha256 = ""; nnEval = Setup::initializeNNEvaluator( nnModelFile,nnModelFile,expectedSha256,cfg,logger,seedRand,maxConcurrentEvals,expectedConcurrentEvals, boardXSize,boardYSize,defaultMaxBatchSize,defaultRequireExactNNLen, Setup::SETUP_FOR_GTP ); logger.write("Loaded neural net with nnXLen " + Global::intToString(nnEval->getNNXLen()) + " nnYLen " + Global::intToString(nnEval->getNNYLen())); { bool rulesWereSupported; nnEval->getSupportedRules(currentRules,rulesWereSupported); if(!rulesWereSupported) { throw StringError("Rules " + currentRules.toJsonStringNoKomi() + " from config file " + cfg.getFileName() + " are NOT supported by neural net"); } } //On default setup, also override board size to whatever the neural net was initialized with //So that if the net was initalized smaller, we don't fail with a big board if(wasDefault) { boardXSize = nnEval->getNNXLen(); boardYSize = nnEval->getNNYLen(); } logger.write("Initializing board with boardXSize " + Global::intToString(boardXSize) + " boardYSize " + Global::intToString(boardYSize)); if(!loggingToStderr) cerr << ("Initializing board with boardXSize " + Global::intToString(boardXSize) + " boardYSize " + Global::intToString(boardYSize)) << endl; string searchRandSeed; if(cfg.contains("searchRandSeed")) searchRandSeed = cfg.getString("searchRandSeed"); else searchRandSeed = Global::uint64ToString(seedRand.nextUInt64()); bot = new AsyncBot(params, nnEval, &logger, searchRandSeed); bot->setCopyOfExternalPatternBonusTable(patternBonusTable); Board board(boardXSize,boardYSize); Player pla = P_BLACK; BoardHistory hist(board,pla,currentRules,0); vector<Move> newMoveHistory; setPositionAndRules(pla,board,hist,board,pla,newMoveHistory); clearStatsForNewGame(); } void setPositionAndRules(Player pla, const Board& board, const BoardHistory& h, const Board& newInitialBoard, Player newInitialPla, const vector<Move> newMoveHistory) { BoardHistory hist(h); //Ensure we always have this value correct hist.setAssumeMultipleStartingBlackMovesAreHandicap(assumeMultipleStartingBlackMovesAreHandicap); currentRules = hist.rules; bot->setPosition(pla,board,hist); initialBoard = newInitialBoard; initialPla = newInitialPla; moveHistory = newMoveHistory; recentWinLossValues.clear(); updateDynamicPDA(); } void clearBoard() { assert(bot->getRootHist().rules == currentRules); int newXSize = bot->getRootBoard().x_size; int newYSize = bot->getRootBoard().y_size; Board board(newXSize,newYSize); Player pla = P_BLACK; BoardHistory hist(board,pla,currentRules,0); vector<Move> newMoveHistory; setPositionAndRules(pla,board,hist,board,pla,newMoveHistory); clearStatsForNewGame(); } bool setPosition(const vector<Move>& initialStones) { assert(bot->getRootHist().rules == currentRules); int newXSize = bot->getRootBoard().x_size; int newYSize = bot->getRootBoard().y_size; Board board(newXSize,newYSize); for(int i = 0; i<initialStones.size(); i++) { if(!board.isOnBoard(initialStones[i].loc) || board.colors[initialStones[i].loc] != C_EMPTY) { return false; } bool suc = board.setStone(initialStones[i].loc, initialStones[i].pla); if(!suc) { return false; } } //Make sure nothing died along the way for(int i = 0; i<initialStones.size(); i++) { if(board.colors[initialStones[i].loc] != initialStones[i].pla) { return false; } } Player pla = P_BLACK; BoardHistory hist(board,pla,currentRules,0); hist.setInitialTurnNumber(board.numStonesOnBoard()); //Heuristic to guess at what turn this is vector<Move> newMoveHistory; setPositionAndRules(pla,board,hist,board,pla,newMoveHistory); clearStatsForNewGame(); return true; } void updateKomiIfNew(float newKomi) { bot->setKomiIfNew(newKomi); currentRules.komi = newKomi; } void setStaticPlayoutDoublingAdvantage(double d) { staticPlayoutDoublingAdvantage = d; staticPDATakesPrecedence = true; } void setAnalysisWideRootNoise(double x) { analysisWideRootNoise = x; } void setRootPolicyTemperature(double x) { params.rootPolicyTemperature = x; bot->setParams(params); bot->clearSearch(); } void setNumSearchThreads(int numThreads) { params.numThreads = numThreads; bot->setParams(params); bot->clearSearch(); } void updateDynamicPDA() { updateDynamicPDAHelper( bot->getRootBoard(),bot->getRootHist(), dynamicPlayoutDoublingAdvantageCapPerOppLead, recentWinLossValues, desiredDynamicPDAForWhite ); } bool play(Loc loc, Player pla) { assert(bot->getRootHist().rules == currentRules); bool suc = bot->makeMove(loc,pla,preventEncore); if(suc) moveHistory.push_back(Move(loc,pla)); return suc; } bool undo() { if(moveHistory.size() <= 0) return false; assert(bot->getRootHist().rules == currentRules); vector<Move> moveHistoryCopy = moveHistory; Board undoneBoard = initialBoard; BoardHistory undoneHist(undoneBoard,initialPla,currentRules,0); undoneHist.setInitialTurnNumber(bot->getRootHist().initialTurnNumber); vector<Move> emptyMoveHistory; setPositionAndRules(initialPla,undoneBoard,undoneHist,initialBoard,initialPla,emptyMoveHistory); for(int i = 0; i<moveHistoryCopy.size()-1; i++) { Loc moveLoc = moveHistoryCopy[i].loc; Player movePla = moveHistoryCopy[i].pla; bool suc = play(moveLoc,movePla); assert(suc); (void)suc; //Avoid warning when asserts are off } return true; } bool setRulesNotIncludingKomi(Rules newRules, string& error) { assert(nnEval != NULL); assert(bot->getRootHist().rules == currentRules); newRules.komi = currentRules.komi; bool rulesWereSupported; nnEval->getSupportedRules(newRules,rulesWereSupported); if(!rulesWereSupported) { error = "Rules " + newRules.toJsonStringNoKomi() + " are not supported by this neural net version"; return false; } vector<Move> moveHistoryCopy = moveHistory; Board board = initialBoard; BoardHistory hist(board,initialPla,newRules,0); hist.setInitialTurnNumber(bot->getRootHist().initialTurnNumber); vector<Move> emptyMoveHistory; setPositionAndRules(initialPla,board,hist,initialBoard,initialPla,emptyMoveHistory); for(int i = 0; i<moveHistoryCopy.size(); i++) { Loc moveLoc = moveHistoryCopy[i].loc; Player movePla = moveHistoryCopy[i].pla; bool suc = play(moveLoc,movePla); //Because internally we use a highly tolerant test, we don't expect this to actually trigger //even if a rules change did make some earlier moves illegal. But this check simply futureproofs //things in case we ever do if(!suc) { error = "Could not make the rules change, some earlier moves in the game would now become illegal."; return false; } } return true; } void ponder() { bot->ponder(lastSearchFactor); } struct AnalyzeArgs { bool analyzing = false; bool lz = false; bool kata = false; int minMoves = 0; int maxMoves = 10000000; bool showOwnership = false; bool showOwnershipStdev = false; bool showPVVisits = false; double secondsPerReport = TimeControls::UNLIMITED_TIME_DEFAULT; vector<int> avoidMoveUntilByLocBlack; vector<int> avoidMoveUntilByLocWhite; }; void filterZeroVisitMoves(const AnalyzeArgs& args, vector<AnalysisData> buf) { //Avoid printing moves that have 0 visits, unless we need them //These should already be sorted so that 0-visit moves only appear at the end. int keptMoves = 0; for(int i = 0; i<buf.size(); i++) { if(buf[i].numVisits > 0 || keptMoves < args.minMoves) buf[keptMoves++] = buf[i]; } buf.resize(keptMoves); } std::function<void(const Search* search)> getAnalyzeCallback(Player pla, AnalyzeArgs args) { std::function<void(const Search* search)> callback; //lz-analyze if(args.lz && !args.kata) { //Avoid capturing anything by reference except [this], since this will potentially be used //asynchronously and called after we return callback = [args,pla,this](const Search* search) { vector<AnalysisData> buf; bool duplicateForSymmetries = true; search->getAnalysisData(buf,args.minMoves,false,analysisPVLen,duplicateForSymmetries); filterZeroVisitMoves(args,buf); if(buf.size() > args.maxMoves) buf.resize(args.maxMoves); if(buf.size() <= 0) return; const Board board = search->getRootBoard(); for(int i = 0; i<buf.size(); i++) { if(i > 0) cout << " "; const AnalysisData& data = buf[i]; double winrate = 0.5 * (1.0 + data.winLossValue); double lcb = PlayUtils::getHackedLCBForWinrate(search,data,pla); if(perspective == P_BLACK || (perspective != P_BLACK && perspective != P_WHITE && pla == P_BLACK)) { winrate = 1.0-winrate; lcb = 1.0 - lcb; } cout << "info"; cout << " move " << Location::toString(data.move,board); cout << " visits " << data.numVisits; cout << " winrate " << round(winrate * 10000.0); cout << " prior " << round(data.policyPrior * 10000.0); cout << " lcb " << round(lcb * 10000.0); cout << " order " << data.order; cout << " pv "; if(preventEncore && data.pvContainsPass()) data.writePVUpToPhaseEnd(cout,board,search->getRootHist(),search->getRootPla()); else data.writePV(cout,board); if(args.showPVVisits) { cout << " pvVisits "; if(preventEncore && data.pvContainsPass()) data.writePVVisitsUpToPhaseEnd(cout,board,search->getRootHist(),search->getRootPla()); else data.writePVVisits(cout); } } cout << endl; }; } //kata-analyze, analyze (sabaki) else { callback = [args,pla,this](const Search* search) { vector<AnalysisData> buf; bool duplicateForSymmetries = true; search->getAnalysisData(buf,args.minMoves,false,analysisPVLen,duplicateForSymmetries); filterZeroVisitMoves(args,buf); if(buf.size() > args.maxMoves) buf.resize(args.maxMoves); if(buf.size() <= 0) return; vector<double> ownership, ownershipStdev; if(args.showOwnershipStdev) { static constexpr int64_t ownershipStdevMinVisits = 3; tuple<vector<double>,vector<double>> ownershipAverageAndStdev; ownershipAverageAndStdev = search->getAverageAndStandardDeviationTreeOwnership(ownershipStdevMinVisits); ownership = std::get<0>(ownershipAverageAndStdev); ownershipStdev = std::get<1>(ownershipAverageAndStdev); } else if(args.showOwnership) { static constexpr int64_t ownershipMinVisits = 3; ownership = search->getAverageTreeOwnership(ownershipMinVisits); } ostringstream out; if(!args.kata) { //Hack for sabaki - ensure always showing decimal point. Also causes output to be more verbose with trailing zeros, //unfortunately, despite doing not improving the precision of the values. out << std::showpoint; } const Board board = search->getRootBoard(); for(int i = 0; i<buf.size(); i++) { if(i > 0) out << " "; const AnalysisData& data = buf[i]; double winrate = 0.5 * (1.0 + data.winLossValue); double utility = data.utility; //We still hack the LCB for consistency with LZ-analyze double lcb = PlayUtils::getHackedLCBForWinrate(search,data,pla); ///But now we also offer the proper LCB that KataGo actually uses. double utilityLcb = data.lcb; double scoreMean = data.scoreMean; double lead = data.lead; if(perspective == P_BLACK || (perspective != P_BLACK && perspective != P_WHITE && pla == P_BLACK)) { winrate = 1.0-winrate; lcb = 1.0 - lcb; utility = -utility; scoreMean = -scoreMean; lead = -lead; utilityLcb = -utilityLcb; } out << "info"; out << " move " << Location::toString(data.move,board); out << " visits " << data.numVisits; out << " utility " << utility; out << " winrate " << winrate; out << " scoreMean " << lead; out << " scoreStdev " << data.scoreStdev; out << " scoreLead " << lead; out << " scoreSelfplay " << scoreMean; out << " prior " << data.policyPrior; out << " lcb " << lcb; out << " utilityLcb " << utilityLcb; if(data.isSymmetryOf != Board::NULL_LOC) out << " isSymmetryOf " << Location::toString(data.isSymmetryOf,board); out << " order " << data.order; out << " pv "; if(preventEncore && data.pvContainsPass()) data.writePVUpToPhaseEnd(out,board,search->getRootHist(),search->getRootPla()); else data.writePV(out,board); if(args.showPVVisits) { out << " pvVisits "; if(preventEncore && data.pvContainsPass()) data.writePVVisitsUpToPhaseEnd(out,board,search->getRootHist(),search->getRootPla()); else data.writePVVisits(out); } } if(args.showOwnership) { out << " "; out << "ownership"; int nnXLen = search->nnXLen; for(int y = 0; y<board.y_size; y++) { for(int x = 0; x<board.x_size; x++) { int pos = NNPos::xyToPos(x,y,nnXLen); if(perspective == P_BLACK || (perspective != P_BLACK && perspective != P_WHITE && pla == P_BLACK)) out << " " << -ownership[pos]; else out << " " << ownership[pos]; } } } if(args.showOwnershipStdev) { out << " "; out << "ownershipStdev"; int nnXLen = search->nnXLen; for(int y = 0; y<board.y_size; y++) { for(int x = 0; x<board.x_size; x++) { int pos = NNPos::xyToPos(x,y,nnXLen); out << " " << ownershipStdev[pos]; } } } cout << out.str() << endl; }; } return callback; } void genMove( Player pla, Logger& logger, double searchFactorWhenWinningThreshold, double searchFactorWhenWinning, enabled_t cleanupBeforePass, enabled_t friendlyPass, bool ogsChatToStderr, bool allowResignation, double resignThreshold, int resignConsecTurns, double resignMinScoreDifference, bool logSearchInfo, bool debug, bool playChosenMove, string& response, bool& responseIsError, bool& maybeStartPondering, AnalyzeArgs args ) { ClockTimer timer; response = ""; responseIsError = false; maybeStartPondering = false; nnEval->clearStats(); TimeControls tc = pla == P_BLACK ? bTimeControls : wTimeControls; //Update dynamic PDA given whatever the most recent values are, if we're using dynamic updateDynamicPDA(); //Make sure we have the right parameters, in case someone ran analysis in the meantime. if(staticPDATakesPrecedence) { if(params.playoutDoublingAdvantage != staticPlayoutDoublingAdvantage) { params.playoutDoublingAdvantage = staticPlayoutDoublingAdvantage; bot->setParams(params); } } else { double desiredDynamicPDA = (params.playoutDoublingAdvantagePla == P_WHITE) ? desiredDynamicPDAForWhite : (params.playoutDoublingAdvantagePla == P_BLACK) ? -desiredDynamicPDAForWhite : (params.playoutDoublingAdvantagePla == C_EMPTY && pla == P_WHITE) ? desiredDynamicPDAForWhite : (params.playoutDoublingAdvantagePla == C_EMPTY && pla == P_BLACK) ? -desiredDynamicPDAForWhite : (assert(false),0.0); if(params.playoutDoublingAdvantage != desiredDynamicPDA) { params.playoutDoublingAdvantage = desiredDynamicPDA; bot->setParams(params); } } Player avoidMYTDaggerHackPla = avoidMYTDaggerHack ? pla : C_EMPTY; if(params.avoidMYTDaggerHackPla != avoidMYTDaggerHackPla) { params.avoidMYTDaggerHackPla = avoidMYTDaggerHackPla; bot->setParams(params); } if(params.wideRootNoise != genmoveWideRootNoise) { params.wideRootNoise = genmoveWideRootNoise; bot->setParams(params); } if(params.antiMirror != genmoveAntiMirror) { params.antiMirror = genmoveAntiMirror; bot->setParams(params); } { double avoidRepeatedPatternUtility = normalAvoidRepeatedPatternUtility; if(!args.analyzing) { double initialOppAdvantage = initialBlackAdvantage(bot->getRootHist()) * (pla == P_WHITE ? 1 : -1); if(initialOppAdvantage > getPointsThresholdForHandicapGame(getBoardSizeScaling(bot->getRootBoard()))) avoidRepeatedPatternUtility = handicapAvoidRepeatedPatternUtility; } if(params.avoidRepeatedPatternUtility != avoidRepeatedPatternUtility) { params.avoidRepeatedPatternUtility = avoidRepeatedPatternUtility; bot->setParams(params); } } //Play faster when winning double searchFactor = PlayUtils::getSearchFactor(searchFactorWhenWinningThreshold,searchFactorWhenWinning,params,recentWinLossValues,pla); lastSearchFactor = searchFactor; Loc moveLoc; bot->setAvoidMoveUntilByLoc(args.avoidMoveUntilByLocBlack,args.avoidMoveUntilByLocWhite); if(args.analyzing) { std::function<void(const Search* search)> callback = getAnalyzeCallback(pla,args); if(args.showOwnership || args.showOwnershipStdev) bot->setAlwaysIncludeOwnerMap(true); else bot->setAlwaysIncludeOwnerMap(false); moveLoc = bot->genMoveSynchronousAnalyze(pla, tc, searchFactor, args.secondsPerReport, callback); //Make sure callback happens at least once callback(bot->getSearch()); } else { moveLoc = bot->genMoveSynchronous(pla,tc,searchFactor); } bool isLegal = bot->isLegalStrict(moveLoc,pla); if(moveLoc == Board::NULL_LOC || !isLegal) { responseIsError = true; response = "genmove returned null location or illegal move"; ostringstream sout; sout << "genmove null location or illegal move!?!" << "\n"; sout << bot->getRootBoard() << "\n"; sout << "Pla: " << PlayerIO::playerToString(pla) << "\n"; sout << "MoveLoc: " << Location::toString(moveLoc,bot->getRootBoard()) << "\n"; logger.write(sout.str()); genmoveTimeSum += timer.getSeconds(); return; } ReportedSearchValues values; double winLossValue; double lead; { values = bot->getSearch()->getRootValuesRequireSuccess(); winLossValue = values.winLossValue; lead = values.lead; } //Record data for resignation or adjusting handicap behavior ------------------------ recentWinLossValues.push_back(winLossValue); //Decide whether we should resign--------------------- bool resigned = allowResignation && shouldResign( bot->getRootBoard(),bot->getRootHist(),pla,recentWinLossValues,lead, resignThreshold,resignConsecTurns,resignMinScoreDifference ); //Snapshot the time NOW - all meaningful play-related computation time is done, the rest is just //output of various things. double timeTaken = timer.getSeconds(); genmoveTimeSum += timeTaken; //Chatting and logging ---------------------------- if(ogsChatToStderr) { int64_t visits = bot->getSearch()->getRootVisits(); double winrate = 0.5 * (1.0 + (values.winValue - values.lossValue)); double leadForPrinting = lead; //Print winrate from desired perspective if(perspective == P_BLACK || (perspective != P_BLACK && perspective != P_WHITE && pla == P_BLACK)) { winrate = 1.0 - winrate; leadForPrinting = -leadForPrinting; } cerr << "CHAT:" << "Visits " << visits << " Winrate " << Global::strprintf("%.2f%%", winrate * 100.0) << " ScoreLead " << Global::strprintf("%.1f", leadForPrinting) << " ScoreStdev " << Global::strprintf("%.1f", values.expectedScoreStdev); if(params.playoutDoublingAdvantage != 0.0) { cerr << Global::strprintf( " (PDA %.2f)", bot->getSearch()->getRootPla() == getOpp(params.playoutDoublingAdvantagePla) ? -params.playoutDoublingAdvantage : params.playoutDoublingAdvantage); } cerr << " PV "; bot->getSearch()->printPVForMove(cerr,bot->getSearch()->rootNode, moveLoc, analysisPVLen); cerr << endl; } if(logSearchInfo) { ostringstream sout; PlayUtils::printGenmoveLog(sout,bot,nnEval,moveLoc,timeTaken,perspective); logger.write(sout.str()); } if(debug) { PlayUtils::printGenmoveLog(cerr,bot,nnEval,moveLoc,timeTaken,perspective); } //Hacks-------------------------------------------------- //At least one of these hacks will use the bot to search stuff and clears its tree, so we apply them AFTER //all relevant logging and stuff. //Implement friendly pass - in area scoring rules other than tromp-taylor, maybe pass once there are no points //left to gain. int64_t numVisitsForFriendlyPass = 8 + std::min((int64_t)1000, std::min(params.maxVisits, params.maxPlayouts) / 10); moveLoc = PlayUtils::maybeFriendlyPass(cleanupBeforePass, friendlyPass, pla, moveLoc, bot->getSearchStopAndWait(), numVisitsForFriendlyPass); //Implement cleanupBeforePass hack - if the bot wants to pass, instead cleanup if there is something to clean //and we are in a ruleset where this is necessary or the user has configured it. moveLoc = PlayUtils::maybeCleanupBeforePass(cleanupBeforePass, friendlyPass, pla, moveLoc, bot); //Actual reporting of chosen move--------------------- if(resigned) response = "resign"; else response = Location::toString(moveLoc,bot->getRootBoard()); if(!resigned && moveLoc != Board::NULL_LOC && isLegal && playChosenMove) { bool suc = bot->makeMove(moveLoc,pla,preventEncore); if(suc) moveHistory.push_back(Move(moveLoc,pla)); assert(suc); (void)suc; //Avoid warning when asserts are off maybeStartPondering = true; } if(args.analyzing) { response = "play " + response; } return; } void clearCache() { bot->clearSearch(); nnEval->clearCache(); } void placeFixedHandicap(int n, string& response, bool& responseIsError) { int xSize = bot->getRootBoard().x_size; int ySize = bot->getRootBoard().y_size; Board board(xSize,ySize); try { PlayUtils::placeFixedHandicap(board,n); } catch(const StringError& e) { responseIsError = true; response = string(e.what()) + ", try place_free_handicap"; return; } assert(bot->getRootHist().rules == currentRules); Player pla = P_BLACK; BoardHistory hist(board,pla,currentRules,0); //Also switch the initial player, expecting white should be next. hist.clear(board,P_WHITE,currentRules,0); hist.setAssumeMultipleStartingBlackMovesAreHandicap(assumeMultipleStartingBlackMovesAreHandicap); hist.setInitialTurnNumber(board.numStonesOnBoard()); //Should give more accurate temperaure and time control behavior pla = P_WHITE; response = ""; for(int y = 0; y<board.y_size; y++) { for(int x = 0; x<board.x_size; x++) { Loc loc = Location::getLoc(x,y,board.x_size); if(board.colors[loc] != C_EMPTY) { response += " " + Location::toString(loc,board); } } } response = Global::trim(response); (void)responseIsError; vector<Move> newMoveHistory; setPositionAndRules(pla,board,hist,board,pla,newMoveHistory); clearStatsForNewGame(); } void placeFreeHandicap(int n, string& response, bool& responseIsError, Rand& rand) { stopAndWait(); //If asked to place more, we just go ahead and only place up to 30, or a quarter of the board int xSize = bot->getRootBoard().x_size; int ySize = bot->getRootBoard().y_size; int maxHandicap = xSize*ySize / 4; if(maxHandicap > 30) maxHandicap = 30; if(n > maxHandicap) n = maxHandicap; assert(bot->getRootHist().rules == currentRules); Board board(xSize,ySize); Player pla = P_BLACK; BoardHistory hist(board,pla,currentRules,0); double extraBlackTemperature = 0.25; PlayUtils::playExtraBlack(bot->getSearchStopAndWait(), n, board, hist, extraBlackTemperature, rand); //Also switch the initial player, expecting white should be next. hist.clear(board,P_WHITE,currentRules,0); hist.setAssumeMultipleStartingBlackMovesAreHandicap(assumeMultipleStartingBlackMovesAreHandicap); hist.setInitialTurnNumber(board.numStonesOnBoard()); //Should give more accurate temperaure and time control behavior pla = P_WHITE; response = ""; for(int y = 0; y<board.y_size; y++) { for(int x = 0; x<board.x_size; x++) { Loc loc = Location::getLoc(x,y,board.x_size); if(board.colors[loc] != C_EMPTY) { response += " " + Location::toString(loc,board); } } } response = Global::trim(response); (void)responseIsError; vector<Move> newMoveHistory; setPositionAndRules(pla,board,hist,board,pla,newMoveHistory); clearStatsForNewGame(); } void analyze(Player pla, AnalyzeArgs args) { assert(args.analyzing); //Analysis should ALWAYS be with the static value to prevent random hard-to-predict changes //for users. if(params.playoutDoublingAdvantage != staticPlayoutDoublingAdvantage) { params.playoutDoublingAdvantage = staticPlayoutDoublingAdvantage; bot->setParams(params); } if(params.avoidMYTDaggerHackPla != C_EMPTY) { params.avoidMYTDaggerHackPla = C_EMPTY; bot->setParams(params); } //Also wide root, if desired if(params.wideRootNoise != analysisWideRootNoise) { params.wideRootNoise = analysisWideRootNoise; bot->setParams(params); } if(params.antiMirror != analysisAntiMirror) { params.antiMirror = analysisAntiMirror; bot->setParams(params); } std::function<void(const Search* search)> callback = getAnalyzeCallback(pla,args); bot->setAvoidMoveUntilByLoc(args.avoidMoveUntilByLocBlack,args.avoidMoveUntilByLocWhite); if(args.showOwnership || args.showOwnershipStdev) bot->setAlwaysIncludeOwnerMap(true); else bot->setAlwaysIncludeOwnerMap(false); double searchFactor = 1e40; //go basically forever bot->analyzeAsync(pla, searchFactor, args.secondsPerReport, callback); } void computeAnticipatedWinnerAndScore(Player& winner, double& finalWhiteMinusBlackScore) { stopAndWait(); //No playoutDoublingAdvantage to avoid bias //Also never assume the game will end abruptly due to pass { SearchParams tmpParams = params; tmpParams.playoutDoublingAdvantage = 0.0; tmpParams.conservativePass = true; bot->setParams(tmpParams); } //Make absolutely sure we can restore the bot's old state const Player oldPla = bot->getRootPla(); const Board oldBoard = bot->getRootBoard(); const BoardHistory oldHist = bot->getRootHist(); Board board = bot->getRootBoard(); BoardHistory hist = bot->getRootHist(); Player pla = bot->getRootPla(); //Tromp-taylorish scoring, or finished territory game scoring (including noresult) if(hist.isGameFinished && ( (hist.rules.scoringRule == Rules::SCORING_AREA && !hist.rules.friendlyPassOk) || (hist.rules.scoringRule == Rules::SCORING_TERRITORY) ) ) { //For GTP purposes, we treat noResult as a draw since there is no provision for anything else. winner = hist.winner; finalWhiteMinusBlackScore = hist.finalWhiteMinusBlackScore; } //Human-friendly score or incomplete game score estimation else { int64_t numVisits = std::max(50, params.numThreads * 10); //Try computing the lead for white double lead = PlayUtils::computeLead(bot->getSearchStopAndWait(),NULL,board,hist,pla,numVisits,OtherGameProperties()); //Round lead to nearest integer or half-integer if(hist.rules.gameResultWillBeInteger()) lead = round(lead); else lead = round(lead+0.5)-0.5; finalWhiteMinusBlackScore = lead; winner = lead > 0 ? P_WHITE : lead < 0 ? P_BLACK : C_EMPTY; } //Restore bot->setPosition(oldPla,oldBoard,oldHist); bot->setParams(params); } vector<bool> computeAnticipatedStatuses() { stopAndWait(); //Make absolutely sure we can restore the bot's old state const Player oldPla = bot->getRootPla(); const Board oldBoard = bot->getRootBoard(); const BoardHistory oldHist = bot->getRootHist(); Board board = bot->getRootBoard(); BoardHistory hist = bot->getRootHist(); Player pla = bot->getRootPla(); int64_t numVisits = std::max(100, params.numThreads * 20); vector<bool> isAlive; //Tromp-taylorish statuses, or finished territory game statuses (including noresult) if(hist.isGameFinished && ( (hist.rules.scoringRule == Rules::SCORING_AREA && !hist.rules.friendlyPassOk) || (hist.rules.scoringRule == Rules::SCORING_TERRITORY) ) ) isAlive = PlayUtils::computeAnticipatedStatusesSimple(board,hist); //Human-friendly statuses or incomplete game status estimation else { vector<double> ownershipsBuf; isAlive = PlayUtils::computeAnticipatedStatusesWithOwnership(bot->getSearchStopAndWait(),board,hist,pla,numVisits,ownershipsBuf); } //Restore bot->setPosition(oldPla,oldBoard,oldHist); return isAlive; } string rawNN(int whichSymmetry) { if(nnEval == NULL) return ""; ostringstream out; for(int symmetry = 0; symmetry < SymmetryHelpers::NUM_SYMMETRIES; symmetry++) { if(whichSymmetry == NNInputs::SYMMETRY_ALL || whichSymmetry == symmetry) { Board board = bot->getRootBoard(); BoardHistory hist = bot->getRootHist(); Player nextPla = bot->getRootPla(); MiscNNInputParams nnInputParams; nnInputParams.playoutDoublingAdvantage = (params.playoutDoublingAdvantagePla == C_EMPTY || params.playoutDoublingAdvantagePla == nextPla) ? staticPlayoutDoublingAdvantage : -staticPlayoutDoublingAdvantage; nnInputParams.symmetry = symmetry; NNResultBuf buf; bool skipCache = true; bool includeOwnerMap = true; nnEval->evaluate(board,hist,nextPla,nnInputParams,buf,skipCache,includeOwnerMap); NNOutput* nnOutput = buf.result.get(); out << "symmetry " << symmetry << endl; out << "whiteWin " << Global::strprintf("%.6f",nnOutput->whiteWinProb) << endl; out << "whiteLoss " << Global::strprintf("%.6f",nnOutput->whiteLossProb) << endl; out << "noResult " << Global::strprintf("%.6f",nnOutput->whiteNoResultProb) << endl; out << "whiteLead " << Global::strprintf("%.3f",nnOutput->whiteLead) << endl; out << "whiteScoreSelfplay " << Global::strprintf("%.3f",nnOutput->whiteScoreMean) << endl; out << "whiteScoreSelfplaySq " << Global::strprintf("%.3f",nnOutput->whiteScoreMeanSq) << endl; out << "varTimeLeft " << Global::strprintf("%.3f",nnOutput->varTimeLeft) << endl; out << "shorttermWinlossError " << Global::strprintf("%.3f",nnOutput->shorttermWinlossError) << endl; out << "shorttermScoreError " << Global::strprintf("%.3f",nnOutput->shorttermScoreError) << endl; out << "policy" << endl; for(int y = 0; y<board.y_size; y++) { for(int x = 0; x<board.x_size; x++) { int pos = NNPos::xyToPos(x,y,nnOutput->nnXLen); float prob = nnOutput->policyProbs[pos]; if(prob < 0) out << " NAN "; else out << Global::strprintf("%8.6f ", prob); } out << endl; } out << "policyPass "; { int pos = NNPos::locToPos(Board::PASS_LOC,board.x_size,nnOutput->nnXLen,nnOutput->nnYLen); float prob = nnOutput->policyProbs[pos]; if(prob < 0) out << " NAN "; // Probably shouldn't ever happen for pass unles the rules change, but we handle it anyways else out << Global::strprintf("%8.6f ", prob); out << endl; } out << "whiteOwnership" << endl; for(int y = 0; y<board.y_size; y++) { for(int x = 0; x<board.x_size; x++) { int pos = NNPos::xyToPos(x,y,nnOutput->nnXLen); float whiteOwn = nnOutput->whiteOwnerMap[pos]; out << Global::strprintf("%9.7f ", whiteOwn); } out << endl; } out << endl; } } return Global::trim(out.str()); } SearchParams getParams() { return params; } void setParams(SearchParams p) { params = p; bot->setParams(params); } }; //User should pre-fill pla with a default value, as it will not get filled in if the parsed command doesn't specify static GTPEngine::AnalyzeArgs parseAnalyzeCommand( const string& command, const vector<string>& pieces, Player& pla, bool& parseFailed, GTPEngine* engine ) { int numArgsParsed = 0; bool isLZ = (command == "lz-analyze" || command == "lz-genmove_analyze"); bool isKata = (command == "kata-analyze" || command == "kata-genmove_analyze"); double lzAnalyzeInterval = TimeControls::UNLIMITED_TIME_DEFAULT; int minMoves = 0; int maxMoves = 10000000; bool showOwnership = false; bool showOwnershipStdev = false; bool showPVVisits = false; vector<int> avoidMoveUntilByLocBlack; vector<int> avoidMoveUntilByLocWhite; bool gotAvoidMovesBlack = false; bool gotAllowMovesBlack = false; bool gotAvoidMovesWhite = false; bool gotAllowMovesWhite = false; parseFailed = false; //Format: //lz-analyze [optional player] [optional interval float] <keys and values> //Keys and values consists of zero or more of: //interval <float interval in centiseconds> //avoid <player> <comma-separated moves> <until movenum> //minmoves <int min number of moves to show> //maxmoves <int max number of moves to show> //ownership <bool whether to show ownership or not> //ownershipStdev <bool whether to show ownershipStdev or not> //pvVisits <bool whether to show pvVisits or not> //Parse optional player if(pieces.size() > numArgsParsed && PlayerIO::tryParsePlayer(pieces[numArgsParsed],pla)) numArgsParsed += 1; //Parse optional interval float if(pieces.size() > numArgsParsed && Global::tryStringToDouble(pieces[numArgsParsed],lzAnalyzeInterval) && !isnan(lzAnalyzeInterval) && lzAnalyzeInterval >= 0 && lzAnalyzeInterval < TimeControls::MAX_USER_INPUT_TIME) numArgsParsed += 1; //Now loop and handle all key value pairs while(pieces.size() > numArgsParsed) { const string& key = pieces[numArgsParsed]; numArgsParsed += 1; //Make sure we have a value. If not, then we fail. if(pieces.size() <= numArgsParsed) { parseFailed = true; break; } const string& value = pieces[numArgsParsed]; numArgsParsed += 1; if(key == "interval" && Global::tryStringToDouble(value,lzAnalyzeInterval) && !isnan(lzAnalyzeInterval) && lzAnalyzeInterval >= 0 && lzAnalyzeInterval < TimeControls::MAX_USER_INPUT_TIME) { continue; } else if(key == "avoid" || key == "allow") { //Parse two more arguments if(pieces.size() < numArgsParsed+2) { parseFailed = true; break; } const string& movesStr = pieces[numArgsParsed]; numArgsParsed += 1; const string& untilDepthStr = pieces[numArgsParsed]; numArgsParsed += 1; int untilDepth = -1; if(!Global::tryStringToInt(untilDepthStr,untilDepth) || untilDepth < 1) { parseFailed = true; break; } Player avoidPla = C_EMPTY; if(!PlayerIO::tryParsePlayer(value,avoidPla)) { parseFailed = true; break; } vector<Loc> parsedLocs; vector<string> locPieces = Global::split(movesStr,','); for(size_t i = 0; i<locPieces.size(); i++) { string s = Global::trim(locPieces[i]); if(s.size() <= 0) continue; Loc loc; if(!tryParseLoc(s,engine->bot->getRootBoard(),loc)) { parseFailed = true; break; } parsedLocs.push_back(loc); } if(parseFailed) break; //Make sure the same analyze command can't specify both avoid and allow, and allow at most one allow. vector<int>& avoidMoveUntilByLoc = avoidPla == P_BLACK ? avoidMoveUntilByLocBlack : avoidMoveUntilByLocWhite; bool& gotAvoidMoves = avoidPla == P_BLACK ? gotAvoidMovesBlack : gotAvoidMovesWhite; bool& gotAllowMoves = avoidPla == P_BLACK ? gotAllowMovesBlack : gotAllowMovesWhite; if((key == "allow" && gotAvoidMoves) || (key == "allow" && gotAllowMoves) || (key == "avoid" && gotAllowMoves)) { parseFailed = true; break; } avoidMoveUntilByLoc.resize(Board::MAX_ARR_SIZE); if(key == "allow") { std::fill(avoidMoveUntilByLoc.begin(),avoidMoveUntilByLoc.end(),untilDepth); for(Loc loc: parsedLocs) { avoidMoveUntilByLoc[loc] = 0; } } else { for(Loc loc: parsedLocs) { avoidMoveUntilByLoc[loc] = untilDepth; } } gotAvoidMoves |= (key == "avoid"); gotAllowMoves |= (key == "allow"); continue; } else if(key == "minmoves" && Global::tryStringToInt(value,minMoves) && minMoves >= 0 && minMoves < 1000000000) { continue; } else if(key == "maxmoves" && Global::tryStringToInt(value,maxMoves) && maxMoves >= 0 && maxMoves < 1000000000) { continue; } else if(isKata && key == "ownership" && Global::tryStringToBool(value,showOwnership)) { continue; } else if(isKata && key == "ownershipStdev" && Global::tryStringToBool(value,showOwnershipStdev)) { continue; } else if(isKata && key == "pvVisits" && Global::tryStringToBool(value,showPVVisits)) { continue; } parseFailed = true; break; } GTPEngine::AnalyzeArgs args = GTPEngine::AnalyzeArgs(); args.analyzing = true; args.lz = isLZ; args.kata = isKata; //Convert from centiseconds to seconds args.secondsPerReport = lzAnalyzeInterval * 0.01; args.minMoves = minMoves; args.maxMoves = maxMoves; args.showOwnership = showOwnership; args.showOwnershipStdev = showOwnershipStdev; args.showPVVisits = showPVVisits; args.avoidMoveUntilByLocBlack = avoidMoveUntilByLocBlack; args.avoidMoveUntilByLocWhite = avoidMoveUntilByLocWhite; return args; } int MainCmds::gtp(const vector<string>& args) { Board::initHash(); ScoreValue::initTables(); Rand seedRand; ConfigParser cfg; string nnModelFile; string overrideVersion; KataGoCommandLine cmd("Run KataGo main GTP engine for playing games or casual analysis."); try { cmd.addConfigFileArg(KataGoCommandLine::defaultGtpConfigFileName(),"gtp_example.cfg"); cmd.addModelFileArg(); cmd.setShortUsageArgLimit(); cmd.addOverrideConfigArg(); TCLAP::ValueArg<string> overrideVersionArg("","override-version","Force KataGo to say a certain value in response to gtp version command",false,string(),"VERSION"); cmd.add(overrideVersionArg); cmd.parseArgs(args); nnModelFile = cmd.getModelFile(); overrideVersion = overrideVersionArg.getValue(); cmd.getConfig(cfg); } catch (TCLAP::ArgException &e) { cerr << "Error: " << e.error() << " for argument " << e.argId() << endl; return 1; } Logger logger; if(cfg.contains("logFile") && cfg.contains("logDir")) throw StringError("Cannot specify both logFile and logDir in config"); else if(cfg.contains("logFile")) logger.addFile(cfg.getString("logFile")); else if(cfg.contains("logDir")) { MakeDir::make(cfg.getString("logDir")); Rand rand; logger.addFile(cfg.getString("logDir") + "/" + DateTime::getCompactDateTimeString() + "-" + Global::uint32ToHexString(rand.nextUInt()) + ".log"); } const bool logAllGTPCommunication = cfg.getBool("logAllGTPCommunication"); const bool logSearchInfo = cfg.getBool("logSearchInfo"); bool loggingToStderr = false; const bool logTimeStamp = cfg.contains("logTimeStamp") ? cfg.getBool("logTimeStamp") : true; if(!logTimeStamp) logger.setLogTime(false); bool startupPrintMessageToStderr = true; if(cfg.contains("startupPrintMessageToStderr")) startupPrintMessageToStderr = cfg.getBool("startupPrintMessageToStderr"); if(cfg.contains("logToStderr") && cfg.getBool("logToStderr")) { loggingToStderr = true; logger.setLogToStderr(true); } logger.write("GTP Engine starting..."); logger.write(Version::getKataGoVersionForHelp()); //Also check loggingToStderr so that we don't duplicate the message from the log file if(startupPrintMessageToStderr && !loggingToStderr) { cerr << Version::getKataGoVersionForHelp() << endl; } //Defaults to 7.5 komi, gtp will generally override this const bool loadKomiFromCfg = false; Rules initialRules = Setup::loadSingleRules(cfg,loadKomiFromCfg); logger.write("Using " + initialRules.toStringNoKomiMaybeNice() + " rules initially, unless GTP/GUI overrides this"); if(startupPrintMessageToStderr && !loggingToStderr) { cerr << "Using " + initialRules.toStringNoKomiMaybeNice() + " rules initially, unless GTP/GUI overrides this" << endl; } bool isForcingKomi = false; float forcedKomi = 0; if(cfg.contains("ignoreGTPAndForceKomi")) { isForcingKomi = true; forcedKomi = cfg.getFloat("ignoreGTPAndForceKomi", Rules::MIN_USER_KOMI, Rules::MAX_USER_KOMI); initialRules.komi = forcedKomi; } SearchParams initialParams = Setup::loadSingleParams(cfg,Setup::SETUP_FOR_GTP); logger.write("Using " + Global::intToString(initialParams.numThreads) + " CPU thread(s) for search"); //Set a default for conservativePass that differs from matches or selfplay if(!cfg.contains("conservativePass") && !cfg.contains("conservativePass0")) initialParams.conservativePass = true; if(!cfg.contains("fillDameBeforePass") && !cfg.contains("fillDameBeforePass0")) initialParams.fillDameBeforePass = true; const bool ponderingEnabled = cfg.getBool("ponderingEnabled"); const enabled_t cleanupBeforePass = cfg.contains("cleanupBeforePass") ? cfg.getEnabled("cleanupBeforePass") : enabled_t::Auto; const enabled_t friendlyPass = cfg.contains("friendlyPass") ? cfg.getEnabled("friendlyPass") : enabled_t::Auto; if(cleanupBeforePass == enabled_t::True && friendlyPass == enabled_t::True) throw StringError("Cannot specify both cleanupBeforePass = true and friendlyPass = true at the same time"); const bool allowResignation = cfg.contains("allowResignation") ? cfg.getBool("allowResignation") : false; const double resignThreshold = cfg.contains("allowResignation") ? cfg.getDouble("resignThreshold",-1.0,0.0) : -1.0; //Threshold on [-1,1], regardless of winLossUtilityFactor const int resignConsecTurns = cfg.contains("resignConsecTurns") ? cfg.getInt("resignConsecTurns",1,100) : 3; const double resignMinScoreDifference = cfg.contains("resignMinScoreDifference") ? cfg.getDouble("resignMinScoreDifference",0.0,1000.0) : -1e10; Setup::initializeSession(cfg); const double searchFactorWhenWinning = cfg.contains("searchFactorWhenWinning") ? cfg.getDouble("searchFactorWhenWinning",0.01,1.0) : 1.0; const double searchFactorWhenWinningThreshold = cfg.contains("searchFactorWhenWinningThreshold") ? cfg.getDouble("searchFactorWhenWinningThreshold",0.0,1.0) : 1.0; const bool ogsChatToStderr = cfg.contains("ogsChatToStderr") ? cfg.getBool("ogsChatToStderr") : false; const int analysisPVLen = cfg.contains("analysisPVLen") ? cfg.getInt("analysisPVLen",1,1000) : 13; const bool assumeMultipleStartingBlackMovesAreHandicap = cfg.contains("assumeMultipleStartingBlackMovesAreHandicap") ? cfg.getBool("assumeMultipleStartingBlackMovesAreHandicap") : true; const bool preventEncore = cfg.contains("preventCleanupPhase") ? cfg.getBool("preventCleanupPhase") : true; const double dynamicPlayoutDoublingAdvantageCapPerOppLead = cfg.contains("dynamicPlayoutDoublingAdvantageCapPerOppLead") ? cfg.getDouble("dynamicPlayoutDoublingAdvantageCapPerOppLead",0.0,0.5) : 0.045; double staticPlayoutDoublingAdvantage = initialParams.playoutDoublingAdvantage; const bool staticPDATakesPrecedence = cfg.contains("playoutDoublingAdvantage") && !cfg.contains("dynamicPlayoutDoublingAdvantageCapPerOppLead"); const bool avoidMYTDaggerHack = cfg.contains("avoidMYTDaggerHack") ? cfg.getBool("avoidMYTDaggerHack") : false; const double normalAvoidRepeatedPatternUtility = initialParams.avoidRepeatedPatternUtility; const double handicapAvoidRepeatedPatternUtility = (cfg.contains("avoidRepeatedPatternUtility") || cfg.contains("avoidRepeatedPatternUtility0")) ? initialParams.avoidRepeatedPatternUtility : 0.005; int defaultBoardXSize = -1; int defaultBoardYSize = -1; Setup::loadDefaultBoardXYSize(cfg,logger,defaultBoardXSize,defaultBoardYSize); const bool forDeterministicTesting = cfg.contains("forDeterministicTesting") ? cfg.getBool("forDeterministicTesting") : false; if(forDeterministicTesting) seedRand.init("forDeterministicTesting"); const double genmoveWideRootNoise = initialParams.wideRootNoise; const double analysisWideRootNoise = cfg.contains("analysisWideRootNoise") ? cfg.getDouble("analysisWideRootNoise",0.0,5.0) : Setup::DEFAULT_ANALYSIS_WIDE_ROOT_NOISE; const bool analysisAntiMirror = initialParams.antiMirror; const bool genmoveAntiMirror = cfg.contains("genmoveAntiMirror") ? cfg.getBool("genmoveAntiMirror") : cfg.contains("antiMirror") ? cfg.getBool("antiMirror") : true; std::unique_ptr<PatternBonusTable> patternBonusTable = nullptr; { std::vector<std::unique_ptr<PatternBonusTable>> tables = Setup::loadAvoidSgfPatternBonusTables(cfg,logger); assert(tables.size() == 1); patternBonusTable = std::move(tables[0]); } Player perspective = Setup::parseReportAnalysisWinrates(cfg,C_EMPTY); GTPEngine* engine = new GTPEngine( nnModelFile,initialParams,initialRules, assumeMultipleStartingBlackMovesAreHandicap,preventEncore, dynamicPlayoutDoublingAdvantageCapPerOppLead, staticPlayoutDoublingAdvantage,staticPDATakesPrecedence, normalAvoidRepeatedPatternUtility, handicapAvoidRepeatedPatternUtility, avoidMYTDaggerHack, genmoveWideRootNoise,analysisWideRootNoise, genmoveAntiMirror,analysisAntiMirror, perspective,analysisPVLen, std::move(patternBonusTable) ); engine->setOrResetBoardSize(cfg,logger,seedRand,defaultBoardXSize,defaultBoardYSize,loggingToStderr); //If nobody specified any time limit in any way, then assume a relatively fast time control if(!cfg.contains("maxPlayouts") && !cfg.contains("maxVisits") && !cfg.contains("maxTime")) { double mainTime = 1.0; double byoYomiTime = 5.0; int byoYomiPeriods = 5; TimeControls tc = TimeControls::canadianOrByoYomiTime(mainTime,byoYomiTime,byoYomiPeriods,1); engine->bTimeControls = tc; engine->wTimeControls = tc; } //Check for unused config keys cfg.warnUnusedKeys(cerr,&logger); logger.write("Loaded config " + cfg.getFileName()); logger.write("Loaded model "+ nnModelFile); cmd.logOverrides(logger); logger.write("Model name: "+ (engine->nnEval == NULL ? string() : engine->nnEval->getInternalModelName())); logger.write("GTP ready, beginning main protocol loop"); //Also check loggingToStderr so that we don't duplicate the message from the log file if(startupPrintMessageToStderr && !loggingToStderr) { cerr << "Loaded config " << cfg.getFileName() << endl; cerr << "Loaded model " << nnModelFile << endl; cerr << "Model name: "+ (engine->nnEval == NULL ? string() : engine->nnEval->getInternalModelName()) << endl; cerr << "GTP ready, beginning main protocol loop" << endl; } bool currentlyAnalyzing = false; string line; while(getline(cin,line)) { //Parse command, extracting out the command itself, the arguments, and any GTP id number for the command. string command; vector<string> pieces; bool hasId = false; int id = 0; { //Filter down to only "normal" ascii characters. Also excludes carrage returns. //Newlines are already handled by getline size_t newLen = 0; for(size_t i = 0; i < line.length(); i++) if(((int)line[i] >= 32 && (int)line[i] <= 126) || line[i] == '\t') line[newLen++] = line[i]; line.erase(line.begin()+newLen, line.end()); //Remove comments size_t commentPos = line.find("#"); if(commentPos != string::npos) line = line.substr(0, commentPos); //Convert tabs to spaces for(size_t i = 0; i < line.length(); i++) if(line[i] == '\t') line[i] = ' '; line = Global::trim(line); //Upon any input line at all, stop any analysis and output a newline if(currentlyAnalyzing) { currentlyAnalyzing = false; engine->stopAndWait(); cout << endl; } if(line.length() == 0) continue; if(logAllGTPCommunication) logger.write("Controller: " + line); //Parse id number of command, if present size_t digitPrefixLen = 0; while(digitPrefixLen < line.length() && Global::isDigit(line[digitPrefixLen])) digitPrefixLen++; if(digitPrefixLen > 0) { hasId = true; try { id = Global::parseDigits(line,0,digitPrefixLen); } catch(const IOError& e) { cout << "? GTP id '" << id << "' could not be parsed: " << e.what() << endl; continue; } line = line.substr(digitPrefixLen); } line = Global::trim(line); if(line.length() <= 0) { cout << "? empty command" << endl; continue; } pieces = Global::split(line,' '); for(size_t i = 0; i<pieces.size(); i++) pieces[i] = Global::trim(pieces[i]); assert(pieces.size() > 0); command = pieces[0]; pieces.erase(pieces.begin()); } bool responseIsError = false; bool suppressResponse = false; bool shouldQuitAfterResponse = false; bool maybeStartPondering = false; string response; if(command == "protocol_version") { response = "2"; } else if(command == "name") { response = "KataGo"; } else if(command == "version") { if(overrideVersion.size() > 0) response = overrideVersion; else response = Version::getKataGoVersion(); } else if(command == "known_command") { if(pieces.size() != 1) { responseIsError = true; response = "Expected single argument for known_command but got '" + Global::concat(pieces," ") + "'"; } else { if(std::find(knownCommands.begin(), knownCommands.end(), pieces[0]) != knownCommands.end()) response = "true"; else response = "false"; } } else if(command == "list_commands") { for(size_t i = 0; i<knownCommands.size(); i++) { response += knownCommands[i]; if(i < knownCommands.size()-1) response += "\n"; } } else if(command == "quit") { shouldQuitAfterResponse = true; logger.write("Quit requested by controller"); } else if(command == "boardsize" || command == "rectangular_boardsize") { int newXSize = 0; int newYSize = 0; bool suc = false; if(pieces.size() == 1) { if(contains(pieces[0],':')) { vector<string> subpieces = Global::split(pieces[0],':'); if(subpieces.size() == 2 && Global::tryStringToInt(subpieces[0], newXSize) && Global::tryStringToInt(subpieces[1], newYSize)) suc = true; } else { if(Global::tryStringToInt(pieces[0], newXSize)) { suc = true; newYSize = newXSize; } } } else if(pieces.size() == 2) { if(Global::tryStringToInt(pieces[0], newXSize) && Global::tryStringToInt(pieces[1], newYSize)) suc = true; } if(!suc) { responseIsError = true; response = "Expected int argument for boardsize or pair of ints but got '" + Global::concat(pieces," ") + "'"; } else if(newXSize < 2 || newYSize < 2) { responseIsError = true; response = "unacceptable size"; } else if(newXSize > Board::MAX_LEN || newYSize > Board::MAX_LEN) { responseIsError = true; response = Global::strprintf("unacceptable size (Board::MAX_LEN is %d, consider increasing and recompiling)",(int)Board::MAX_LEN); } else { engine->setOrResetBoardSize(cfg,logger,seedRand,newXSize,newYSize,loggingToStderr); } } else if(command == "clear_board") { engine->clearBoard(); } else if(command == "komi") { float newKomi = 0; if(pieces.size() != 1 || !Global::tryStringToFloat(pieces[0],newKomi)) { responseIsError = true; response = "Expected single float argument for komi but got '" + Global::concat(pieces," ") + "'"; } //GTP spec says that we should accept any komi, but we're going to ignore that. else if(isnan(newKomi) || newKomi < Rules::MIN_USER_KOMI || newKomi > Rules::MAX_USER_KOMI) { responseIsError = true; response = "unacceptable komi"; } else if(!Rules::komiIsIntOrHalfInt(newKomi)) { responseIsError = true; response = "komi must be an integer or half-integer"; } else { if(isForcingKomi) newKomi = forcedKomi; engine->updateKomiIfNew(newKomi); //In case the controller tells us komi every move, restart pondering afterward. maybeStartPondering = engine->bot->getRootHist().moveHistory.size() > 0; } } else if(command == "get_komi") { response = Global::doubleToString(engine->getCurrentRules().komi); } else if(command == "kata-get-rules") { if(pieces.size() != 0) { response = "Expected no arguments for kata-get-rules but got '" + Global::concat(pieces," ") + "'"; } else { response = engine->getCurrentRules().toJsonStringNoKomi(); } } else if(command == "kata-set-rules") { string rest = Global::concat(pieces," "); bool parseSuccess = false; Rules newRules; try { newRules = Rules::parseRulesWithoutKomi(rest,engine->getCurrentRules().komi); parseSuccess = true; } catch(const StringError& err) { responseIsError = true; response = "Unknown rules '" + rest + "', " + err.what(); } if(parseSuccess) { string error; bool suc = engine->setRulesNotIncludingKomi(newRules,error); if(!suc) { responseIsError = true; response = error; } logger.write("Changed rules to " + newRules.toStringNoKomiMaybeNice()); if(!loggingToStderr) cerr << "Changed rules to " + newRules.toStringNoKomiMaybeNice() << endl; } } else if(command == "kata-set-rule") { if(pieces.size() != 2) { responseIsError = true; response = "Expected two arguments for kata-set-rule but got '" + Global::concat(pieces," ") + "'"; } else { bool parseSuccess = false; Rules currentRules = engine->getCurrentRules(); Rules newRules; try { newRules = Rules::updateRules(pieces[0], pieces[1], currentRules); parseSuccess = true; } catch(const StringError& err) { responseIsError = true; response = err.what(); } if(parseSuccess) { string error; bool suc = engine->setRulesNotIncludingKomi(newRules,error); if(!suc) { responseIsError = true; response = error; } logger.write("Changed rules to " + newRules.toStringNoKomiMaybeNice()); if(!loggingToStderr) cerr << "Changed rules to " + newRules.toStringNoKomiMaybeNice() << endl; } } } else if(command == "kgs-rules") { bool parseSuccess = false; Rules newRules; if(pieces.size() <= 0) { responseIsError = true; response = "Expected one argument kgs-rules"; } else { string s = Global::toLower(Global::trim(pieces[0])); if(s == "chinese") { newRules = Rules::parseRulesWithoutKomi("chinese-kgs",engine->getCurrentRules().komi); parseSuccess = true; } else if(s == "aga") { newRules = Rules::parseRulesWithoutKomi("aga",engine->getCurrentRules().komi); parseSuccess = true; } else if(s == "new_zealand") { newRules = Rules::parseRulesWithoutKomi("new_zealand",engine->getCurrentRules().komi); parseSuccess = true; } else if(s == "japanese") { newRules = Rules::parseRulesWithoutKomi("japanese",engine->getCurrentRules().komi); parseSuccess = true; } else { responseIsError = true; response = "Unknown rules '" + s + "'"; } } if(parseSuccess) { string error; bool suc = engine->setRulesNotIncludingKomi(newRules,error); if(!suc) { responseIsError = true; response = error; } logger.write("Changed rules to " + newRules.toStringNoKomiMaybeNice()); if(!loggingToStderr) cerr << "Changed rules to " + newRules.toStringNoKomiMaybeNice() << endl; } } else if(command == "kata-list-params") { //For now, rootPolicyTemperature is hidden since it's not clear we want to support it response = "playoutDoublingAdvantage analysisWideRootNoise"; } else if(command == "kata-get-param") { if(pieces.size() != 1) { responseIsError = true; response = "Expected one arguments for kata-get-param but got '" + Global::concat(pieces," ") + "'"; } else { SearchParams params = engine->getParams(); if(pieces[0] == "playoutDoublingAdvantage") { response = Global::doubleToString(engine->staticPlayoutDoublingAdvantage); } else if(pieces[0] == "rootPolicyTemperature") { response = Global::doubleToString(params.rootPolicyTemperature); } else if(pieces[0] == "analysisWideRootNoise") { response = Global::doubleToString(engine->analysisWideRootNoise); } else { responseIsError = true; response = "Invalid parameter"; } } } else if(command == "kata-set-param") { if(pieces.size() != 2) { responseIsError = true; response = "Expected two arguments for kata-set-param but got '" + Global::concat(pieces," ") + "'"; } else { int i; double d; if(pieces[0] == "playoutDoublingAdvantage") { if(Global::tryStringToDouble(pieces[1],d) && d >= -3.0 && d <= 3.0) engine->setStaticPlayoutDoublingAdvantage(d); else { responseIsError = true; response = "Invalid value for " + pieces[0] + ", must be float from -3.0 to 3.0"; } } else if(pieces[0] == "rootPolicyTemperature") { if(Global::tryStringToDouble(pieces[1],d) && d >= 0.01 && d <= 100.0) engine->setRootPolicyTemperature(d); else { responseIsError = true; response = "Invalid value for " + pieces[0] + ", must be float from 0.01 to 100.0"; } } else if(pieces[0] == "analysisWideRootNoise") { if(Global::tryStringToDouble(pieces[1],d) && d >= 0.0 && d <= 5.0) engine->setAnalysisWideRootNoise(d); else { responseIsError = true; response = "Invalid value for " + pieces[0] + ", must be float from 0.0 to 2.0"; } } else if(pieces[0] == "numSearchThreads") { if(Global::tryStringToInt(pieces[1],i) && i >= 1 && i <= 1024) engine->setNumSearchThreads(i); else { responseIsError = true; response = "Invalid value for " + pieces[0] + ", must be integer from 1 to 1024"; } } else { responseIsError = true; response = "Unknown or invalid parameter: " + pieces[0]; } } } else if(command == "time_settings") { double mainTime; double byoYomiTime; int byoYomiStones; bool success = false; try { mainTime = parseTime(pieces,0,"main time"); byoYomiTime = parseTime(pieces,1,"byo-yomi per-period time"); byoYomiStones = parseByoYomiStones(pieces,2); success = true; } catch(const StringError& e) { responseIsError = true; response = e.what(); } if(success) { TimeControls tc; //This means no time limits, according to gtp spec if(byoYomiStones == 0 && byoYomiTime > 0.0) tc = TimeControls(); else if(byoYomiStones == 0) tc = TimeControls::absoluteTime(mainTime); else tc = TimeControls::canadianOrByoYomiTime(mainTime,byoYomiTime,1,byoYomiStones); engine->bTimeControls = tc; engine->wTimeControls = tc; } } else if(command == "kata-list_time_settings") { response = "none"; response += " "; response += "absolute"; response += " "; response += "byoyomi"; response += " "; response += "canadian"; response += " "; response += "fischer"; response += " "; response += "fischer-capped"; } else if(command == "kgs-time_settings" || command == "kata-time_settings") { if(pieces.size() < 1) { responseIsError = true; if(command == "kata-time_settings") response = "Expected 'none', 'absolute', 'byoyomi', 'canadian', 'fischer', or 'fischer-capped' as first argument for kata-time_settings"; else response = "Expected 'none', 'absolute', 'byoyomi', or 'canadian' as first argument for kgs-time_settings"; } else { string what = Global::toLower(Global::trim(pieces[0])); if(what == "none") { TimeControls tc = TimeControls(); engine->bTimeControls = tc; engine->wTimeControls = tc; } else if(what == "absolute") { double mainTime; TimeControls tc; bool success = false; try { mainTime = parseTime(pieces,1,"main time"); tc = TimeControls::absoluteTime(mainTime); success = true; } catch(const StringError& e) { responseIsError = true; response = e.what(); } if(success) { engine->bTimeControls = tc; engine->wTimeControls = tc; } } else if(what == "canadian") { double mainTime; double byoYomiTime; int byoYomiStones; TimeControls tc; bool success = false; try { mainTime = parseTime(pieces,1,"main time"); byoYomiTime = parseTime(pieces,2,"byo-yomi period time"); byoYomiStones = parseByoYomiStones(pieces,3); //Use the same hack in time-settings - if somehow someone specifies positive overtime but 0 stones for it, intepret as no time control if(byoYomiStones == 0 && byoYomiTime > 0.0) tc = TimeControls(); else if(byoYomiStones == 0) tc = TimeControls::absoluteTime(mainTime); else tc = TimeControls::canadianOrByoYomiTime(mainTime,byoYomiTime,1,byoYomiStones); success = true; } catch(const StringError& e) { responseIsError = true; response = e.what(); } if(success) { engine->bTimeControls = tc; engine->wTimeControls = tc; } } else if(what == "byoyomi") { double mainTime; double byoYomiTime; int byoYomiPeriods; TimeControls tc; bool success = false; try { mainTime = parseTime(pieces,1,"main time"); byoYomiTime = parseTime(pieces,2,"byo-yomi per-period time"); byoYomiPeriods = parseByoYomiPeriods(pieces,3); if(byoYomiPeriods == 0) tc = TimeControls::absoluteTime(mainTime); else tc = TimeControls::canadianOrByoYomiTime(mainTime,byoYomiTime,byoYomiPeriods,1); success = true; } catch(const StringError& e) { responseIsError = true; response = e.what(); } if(success) { engine->bTimeControls = tc; engine->wTimeControls = tc; } } else if(what == "fischer" && command == "kata-time_settings") { double mainTime; double increment; TimeControls tc; bool success = false; try { mainTime = parseTime(pieces,1,"main time"); increment = parseTime(pieces,2,"increment time"); tc = TimeControls::fischerTime(mainTime,increment); success = true; } catch(const StringError& e) { responseIsError = true; response = e.what(); } if(success) { engine->bTimeControls = tc; engine->wTimeControls = tc; } } else if(what == "fischer-capped" && command == "kata-time_settings") { double mainTime; double increment; double mainTimeLimit; double maxTimePerMove; TimeControls tc; bool success = false; try { mainTime = parseTime(pieces,1,"main time"); increment = parseTime(pieces,2,"increment time"); mainTimeLimit = parseTimeAllowNegative(pieces,3,"main time limit"); maxTimePerMove = parseTimeAllowNegative(pieces,4,"max time per move"); if(mainTimeLimit < 0) mainTimeLimit = TimeControls::MAX_USER_INPUT_TIME; if(maxTimePerMove < 0) maxTimePerMove = TimeControls::MAX_USER_INPUT_TIME; tc = TimeControls::fischerCappedTime(mainTime,increment,mainTimeLimit,maxTimePerMove); success = true; } catch(const StringError& e) { responseIsError = true; response = e.what(); } if(success) { engine->bTimeControls = tc; engine->wTimeControls = tc; } } else { responseIsError = true; if(command == "kata-time_settings") response = "Expected 'none', 'absolute', 'byoyomi', 'canadian', 'fischer', or 'fischer-capped' as first argument for kata-time_settings"; else response = "Expected 'none', 'absolute', 'byoyomi', or 'canadian' as first argument for kgs-time_settings"; } } } else if(command == "time_left") { Player pla; double time; int stones; if(pieces.size() != 3 || !PlayerIO::tryParsePlayer(pieces[0],pla) || !Global::tryStringToDouble(pieces[1],time) || !Global::tryStringToInt(pieces[2],stones) ) { responseIsError = true; response = "Expected player and float time and int stones for time_left but got '" + Global::concat(pieces," ") + "'"; } //Be slightly tolerant of negative time left else if(isnan(time) || time < -10.0 || time > TimeControls::MAX_USER_INPUT_TIME) { responseIsError = true; response = "invalid time"; } else if(stones < 0 || stones > 100000) { responseIsError = true; response = "invalid stones"; } else { TimeControls tc = pla == P_BLACK ? engine->bTimeControls : engine->wTimeControls; if(stones > 0 && tc.originalNumPeriods <= 0) { responseIsError = true; response = "stones left in period is > 0 but the time control used does not have any overtime periods"; } else { //Main time if(stones == 0) { tc.mainTimeLeft = time; tc.inOvertime = false; tc.numPeriodsLeftIncludingCurrent = tc.originalNumPeriods; tc.numStonesLeftInPeriod = 0; tc.timeLeftInPeriod = 0; } else { //Hack for KGS byo-yomi - interpret num stones as periods instead if(tc.originalNumPeriods > 1 && tc.numStonesPerPeriod == 1) { tc.mainTimeLeft = 0.0; tc.inOvertime = true; tc.numPeriodsLeftIncludingCurrent = std::min(stones,tc.originalNumPeriods); tc.numStonesLeftInPeriod = 1; tc.timeLeftInPeriod = time; } //Normal canadian time interpertation of GTP else { tc.mainTimeLeft = 0.0; tc.inOvertime = true; tc.numPeriodsLeftIncludingCurrent = 1; tc.numStonesLeftInPeriod = std::min(stones,tc.numStonesPerPeriod); tc.timeLeftInPeriod = time; } } if(pla == P_BLACK) engine->bTimeControls = tc; else engine->wTimeControls = tc; //In case the controller tells us komi every move, restart pondering afterward. maybeStartPondering = engine->bot->getRootHist().moveHistory.size() > 0; } } } else if(command == "kata-debug-print-tc") { response += "Black "+ engine->bTimeControls.toDebugString(engine->bot->getRootBoard(),engine->bot->getRootHist(),initialParams.lagBuffer); response += "\n"; response += "White "+ engine->wTimeControls.toDebugString(engine->bot->getRootBoard(),engine->bot->getRootHist(),initialParams.lagBuffer); } else if(command == "play") { Player pla; Loc loc; if(pieces.size() != 2) { responseIsError = true; response = "Expected two arguments for play but got '" + Global::concat(pieces," ") + "'"; } else if(!PlayerIO::tryParsePlayer(pieces[0],pla)) { responseIsError = true; response = "Could not parse color: '" + pieces[0] + "'"; } else if(!tryParseLoc(pieces[1],engine->bot->getRootBoard(),loc)) { responseIsError = true; response = "Could not parse vertex: '" + pieces[1] + "'"; } else { bool suc = engine->play(loc,pla); if(!suc) { responseIsError = true; response = "illegal move"; } maybeStartPondering = true; } } else if(command == "set_position") { if(pieces.size() % 2 != 0) { responseIsError = true; response = "Expected a space-separated sequence of <COLOR> <VERTEX> pairs but got '" + Global::concat(pieces," ") + "'"; } else { vector<Move> initialStones; for(int i = 0; i<pieces.size(); i += 2) { Player pla; Loc loc; if(!PlayerIO::tryParsePlayer(pieces[i],pla)) { responseIsError = true; response = "Expected a space-separated sequence of <COLOR> <VERTEX> pairs but got '" + Global::concat(pieces," ") + "': "; response += "could not parse color: '" + pieces[0] + "'"; break; } else if(!tryParseLoc(pieces[i+1],engine->bot->getRootBoard(),loc)) { responseIsError = true; response = "Expected a space-separated sequence of <COLOR> <VERTEX> pairs but got '" + Global::concat(pieces," ") + "': "; response += "Could not parse vertex: '" + pieces[1] + "'"; break; } else if(loc == Board::PASS_LOC) { responseIsError = true; response = "Expected a space-separated sequence of <COLOR> <VERTEX> pairs but got '" + Global::concat(pieces," ") + "': "; response += "Could not parse vertex: '" + pieces[1] + "'"; break; } initialStones.push_back(Move(loc,pla)); } if(!responseIsError) { bool suc = engine->setPosition(initialStones); if(!suc) { responseIsError = true; response = "Illegal stone placements - overlapping stones or stones with no liberties?"; } maybeStartPondering = false; } } } else if(command == "undo") { bool suc = engine->undo(); if(!suc) { responseIsError = true; response = "cannot undo"; } } else if(command == "genmove" || command == "genmove_debug" || command == "search_debug") { Player pla; if(pieces.size() != 1) { responseIsError = true; response = "Expected one argument for genmove but got '" + Global::concat(pieces," ") + "'"; } else if(!PlayerIO::tryParsePlayer(pieces[0],pla)) { responseIsError = true; response = "Could not parse color: '" + pieces[0] + "'"; } else { bool debug = command == "genmove_debug" || command == "search_debug"; bool playChosenMove = command != "search_debug"; engine->genMove( pla, logger,searchFactorWhenWinningThreshold,searchFactorWhenWinning, cleanupBeforePass,friendlyPass,ogsChatToStderr, allowResignation,resignThreshold,resignConsecTurns,resignMinScoreDifference, logSearchInfo,debug,playChosenMove, response,responseIsError,maybeStartPondering, GTPEngine::AnalyzeArgs() ); } } else if(command == "genmove_analyze" || command == "lz-genmove_analyze" || command == "kata-genmove_analyze") { Player pla = engine->bot->getRootPla(); bool parseFailed = false; GTPEngine::AnalyzeArgs analyzeArgs = parseAnalyzeCommand(command, pieces, pla, parseFailed, engine); if(parseFailed) { responseIsError = true; response = "Could not parse genmove_analyze arguments or arguments out of range: '" + Global::concat(pieces," ") + "'"; } else { bool debug = false; bool playChosenMove = true; //Make sure the "equals" for GTP is printed out prior to the first analyze line, regardless of thread racing if(hasId) cout << "=" << Global::intToString(id) << endl; else cout << "=" << endl; engine->genMove( pla, logger,searchFactorWhenWinningThreshold,searchFactorWhenWinning, cleanupBeforePass,friendlyPass,ogsChatToStderr, allowResignation,resignThreshold,resignConsecTurns,resignMinScoreDifference, logSearchInfo,debug,playChosenMove, response,responseIsError,maybeStartPondering, analyzeArgs ); //And manually handle the result as well. In case of error, don't report any play. suppressResponse = true; if(!responseIsError) { cout << response << endl; cout << endl; } else { cout << endl; if(!loggingToStderr) cerr << response << endl; } } } else if(command == "clear_cache") { engine->clearCache(); } else if(command == "showboard") { ostringstream sout; engine->bot->getRootHist().printBasicInfo(sout, engine->bot->getRootBoard()); response = Global::trim(filterDoubleNewlines(sout.str())); } else if(command == "fixed_handicap") { int n; if(pieces.size() != 1) { responseIsError = true; response = "Expected one argument for fixed_handicap but got '" + Global::concat(pieces," ") + "'"; } else if(!Global::tryStringToInt(pieces[0],n)) { responseIsError = true; response = "Could not parse number of handicap stones: '" + pieces[0] + "'"; } else if(n < 2) { responseIsError = true; response = "Number of handicap stones less than 2: '" + pieces[0] + "'"; } else if(!engine->bot->getRootBoard().isEmpty()) { responseIsError = true; response = "Board is not empty"; } else { engine->placeFixedHandicap(n,response,responseIsError); } } else if(command == "place_free_handicap") { int n; if(pieces.size() != 1) { responseIsError = true; response = "Expected one argument for place_free_handicap but got '" + Global::concat(pieces," ") + "'"; } else if(!Global::tryStringToInt(pieces[0],n)) { responseIsError = true; response = "Could not parse number of handicap stones: '" + pieces[0] + "'"; } else if(n < 2) { responseIsError = true; response = "Number of handicap stones less than 2: '" + pieces[0] + "'"; } else if(!engine->bot->getRootBoard().isEmpty()) { responseIsError = true; response = "Board is not empty"; } else { engine->placeFreeHandicap(n,response,responseIsError,seedRand); } } else if(command == "set_free_handicap") { if(!engine->bot->getRootBoard().isEmpty()) { responseIsError = true; response = "Board is not empty"; } else { vector<Loc> locs; int xSize = engine->bot->getRootBoard().x_size; int ySize = engine->bot->getRootBoard().y_size; Board board(xSize,ySize); for(int i = 0; i<pieces.size(); i++) { Loc loc; bool suc = tryParseLoc(pieces[i],board,loc); if(!suc || loc == Board::PASS_LOC) { responseIsError = true; response = "Invalid handicap location: " + pieces[i]; } locs.push_back(loc); } for(int i = 0; i<locs.size(); i++) board.setStone(locs[i],P_BLACK); Player pla = P_WHITE; BoardHistory hist(board,pla,engine->getCurrentRules(),0); hist.setInitialTurnNumber(board.numStonesOnBoard()); //Should give more accurate temperaure and time control behavior vector<Move> newMoveHistory; engine->setPositionAndRules(pla,board,hist,board,pla,newMoveHistory); } } else if(command == "final_score") { engine->stopAndWait(); Player winner = C_EMPTY; double finalWhiteMinusBlackScore = 0.0; engine->computeAnticipatedWinnerAndScore(winner,finalWhiteMinusBlackScore); if(winner == C_EMPTY) response = "0"; else if(winner == C_BLACK) response = "B+" + Global::strprintf("%.1f",-finalWhiteMinusBlackScore); else if(winner == C_WHITE) response = "W+" + Global::strprintf("%.1f",finalWhiteMinusBlackScore); else ASSERT_UNREACHABLE; } else if(command == "final_status_list") { int statusMode = 0; if(pieces.size() != 1) { responseIsError = true; response = "Expected one argument for final_status_list but got '" + Global::concat(pieces," ") + "'"; } else { if(pieces[0] == "alive") statusMode = 0; else if(pieces[0] == "seki") statusMode = 1; else if(pieces[0] == "dead") statusMode = 2; else { responseIsError = true; response = "Argument to final_status_list must be 'alive' or 'seki' or 'dead'"; statusMode = 3; } if(statusMode < 3) { vector<bool> isAlive = engine->computeAnticipatedStatuses(); Board board = engine->bot->getRootBoard(); vector<Loc> locsToReport; if(statusMode == 0) { for(int y = 0; y<board.y_size; y++) { for(int x = 0; x<board.x_size; x++) { Loc loc = Location::getLoc(x,y,board.x_size); if(board.colors[loc] != C_EMPTY && isAlive[loc]) locsToReport.push_back(loc); } } } if(statusMode == 2) { for(int y = 0; y<board.y_size; y++) { for(int x = 0; x<board.x_size; x++) { Loc loc = Location::getLoc(x,y,board.x_size); if(board.colors[loc] != C_EMPTY && !isAlive[loc]) locsToReport.push_back(loc); } } } response = ""; for(int i = 0; i<locsToReport.size(); i++) { Loc loc = locsToReport[i]; if(i > 0) response += " "; response += Location::toString(loc,board); } } } } else if(command == "loadsgf") { if(pieces.size() != 1 && pieces.size() != 2) { responseIsError = true; response = "Expected one or two arguments for loadsgf but got '" + Global::concat(pieces," ") + "'"; } else { string filename = pieces[0]; bool parseFailed = false; bool moveNumberSpecified = false; int moveNumber = 0; if(pieces.size() == 2) { bool suc = Global::tryStringToInt(pieces[1],moveNumber); moveNumber--; if(!suc || moveNumber < 0 || moveNumber > 10000000) parseFailed = true; else { moveNumberSpecified = true; } } if(parseFailed) { responseIsError = true; response = "Invalid value for moveNumber for loadsgf"; } else { Board sgfInitialBoard; Player sgfInitialNextPla; BoardHistory sgfInitialHist; Rules sgfRules; Board sgfBoard; Player sgfNextPla; BoardHistory sgfHist; bool sgfParseSuccess = false; CompactSgf* sgf = NULL; try { sgf = CompactSgf::loadFile(filename); if(sgf->moves.size() > 0x3FFFFFFF) throw StringError("Sgf has too many moves"); if(!moveNumberSpecified || moveNumber > sgf->moves.size()) moveNumber = (int)sgf->moves.size(); sgfRules = sgf->getRulesOrWarn( engine->getCurrentRules(), //Use current rules as default [&logger](const string& msg) { logger.write(msg); cerr << msg << endl; } ); if(engine->nnEval != NULL) { bool rulesWereSupported; Rules supportedRules = engine->nnEval->getSupportedRules(sgfRules,rulesWereSupported); if(!rulesWereSupported) { ostringstream out; out << "WARNING: Rules " << sgfRules.toJsonStringNoKomi() << " from sgf not supported by neural net, using " << supportedRules.toJsonStringNoKomi() << " instead"; logger.write(out.str()); if(!loggingToStderr) cerr << out.str() << endl; sgfRules = supportedRules; } } if(isForcingKomi) sgfRules.komi = forcedKomi; { //See if the rules differ, IGNORING komi differences Rules currentRules = engine->getCurrentRules(); currentRules.komi = sgfRules.komi; if(sgfRules != currentRules) { ostringstream out; out << "Changing rules to " << sgfRules.toJsonStringNoKomi(); logger.write(out.str()); if(!loggingToStderr) cerr << out.str() << endl; } } sgf->setupInitialBoardAndHist(sgfRules, sgfInitialBoard, sgfInitialNextPla, sgfInitialHist); sgfInitialHist.setInitialTurnNumber(sgfInitialBoard.numStonesOnBoard()); //Should give more accurate temperaure and time control behavior sgfBoard = sgfInitialBoard; sgfNextPla = sgfInitialNextPla; sgfHist = sgfInitialHist; sgf->playMovesTolerant(sgfBoard,sgfNextPla,sgfHist,moveNumber,preventEncore); delete sgf; sgf = NULL; sgfParseSuccess = true; } catch(const StringError& err) { delete sgf; sgf = NULL; responseIsError = true; response = "Could not load sgf: " + string(err.what()); } catch(...) { delete sgf; sgf = NULL; responseIsError = true; response = "Cannot load file"; } if(sgfParseSuccess) { if(sgfRules.komi != engine->getCurrentRules().komi) { ostringstream out; out << "Changing komi to " << sgfRules.komi; logger.write(out.str()); if(!loggingToStderr) cerr << out.str() << endl; } engine->setOrResetBoardSize(cfg,logger,seedRand,sgfBoard.x_size,sgfBoard.y_size,loggingToStderr); engine->setPositionAndRules(sgfNextPla, sgfBoard, sgfHist, sgfInitialBoard, sgfInitialNextPla, sgfHist.moveHistory); } } } } else if(command == "printsgf") { if(pieces.size() != 0 && pieces.size() != 1) { responseIsError = true; response = "Expected zero or one argument for print but got '" + Global::concat(pieces," ") + "'"; } else if(pieces.size() == 0 || pieces[0] == "-") { ostringstream out; WriteSgf::writeSgf(out,"","",engine->bot->getRootHist(),NULL,true,false); response = out.str(); } else { ofstream out; if(FileUtils::tryOpen(out,pieces[0])) { WriteSgf::writeSgf(out,"","",engine->bot->getRootHist(),NULL,true,false); out.close(); response = ""; } else { responseIsError = true; response = "Could not open or write to file: " + pieces[0]; } } } else if(command == "analyze" || command == "lz-analyze" || command == "kata-analyze") { Player pla = engine->bot->getRootPla(); bool parseFailed = false; GTPEngine::AnalyzeArgs analyzeArgs = parseAnalyzeCommand(command, pieces, pla, parseFailed, engine); if(parseFailed) { responseIsError = true; response = "Could not parse analyze arguments or arguments out of range: '" + Global::concat(pieces," ") + "'"; } else { //Make sure the "equals" for GTP is printed out prior to the first analyze line, regardless of thread racing if(hasId) cout << "=" << Global::intToString(id) << endl; else cout << "=" << endl; engine->analyze(pla, analyzeArgs); //No response - currentlyAnalyzing will make sure we get a newline at the appropriate time, when stopped. suppressResponse = true; currentlyAnalyzing = true; } } else if(command == "kata-raw-nn") { int whichSymmetry = NNInputs::SYMMETRY_ALL; bool parsed = false; if(pieces.size() == 1) { string s = Global::trim(Global::toLower(pieces[0])); if(s == "all") parsed = true; else if(Global::tryStringToInt(s,whichSymmetry) && whichSymmetry >= 0 && whichSymmetry <= SymmetryHelpers::NUM_SYMMETRIES-1) parsed = true; } if(!parsed) { responseIsError = true; response = "Expected one argument 'all' or symmetry index [0-7] for kata-raw-nn but got '" + Global::concat(pieces," ") + "'"; } else { response = engine->rawNN(whichSymmetry); } } else if(command == "debug_moves") { PrintTreeOptions options; options = options.maxDepth(1); string printBranch; for(size_t i = 0; i<pieces.size(); i++) { if(i > 0) printBranch += " "; printBranch += pieces[i]; } try { if(printBranch.length() > 0) options = options.onlyBranch(engine->bot->getRootBoard(),printBranch); } catch(const StringError& e) { (void)e; responseIsError = true; response = "Invalid move sequence"; } if(!responseIsError) { Search* search = engine->bot->getSearchStopAndWait(); ostringstream sout; Player pla = engine->bot->getRootPla(); Board board = engine->bot->getRootBoard(); BoardHistory hist = engine->bot->getRootHist(); bool allLegal = true; for(Loc loc: options.branch_) { bool suc = hist.makeBoardMoveTolerant(board, loc, pla, false); if(!suc) { allLegal = false; break; } pla = getOpp(pla); } if(allLegal) { Board::printBoard(sout, board, Board::NULL_LOC, &hist.moveHistory); } search->printTree(sout, search->rootNode, options, perspective); response = filterDoubleNewlines(sout.str()); } } else if(command == "cputime" || command == "gomill-cpu_time") { response = Global::doubleToString(engine->genmoveTimeSum); } else if(command == "stop") { //Stop any ongoing ponder or analysis engine->stopAndWait(); } else { responseIsError = true; response = "unknown command"; } //Postprocessing of response if(hasId) response = Global::intToString(id) + " " + response; else response = " " + response; if(responseIsError) response = "?" + response; else response = "=" + response; if(!suppressResponse) { cout << response << endl; cout << endl; } if(logAllGTPCommunication) logger.write(response); if(shouldQuitAfterResponse) break; if(maybeStartPondering && ponderingEnabled) engine->ponder(); } //Close read loop delete engine; engine = NULL; NeuralNet::globalCleanup(); ScoreValue::freeTables(); logger.write("All cleaned up, quitting"); return 0; }
#include "frmgaugeround.h" #include <QApplication> int main(int argc, char *argv[]) { QApplication a(argc, argv); frmGaugeRound w; w.show(); return a.exec(); }
/* Copyright (c) 2007-2010, 2013-2019, Arvid Norberg Copyright (c) 2014, Steven Siloti Copyright (c) 2015, Thomas Yuan Copyright (c) 2016, Alden Torres All rights reserved. You may use, distribute and modify this code under the terms of the BSD license, see LICENSE file. */ #ifndef OBSERVER_HPP #define OBSERVER_HPP #include <cstdint> #include <memory> #include <libtorrent/time.hpp> #include <libtorrent/address.hpp> #include <libtorrent/flags.hpp> #include <libtorrent/socket.hpp> // for udp #include <libtorrent/kademlia/node_id.hpp> namespace libtorrent { namespace dht { struct dht_observer; struct observer; struct msg; struct traversal_algorithm; using observer_flags_t = libtorrent::flags::bitfield_flag<std::uint8_t, struct observer_flags_tag>; struct TORRENT_EXTRA_EXPORT observer : std::enable_shared_from_this<observer> { observer(std::shared_ptr<traversal_algorithm> a , udp::endpoint const& ep, node_id const& id) : m_algorithm(std::move(a)) , m_id(id) { TORRENT_ASSERT(m_algorithm); set_target(ep); } observer(observer const&) = delete; observer& operator=(observer const&) = delete; // defined in rpc_manager.cpp virtual ~observer(); // this is called when a reply is received virtual void reply(msg const& m) = 0; // this is called if no response has been received after // a few seconds, before the request has timed out void short_timeout(); bool has_short_timeout() const { return bool(flags & flag_short_timeout); } // this is called when no reply has been received within // some timeout, or a reply with incorrect format. virtual void timeout(); // if this is called the destructor should // not invoke any new messages, and should // only clean up. It means the rpc-manager // is being destructed void abort(); dht_observer* get_observer() const; traversal_algorithm* algorithm() const { return m_algorithm.get(); } time_point sent() const { return m_sent; } void set_target(udp::endpoint const& ep); address target_addr() const; udp::endpoint target_ep() const; void set_id(node_id const& id); node_id const& id() const { return m_id; } static inline constexpr observer_flags_t flag_queried = 0_bit; static inline constexpr observer_flags_t flag_initial = 1_bit; static inline constexpr observer_flags_t flag_no_id = 2_bit; static inline constexpr observer_flags_t flag_short_timeout = 3_bit; static inline constexpr observer_flags_t flag_failed = 4_bit; static inline constexpr observer_flags_t flag_ipv6_address = 5_bit; static inline constexpr observer_flags_t flag_alive = 6_bit; static inline constexpr observer_flags_t flag_done = 7_bit; protected: void done(); private: std::shared_ptr<observer> self() { return shared_from_this(); } time_point m_sent; std::shared_ptr<traversal_algorithm> const m_algorithm; node_id m_id; union addr_t { address_v6::bytes_type v6; address_v4::bytes_type v4; } m_addr; std::uint16_t m_port = 0; public: observer_flags_t flags{}; #if TORRENT_USE_ASSERTS bool m_in_constructor = true; bool m_was_sent = false; bool m_was_abandoned = false; bool m_in_use = true; #endif }; using observer_ptr = std::shared_ptr<observer>; } } #endif
// Copyright (C) 2002-2009 Nikolaus Gebhardt // This file is part of the "Irrlicht Engine". // For conditions of distribution and use, see copyright notice in irrlicht.h #include "IrrCompileConfig.h" #ifdef _IRR_COMPILE_WITH_STL_WRITER_ #include "CSTLMeshWriter.h" #include "os.h" #include "IMesh.h" #include "IMeshBuffer.h" #include "IAttributes.h" #include "ISceneManager.h" #include "IMeshCache.h" #include "IWriteFile.h" namespace irr { namespace scene { CSTLMeshWriter::CSTLMeshWriter(scene::ISceneManager* smgr) : SceneManager(smgr) { #ifdef _DEBUG setDebugName("CSTLMeshWriter"); #endif if (SceneManager) SceneManager->grab(); } CSTLMeshWriter::~CSTLMeshWriter() { if (SceneManager) SceneManager->drop(); } //! Returns the type of the mesh writer EMESH_WRITER_TYPE CSTLMeshWriter::getType() const { return EMWT_STL; } //! writes a mesh bool CSTLMeshWriter::writeMesh(io::IWriteFile* file, scene::IMesh* mesh, s32 flags) { if (!file) return false; os::Printer::log("Writing mesh", file->getFileName()); if (flags & scene::EMWF_WRITE_COMPRESSED) return writeMeshBinary(file, mesh, flags); else return writeMeshASCII(file, mesh, flags); } bool CSTLMeshWriter::writeMeshBinary(io::IWriteFile* file, scene::IMesh* mesh, s32 flags) { // write STL MESH header file->write("binary ",7); const core::stringc name(SceneManager->getMeshCache()->getMeshName(mesh)); const s32 sizeleft = 73-name.size(); // 80 byte header if (sizeleft<0) file->write(name.c_str(),73); else { char* buf = new char[80]; memset(buf, 0, 80); file->write(name.c_str(),name.size()); file->write(buf,sizeleft); delete [] buf; } u32 facenum = 0; for (u32 j=0; j<mesh->getMeshBufferCount(); ++j) facenum += mesh->getMeshBuffer(j)->getIndexCount()/3; file->write(&facenum,4); // write mesh buffers for (u32 i=0; i<mesh->getMeshBufferCount(); ++i) { IMeshBuffer* buffer = mesh->getMeshBuffer(i); if (buffer) { const u32 indexCount = buffer->getIndexCount(); const u16 attributes = 0; for (u32 j=0; j<indexCount; j+=3) { const core::vector3df& v1 = buffer->getPosition(buffer->getIndices()[j]); const core::vector3df& v2 = buffer->getPosition(buffer->getIndices()[j+1]); const core::vector3df& v3 = buffer->getPosition(buffer->getIndices()[j+2]); const core::plane3df tmpplane(v1,v2,v3); file->write(&tmpplane.Normal, 12); file->write(&v1, 12); file->write(&v2, 12); file->write(&v3, 12); file->write(&attributes, 2); } } } return true; } bool CSTLMeshWriter::writeMeshASCII(io::IWriteFile* file, scene::IMesh* mesh, s32 flags) { // write STL MESH header file->write("solid ",6); const core::stringc name(SceneManager->getMeshCache()->getMeshName(mesh)); file->write(name.c_str(),name.size()); file->write("\n\n",2); // write mesh buffers for (u32 i=0; i<mesh->getMeshBufferCount(); ++i) { IMeshBuffer* buffer = mesh->getMeshBuffer(i); if (buffer) { const u32 indexCount = buffer->getIndexCount(); for (u32 j=0; j<indexCount; j+=3) { writeFace(file, buffer->getPosition(buffer->getIndices()[j]), buffer->getPosition(buffer->getIndices()[j+1]), buffer->getPosition(buffer->getIndices()[j+2])); } file->write("\n",1); } } file->write("endsolid ",9); file->write(name.c_str(),name.size()); return true; } void CSTLMeshWriter::getVectorAsStringLine(const core::vector3df& v, core::stringc& s) const { s = core::stringc(v.X); s += " "; s += core::stringc(v.Y); s += " "; s += core::stringc(v.Z); s += "\n"; } void CSTLMeshWriter::writeFace(io::IWriteFile* file, const core::vector3df& v1, const core::vector3df& v2, const core::vector3df& v3) { core::stringc tmp; file->write("facet normal ",13); getVectorAsStringLine(core::plane3df(v1,v2,v3).Normal, tmp); file->write(tmp.c_str(),tmp.size()); file->write(" outer loop\n",13); file->write(" vertex ",11); getVectorAsStringLine(v1, tmp); file->write(tmp.c_str(),tmp.size()); file->write(" vertex ",11); getVectorAsStringLine(v2, tmp); file->write(tmp.c_str(),tmp.size()); file->write(" vertex ",11); getVectorAsStringLine(v3, tmp); file->write(tmp.c_str(),tmp.size()); file->write(" endloop\n",10); file->write("endfacet\n",9); } } // end namespace } // end namespace #endif
#ifdef USE_OMP #include <omp.h> #endif // USE_OMP #include "rawscale.h" #include "minmax.h" /// Clamp function template <class T> T CLAMP(const T &value, const T &min_value, const T &max_value) { return ((value < min_value) ? min_value : (value > max_value) ? max_value : value); } RawScaleWeightsTable::RawScaleWeightsTable( RAWGenericFilter* pFilter, unsigned uDstSize, unsigned uSrcSize ) : _WeightTable( NULL ), _WindowSize( 0 ), _LineLength( uDstSize ) { if ( pFilter != NULL ) { unsigned u; double dWidth; double dFScale = 1.0; const \ double dFilterWidth = pFilter->GetWidth(); const \ double dScale = double(uDstSize) / double(uSrcSize); if( dScale < 1.0 ) { dWidth = dFilterWidth / dScale; dFScale = dScale; } else { dWidth= dFilterWidth; } _WindowSize = 2 * (int)ceil(dWidth) + 1; _WeightTable = new Contribution[ _LineLength + 1 ]; if ( _WeightTable != NULL) { for( u=0; u<_LineLength; u++ ) { _WeightTable[ u ].Weights = new double[ _WindowSize + 1 ]; } const double dOffset = ( 0.5 / dScale ) - 0.5; for( u=0; u<_LineLength; u++ ) { const double dCenter = (double)u / dScale + dOffset; int iLeft = MAX( 0, (int)floor (dCenter - dWidth) ); int iRight = MIN( (int)ceil (dCenter + dWidth), int(uSrcSize) - 1 ); if( ( iRight - iLeft + 1 ) > int(_WindowSize) ) { if( iLeft < ( int(uSrcSize) - 1 / 2 ) ) { iLeft++; } else { iRight--; } } _WeightTable[ u ].Left = iLeft; _WeightTable[ u ].Right = iRight; int iSrc = 0; double dTotalWeight = 0; for( iSrc=iLeft; iSrc<=iRight; iSrc++ ) { const double weight = dFScale * pFilter->Filter( dFScale * (dCenter - (double)iSrc) ); if ( _WeightTable[ u ].Weights != NULL ) { _WeightTable[ u ].Weights[ iSrc - iLeft ] = weight; } dTotalWeight += weight; } if( ( dTotalWeight > 0 ) && ( dTotalWeight != 1 ) ) { for( iSrc = iLeft; iSrc <= iRight; iSrc++ ) { if ( _WeightTable[ u ].Weights != NULL ) { _WeightTable[ u ].Weights[ iSrc-iLeft ] /= dTotalWeight; } } iSrc = iRight - iLeft; if ( _WeightTable[ u ].Weights != NULL ) { while( _WeightTable[ u ].Weights[ iSrc ] == 0 ) { _WeightTable[ u ].Right--; iSrc--; if( _WeightTable[ u ].Right == _WeightTable[ u ].Left ) break; } } } } } /// of if ( _WeightTable != NULL) } /// of if ( pFilter != NULL ) } RawScaleWeightsTable::~RawScaleWeightsTable() { if ( _WeightTable != NULL ) { for( unsigned u = 0; u < _LineLength; u++ ) { if ( _WeightTable[u].Weights != NULL ) { delete[] _WeightTable[u].Weights; } } delete[] _WeightTable; } } double RawScaleWeightsTable::getWeight( unsigned dst_pos, unsigned src_pos ) { if ( dst_pos < _LineLength ) { //int sz = _WeightTable[dst_pos].Right - _WeightTable[dst_pos].Left; if ( src_pos < _WindowSize ) { return _WeightTable[dst_pos].Weights[src_pos]; } } return 0.0; } unsigned RawScaleWeightsTable::getLeftBoundary( unsigned dst_pos ) { return _WeightTable[dst_pos].Left; } unsigned RawScaleWeightsTable::getRightBoundary( unsigned dst_pos ) { return _WeightTable[dst_pos].Right; } // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- RAWResizeEngine::RAWResizeEngine( RAWGenericFilter* filter ) : _pFilter( filter ) { } unsigned RAWResizeEngine::scale( const unsigned short* src, unsigned src_width, unsigned src_height, unsigned dst_width, unsigned dst_height, unsigned short** dst ) { if ( src == NULL) return 0; if ( ( src_width == 0 ) || ( src_width == 0 ) || ( dst_width == 0 ) || ( dst_height == 0 ) ) return 0; unsigned imgsz = dst_width * dst_height; if ( *dst != NULL ) { delete[] *dst; } *dst = new unsigned short[ imgsz ]; if ( *dst == NULL ) { return 0; } if ( ( src_width == dst_width ) && ( src_height == dst_height ) ) { if ( *dst != NULL ) { unsigned cpsz = src_width * src_height * sizeof( unsigned short ); memcpy( *dst, src, cpsz ); return cpsz; } } if ( dst_width <= src_width ) { unsigned short* tmp_buff = NULL; if ( src_width != dst_width ) { if ( src_height != dst_height ) { tmp_buff = new unsigned short[ dst_width * src_height ]; if ( tmp_buff == NULL ) { delete[] *dst; return 0; } } else { tmp_buff = *dst; } horizontalFilter( src, src_height, src_width, 0, 0, tmp_buff, dst_width ); } else { tmp_buff = (unsigned short*)src; } if ( src_height != dst_height ) { verticalFilter( tmp_buff, dst_width, src_height, 0, 0, *dst, dst_width, dst_height ); } if ( ( tmp_buff != src ) && ( tmp_buff != *dst ) ) { delete[] tmp_buff; tmp_buff = NULL; } } else /// == ( dst_width > src->w() ) { unsigned short* tmp_buff = NULL; if ( src_height != dst_height ) { if ( src_width != dst_width ) { tmp_buff = new unsigned short[ src_width * dst_height ]; if ( tmp_buff == NULL ) { delete[] dst; return 0; } } else { tmp_buff = *dst; } verticalFilter( src, src_width, src_height, 0, 0, tmp_buff, dst_width, dst_height ); } else { tmp_buff = (unsigned short*)src; } if ( src_width != dst_width ) { horizontalFilter( tmp_buff, dst_height, src_width, 0, 0, *dst, dst_width ); } if ( ( tmp_buff != src ) && ( tmp_buff != *dst ) ) { delete[] tmp_buff; tmp_buff = NULL; } } if ( dst != NULL ) { return imgsz * sizeof( unsigned short ); } return 0; } void RAWResizeEngine::horizontalFilter( const unsigned short* src, const unsigned height, const unsigned src_width, const unsigned src_offset_x, const unsigned src_offset_y, unsigned short* dst, const unsigned dst_width ) { // allocate and calculate the contributions RawScaleWeightsTable weightsTable( _pFilter, dst_width, src_width ); unsigned y = 0; unsigned x = 0; unsigned i = 0; #pragma omp parallel for private(x,i) for ( y = 0; y < height; y++) { const unsigned short* src_bits = &src[ ( ( y + src_offset_y ) * src_width ) + src_offset_x ]; unsigned short* dst_bits = &dst[ y * dst_width ]; // scale each row for ( x = 0; x < dst_width; x++) { // loop through row const unsigned iLeft = weightsTable.getLeftBoundary(x); /// retrieve left boundary const unsigned iLimit = weightsTable.getRightBoundary(x) - iLeft; /// retrieve right boundary const unsigned short* pixel = src_bits + iLeft; double gray = 0.0; // for(i = iLeft to iRight) for ( i = 0; i <= iLimit; i++) { // scan between boundaries // accumulate weighted effect of each neighboring pixel const double weight = weightsTable.getWeight(x, i); double dpixel = *pixel; gray += ( weight * dpixel ); pixel++; } *dst_bits = (unsigned short)CLAMP<long long>((long long)(gray + 0.5f), 0, 0xFFFFFFFF); dst_bits++; } } } /// Performs vertical image filtering void RAWResizeEngine::verticalFilter( const unsigned short* src, unsigned width, unsigned src_height, unsigned src_offset_x, unsigned src_offset_y, unsigned short* dst, const unsigned dst_width, unsigned dst_height) { // allocate and calculate the contributions RawScaleWeightsTable weightsTable( _pFilter, dst_height, src_height ); //unsigned dst_pitch = dst_width * src_bpp; unsigned dst_pitch = width; unsigned short* dst_base = dst; unsigned src_pitch = width; unsigned y = 0; unsigned x = 0; unsigned i = 0; #pragma omp parallel for private(y,i) for ( x = 0; x < width; x++) { // work on column x in dst const unsigned index = x; unsigned short* dst_bits = dst_base + index; // scale each column for ( y = 0; y < dst_height; y++) { const unsigned short* src_base = &src[ ( src_offset_y * width ) + ( src_offset_y * src_pitch + src_offset_x ) ]; // loop through column const unsigned iLeft = weightsTable.getLeftBoundary(y); // retrieve left boundary const unsigned iLimit = weightsTable.getRightBoundary(y) - iLeft; // retrieve right boundary const unsigned short* src_bits = src_base + ( iLeft * src_pitch + index ); double gray = 0.0; for ( i = 0; i <= iLimit; i++) { // scan between boundaries // accumulate weighted effect of each neighboring pixel const double weight = weightsTable.getWeight(y, i); double dpixel = *src_bits; gray += weight * dpixel; src_bits += src_pitch; } // clamp and place result in destination pixel *dst_bits = (unsigned short)CLAMP<long long>((long long) (gray + 0.5f), 0, 0xFFFFFFFF); dst_bits += dst_pitch; } } }
/****************************** RMX SDK ******************************\ * Copyright (c) 2007 Vincent E. Milum Jr., All rights reserved. * * * * See license.txt for more information * * * * Latest SDK versions can be found at: http://rmx.sourceforge.net * \***********************************************************************/ #include "../rmxBase.h" #include "MessageWnd.h" vMessageWnd::vMessageWnd(const char *Classname, vMessageWnd *parentwnd) : classname(Classname) { parent = parentwnd; hwnd = NULL; hparent = HWND_MESSAGE; msgmsg = 0; msgparam1 = 0; msgparam2 = 0; } vMessageWnd::vMessageWnd(const wchar_t *Classname, vMessageWnd *parentwnd) : classname(Classname) { parent = parentwnd; hwnd = NULL; hparent = HWND_MESSAGE; msgmsg = 0; msgparam1 = 0; msgparam2 = 0; } vMessageWnd::~vMessageWnd() { SetWindowLongPtr(getWnd(), GWLP_USERDATA, (DWORD)NULL); DestroyWindow(hwnd); hwnd = NULL; } HWND vMessageWnd::init() { if (hwnd) return NULL; hwnd = onCreateWindow(); if (hwnd) { onInit(); onPostInit(); } else { CONSOLE_MAIN->print("vMessageWnd:init()"); } return hwnd; } HWND vMessageWnd::onCreateWindow() { rmxUtf8ToWide str(getClassName()); WNDCLASSEX wc; ZeroMemory(&wc, sizeof(WNDCLASSEX)); if (GetClassInfoEx(RMXOS::getInstance(), str.getBuffer(), &wc) == 0) { wc.cbSize = sizeof(WNDCLASSEX); wc.lpfnWndProc = (WNDPROC)vMessageWnd::static_wndProc; wc.hInstance = RMXOS::getInstance(); wc.lpszClassName = str.getBuffer(); if (!RegisterClassEx(&wc)) { CONSOLE_MAIN->print("vMessageWnd:onCreateWindow()"); return NULL; } } if (parent) hparent = parent->getWnd(); if (hparent == HWND_MESSAGE) if (!RMXOS::isWin50()) hparent = NULL; rmxUtf8ToWide name(*this); HWND hwnd = CreateWindowEx(0, str.getBuffer(), name.getBuffer(), 0, 0, 0, 0, 0, hparent, 0, RMXOS::getInstance(), this); return hwnd; } VUINT vMessageWnd::sendMessage(UINT msg, VUINT param1, VUINT param2) { return SendMessage(getWnd(), msg, param1, param2); } VUINT vMessageWnd::sendMessageA(UINT msg, VUINT param1, VUINT param2) { return SendMessageA(getWnd(), msg, param1, param2); } VUINT vMessageWnd::sendMessageW(UINT msg, VUINT param1, VUINT param2) { return SendMessageW(getWnd(), msg, param1, param2); } VUINT vMessageWnd::postMessage(UINT msg, VUINT param1, VUINT param2) { return PostMessage(getWnd(), msg, param1, param2); } VUINT vMessageWnd::postMessageA(UINT msg, VUINT param1, VUINT param2) { return PostMessageA(getWnd(), msg, param1, param2); } VUINT vMessageWnd::postMessageW(UINT msg, VUINT param1, VUINT param2) { return PostMessageW(getWnd(), msg, param1, param2); } VUINT vMessageWnd::wndProc(UINT msg, VUINT param1, VUINT param2) { return DefWindowProc(getWnd(), msg, param1, param2); } VUINT vMessageWnd::wndProc_setup(UINT msg, VUINT param1, VUINT param2) { msgmsg = msg; msgparam1 = param1; msgparam2 = param2; return wndProc(msg, param1, param2); } LRESULT CALLBACK vMessageWnd::static_wndProc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam) { if (msg == WM_INITDIALOG) { SetWindowLongPtr(hwnd, GWLP_USERDATA, lparam); } else if (msg == WM_CREATE) { CREATESTRUCT *create = (CREATESTRUCT*) lparam; SetWindowLongPtr(hwnd, GWLP_USERDATA, (DWORD)create->lpCreateParams); } vMessageWnd *wnd = (vMessageWnd*)GetWindowLongPtr(hwnd, GWLP_USERDATA); return wnd ? wnd->wndProc_setup(msg, wparam, lparam) : DefWindowProc(hwnd, msg, wparam, lparam); }
// Copyright (c) 2007-2012 Hartmut Kaiser // // SPDX-License-Identifier: BSL-1.0 // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #if !defined(HPX_HEARTBEAT_WIN_PERF_COUNTERS_2011_JUL_24_0259PM) #define HPX_HEARTBEAT_WIN_PERF_COUNTERS_2011_JUL_24_0259PM #include <hpx/hpx.hpp> /////////////////////////////////////////////////////////////////////////////// // This is code specific to Windows #if defined(HPX_WINDOWS) #include <cstdint> /////////////////////////////////////////////////////////////////////////////// // Install the windows performance counters exposing the HPX counters. void install_windows_counters(); // Update the data to be exposed as the windows performance counter values. void update_windows_counters(std::uint64_t value); // Uninstall the windows performance counters exposing the HPX counters. void uninstall_windows_counters(); #endif #endif
// ____ ______ __ // / __ \ / ____// / // / /_/ // / / / // / ____// /___ / /___ PixInsight Class Library // /_/ \____//_____/ PCL 02.01.11.0938 // ---------------------------------------------------------------------------- // pcl/Cursor.cpp - Released 2019-01-21T12:06:21Z // ---------------------------------------------------------------------------- // This file is part of the PixInsight Class Library (PCL). // PCL is a multiplatform C++ framework for development of PixInsight modules. // // Copyright (c) 2003-2019 Pleiades Astrophoto S.L. All Rights Reserved. // // Redistribution and use in both source and binary forms, with or without // modification, is permitted provided that the following conditions are met: // // 1. All redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // 2. All redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. Neither the names "PixInsight" and "Pleiades Astrophoto", nor the names // of their contributors, may be used to endorse or promote products derived // from this software without specific prior written permission. For written // permission, please contact info@pixinsight.com. // // 4. All products derived from this software, in any form whatsoever, must // reproduce the following acknowledgment in the end-user documentation // and/or other materials provided with the product: // // "This product is based on software from the PixInsight project, developed // by Pleiades Astrophoto and its contributors (http://pixinsight.com/)." // // Alternatively, if that is where third-party acknowledgments normally // appear, this acknowledgment must be reproduced in the product itself. // // THIS SOFTWARE IS PROVIDED BY PLEIADES ASTROPHOTO AND ITS CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED // TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL PLEIADES ASTROPHOTO OR ITS // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, BUSINESS // INTERRUPTION; PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; AND LOSS OF USE, // DATA OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // ---------------------------------------------------------------------------- #include <pcl/AutoLock.h> #include <pcl/Bitmap.h> #include <pcl/Cursor.h> #include <pcl/api/APIException.h> #include <pcl/api/APIInterface.h> namespace pcl { // ---------------------------------------------------------------------------- Cursor::Cursor( std_cursor stdShape ) : UIObject( (*API->Cursor->CreateCursor)( ModuleHandle(), stdShape ) ) { if ( IsNull() ) throw APIFunctionError( "CreateCursor" ); } Cursor::Cursor( const Bitmap& p, const pcl::Point& hotSpot ) : UIObject( (*API->Cursor->CreateBitmapCursor)( ModuleHandle(), p.handle, hotSpot.x, hotSpot.y ) ) { if ( IsNull() ) throw APIFunctionError( "CreateBitmapCursor" ); } Cursor::Cursor( const Bitmap& p, int hotSpotX, int hotSpotY ) : UIObject( (*API->Cursor->CreateBitmapCursor)( ModuleHandle(), p.handle, hotSpotX, hotSpotY ) ) { if ( IsNull() ) throw APIFunctionError( "CreateBitmapCursor" ); } // ---------------------------------------------------------------------------- Cursor& Cursor::Null() { static Cursor* nullCursor = nullptr; static Mutex mutex; volatile AutoLock lock( mutex ); if ( nullCursor == nullptr ) nullCursor = new Cursor( nullptr ); return *nullCursor; } // ---------------------------------------------------------------------------- pcl::Point Cursor::HotSpot() const { pcl::Point p; (*API->Cursor->GetCursorHotSpot)( handle, &p.x, &p.y ); return p; } // ---------------------------------------------------------------------------- pcl::Point Cursor::Position() { pcl::Point p; (*API->Global->GetCursorPosition)( &p.x, &p.y ); return p; } // ---------------------------------------------------------------------------- void Cursor::SetPosition( int x, int y ) { (*API->Global->SetCursorPosition)( x, y ); } // ---------------------------------------------------------------------------- void* Cursor::CloneHandle() const { return (*API->Cursor->CloneCursor)( ModuleHandle(), handle ); } // ---------------------------------------------------------------------------- } // pcl // ---------------------------------------------------------------------------- // EOF pcl/Cursor.cpp - Released 2019-01-21T12:06:21Z
// Pyraminx.cpp #include "Pyraminx.h" wxIMPLEMENT_DYNAMIC_CLASS( Pyraminx, PyraminxBase ); Pyraminx::Pyraminx( void ) { } /*virtual*/ Pyraminx::~Pyraminx( void ) { } /*virtual*/ int Pyraminx::Layers( void ) { return 3; } // Pyraminx.cpp
#include <MaterialXGenShader/Syntax.h> #include <MaterialXGenShader/Shader.h> #include <MaterialXCore/Value.h> namespace MaterialX { Syntax::Syntax() { } void Syntax::registerTypeSyntax(const TypeDesc* type, TypeSyntaxPtr syntax) { auto it = _typeSyntaxByType.find(type); if (it != _typeSyntaxByType.end()) { _typeSyntaxs[it->second] = syntax; } else { _typeSyntaxs.push_back(syntax); _typeSyntaxByType[type] = _typeSyntaxs.size() - 1; } // Make this type a restricted name registerRestrictedNames({ syntax->getName() }); } void Syntax::registerRestrictedNames(const StringSet& names) { _restrictedNames.insert(names.begin(), names.end()); } void Syntax::registerInvalidTokens(const StringMap& tokens) { _invalidTokens.insert(tokens.begin(), tokens.end()); } /// Returns the type syntax object for a named type. /// Throws an exception if a type syntax is not defined for the given type. const TypeSyntax& Syntax::getTypeSyntax(const TypeDesc* type) const { auto it = _typeSyntaxByType.find(type); if (it == _typeSyntaxByType.end()) { throw ExceptionShaderGenError("No syntax is defined for the given type '" + type->getName() + "'."); } return *_typeSyntaxs[it->second]; } string Syntax::getValue(const TypeDesc* type, const Value& value, bool uniform) const { const TypeSyntax& syntax = getTypeSyntax(type); return syntax.getValue(value, uniform); } const string& Syntax::getDefaultValue(const TypeDesc* type, bool uniform) const { const TypeSyntax& syntax = getTypeSyntax(type); return syntax.getDefaultValue(uniform); } const string& Syntax::getTypeName(const TypeDesc* type) const { const TypeSyntax& syntax = getTypeSyntax(type); return syntax.getName(); } string Syntax::getOutputTypeName(const TypeDesc* type) const { const TypeSyntax& syntax = getTypeSyntax(type); const string& outputModifier = getOutputQualifier(); return outputModifier.size() ? outputModifier + " " + syntax.getName() : syntax.getName(); } const string& Syntax::getTypeAlias(const TypeDesc* type) const { const TypeSyntax& syntax = getTypeSyntax(type); return syntax.getTypeAlias(); } const string& Syntax::getTypeDefinition(const TypeDesc* type) const { const TypeSyntax& syntax = getTypeSyntax(type); return syntax.getTypeDefinition(); } string Syntax::getSwizzledVariable(const string& srcName, const TypeDesc* srcType, const string& channels, const TypeDesc* dstType) const { static const std::unordered_map<char, size_t> s_channelsMapping = { { 'r', 0 },{ 'x', 0 }, { 'g', 1 },{ 'y', 1 }, { 'b', 2 },{ 'z', 2 }, { 'a', 3 },{ 'w', 3 } }; const TypeSyntax& srcSyntax = getTypeSyntax(srcType); const TypeSyntax& dstSyntax = getTypeSyntax(dstType); const vector<string>& srcMembers = srcSyntax.getMembers(); vector<string> membersSwizzled; for (size_t i = 0; i < channels.size(); ++i) { const char ch = channels[i]; if (ch == '0' || ch == '1') { membersSwizzled.push_back(string(1,ch)); continue; } auto it = s_channelsMapping.find(ch); if (it == s_channelsMapping.end()) { throw ExceptionShaderGenError("Invalid channel pattern '" + channels + "'."); } if (srcMembers.empty()) { membersSwizzled.push_back(srcName); } else { int channelIndex = srcType->getChannelIndex(ch); if (channelIndex < 0 || channelIndex >= static_cast<int>(srcMembers.size())) { throw ExceptionShaderGenError("Given channel index: '" + string(1,ch) + "' in channels pattern is incorrect for type '" + srcType->getName() + "'."); } membersSwizzled.push_back(srcName + srcMembers[channelIndex]); } } return dstSyntax.getValue(membersSwizzled, false); } void Syntax::makeUnique(string& name, UniqueNameMap& uniqueNames) const { if (_invalidTokens.size()) { name = replaceSubstrings(name, _invalidTokens); } UniqueNameMap::iterator it = uniqueNames.find(name); if (it != uniqueNames.end()) { name += std::to_string(++(it->second)); } else { if (_restrictedNames.count(name)) { uniqueNames[name] = 1; name += "1"; } else { uniqueNames[name] = 0; } } } const vector<string> TypeSyntax::EMPTY_MEMBERS; TypeSyntax::TypeSyntax(const string& name, const string& defaultValue, const string& uniformDefaultValue, const string& typeAlias, const string& typeDefinition, const vector<string>& members) : _name(name) , _defaultValue(defaultValue) , _uniformDefaultValue(uniformDefaultValue) , _typeAlias(typeAlias) , _typeDefinition(typeDefinition) , _members(members) { } ScalarTypeSyntax::ScalarTypeSyntax(const string& name, const string& defaultValue, const string& uniformDefaultValue, const string& typeAlias, const string& typeDefinition) : TypeSyntax(name, defaultValue, uniformDefaultValue, typeAlias, typeDefinition, EMPTY_MEMBERS) { } string ScalarTypeSyntax::getValue(const Value& value, bool /*uniform*/) const { return value.getValueString(); } string ScalarTypeSyntax::getValue(const vector<string>& values, bool /*uniform*/) const { if (values.empty()) { throw ExceptionShaderGenError("No values given to construct a value"); } return values[0]; } StringTypeSyntax::StringTypeSyntax(const string& name, const string& defaultValue, const string& uniformDefaultValue, const string& typeAlias, const string& typeDefinition) : ScalarTypeSyntax(name, defaultValue, uniformDefaultValue, typeAlias, typeDefinition) { } string StringTypeSyntax::getValue(const Value& value, bool /*uniform*/) const { return "\"" + value.getValueString() + "\""; } AggregateTypeSyntax::AggregateTypeSyntax(const string& name, const string& defaultValue, const string& uniformDefaultValue, const string& typeAlias, const string& typeDefinition, const vector<string>& members) : TypeSyntax(name, defaultValue, uniformDefaultValue, typeAlias, typeDefinition, members) { } string AggregateTypeSyntax::getValue(const Value& value, bool /*uniform*/) const { return getName() + "(" + value.getValueString() + ")"; } string AggregateTypeSyntax::getValue(const vector<string>& values, bool /*uniform*/) const { if (values.empty()) { throw ExceptionShaderGenError("No values given to construct a value"); } string result = getName() + "(" + values[0]; for (size_t i=1; i<values.size(); ++i) { result += ", " + values[i]; } result += ")"; return result; } }
//============================================================================== // Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II // Copyright 2009 - 2011 LRI UMR 8623 CNRS/Univ Paris Sud XI // // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE.txt or copy at // http://www.boost.org/LICENSE_1_0.txt //============================================================================== #ifndef BOOST_SIMD_BITWISE_FUNCTIONS_SCALAR_RSHR_HPP_INCLUDED #define BOOST_SIMD_BITWISE_FUNCTIONS_SCALAR_RSHR_HPP_INCLUDED #include <boost/simd/bitwise/functions/rshr.hpp> #include <boost/simd/include/functions/simd/shift_left.hpp> #include <boost/simd/include/functions/scalar/shr.hpp> #include <boost/simd/include/functions/scalar/unary_minus.hpp> #include <boost/simd/include/functions/scalar/bitwise_cast.hpp> #include <boost/dispatch/meta/as_integer.hpp> namespace boost { namespace simd { namespace ext { BOOST_DISPATCH_IMPLEMENT ( rshr_, tag::cpu_, (A0)(A1) , (scalar_< arithmetic_<A0> >) (scalar_< integer_<A1> >) ) { typedef A0 result_type; BOOST_SIMD_FUNCTOR_CALL(2) { return (a1>0) ? shr(a0, a1): shl(a0, -a1); } }; BOOST_DISPATCH_IMPLEMENT ( rshr_, tag::cpu_, (A0)(A1) , (scalar_< arithmetic_<A0> >) (scalar_< unsigned_<A1> >) ) { typedef A0 result_type; BOOST_SIMD_FUNCTOR_CALL(2) { return shr(a0, a1); } }; BOOST_DISPATCH_IMPLEMENT ( rshr_, tag::cpu_, (A0)(A1) , (scalar_< floating_<A0> >)(scalar_< integer_<A1> >) ) { typedef A0 result_type; BOOST_SIMD_FUNCTOR_CALL(2) { typedef typename dispatch::meta::as_integer<A0, signed>::type itype; return bitwise_cast<result_type>(rshr(bitwise_cast<itype>(a0),a1)); } }; } } } #endif
#include <avr/io.h> #include <avr/sleep.h> #include <avr/interrupt.h> #include <Arduino.h> #include "atomic.h" #include "device.h" #include "timer.h" static Device *t1; ISR(TIM1_COMPA_vect) { if (t1) t1->ready(); } bool Timer::begin() { t1 = this; TCCR1A = 0; // CTC mode, no prescaler TCCR1B = _BV(WGM12) | _BV(CS10); OCR1A = F_CPU / 1000 - 1; // 1ms return false; } void Timer::_enable(bool e) { Atomic block; TCNT1 = 0; if (e) TIMSK1 |= _BV(OCIE1A); else TIMSK1 &= ~_BV(OCIE1A); } unsigned Timer::_sleepmode() { return SLEEP_MODE_IDLE; }
/* ------------------------------------------------------------------ * Copyright (C) 2008 PacketVideo * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. * See the License for the specific language governing permissions * and limitations under the License. * ------------------------------------------------------------------- */ /**************************************************************************************** Portions of this file are derived from the following 3GPP standard: 3GPP TS 26.173 ANSI-C code for the Adaptive Multi-Rate - Wideband (AMR-WB) speech codec Available from http://www.3gpp.org (C) 2007, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC) Permission to distribute, modify and use this file under the standard license terms listed above has been obtained from the copyright holder. ****************************************************************************************/ /* ------------------------------------------------------------------------------ Filename: phase_dispersion.cpp Date: 05/08/2007 ------------------------------------------------------------------------------ REVISION HISTORY Description: ------------------------------------------------------------------------------ INPUT AND OUTPUT DEFINITIONS int16 gain_code, (i) Q0 : gain of code int16 gain_pit, (i) Q14 : gain of pitch int16 code[], (i/o) : code vector int16 mode, (i) : level, 0=hi, 1=lo, 2=off int16 disp_mem[], (i/o) : static memory (size = 8) int16 ScratchMem[] ------------------------------------------------------------------------------ FUNCTION DESCRIPTION post-processing to enhance noise in low bit rate. ------------------------------------------------------------------------------ REQUIREMENTS ------------------------------------------------------------------------------ REFERENCES ------------------------------------------------------------------------------ PSEUDO-CODE ------------------------------------------------------------------------------ */ /*---------------------------------------------------------------------------- ; INCLUDES ----------------------------------------------------------------------------*/ #include "pv_amr_wb_type_defs.h" #include "pvamrwbdecoder_basic_op.h" #include "pvamrwbdecoder_cnst.h" #include "pvamrwbdecoder_mem_funcs.h" #include "pvamrwbdecoder_acelp.h" #include "pvamrwb_math_op.h" /*---------------------------------------------------------------------------- ; MACROS ; Define module specific macros here ----------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------- ; DEFINES ; Include all pre-processor statements here. Include conditional ; compile variables also. ----------------------------------------------------------------------------*/ #define pitch_0_9 14746 /* 0.9 in Q14 */ #define pitch_0_6 9830 /* 0.6 in Q14 */ #define L_SUBFR 64 /*---------------------------------------------------------------------------- ; LOCAL FUNCTION DEFINITIONS ; Function Prototype declaration ----------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------- ; LOCAL STORE/BUFFER/POINTER DEFINITIONS ; Variable declaration - defined here and used outside this module ----------------------------------------------------------------------------*/ /* impulse response with phase dispersion */ /* 2.0 - 6.4 kHz phase dispersion */ const int16 ph_imp_low[L_SUBFR] = { 20182, 9693, 3270, -3437, 2864, -5240, 1589, -1357, 600, 3893, -1497, -698, 1203, -5249, 1199, 5371, -1488, -705, -2887, 1976, 898, 721, -3876, 4227, -5112, 6400, -1032, -4725, 4093, -4352, 3205, 2130, -1996, -1835, 2648, -1786, -406, 573, 2484, -3608, 3139, -1363, -2566, 3808, -639, -2051, -541, 2376, 3932, -6262, 1432, -3601, 4889, 370, 567, -1163, -2854, 1914, 39, -2418, 3454, 2975, -4021, 3431 }; /* 3.2 - 6.4 kHz phase dispersion */ const int16 ph_imp_mid[L_SUBFR] = { 24098, 10460, -5263, -763, 2048, -927, 1753, -3323, 2212, 652, -2146, 2487, -3539, 4109, -2107, -374, -626, 4270, -5485, 2235, 1858, -2769, 744, 1140, -763, -1615, 4060, -4574, 2982, -1163, 731, -1098, 803, 167, -714, 606, -560, 639, 43, -1766, 3228, -2782, 665, 763, 233, -2002, 1291, 1871, -3470, 1032, 2710, -4040, 3624, -4214, 5292, -4270, 1563, 108, -580, 1642, -2458, 957, 544, 2540 }; /*---------------------------------------------------------------------------- ; EXTERNAL FUNCTION REFERENCES ; Declare functions defined elsewhere and referenced in this module ----------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------- ; EXTERNAL GLOBAL STORE/BUFFER/POINTER REFERENCES ; Declare variables used in this module but defined elsewhere ----------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------- ; FUNCTION CODE ----------------------------------------------------------------------------*/ void phase_dispersion( int16 gain_code, /* (i) Q0 : gain of code */ int16 gain_pit, /* (i) Q14 : gain of pitch */ int16 code[], /* (i/o) : code vector */ int16 mode, /* (i) : level, 0=hi, 1=lo, 2=off */ int16 disp_mem[], /* (i/o) : static memory (size = 8) */ int16 ScratchMem[] ) { int16 i, j, state; int16 *prev_gain_pit, *prev_gain_code, *prev_state; int16 *code2 = ScratchMem; prev_state = disp_mem; prev_gain_code = disp_mem + 1; prev_gain_pit = disp_mem + 2; pv_memset((void *)code2, 0, (2*L_SUBFR)*sizeof(*code2)); if (gain_pit < pitch_0_6) { state = 0; } else if (gain_pit < pitch_0_9) { state = 1; } else { state = 2; } for (i = 5; i > 0; i--) { prev_gain_pit[i] = prev_gain_pit[i - 1]; } prev_gain_pit[0] = gain_pit; if (sub_int16(gain_code, *prev_gain_code) > shl_int16(*prev_gain_code, 1)) { /* onset */ if (state < 2) { state++; } } else { j = 0; for (i = 0; i < 6; i++) { if (prev_gain_pit[i] < pitch_0_6) { j++; } } if (j > 2) { state = 0; } if (state > *prev_state + 1) { state--; } } *prev_gain_code = gain_code; *prev_state = state; /* circular convolution */ state += mode; /* level of dispersion */ if (state == 0) { for (i = 0; i < L_SUBFR; i++) { if (code[i] != 0) { for (j = 0; j < L_SUBFR; j++) { code2[i + j] = add_int16(code2[i + j], mult_int16_r(code[i], ph_imp_low[j])); } } } } else if (state == 1) { for (i = 0; i < L_SUBFR; i++) { if (code[i] != 0) { for (j = 0; j < L_SUBFR; j++) { code2[i + j] = add_int16(code2[i + j], mult_int16_r(code[i], ph_imp_mid[j])); } } } } if (state < 2) { for (i = 0; i < L_SUBFR; i++) { code[i] = add_int16(code2[i], code2[i + L_SUBFR]); } } return; }
/****************************************************************************** * * Project: OpenGIS Simple Features Reference Implementation * Purpose: Implements OGRGRASSDriver class. * Author: Radim Blazek, radim.blazek@gmail.com * ****************************************************************************** * Copyright (c) 2005, Radim Blazek <radim.blazek@gmail.com> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include "ogrgrass.h" #include "cpl_conv.h" #include "cpl_string.h" CPL_CVSID("$Id: ogrgrassdriver.cpp 1761acd90777d5bcc49eddbc13c193098f0ed40b 2020-10-01 12:12:00 +0200 Even Rouault $") /************************************************************************/ /* ~OGRGRASSDriver() */ /************************************************************************/ OGRGRASSDriver::~OGRGRASSDriver() { } /************************************************************************/ /* GetName() */ /************************************************************************/ const char *OGRGRASSDriver::GetName() { return "OGR_GRASS"; } /************************************************************************/ /* Open() */ /************************************************************************/ OGRDataSource *OGRGRASSDriver::Open( const char * pszFilename, int bUpdate ) { OGRGRASSDataSource *poDS = new OGRGRASSDataSource(); if( !poDS->Open( pszFilename, bUpdate, TRUE ) ) { delete poDS; return NULL; } else { return poDS; } } /************************************************************************/ /* TestCapability() */ /************************************************************************/ int OGRGRASSDriver::TestCapability( const char * /*pszCap*/ ) { return FALSE; } /************************************************************************/ /* RegisterOGRGRASS() */ /************************************************************************/ void RegisterOGRGRASS() { if (! GDAL_CHECK_VERSION("OGR/GRASS driver")) return; if( GDALGetDriverByName( "OGR_GRASS" ) != NULL ) return; OGRGRASSDriver *poDriver = new OGRGRASSDriver(); poDriver->SetDescription( "GRASS" ); poDriver->SetMetadataItem( GDAL_DCAP_VECTOR, "YES" ); poDriver->SetMetadataItem( GDAL_DMD_LONGNAME, "GRASS Vectors (5.7+)" ); poDriver->SetMetadataItem( GDAL_DMD_HELPTOPIC, "drivers/vector/grass.html" ); OGRSFDriverRegistrar::GetRegistrar()->RegisterDriver( poDriver ); }
// Copyright (c) 2020 The Zortcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <test/fuzz/FuzzedDataProvider.h> #include <test/fuzz/fuzz.h> #include <test/fuzz/util.h> #include <cstdint> #include <string> #include <vector> #if defined(__has_builtin) #if __has_builtin(__builtin_add_overflow) #define HAVE_BUILTIN_ADD_OVERFLOW #endif #elif defined(__GNUC__) && (__GNUC__ >= 5) #define HAVE_BUILTIN_ADD_OVERFLOW #endif namespace { template <typename T> void TestAdditionOverflow(FuzzedDataProvider& fuzzed_data_provider) { const T i = fuzzed_data_provider.ConsumeIntegral<T>(); const T j = fuzzed_data_provider.ConsumeIntegral<T>(); const bool is_addition_overflow_custom = AdditionOverflow(i, j); #if defined(HAVE_BUILTIN_ADD_OVERFLOW) T result_builtin; const bool is_addition_overflow_builtin = __builtin_add_overflow(i, j, &result_builtin); assert(is_addition_overflow_custom == is_addition_overflow_builtin); if (!is_addition_overflow_custom) { assert(i + j == result_builtin); } #else if (!is_addition_overflow_custom) { (void)(i + j); } #endif } } // namespace void test_one_input(const std::vector<uint8_t>& buffer) { FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size()); TestAdditionOverflow<int64_t>(fuzzed_data_provider); TestAdditionOverflow<uint64_t>(fuzzed_data_provider); TestAdditionOverflow<int32_t>(fuzzed_data_provider); TestAdditionOverflow<uint32_t>(fuzzed_data_provider); TestAdditionOverflow<int16_t>(fuzzed_data_provider); TestAdditionOverflow<uint16_t>(fuzzed_data_provider); TestAdditionOverflow<char>(fuzzed_data_provider); TestAdditionOverflow<unsigned char>(fuzzed_data_provider); TestAdditionOverflow<signed char>(fuzzed_data_provider); }
/* * Copyright (C) 2011 Google Inc. All rights reserved. * Copyright (C) 2011, 2012, 2015 Ericsson AB. All rights reserved. * Copyright (C) 2013-2019 Apple Inc. All rights reserved. * Copyright (C) 2013 Nokia Corporation and/or its subsidiary(-ies). * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "MediaStream.h" #if ENABLE(MEDIA_STREAM) #include "Document.h" #include "Event.h" #include "EventNames.h" #include "Logging.h" #include "MediaStreamTrackEvent.h" #include "Page.h" #include "RealtimeMediaSource.h" #include <wtf/IsoMallocInlines.h> namespace WebCore { WTF_MAKE_ISO_ALLOCATED_IMPL(MediaStream); Ref<MediaStream> MediaStream::create(Document& document) { return MediaStream::create(document, MediaStreamPrivate::create(document.logger(), { })); } Ref<MediaStream> MediaStream::create(Document& document, MediaStream& stream) { return adoptRef(*new MediaStream(document, stream.getTracks())); } Ref<MediaStream> MediaStream::create(Document& document, const MediaStreamTrackVector& tracks) { return adoptRef(*new MediaStream(document, tracks)); } Ref<MediaStream> MediaStream::create(Document& document, Ref<MediaStreamPrivate>&& streamPrivate) { return adoptRef(*new MediaStream(document, WTFMove(streamPrivate))); } static inline MediaStreamTrackPrivateVector createTrackPrivateVector(const MediaStreamTrackVector& tracks) { return map(tracks, [](auto& track) { return makeRefPtr(&track->privateTrack()); }); } MediaStream::MediaStream(Document& document, const MediaStreamTrackVector& tracks) : ActiveDOMObject(document) , m_private(MediaStreamPrivate::create(document.logger(), createTrackPrivateVector(tracks))) { // This constructor preserves MediaStreamTrack instances and must be used by calls originating // from the JavaScript MediaStream constructor. for (auto& track : tracks) m_trackSet.add(track->id(), track); setIsActive(m_private->active()); m_private->addObserver(*this); suspendIfNeeded(); } MediaStream::MediaStream(Document& document, Ref<MediaStreamPrivate>&& streamPrivate) : ActiveDOMObject(document) , m_private(WTFMove(streamPrivate)) { ALWAYS_LOG(LOGIDENTIFIER); for (auto& trackPrivate : m_private->tracks()) m_trackSet.add(trackPrivate->id(), MediaStreamTrack::create(document, *trackPrivate)); setIsActive(m_private->active()); m_private->addObserver(*this); suspendIfNeeded(); } MediaStream::~MediaStream() { // Set isActive to false immediately so any callbacks triggered by shutting down, e.g. // mediaState(), are short circuited. m_isActive = false; m_private->removeObserver(*this); if (auto* document = this->document()) { if (m_isWaitingUntilMediaCanStart) document->removeMediaCanStartListener(*this); } } RefPtr<MediaStream> MediaStream::clone() { ALWAYS_LOG(LOGIDENTIFIER); MediaStreamTrackVector clonedTracks; clonedTracks.reserveInitialCapacity(m_trackSet.size()); for (auto& track : m_trackSet.values()) clonedTracks.uncheckedAppend(track->clone()); return MediaStream::create(*document(), clonedTracks); } void MediaStream::addTrack(MediaStreamTrack& track) { ALWAYS_LOG(LOGIDENTIFIER, track.logIdentifier()); if (getTrackById(track.privateTrack().id())) return; internalAddTrack(track); m_private->addTrack(track.privateTrack()); } void MediaStream::removeTrack(MediaStreamTrack& track) { ALWAYS_LOG(LOGIDENTIFIER, track.logIdentifier()); if (auto taken = internalTakeTrack(track.id())) { ASSERT(taken.get() == &track); m_private->removeTrack(track.privateTrack()); } } MediaStreamTrack* MediaStream::getTrackById(String id) { auto iterator = m_trackSet.find(id); if (iterator != m_trackSet.end()) return iterator->value.get(); return nullptr; } MediaStreamTrackVector MediaStream::getAudioTracks() const { return trackVectorForType(RealtimeMediaSource::Type::Audio); } MediaStreamTrackVector MediaStream::getVideoTracks() const { return trackVectorForType(RealtimeMediaSource::Type::Video); } MediaStreamTrackVector MediaStream::getTracks() const { return copyToVector(m_trackSet.values()); } void MediaStream::activeStatusChanged() { updateActiveState(); } void MediaStream::didAddTrack(MediaStreamTrackPrivate& trackPrivate) { ScriptExecutionContext* context = scriptExecutionContext(); if (!context) return; if (getTrackById(trackPrivate.id())) return; auto track = MediaStreamTrack::create(*context, trackPrivate); internalAddTrack(track.copyRef()); dispatchEvent(MediaStreamTrackEvent::create(eventNames().addtrackEvent, Event::CanBubble::No, Event::IsCancelable::No, WTFMove(track))); } void MediaStream::didRemoveTrack(MediaStreamTrackPrivate& trackPrivate) { if (auto track = internalTakeTrack(trackPrivate.id())) dispatchEvent(MediaStreamTrackEvent::create(eventNames().removetrackEvent, Event::CanBubble::No, Event::IsCancelable::No, WTFMove(track))); } void MediaStream::addTrackFromPlatform(Ref<MediaStreamTrack>&& track) { ALWAYS_LOG(LOGIDENTIFIER, track->logIdentifier()); auto& privateTrack = track->privateTrack(); internalAddTrack(track.copyRef()); m_private->addTrack(privateTrack); dispatchEvent(MediaStreamTrackEvent::create(eventNames().addtrackEvent, Event::CanBubble::No, Event::IsCancelable::No, WTFMove(track))); } void MediaStream::internalAddTrack(Ref<MediaStreamTrack>&& trackToAdd) { ASSERT(!m_trackSet.contains(trackToAdd->id())); m_trackSet.add(trackToAdd->id(), WTFMove(trackToAdd)); updateActiveState(); } RefPtr<MediaStreamTrack> MediaStream::internalTakeTrack(const String& trackId) { auto track = m_trackSet.take(trackId); if (track) updateActiveState(); return track; } void MediaStream::setIsActive(bool active) { if (m_isActive == active) return; ALWAYS_LOG(LOGIDENTIFIER, active); m_isActive = active; statusDidChange(); } void MediaStream::mediaCanStart(Document& document) { ALWAYS_LOG(LOGIDENTIFIER); ASSERT_UNUSED(document, &document == this->document()); ASSERT(m_isWaitingUntilMediaCanStart); if (m_isWaitingUntilMediaCanStart) { m_isWaitingUntilMediaCanStart = false; startProducingData(); } } void MediaStream::startProducingData() { Document* document = this->document(); if (!document || !document->page()) return; ALWAYS_LOG(LOGIDENTIFIER); // If we can't start a load right away, start it later. if (!document->page()->canStartMedia()) { ALWAYS_LOG(LOGIDENTIFIER, "not allowed to start in background, waiting"); if (m_isWaitingUntilMediaCanStart) return; m_isWaitingUntilMediaCanStart = true; document->addMediaCanStartListener(*this); return; } if (m_isProducingData) return; m_isProducingData = true; m_private->startProducingData(); } void MediaStream::stopProducingData() { ALWAYS_LOG(LOGIDENTIFIER); if (!m_isProducingData) return; m_isProducingData = false; m_private->stopProducingData(); } MediaProducer::MediaStateFlags MediaStream::mediaState() const { MediaProducer::MediaStateFlags state = MediaProducer::IsNotPlaying; if (!m_isActive || !document() || !document()->page()) return state; for (const auto& track : m_trackSet.values()) state |= track->mediaState(); return state; } void MediaStream::statusDidChange() { if (auto* document = this->document()) { if (!m_isActive) return; document->updateIsPlayingMedia(); } } void MediaStream::characteristicsChanged() { auto state = mediaState(); if (m_state != state) { m_state = state; statusDidChange(); } } void MediaStream::updateActiveState() { bool active = false; for (auto& track : m_trackSet.values()) { if (!track->ended()) { active = true; break; } } if (m_isActive == active) return; setIsActive(active); } MediaStreamTrackVector MediaStream::trackVectorForType(RealtimeMediaSource::Type filterType) const { MediaStreamTrackVector tracks; for (auto& track : m_trackSet.values()) { if (track->source().type() == filterType) tracks.append(track); } return tracks; } Document* MediaStream::document() const { return downcast<Document>(scriptExecutionContext()); } void MediaStream::stop() { m_isActive = false; } const char* MediaStream::activeDOMObjectName() const { return "MediaStream"; } bool MediaStream::virtualHasPendingActivity() const { return m_isActive; } #if !RELEASE_LOG_DISABLED WTFLogChannel& MediaStream::logChannel() const { return LogWebRTC; } #endif } // namespace WebCore #endif // ENABLE(MEDIA_STREAM)
//===--- CSClosure.cpp - Closures -----------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // This file implements constraint generation and solution application for // closures. It provides part of the implementation of the ConstraintSystem // class. // //===----------------------------------------------------------------------===// #include "MiscDiagnostics.h" #include "TypeChecker.h" #include "swift/Sema/ConstraintSystem.h" using namespace swift; using namespace swift::constraints; namespace { // Produce an implicit empty tuple expression. Expr *getVoidExpr(ASTContext &ctx) { auto *voidExpr = TupleExpr::createEmpty(ctx, /*LParenLoc=*/SourceLoc(), /*RParenLoc=*/SourceLoc(), /*Implicit=*/true); voidExpr->setType(ctx.TheEmptyTupleType); return voidExpr; } /// Find any type variable references inside of an AST node. class TypeVariableRefFinder : public ASTWalker { ConstraintSystem &CS; ASTNode Parent; llvm::SmallPtrSetImpl<TypeVariableType *> &ReferencedVars; public: TypeVariableRefFinder( ConstraintSystem &cs, ASTNode parent, llvm::SmallPtrSetImpl<TypeVariableType *> &referencedVars) : CS(cs), Parent(parent), ReferencedVars(referencedVars) {} std::pair<bool, Expr *> walkToExprPre(Expr *expr) override { if (auto *DRE = dyn_cast<DeclRefExpr>(expr)) { if (auto type = CS.getTypeIfAvailable(DRE->getDecl())) inferVariables(type); } return {true, expr}; } std::pair<bool, Stmt *> walkToStmtPre(Stmt *stmt) override { // Return statements have to reference outside result type // since all of them are joined by it if it's not specified // explicitly. if (isa<ReturnStmt>(stmt)) { if (auto *closure = getAsExpr<ClosureExpr>(Parent)) { inferVariables(CS.getClosureType(closure)->getResult()); } } return {true, stmt}; } private: void inferVariables(Type type) { type = type->getWithoutSpecifierType(); // Record the type variable itself because it has to // be in scope even when already bound. if (auto *typeVar = type->getAs<TypeVariableType>()) { ReferencedVars.insert(typeVar); // It is possible that contextual type of a parameter/result // has been assigned to e.g. an anonymous or named argument // early, to facilitate closure type checking. Such a // type can have type variables inside e.g. // // func test<T>(_: (UnsafePointer<T>) -> Void) {} // // test { ptr in // ... // } // // Type variable representing `ptr` in the body of // this closure would be bound to `UnsafePointer<$T>` // in this case, where `$T` is a type variable for a // generic parameter `T`. type = CS.getFixedTypeRecursive(typeVar, /*wantRValue=*/false); if (type->isEqual(typeVar)) return; } if (type->hasTypeVariable()) { SmallPtrSet<TypeVariableType *, 4> typeVars; type->getTypeVariables(typeVars); ReferencedVars.insert(typeVars.begin(), typeVars.end()); } } }; /// Find any references to not yet resolved outer closure parameters /// used in the body of the inner closure. This is required because /// isolated conjunctions, just like single-expression closures, have /// to be connected to type variables they are going to use, otherwise /// they'll get placed in a separate solver component and would never /// produce a solution. class UnresolvedClosureParameterCollector : public ASTWalker { ConstraintSystem &CS; llvm::SmallSetVector<TypeVariableType *, 4> Vars; public: UnresolvedClosureParameterCollector(ConstraintSystem &cs) : CS(cs) {} std::pair<bool, Expr *> walkToExprPre(Expr *expr) override { if (auto *DRE = dyn_cast<DeclRefExpr>(expr)) { auto *decl = DRE->getDecl(); if (isa<ParamDecl>(decl)) { if (auto type = CS.getTypeIfAvailable(decl)) { if (auto *typeVar = type->getAs<TypeVariableType>()) { Vars.insert(typeVar); } else if (type->hasTypeVariable()) { // Parameter or result type could be only partially // resolved e.g. `{ (x: X) -> Void in ... }` where // `X` is a generic type. SmallPtrSet<TypeVariableType *, 4> typeVars; type->getTypeVariables(typeVars); Vars.insert(typeVars.begin(), typeVars.end()); } } } } return {true, expr}; } ArrayRef<TypeVariableType *> getVariables() const { return Vars.getArrayRef(); } }; // MARK: Constraint generation /// Check whether it makes sense to convert this element into a constraint. static bool isViableElement(ASTNode element) { if (auto *decl = element.dyn_cast<Decl *>()) { // - Ignore variable declarations, they are handled by pattern bindings; // - Ignore #if, the chosen children should appear in the // surrounding context; // - Skip #warning and #error, they are handled during solution // application. if (isa<VarDecl>(decl) || isa<IfConfigDecl>(decl) || isa<PoundDiagnosticDecl>(decl)) return false; } if (auto *stmt = element.dyn_cast<Stmt *>()) { // Empty brace statements are now viable because they do not require // inference. if (auto *braceStmt = dyn_cast<BraceStmt>(stmt)) { return braceStmt->getNumElements() > 0; } } return true; } using ElementInfo = std::tuple<ASTNode, ContextualTypeInfo, /*isDiscarded=*/bool, ConstraintLocator *>; static void createConjunction(ConstraintSystem &cs, ArrayRef<ElementInfo> elements, ConstraintLocator *locator) { bool isIsolated = false; SmallVector<Constraint *, 4> constraints; SmallVector<TypeVariableType *, 2> referencedVars; if (locator->directlyAt<ClosureExpr>()) { auto *closure = castToExpr<ClosureExpr>(locator->getAnchor()); // Conjunction associated with the body of the closure has to // reference a type variable representing closure type, // otherwise it would get disconnected from its contextual type. referencedVars.push_back(cs.getType(closure)->castTo<TypeVariableType>()); // Body of the closure is always isolated from its context, only // its individual elements are allowed access to type information // from the outside e.g. parameters/result type. isIsolated = true; } UnresolvedClosureParameterCollector paramCollector(cs); for (const auto &entry : elements) { ASTNode element = std::get<0>(entry); ContextualTypeInfo context = std::get<1>(entry); bool isDiscarded = std::get<2>(entry); ConstraintLocator *elementLoc = std::get<3>(entry); if (!isViableElement(element)) continue; // If this conjunction going to represent a body of a closure, // let's collect references to not yet resolved outer // closure parameters. if (isIsolated) element.walk(paramCollector); constraints.push_back(Constraint::createClosureBodyElement( cs, element, context, elementLoc, isDiscarded)); } // It's possible that there are no viable elements in the body, // because e.g. whole body is an `#if` statement or it only has // declarations that are checked during solution application. // In such cases, let's avoid creating a conjunction. if (constraints.empty()) return; for (auto *externalVar : paramCollector.getVariables()) referencedVars.push_back(externalVar); cs.addUnsolvedConstraint(Constraint::createConjunction( cs, constraints, isIsolated, locator, referencedVars)); } ElementInfo makeElement(ASTNode node, ConstraintLocator *locator, ContextualTypeInfo context = ContextualTypeInfo(), bool isDiscarded = false) { return std::make_tuple(node, context, isDiscarded, locator); } static ProtocolDecl *getSequenceProtocol(ASTContext &ctx, SourceLoc loc, bool inAsyncContext) { return TypeChecker::getProtocol(ctx, loc, inAsyncContext ? KnownProtocolKind::AsyncSequence : KnownProtocolKind::Sequence); } /// Statement visitor that generates constraints for a given closure body. class ClosureConstraintGenerator : public StmtVisitor<ClosureConstraintGenerator, void> { friend StmtVisitor<ClosureConstraintGenerator, void>; ConstraintSystem &cs; ClosureExpr *closure; ConstraintLocator *locator; public: /// Whether an error was encountered while generating constraints. bool hadError = false; ClosureConstraintGenerator(ConstraintSystem &cs, ClosureExpr *closure, ConstraintLocator *locator) : cs(cs), closure(closure), locator(locator) {} void visitPattern(Pattern *pattern, ContextualTypeInfo context) { auto parentElement = locator->getLastElementAs<LocatorPathElt::ClosureBodyElement>(); if (!parentElement) { hadError = true; return; } if (auto *stmt = parentElement->getElement().dyn_cast<Stmt *>()) { if (isa<ForEachStmt>(stmt)) { visitForEachPattern(pattern, cast<ForEachStmt>(stmt)); return; } if (isa<CaseStmt>(stmt)) { visitCaseItemPattern(pattern, context); return; } } llvm_unreachable("Unsupported pattern"); } void visitCaseItem(CaseLabelItem *caseItem, ContextualTypeInfo context) { assert(context.purpose == CTP_CaseStmt); // Resolve the pattern. auto *pattern = caseItem->getPattern(); if (!caseItem->isPatternResolved()) { pattern = TypeChecker::resolvePattern(pattern, closure, /*isStmtCondition=*/false); if (!pattern) { hadError = true; return; } } // Let's generate constraints for pattern + where clause. // The assumption is that this shouldn't be too complex // to handle, but if it turns out to be false, this could // always be converted into a conjunction. // Generate constraints for pattern. visitPattern(pattern, context); auto *guardExpr = caseItem->getGuardExpr(); // Generate constraints for `where` clause (if any). if (guardExpr) { guardExpr = cs.generateConstraints(guardExpr, closure); if (!guardExpr) { hadError = true; return; } } // Save information about case item so it could be referenced during // solution application. cs.setCaseLabelItemInfo(caseItem, {pattern, guardExpr}); } private: /// This method handles both pattern and the sequence expression /// associated with `for-in` loop because types in this situation /// flow in both directions: /// /// - From pattern to sequence, informing its element type e.g. /// `for i: Int8 in 0 ..< 8` /// /// - From sequence to pattern, when pattern has no type information. void visitForEachPattern(Pattern *pattern, ForEachStmt *forEachStmt) { auto &ctx = cs.getASTContext(); bool isAsync = forEachStmt->getAwaitLoc().isValid(); // Verify pattern. { auto contextualPattern = ContextualPattern::forRawPattern(pattern, closure); Type patternType = TypeChecker::typeCheckPattern(contextualPattern); if (patternType->hasError()) { hadError = true; return; } } auto *sequenceProto = getSequenceProtocol(ctx, forEachStmt->getForLoc(), isAsync); if (!sequenceProto) { hadError = true; return; } auto *contextualLocator = cs.getConstraintLocator( locator, LocatorPathElt::ContextualType(CTP_ForEachStmt)); // Generate constraints to initialize the pattern. auto initType = cs.generateConstraints(pattern, contextualLocator, /*shouldBindPatternOneWay=*/false, /*patternBinding=*/nullptr, /*patternIndex=*/0); if (!initType) { hadError = true; return; } // Let's generate constraints for sequence associated with `for-in` // statement. We can't do that separately because pattern can inform // a type of the sequence e.g. `for in i: Int8 in 0 ..< 8 { ... }` auto *sequenceExpr = forEachStmt->getSequence(); auto *sequenceLocator = cs.getConstraintLocator(sequenceExpr); { SolutionApplicationTarget target( sequenceExpr, closure, CTP_ForEachSequence, sequenceProto->getDeclaredInterfaceType(), /*isDiscarded=*/false); if (cs.generateConstraints(target, FreeTypeVariableBinding::Disallow)) { hadError = true; return; } cs.setSolutionApplicationTarget(sequenceExpr, target); } Type sequenceType = cs.createTypeVariable(sequenceLocator, TVO_CanBindToNoEscape); // This "workaround" warrants an explanation for posterity. // // The reason why we can't simplify use \c getType(sequenceExpr) here // is due to how dependent member types are handled by \c simplifyTypeImpl // - if the base type didn't change (and it wouldn't because it's a fully // resolved concrete type) after simplification attempt the // whole dependent member type would be just re-created without attempting // to resolve it, so we have to use an intermediary here so that // \c elementType and \c iteratorType can be resolved correctly. cs.addConstraint(ConstraintKind::Conversion, cs.getType(sequenceExpr), sequenceType, sequenceLocator); auto elementAssocType = sequenceProto->getAssociatedType(ctx.Id_Element); Type elementType = DependentMemberType::get(sequenceType, elementAssocType); auto iteratorAssocType = sequenceProto->getAssociatedType( isAsync ? ctx.Id_AsyncIterator : ctx.Id_Iterator); Type iteratorType = DependentMemberType::get(sequenceType, iteratorAssocType); cs.addConstraint( ConstraintKind::Conversion, elementType, initType, cs.getConstraintLocator(contextualLocator, ConstraintLocator::SequenceElementType)); // Reference the makeIterator witness. FuncDecl *makeIterator = isAsync ? ctx.getAsyncSequenceMakeAsyncIterator() : ctx.getSequenceMakeIterator(); Type makeIteratorType = cs.createTypeVariable(locator, TVO_CanBindToNoEscape); cs.addValueWitnessConstraint(LValueType::get(sequenceType), makeIterator, makeIteratorType, closure, FunctionRefKind::Compound, contextualLocator); // After successful constraint generation, let's record // solution application target with all relevant information. { auto target = SolutionApplicationTarget::forForEachStmt( forEachStmt, sequenceProto, closure, /*bindTypeVarsOneWay=*/false, /*contextualPurpose=*/CTP_ForEachSequence); auto &targetInfo = target.getForEachStmtInfo(); targetInfo.sequenceType = sequenceType; targetInfo.elementType = elementType; targetInfo.iteratorType = iteratorType; targetInfo.initType = initType; target.setPattern(pattern); cs.setSolutionApplicationTarget(forEachStmt, target); } } void visitCaseItemPattern(Pattern *pattern, ContextualTypeInfo context) { Type patternType = cs.generateConstraints( pattern, locator, /*bindPatternVarsOneWay=*/false, /*patternBinding=*/nullptr, /*patternIndex=*/0); if (!patternType) { hadError = true; return; } // Convert the contextual type to the pattern, which establishes the // bindings. cs.addConstraint(ConstraintKind::Conversion, context.getType(), patternType, locator); // For any pattern variable that has a parent variable (i.e., another // pattern variable with the same name in the same case), require that // the types be equivalent. pattern->forEachNode([&](Pattern *pattern) { auto namedPattern = dyn_cast<NamedPattern>(pattern); if (!namedPattern) return; auto var = namedPattern->getDecl(); if (auto parentVar = var->getParentVarDecl()) { cs.addConstraint( ConstraintKind::Equal, cs.getType(parentVar), cs.getType(var), cs.getConstraintLocator( locator, LocatorPathElt::PatternMatch(namedPattern))); } }); } void visitPatternBinding(PatternBindingDecl *patternBinding, SmallVectorImpl<ElementInfo> &patterns) { auto *baseLoc = cs.getConstraintLocator( locator, LocatorPathElt::ClosureBodyElement(patternBinding)); for (unsigned index : range(patternBinding->getNumPatternEntries())) { auto *pattern = TypeChecker::resolvePattern( patternBinding->getPattern(index), patternBinding->getDeclContext(), /*isStmtCondition=*/true); if (!pattern) { hadError = true; return; } // Reset binding to point to the resolved pattern. This is required // before calling `forPatternBindingDecl`. patternBinding->setPattern(index, pattern, patternBinding->getInitContext(index)); patterns.push_back(makeElement( patternBinding, cs.getConstraintLocator( baseLoc, LocatorPathElt::PatternBindingElement(index)))); } } Optional<SolutionApplicationTarget> getTargetForPattern(PatternBindingDecl *patternBinding, unsigned index, Type patternType) { auto hasPropertyWrapper = [&](Pattern *pattern) -> bool { if (auto *singleVar = pattern->getSingleVar()) return singleVar->hasAttachedPropertyWrapper(); return false; }; auto *pattern = patternBinding->getPattern(index); auto *init = patternBinding->getInit(index); if (!init && patternBinding->isDefaultInitializable(index) && pattern->hasStorage()) { init = TypeChecker::buildDefaultInitializer(patternType); } if (init) { return SolutionApplicationTarget::forInitialization( init, patternBinding->getDeclContext(), patternType, patternBinding, index, /*bindPatternVarsOneWay=*/false); } // If there was no initializer, there could be one from a property // wrapper which has to be pre-checked before use. This is not a // problem in top-level code because pattern bindings go through // `typeCheckExpression` which does pre-check automatically and // result builders do not allow declaring local wrapped variables. if (hasPropertyWrapper(pattern)) { auto target = SolutionApplicationTarget::forInitialization( init, patternBinding->getDeclContext(), patternType, patternBinding, index, /*bindPatternVarsOneWay=*/false); if (ConstraintSystem::preCheckTarget( target, /*replaceInvalidRefsWithErrors=*/true, /*LeaveCLosureBodyUnchecked=*/false)) return None; return target; } return SolutionApplicationTarget::forUninitializedVar(patternBinding, index, patternType); } void visitPatternBindingElement(PatternBindingDecl *patternBinding) { assert(locator->isLastElement<LocatorPathElt::PatternBindingElement>()); auto index = locator->castLastElementTo<LocatorPathElt::PatternBindingElement>() .getIndex(); auto contextualPattern = ContextualPattern::forPatternBindingDecl(patternBinding, index); Type patternType = TypeChecker::typeCheckPattern(contextualPattern); // Fail early if pattern couldn't be type-checked. if (!patternType || patternType->hasError()) { hadError = true; return; } auto target = getTargetForPattern(patternBinding, index, patternType); if (!target || cs.generateConstraints(*target, FreeTypeVariableBinding::Disallow)) { hadError = true; return; } // Keep track of this binding entry. cs.setSolutionApplicationTarget({patternBinding, index}, *target); } void visitDecl(Decl *decl) { if (isSupportedMultiStatementClosure()) { if (auto patternBinding = dyn_cast<PatternBindingDecl>(decl)) { if (locator->isLastElement<LocatorPathElt::PatternBindingElement>()) visitPatternBindingElement(patternBinding); else llvm_unreachable("cannot visit pattern binding directly"); return; } } // Just ignore #if; the chosen children should appear in the // surrounding context. This isn't good for source tools but it // at least works. if (isa<IfConfigDecl>(decl)) return; // Skip #warning/#error; we'll handle them when applying the closure. if (isa<PoundDiagnosticDecl>(decl)) return; // Ignore variable declarations, because they're always handled within // their enclosing pattern bindings. if (isa<VarDecl>(decl)) return; // Other declarations will be handled at application time. } void visitBreakStmt(BreakStmt *breakStmt) { assert(isSupportedMultiStatementClosure() && "Unsupported statement: Break"); } void visitContinueStmt(ContinueStmt *continueStmt) { assert(isSupportedMultiStatementClosure() && "Unsupported statement: Continue"); } void visitDeferStmt(DeferStmt *deferStmt) { assert(isSupportedMultiStatementClosure() && "Unsupported statement: Defer"); } void visitFallthroughStmt(FallthroughStmt *fallthroughStmt) { assert(isSupportedMultiStatementClosure() && "Unsupported statement: Fallthrough"); } void visitStmtCondition(LabeledConditionalStmt *S, SmallVectorImpl<ElementInfo> &elements, ConstraintLocator *locator) { auto *condLocator = cs.getConstraintLocator(locator, ConstraintLocator::Condition); for (auto &condition : S->getCond()) elements.push_back(makeElement(&condition, condLocator)); } void visitIfStmt(IfStmt *ifStmt) { assert(isSupportedMultiStatementClosure() && "Unsupported statement: If"); SmallVector<ElementInfo, 4> elements; // Condition visitStmtCondition(ifStmt, elements, locator); // Then Branch { auto *thenLoc = cs.getConstraintLocator( locator, LocatorPathElt::TernaryBranch(/*then=*/true)); elements.push_back(makeElement(ifStmt->getThenStmt(), thenLoc)); } // Else Branch (if any). if (auto *elseStmt = ifStmt->getElseStmt()) { auto *elseLoc = cs.getConstraintLocator( locator, LocatorPathElt::TernaryBranch(/*then=*/false)); elements.push_back(makeElement(ifStmt->getElseStmt(), elseLoc)); } createConjunction(cs, elements, locator); } void visitGuardStmt(GuardStmt *guardStmt) { assert(isSupportedMultiStatementClosure() && "Unsupported statement: Guard"); SmallVector<ElementInfo, 4> elements; visitStmtCondition(guardStmt, elements, locator); elements.push_back(makeElement(guardStmt->getBody(), locator)); createConjunction(cs, elements, locator); } void visitWhileStmt(WhileStmt *whileStmt) { assert(isSupportedMultiStatementClosure() && "Unsupported statement: While"); SmallVector<ElementInfo, 4> elements; visitStmtCondition(whileStmt, elements, locator); elements.push_back(makeElement(whileStmt->getBody(), locator)); createConjunction(cs, elements, locator); } void visitDoStmt(DoStmt *doStmt) { assert(isSupportedMultiStatementClosure() && "Unsupported statement: Do"); visitBraceStmt(doStmt->getBody()); } void visitRepeatWhileStmt(RepeatWhileStmt *repeatWhileStmt) { assert(isSupportedMultiStatementClosure() && "Unsupported statement: RepeatWhile"); createConjunction(cs, {makeElement(repeatWhileStmt->getCond(), cs.getConstraintLocator( locator, ConstraintLocator::Condition), getContextForCondition()), makeElement(repeatWhileStmt->getBody(), locator)}, locator); } void visitPoundAssertStmt(PoundAssertStmt *poundAssertStmt) { assert(isSupportedMultiStatementClosure() && "Unsupported statement: PoundAssert"); createConjunction(cs, {makeElement(poundAssertStmt->getCondition(), cs.getConstraintLocator( locator, ConstraintLocator::Condition), getContextForCondition())}, locator); } void visitThrowStmt(ThrowStmt *throwStmt) { assert(isSupportedMultiStatementClosure() && "Unsupported statement: Throw"); if (!cs.getASTContext().getErrorDecl()) { hadError = true; return; } auto errType = cs.getASTContext().getErrorExistentialType(); auto *errorExpr = throwStmt->getSubExpr(); createConjunction( cs, {makeElement( errorExpr, cs.getConstraintLocator( locator, LocatorPathElt::ClosureBodyElement(errorExpr)), {errType, CTP_ThrowStmt})}, locator); } void visitForEachStmt(ForEachStmt *forEachStmt) { assert(isSupportedMultiStatementClosure() && "Unsupported statement: ForEach"); auto *stmtLoc = cs.getConstraintLocator(locator); SmallVector<ElementInfo, 4> elements; // For-each pattern. // // Note that we don't record a sequence here, it would // be handled together with pattern because pattern can // inform a type of sequence element e.g. `for i: Int8 in 0 ..< 8` { Pattern *pattern = TypeChecker::resolvePattern(forEachStmt->getPattern(), closure, /*isStmtCondition=*/false); if (!pattern) { hadError = true; return; } elements.push_back(makeElement(pattern, stmtLoc)); } // `where` clause if any. if (auto *whereClause = forEachStmt->getWhere()) { elements.push_back( makeElement(whereClause, stmtLoc, getContextForCondition())); } // Body of the `for-in` loop. elements.push_back(makeElement(forEachStmt->getBody(), stmtLoc)); createConjunction(cs, elements, locator); } void visitSwitchStmt(SwitchStmt *switchStmt) { assert(isSupportedMultiStatementClosure() && "Unsupported statement: Switch"); auto *switchLoc = cs.getConstraintLocator( locator, LocatorPathElt::ClosureBodyElement(switchStmt)); SmallVector<ElementInfo, 4> elements; { auto *subjectExpr = switchStmt->getSubjectExpr(); { elements.push_back(makeElement(subjectExpr, switchLoc)); SolutionApplicationTarget target(subjectExpr, closure, CTP_Unused, Type(), /*isDiscarded=*/false); cs.setSolutionApplicationTarget(switchStmt, target); } for (auto rawCase : switchStmt->getRawCases()) elements.push_back(makeElement(rawCase, switchLoc)); } createConjunction(cs, elements, switchLoc); } void visitDoCatchStmt(DoCatchStmt *doStmt) { assert(isSupportedMultiStatementClosure() && "Unsupported statement: DoCatch"); auto *doLoc = cs.getConstraintLocator( locator, LocatorPathElt::ClosureBodyElement(doStmt)); SmallVector<ElementInfo, 4> elements; // First, let's record a body of `do` statement. elements.push_back(makeElement(doStmt->getBody(), doLoc)); // After that has been type-checked, let's switch to // individual `catch` statements. for (auto *catchStmt : doStmt->getCatches()) elements.push_back(makeElement(catchStmt, doLoc)); createConjunction(cs, elements, doLoc); } void visitCaseStmt(CaseStmt *caseStmt) { assert(isSupportedMultiStatementClosure() && "Unsupported statement: Case"); Type contextualTy; { auto parent = locator->castLastElementTo<LocatorPathElt::ClosureBodyElement>() .getElement(); if (parent.isStmt(StmtKind::Switch)) { auto *switchStmt = cast<SwitchStmt>(parent.get<Stmt *>()); contextualTy = cs.getType(switchStmt->getSubjectExpr()); } else if (parent.isStmt(StmtKind::DoCatch)) { contextualTy = cs.getASTContext().getErrorExistentialType(); } else { hadError = true; return; } } bindSwitchCasePatternVars(closure, caseStmt); auto *caseLoc = cs.getConstraintLocator( locator, LocatorPathElt::ClosureBodyElement(caseStmt)); SmallVector<ElementInfo, 4> elements; for (auto &caseLabelItem : caseStmt->getMutableCaseLabelItems()) { elements.push_back( makeElement(&caseLabelItem, caseLoc, {contextualTy, CTP_CaseStmt})); } elements.push_back(makeElement(caseStmt->getBody(), caseLoc)); createConjunction(cs, elements, caseLoc); } void visitBraceStmt(BraceStmt *braceStmt) { if (isSupportedMultiStatementClosure()) { auto &ctx = cs.getASTContext(); if (isChildOf(StmtKind::Case)) { auto *caseStmt = cast<CaseStmt>( locator->castLastElementTo<LocatorPathElt::ClosureBodyElement>() .asStmt()); for (auto caseBodyVar : caseStmt->getCaseBodyVariablesOrEmptyArray()) { auto parentVar = caseBodyVar->getParentVarDecl(); assert(parentVar && "Case body variables always have parents"); cs.setType(caseBodyVar, cs.getType(parentVar)); } } SmallVector<ElementInfo, 4> elements; for (auto element : braceStmt->getElements()) { bool isDiscarded = element.is<Expr *>() && (!ctx.LangOpts.Playground && !ctx.LangOpts.DebuggerSupport); if (auto *decl = element.dyn_cast<Decl *>()) { if (auto *PDB = dyn_cast<PatternBindingDecl>(decl)) { visitPatternBinding(PDB, elements); continue; } } elements.push_back(makeElement( element, cs.getConstraintLocator( locator, LocatorPathElt::ClosureBodyElement(element)), /*contextualInfo=*/{}, isDiscarded)); } createConjunction(cs, elements, locator); return; } for (auto node : braceStmt->getElements()) { if (auto expr = node.dyn_cast<Expr *>()) { auto generatedExpr = cs.generateConstraints( expr, closure, /*isInputExpression=*/false); if (!generatedExpr) { hadError = true; } } else if (auto stmt = node.dyn_cast<Stmt *>()) { visit(stmt); } else { visitDecl(node.get<Decl *>()); } } } void visitReturnStmt(ReturnStmt *returnStmt) { auto contextualTy = cs.getClosureType(closure)->getResult(); // Single-expression closures are effectively a `return` statement, // so let's give them a special locator as to indicate that. // Return statements might not have a result if we have a closure whose // implicit returned value is coerced to Void. if (closure->hasSingleExpressionBody() && returnStmt->hasResult()) { auto *expr = returnStmt->getResult(); assert(expr && "single expression closure without expression?"); expr = cs.generateConstraints(expr, closure, /*isInputExpression=*/false); if (!expr) { hadError = true; return; } cs.addConstraint( ConstraintKind::Conversion, cs.getType(expr), contextualTy, cs.getConstraintLocator( closure, LocatorPathElt::ClosureBody( /*hasReturn=*/!returnStmt->isImplicit()))); return; } Expr *resultExpr; if (returnStmt->hasResult()) { resultExpr = returnStmt->getResult(); assert(resultExpr && "non-empty result without expression?"); } else { // If this is simplify `return`, let's create an empty tuple // which is also useful if contextual turns out to be e.g. `Void?`. resultExpr = getVoidExpr(closure->getASTContext()); } SolutionApplicationTarget target(resultExpr, closure, CTP_ReturnStmt, contextualTy, /*isDiscarded=*/false); if (cs.generateConstraints(target, FreeTypeVariableBinding::Disallow)) { hadError = true; return; } cs.setContextualType(target.getAsExpr(), TypeLoc::withoutLoc(contextualTy), CTP_ReturnStmt); cs.setSolutionApplicationTarget(returnStmt, target); } bool isSupportedMultiStatementClosure() const { return !closure->hasSingleExpressionBody() && cs.participatesInInference(closure); } #define UNSUPPORTED_STMT(STMT) void visit##STMT##Stmt(STMT##Stmt *) { \ llvm_unreachable("Unsupported statement kind " #STMT); \ } UNSUPPORTED_STMT(Yield) UNSUPPORTED_STMT(Fail) #undef UNSUPPORTED_STMT private: ContextualTypeInfo getContextForCondition() const { auto boolDecl = cs.getASTContext().getBoolDecl(); assert(boolDecl && "Bool is missing"); return {boolDecl->getDeclaredInterfaceType(), CTP_Condition}; } bool isChildOf(StmtKind kind) { if (locator->getPath().empty()) return false; auto parentElt = locator->getLastElementAs<LocatorPathElt::ClosureBodyElement>(); return parentElt ? parentElt->getElement().isStmt(kind) : false; } }; } bool ConstraintSystem::generateConstraints(ClosureExpr *closure) { auto &ctx = closure->getASTContext(); if (participatesInInference(closure)) { ClosureConstraintGenerator generator(*this, closure, getConstraintLocator(closure)); generator.visit(closure->getBody()); if (closure->hasSingleExpressionBody()) return generator.hadError; } // If this closure has an empty body and no explicit result type // let's bind result type to `Void` since that's the only type empty body // can produce. Otherwise, if (multi-statement) closure doesn't have // an explicit result (no `return` statements) let's default it to `Void`. if (!hasExplicitResult(closure)) { auto constraintKind = (closure->hasEmptyBody() && !closure->hasExplicitResultType()) ? ConstraintKind::Bind : ConstraintKind::Defaultable; addConstraint( constraintKind, getClosureType(closure)->getResult(), ctx.TheEmptyTupleType, getConstraintLocator(closure, ConstraintLocator::ClosureResult)); } return false; } bool ConstraintSystem::isInResultBuilderContext(ClosureExpr *closure) const { if (!closure->hasSingleExpressionBody()) { auto *DC = closure->getParent(); do { // Result builder is applied to a function/getter body. if (auto *AFD = dyn_cast<AbstractFunctionDecl>(DC)) { if (resultBuilderTransformed.count(AFD)) return true; } if (auto *parentClosure = dyn_cast<ClosureExpr>(DC)) { if (resultBuilderTransformed.count(parentClosure)) return true; } } while ((DC = DC->getParent())); } return false; } bool isConditionOfStmt(ConstraintLocatorBuilder locator) { auto last = locator.last(); if (!(last && last->is<LocatorPathElt::Condition>())) return false; SmallVector<LocatorPathElt, 4> path; (void)locator.getLocatorParts(path); path.pop_back(); if (path.empty()) return false; if (auto closureElt = path.back().getAs<LocatorPathElt::ClosureBodyElement>()) return closureElt->getElement().dyn_cast<Stmt *>(); return false; } ConstraintSystem::SolutionKind ConstraintSystem::simplifyClosureBodyElementConstraint( ASTNode element, ContextualTypeInfo context, bool isDiscarded, TypeMatchOptions flags, ConstraintLocatorBuilder locator) { auto *closure = castToExpr<ClosureExpr>(locator.getAnchor()); ClosureConstraintGenerator generator(*this, closure, getConstraintLocator(locator)); if (auto *expr = element.dyn_cast<Expr *>()) { SolutionApplicationTarget target(expr, closure, context.purpose, context.getType(), isDiscarded); if (generateConstraints(target, FreeTypeVariableBinding::Disallow)) return SolutionKind::Error; setSolutionApplicationTarget(expr, target); return SolutionKind::Solved; } else if (auto *stmt = element.dyn_cast<Stmt *>()) { generator.visit(stmt); } else if (auto *cond = element.dyn_cast<StmtConditionElement *>()) { if (generateConstraints({*cond}, closure)) return SolutionKind::Error; } else if (auto *pattern = element.dyn_cast<Pattern *>()) { generator.visitPattern(pattern, context); } else if (auto *caseItem = element.dyn_cast<CaseLabelItem *>()) { generator.visitCaseItem(caseItem, context); } else { generator.visit(element.get<Decl *>()); } return generator.hadError ? SolutionKind::Error : SolutionKind::Solved; } // MARK: Solution application namespace { /// Statement visitor that applies constraints for a given closure body. class ClosureConstraintApplication : public StmtVisitor<ClosureConstraintApplication, ASTNode> { friend StmtVisitor<ClosureConstraintApplication, ASTNode>; Solution &solution; ClosureExpr *closure; Type resultType; RewriteTargetFn rewriteTarget; bool isSingleExpression; /// All `func`s declared in the body of the closure. SmallVector<FuncDecl *, 4> LocalFuncs; public: /// Whether an error was encountered while generating constraints. bool hadError = false; ClosureConstraintApplication( Solution &solution, ClosureExpr *closure, Type resultType, RewriteTargetFn rewriteTarget) : solution(solution), closure(closure), resultType(resultType), rewriteTarget(rewriteTarget), isSingleExpression(closure->hasSingleExpressionBody()) { } private: /// Rewrite an expression without any particularly special context. Expr *rewriteExpr(Expr *expr) { auto result = rewriteTarget( SolutionApplicationTarget(expr, closure, CTP_Unused, Type(), /*isDiscarded=*/false)); if (result) return result->getAsExpr(); return nullptr; } void visitDecl(Decl *decl) { if (isa<IfConfigDecl>(decl)) return; // Variable declaration would be handled by a pattern binding. if (isa<VarDecl>(decl)) return; // Generate constraints for pattern binding declarations. if (auto patternBinding = dyn_cast<PatternBindingDecl>(decl)) { SolutionApplicationTarget target(patternBinding); if (!rewriteTarget(target)) { hadError = true; return; } // Allow `typeCheckDecl` to be called after solution is applied // to a pattern binding. That would materialize required // information e.g. accessors and do access/availability checks. } // Local functions cannot be type-checked in-order because they can // capture variables declared after them. Let's save them to be // processed after the solution has been applied to the body. if (auto *func = dyn_cast<FuncDecl>(decl)) { LocalFuncs.push_back(func); return; } TypeChecker::typeCheckDecl(decl); } ASTNode visitBreakStmt(BreakStmt *breakStmt) { if (auto target = findBreakOrContinueStmtTarget( closure->getASTContext(), closure->getParentSourceFile(), breakStmt->getLoc(), breakStmt->getTargetName(), breakStmt->getTargetLoc(), /*isContinue=*/false, closure)) { breakStmt->setTarget(target); } return breakStmt; } ASTNode visitContinueStmt(ContinueStmt *continueStmt) { if (auto target = findBreakOrContinueStmtTarget( closure->getASTContext(), closure->getParentSourceFile(), continueStmt->getLoc(), continueStmt->getTargetName(), continueStmt->getTargetLoc(), /*isContinue=*/true, closure)) { continueStmt->setTarget(target); } return continueStmt; } ASTNode visitFallthroughStmt(FallthroughStmt *fallthroughStmt) { if (checkFallthroughStmt(closure, fallthroughStmt)) hadError = true; return fallthroughStmt; } ASTNode visitDeferStmt(DeferStmt *deferStmt) { TypeChecker::typeCheckDecl(deferStmt->getTempDecl()); Expr *theCall = deferStmt->getCallExpr(); TypeChecker::typeCheckExpression(theCall, closure); deferStmt->setCallExpr(theCall); return deferStmt; } ASTNode visitIfStmt(IfStmt *ifStmt) { // Rewrite the condition. if (auto condition = rewriteTarget( SolutionApplicationTarget(ifStmt->getCond(), closure))) ifStmt->setCond(*condition->getAsStmtCondition()); else hadError = true; ifStmt->setThenStmt(visit(ifStmt->getThenStmt()).get<Stmt *>()); if (auto elseStmt = ifStmt->getElseStmt()) { ifStmt->setElseStmt(visit(elseStmt).get<Stmt *>()); } return ifStmt; } ASTNode visitGuardStmt(GuardStmt *guardStmt) { if (auto condition = rewriteTarget( SolutionApplicationTarget(guardStmt->getCond(), closure))) guardStmt->setCond(*condition->getAsStmtCondition()); else hadError = true; auto *body = visit(guardStmt->getBody()).get<Stmt *>(); guardStmt->setBody(cast<BraceStmt>(body)); return guardStmt; } ASTNode visitWhileStmt(WhileStmt *whileStmt) { if (auto condition = rewriteTarget( SolutionApplicationTarget(whileStmt->getCond(), closure))) whileStmt->setCond(*condition->getAsStmtCondition()); else hadError = true; auto *body = visit(whileStmt->getBody()).get<Stmt *>(); whileStmt->setBody(cast<BraceStmt>(body)); return whileStmt; } ASTNode visitDoStmt(DoStmt *doStmt) { auto body = visit(doStmt->getBody()).get<Stmt *>(); doStmt->setBody(cast<BraceStmt>(body)); return doStmt; } ASTNode visitRepeatWhileStmt(RepeatWhileStmt *repeatWhileStmt) { auto body = visit(repeatWhileStmt->getBody()).get<Stmt *>(); repeatWhileStmt->setBody(cast<BraceStmt>(body)); // Rewrite the condition. auto &cs = solution.getConstraintSystem(); auto target = *cs.getSolutionApplicationTarget(repeatWhileStmt->getCond()); if (auto condition = rewriteTarget(target)) repeatWhileStmt->setCond(condition->getAsExpr()); else hadError = true; return repeatWhileStmt; } ASTNode visitPoundAssertStmt(PoundAssertStmt *poundAssertStmt) { // FIXME: This should be done through \c solution instead of // constraint system. auto &cs = solution.getConstraintSystem(); // Rewrite the condition. auto target = *cs.getSolutionApplicationTarget(poundAssertStmt->getCondition()); if (auto result = rewriteTarget(target)) poundAssertStmt->setCondition(result->getAsExpr()); else hadError = true; return poundAssertStmt; } ASTNode visitThrowStmt(ThrowStmt *throwStmt) { auto &cs = solution.getConstraintSystem(); // Rewrite the error. auto target = *cs.getSolutionApplicationTarget(throwStmt->getSubExpr()); if (auto result = rewriteTarget(target)) throwStmt->setSubExpr(result->getAsExpr()); else hadError = true; return throwStmt; } ASTNode visitForEachStmt(ForEachStmt *forEachStmt) { ConstraintSystem &cs = solution.getConstraintSystem(); auto forEachTarget = rewriteTarget(*cs.getSolutionApplicationTarget(forEachStmt)); if (!forEachTarget) hadError = true; auto body = visit(forEachStmt->getBody()).get<Stmt *>(); forEachStmt->setBody(cast<BraceStmt>(body)); // Check to see if the sequence expr is throwing (in async context), // if so require the stmt to have a `try`. hadError |= diagnoseUnhandledThrowsInAsyncContext(closure, forEachStmt); return forEachStmt; } ASTNode visitSwitchStmt(SwitchStmt *switchStmt) { ConstraintSystem &cs = solution.getConstraintSystem(); // Rewrite the switch subject. auto subjectTarget = rewriteTarget(*cs.getSolutionApplicationTarget(switchStmt)); if (subjectTarget) { switchStmt->setSubjectExpr(subjectTarget->getAsExpr()); } else { hadError = true; } // Visit the raw cases. bool limitExhaustivityChecks = false; for (auto rawCase : switchStmt->getRawCases()) { if (auto decl = rawCase.dyn_cast<Decl *>()) { visitDecl(decl); continue; } auto caseStmt = cast<CaseStmt>(rawCase.get<Stmt *>()); visitCaseStmt(caseStmt); // Check restrictions on '@unknown'. if (caseStmt->hasUnknownAttr()) { checkUnknownAttrRestrictions(cs.getASTContext(), caseStmt, limitExhaustivityChecks); } } TypeChecker::checkSwitchExhaustiveness(switchStmt, closure, limitExhaustivityChecks); return switchStmt; } ASTNode visitDoCatchStmt(DoCatchStmt *doStmt) { // Translate the body. auto newBody = visit(doStmt->getBody()); doStmt->setBody(newBody.get<Stmt *>()); // Visit the catch blocks. for (auto catchStmt : doStmt->getCatches()) visitCaseStmt(catchStmt); return doStmt; } ASTNode visitCaseStmt(CaseStmt *caseStmt) { // Translate the patterns and guard expressions for each case label item. for (auto &caseItem : caseStmt->getMutableCaseLabelItems()) { SolutionApplicationTarget caseTarget(&caseItem, closure); if (!rewriteTarget(caseTarget)) { hadError = true; } } for (auto *expected : caseStmt->getCaseBodyVariablesOrEmptyArray()) { assert(expected->hasName()); auto prev = expected->getParentVarDecl(); auto type = solution.resolveInterfaceType( solution.getType(prev)->mapTypeOutOfContext()); expected->setInterfaceType(type); } // Translate the body. auto *newBody = visit(caseStmt->getBody()).get<Stmt *>(); caseStmt->setBody(cast<BraceStmt>(newBody)); return caseStmt; } ASTNode visitBraceStmt(BraceStmt *braceStmt) { auto &cs = solution.getConstraintSystem(); // Diagnose defer statement being last one in block. if (!braceStmt->empty()) { if (auto stmt = braceStmt->getLastElement().dyn_cast<Stmt *>()) { if (auto deferStmt = dyn_cast<DeferStmt>(stmt)) { auto &diags = closure->getASTContext().Diags; diags .diagnose(deferStmt->getStartLoc(), diag::defer_stmt_at_block_end) .fixItReplace(deferStmt->getStartLoc(), "do"); } } } for (auto &node : braceStmt->getElements()) { if (auto expr = node.dyn_cast<Expr *>()) { // Rewrite the expression. auto target = *cs.getSolutionApplicationTarget(expr); if (auto rewrittenTarget = rewriteTarget(target)) { node = rewrittenTarget->getAsExpr(); if (target.isDiscardedExpr()) TypeChecker::checkIgnoredExpr(castToExpr(node)); } else { hadError = true; } } else if (auto stmt = node.dyn_cast<Stmt *>()) { node = visit(stmt); } else { visitDecl(node.get<Decl *>()); } } // Source compatibility workaround. // // func test<T>(_: () -> T?) { // ... // } // // A multi-statement closure passed to `test` that has an optional // `Void` result type inferred from the body allows: // - empty `return`(s); // - to skip `return nil` or `return ()` at the end. // // Implicit `return ()` has to be inserted as the last element // of the body if there is none. This wasn't needed before SE-0326 // because result type was (incorrectly) inferred as `Void` due to // the body being skipped. if (!closure->hasSingleExpressionBody() && closure->getBody() == braceStmt) { if (resultType->getOptionalObjectType() && resultType->lookThroughAllOptionalTypes()->isVoid() && !braceStmt->getLastElement().isStmt(StmtKind::Return)) { return addImplicitVoidReturn(braceStmt); } } return braceStmt; } ASTNode addImplicitVoidReturn(BraceStmt *braceStmt) { auto &ctx = closure->getASTContext(); auto &cs = solution.getConstraintSystem(); auto *resultExpr = getVoidExpr(ctx); cs.cacheExprTypes(resultExpr); auto *returnStmt = new (ctx) ReturnStmt(SourceLoc(), resultExpr, /*implicit=*/true); // For a target for newly created result and apply a solution // to it, to make sure that optional injection happens required // number of times. { SolutionApplicationTarget target(resultExpr, closure, CTP_ReturnStmt, resultType, /*isDiscarded=*/false); cs.setSolutionApplicationTarget(returnStmt, target); visitReturnStmt(returnStmt); } // Re-create brace statement with an additional `return` at the end. SmallVector<ASTNode, 4> elements; elements.append(braceStmt->getElements().begin(), braceStmt->getElements().end()); elements.push_back(returnStmt); return BraceStmt::create(ctx, braceStmt->getLBraceLoc(), elements, braceStmt->getRBraceLoc()); } ASTNode visitReturnStmt(ReturnStmt *returnStmt) { if (!returnStmt->hasResult()) { // If contextual is not optional, there is nothing to do here. if (resultType->isVoid()) return returnStmt; // It's possible to infer e.g. `Void?` for cases where // `return` doesn't have an expression. If contextual // type is `Void` wrapped into N optional types, let's // add an implicit `()` expression and let it be injected // into optional required number of times. assert(resultType->getOptionalObjectType() && resultType->lookThroughAllOptionalTypes()->isVoid()); auto &cs = solution.getConstraintSystem(); auto target = *cs.getSolutionApplicationTarget(returnStmt); returnStmt->setResult(target.getAsExpr()); } auto *resultExpr = returnStmt->getResult(); enum { convertToResult, coerceToVoid, coerceFromNever, } mode; auto resultExprType = solution.simplifyType(solution.getType(resultExpr))->getRValueType(); // A closure with a non-void return expression can coerce to a closure // that returns Void. if (resultType->isVoid() && !resultExprType->isVoid()) { mode = coerceToVoid; // A single-expression closure with a Never expression type // coerces to any other function type. } else if (isSingleExpression && resultExprType->isUninhabited()) { mode = coerceFromNever; // Normal rule is to coerce to the return expression to the closure type. } else { mode = convertToResult; } SolutionApplicationTarget resultTarget( resultExpr, closure, mode == convertToResult ? CTP_ReturnStmt : CTP_Unused, mode == convertToResult ? resultType : Type(), /*isDiscarded=*/false); if (auto newResultTarget = rewriteTarget(resultTarget)) resultExpr = newResultTarget->getAsExpr(); switch (mode) { case convertToResult: // Record the coerced expression. returnStmt->setResult(resultExpr); return returnStmt; case coerceToVoid: { // Evaluate the expression, then produce a return statement that // returns nothing. TypeChecker::checkIgnoredExpr(resultExpr); auto &ctx = solution.getConstraintSystem().getASTContext(); auto newReturnStmt = new (ctx) ReturnStmt( returnStmt->getStartLoc(), nullptr, /*implicit=*/true); ASTNode elements[2] = { resultExpr, newReturnStmt }; return BraceStmt::create(ctx, returnStmt->getStartLoc(), elements, returnStmt->getEndLoc(), /*implicit*/ true); } case coerceFromNever: // Replace the return statement with its expression, so that the // expression is evaluated directly. This only works because coercion // from never is limited to single-expression closures. return resultExpr; } return returnStmt; } #define UNSUPPORTED_STMT(STMT) ASTNode visit##STMT##Stmt(STMT##Stmt *) { \ llvm_unreachable("Unsupported statement kind " #STMT); \ } UNSUPPORTED_STMT(Yield) UNSUPPORTED_STMT(Fail) #undef UNSUPPORTED_STMT public: /// Apply solution to the closure and return updated body. ASTNode apply() { auto body = visit(closure->getBody()); // Since local functions can capture variables that are declared // after them, let's type-check them after all of the pattern // bindings have been resolved by applying solution to the body. for (auto *func : LocalFuncs) TypeChecker::typeCheckDecl(func); return body; } }; } SolutionApplicationToFunctionResult ConstraintSystem::applySolution( Solution &solution, AnyFunctionRef fn, DeclContext *&currentDC, RewriteTargetFn rewriteTarget) { auto &cs = solution.getConstraintSystem(); auto closure = dyn_cast_or_null<ClosureExpr>(fn.getAbstractClosureExpr()); FunctionType *closureFnType = nullptr; if (closure) { // Update the closure's type. auto closureType = solution.simplifyType(cs.getType(closure)); cs.setType(closure, closureType); // Coerce the parameter types. closureFnType = closureType->castTo<FunctionType>(); auto *params = closure->getParameters(); TypeChecker::coerceParameterListToType(params, closureFnType); // Find any isolated parameters in this closure and mark them as isolated. for (auto param : solution.isolatedParams) { if (param->getDeclContext() == closure) param->setIsolated(true); } // Coerce the result type, if it was written explicitly. if (closure->hasExplicitResultType()) { closure->setExplicitResultType(closureFnType->getResult()); } } // Enter the context of the function before performing any additional // transformations. llvm::SaveAndRestore<DeclContext *> savedDC(currentDC, fn.getAsDeclContext()); // Apply the result builder transform, if there is one. if (auto transform = solution.getAppliedBuilderTransform(fn)) { // Apply the result builder to the closure. We want to be in the // context of the closure for subsequent transforms. auto newBody = applyResultBuilderTransform( solution, *transform, fn.getBody(), fn.getAsDeclContext(), [&](SolutionApplicationTarget target) { auto resultTarget = rewriteTarget(target); if (resultTarget) { if (auto expr = resultTarget->getAsExpr()) solution.setExprTypes(expr); } return resultTarget; }); if (!newBody) return SolutionApplicationToFunctionResult::Failure; fn.setTypecheckedBody(newBody, /*isSingleExpression=*/false); if (closure) { solution.setExprTypes(closure); } return SolutionApplicationToFunctionResult::Success; } assert(closure && "Can only get here with a closure at the moment"); // If this closure is checked as part of the enclosing expression, handle // that now. // // Multi-statement closures are handled separately because they need to // wait until all of the `ExtInfo` flags are propagated from the context // e.g. parameter could be no-escape if closure is applied to a call. if (closure->hasSingleExpressionBody()) { bool hadError = applySolutionToBody(solution, closure, currentDC, rewriteTarget); return hadError ? SolutionApplicationToFunctionResult::Failure : SolutionApplicationToFunctionResult::Success; } // Otherwise, we need to delay type checking of the closure until later. solution.setExprTypes(closure); closure->setBodyState(ClosureExpr::BodyState::ReadyForTypeChecking); return SolutionApplicationToFunctionResult::Delay; } bool ConstraintSystem::applySolutionToBody(Solution &solution, ClosureExpr *closure, DeclContext *&currentDC, RewriteTargetFn rewriteTarget) { auto &cs = solution.getConstraintSystem(); // Enter the context of the function before performing any additional // transformations. llvm::SaveAndRestore<DeclContext *> savedDC(currentDC, closure); auto closureType = cs.getType(closure)->castTo<FunctionType>(); ClosureConstraintApplication application( solution, closure, closureType->getResult(), rewriteTarget); auto body = application.apply(); if (!body || application.hadError) return true; closure->setBody(cast<BraceStmt>(body.get<Stmt *>()), closure->hasSingleExpressionBody()); closure->setBodyState(ClosureExpr::BodyState::TypeCheckedWithSignature); return false; } void ConjunctionElement::findReferencedVariables( ConstraintSystem &cs, SmallPtrSetImpl<TypeVariableType *> &typeVars) const { auto referencedVars = Element->getTypeVariables(); typeVars.insert(referencedVars.begin(), referencedVars.end()); if (Element->getKind() != ConstraintKind::ClosureBodyElement) return; ASTNode element = Element->getClosureElement(); auto *locator = Element->getLocator(); TypeVariableRefFinder refFinder(cs, locator->getAnchor(), typeVars); if (auto *patternBinding = dyn_cast_or_null<PatternBindingDecl>(element.dyn_cast<Decl *>())) { if (auto patternBindingElt = locator ->getLastElementAs<LocatorPathElt::PatternBindingElement>()) { if (auto *init = patternBinding->getInit(patternBindingElt->getIndex())) init->walk(refFinder); return; } } if (element.is<Decl *>() || element.is<StmtConditionElement *>() || element.is<Expr *>() || element.isStmt(StmtKind::Return)) element.walk(refFinder); }
#include "catch.hpp" extern "C"{ #include "../../open_lin_cfg.h" #include "../../open_lin_data_layer.h" #include "../../open_lin_hw.h" #include "../../open_lin_network_layer.h" #include "../../open_lin_master_data_layer.h" extern uint8_t* get_last_tx(); extern uint8_t get_last_tx_index(); extern t_open_lin_error get_and_clear_sim_error(); } uint8_t master_data_buffer[8]; const t_master_frame_table_item master_frame_table[] = { {10,25,{0x01,OPEN_LIN_FRAME_TYPE_RECEIVE,0x08,master_data_buffer}} }; const uint8_t table_size = sizeof(master_frame_table)/sizeof(t_master_frame_table_item); TEST_CASE("handler call on not initilized master", "[open_lin_master]" ){ open_lin_master_dl_handler(10); } TEST_CASE("init and work with one item table", "[open_lin_master]" ){ get_last_tx_index(); get_and_clear_sim_error(); open_lin_master_dl_init((t_master_frame_table_item *)master_frame_table,table_size); open_lin_master_dl_handler(1); CHECK(get_last_tx_index() == 0); open_lin_master_dl_handler(10); CHECK(get_last_tx_index() == 3); CHECK((get_last_tx()[2]) == 0xC1); // check for PID open_lin_master_dl_handler(10); CHECK(get_and_clear_sim_error() == OPEN_LIN_NO_ERROR); open_lin_master_dl_handler(16); CHECK(get_and_clear_sim_error() == OPEN_LIN_MASTER_ERROR_DATA_RX_TIMEOUT); open_lin_master_dl_handler(11); CHECK(get_last_tx_index() == 3); CHECK((get_last_tx()[2]) == 0xC1); // check for PID } uint8_t master_data_buffer_tx_1[] = {0xAA,0xBB}; uint8_t master_data_buffer_rx_1[1]; const t_master_frame_table_item master_frame_table2[] = { {10,0,{0x02,OPEN_LIN_FRAME_TYPE_TRANSMIT,0x02,master_data_buffer_tx_1}}, {20,25,{0x03,OPEN_LIN_FRAME_TYPE_RECEIVE,0x01,master_data_buffer_rx_1}} }; const uint8_t table_size2 = sizeof(master_frame_table2)/sizeof(t_master_frame_table_item); TEST_CASE("init and work with multiple items table, invalid checksum rx", "[open_lin_master]" ){ get_last_tx_index(); get_and_clear_sim_error(); open_lin_master_dl_init((t_master_frame_table_item *)master_frame_table2,table_size2); open_lin_master_dl_handler(11); CHECK(get_last_tx_index() == 6); CHECK(((get_last_tx()[3] == 0xAA) && (get_last_tx()[4] == 0xBB))); CHECK(get_and_clear_sim_error() == OPEN_LIN_NO_ERROR); open_lin_master_dl_handler(21); CHECK(get_last_tx_index() == 3); CHECK((get_last_tx()[2] == 0x03)); open_lin_master_dl_rx(0x05); open_lin_master_dl_rx(0x06); CHECK(get_and_clear_sim_error() == OPEN_LIN_MASTER_ERROR_CHECKSUM); } TEST_CASE("init and work with multiple items table, valid checksum rx", "[open_lin_master]" ){ extern open_lin_frame_slot_t* last_rx_slot; get_last_tx_index(); get_and_clear_sim_error(); open_lin_master_dl_init((t_master_frame_table_item *)master_frame_table2,table_size2); open_lin_master_dl_handler(11); CHECK(get_last_tx_index() == 6); CHECK(((get_last_tx()[3] == 0xAA) && (get_last_tx()[4] == 0xBB))); CHECK(get_and_clear_sim_error() == OPEN_LIN_NO_ERROR); open_lin_master_dl_handler(21); CHECK(get_last_tx_index() == 3); CHECK((get_last_tx()[2] == 0x03)); open_lin_master_dl_rx(0x05); open_lin_master_dl_rx(0xF7); CHECK(get_and_clear_sim_error() == OPEN_LIN_NO_ERROR); CHECK(last_rx_slot->pid == 0x03); CHECK(last_rx_slot->data_ptr[0] == 0x05); }
#include "utils/FastTimer.hpp" #include "utils/utils.hpp" #include <QMutexLocker> #include <QTimerEvent> #include <QThread> #define TU FastTimerTU namespace TU { constexpr auto NO_TIMER = -1; } FastTimer::FastTimer(QObject *parent) : QObject(parent), mCallback(nullptr), mCallbackData(nullptr), mInterval(0), mTimerType(Qt::CoarseTimer), mTimerId(TU::NO_TIMER) { } void FastTimer::setCallback(CallbackFn function, void *data) { QMutexLocker locker(&mMutex); mCallback = function; mCallbackData = data; } void FastTimer::setInterval(int ms, Qt::TimerType type) { mMutex.lock(); bool changed = false; if (mInterval != ms) { mInterval = ms; changed = true; } if (mTimerType != type) { mTimerType = type; changed = true; } auto timerId = mTimerId; mMutex.unlock(); if (changed && timerId != TU::NO_TIMER) { // restart the timer with the new interval start(); } } void FastTimer::timerEvent(QTimerEvent *evt) { mMutex.lock(); auto const timerId = mTimerId; auto const callback = mCallback; auto const data = mCallbackData; mMutex.unlock(); if (evt->timerId() == timerId && callback) { callback(data); } } void FastTimer::start() { if (objectInCurrentThread(*this)) { QMutexLocker locker(&mMutex); _stopTimer(); _startTimer(); } else { // re-invoke in the object's thread QMetaObject::invokeMethod(this, [this]() { start(); }, Qt::BlockingQueuedConnection); } } void FastTimer::stop() { if (objectInCurrentThread(*this)) { QMutexLocker locker(&mMutex); _stopTimer(); } else { QMetaObject::invokeMethod(this, [this]() { stop(); }, Qt::BlockingQueuedConnection); } } void FastTimer::_startTimer() { mTimerId = startTimer(mInterval, mTimerType); } void FastTimer::_stopTimer() { if (mTimerId != TU::NO_TIMER) { killTimer(mTimerId); mTimerId = -1; } } #undef TU
#ifndef BOOST_MPL_AUX_CONFIG_CTPS_HPP_INCLUDED #define BOOST_MPL_AUX_CONFIG_CTPS_HPP_INCLUDED // Copyright Aleksey Gurtovoy 2000-2004 // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // See http://www.boost.org/libs/mpl for documentation. // $Source: /CVSROOT/boost/boost/mpl/aux_/config/ctps.hpp,v $ // $Date: 2007/10/29 07:32:41 $ // $Revision: 1.1.1.1 $ #include <boost/mpl/aux_/config/workaround.hpp> #include <boost/config.hpp> #if !defined(BOOST_MPL_CFG_NO_NONTYPE_TEMPLATE_PARTIAL_SPEC) \ && !defined(BOOST_MPL_PREPROCESSING_MODE) \ && BOOST_WORKAROUND(__BORLANDC__, < 0x600) # define BOOST_MPL_CFG_NO_NONTYPE_TEMPLATE_PARTIAL_SPEC #endif // BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION is defined in <boost/config.hpp> #endif // BOOST_MPL_AUX_CONFIG_CTPS_HPP_INCLUDED
// RUN: %clang_cc1 -verify -fopenmp %s void foo() { } bool foobool(int argc) { return argc; } struct S1; // expected-note {{declared here}} template <class T, typename S, int N, int ST> // expected-note {{declared here}} T tmain(T argc, S **argv) { //expected-note 2 {{declared here}} #pragma omp for simd simdlen // expected-error {{expected '(' after 'simdlen'}} for (int i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST]; #pragma omp for simd simdlen ( // expected-error {{expected expression}} expected-error {{expected ')'}} expected-note {{to match this '('}} for (int i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST]; #pragma omp for simd simdlen () // expected-error {{expected expression}} for (int i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST]; // expected-error@+3 {{expected ')'}} expected-note@+3 {{to match this '('}} // expected-error@+2 2 {{expression is not an integral constant expression}} // expected-note@+1 2 {{read of non-const variable 'argc' is not allowed in a constant expression}} #pragma omp for simd simdlen (argc for (int i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST]; // expected-error@+1 {{argument to 'simdlen' clause must be a positive integer value}} #pragma omp for simd simdlen (ST // expected-error {{expected ')'}} expected-note {{to match this '('}} for (int i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST]; #pragma omp for simd simdlen (1)) // expected-warning {{extra tokens at the end of '#pragma omp for simd' are ignored}} for (int i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST]; #pragma omp for simd simdlen ((ST > 0) ? 1 + ST : 2) for (int i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST]; // expected-error@+3 2 {{directive '#pragma omp for simd' cannot contain more than one 'simdlen' clause}} // expected-error@+2 2 {{argument to 'simdlen' clause must be a positive integer value}} // expected-error@+1 2 {{expression is not an integral constant expression}} #pragma omp for simd simdlen (foobool(argc)), simdlen (true), simdlen (-5) for (int i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST]; #pragma omp for simd simdlen (S) // expected-error {{'S' does not refer to a value}} for (int i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST]; // expected-error@+1 2 {{expression is not an integral constant expression}} #pragma omp for simd simdlen (argv[1]=2) // expected-error {{expected ')'}} expected-note {{to match this '('}} for (int i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST]; #pragma omp for simd simdlen (4) for (int i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST]; #pragma omp for simd simdlen (N) // expected-error {{argument to 'simdlen' clause must be a positive integer value}} for (T i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST]; return argc; } int main(int argc, char **argv) { #pragma omp for simd simdlen // expected-error {{expected '(' after 'simdlen'}} for (int i = 4; i < 12; i++) argv[0][i] = argv[0][i] - argv[0][i-4]; #pragma omp for simd simdlen ( // expected-error {{expected expression}} expected-error {{expected ')'}} expected-note {{to match this '('}} for (int i = 4; i < 12; i++) argv[0][i] = argv[0][i] - argv[0][i-4]; #pragma omp for simd simdlen () // expected-error {{expected expression}} for (int i = 4; i < 12; i++) argv[0][i] = argv[0][i] - argv[0][i-4]; #pragma omp for simd simdlen (4 // expected-error {{expected ')'}} expected-note {{to match this '('}} for (int i = 4; i < 12; i++) argv[0][i] = argv[0][i] - argv[0][i-4]; #pragma omp for simd simdlen (2+2)) // expected-warning {{extra tokens at the end of '#pragma omp for simd' are ignored}} for (int i = 4; i < 12; i++) argv[0][i] = argv[0][i] - argv[0][i-4]; #pragma omp for simd simdlen (foobool(1) > 0 ? 1 : 2) // expected-error {{expression is not an integral constant expression}} for (int i = 4; i < 12; i++) argv[0][i] = argv[0][i] - argv[0][i-4]; // expected-error@+3 {{expression is not an integral constant expression}} // expected-error@+2 2 {{directive '#pragma omp for simd' cannot contain more than one 'simdlen' clause}} // expected-error@+1 2 {{argument to 'simdlen' clause must be a positive integer value}} #pragma omp for simd simdlen (foobool(argc)), simdlen (true), simdlen (-5) for (int i = 4; i < 12; i++) argv[0][i] = argv[0][i] - argv[0][i-4]; #pragma omp for simd simdlen (S1) // expected-error {{'S1' does not refer to a value}} for (int i = 4; i < 12; i++) argv[0][i] = argv[0][i] - argv[0][i-4]; // expected-error@+1 {{expression is not an integral constant expression}} #pragma omp for simd simdlen (argv[1]=2) // expected-error {{expected ')'}} expected-note {{to match this '('}} for (int i = 4; i < 12; i++) argv[0][i] = argv[0][i] - argv[0][i-4]; // expected-error@+3 {{statement after '#pragma omp for simd' must be a for loop}} // expected-note@+1 {{in instantiation of function template specialization 'tmain<int, char, -1, -2>' requested here}} #pragma omp for simd simdlen(simdlen(tmain<int, char, -1, -2>(argc, argv) // expected-error 2 {{expected ')'}} expected-note 2 {{to match this '('}} foo(); // expected-note@+1 {{in instantiation of function template specialization 'tmain<int, char, 12, 4>' requested here}} return tmain<int, char, 12, 4>(argc, argv); }
/* tests/pybind11_cross_module_tests.cpp -- contains tests that require multiple modules Copyright (c) 2017 Jason Rhinelander <jason@imaginary.ca> All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. */ #include "pybind11_tests.h" #include "local_bindings.h" #include <pybind11/stl_bind.h> #include <numeric> PYBIND11_MODULE(pybind11_cross_module_tests, m) { m.doc() = "pybind11 cross-module test module"; // test_local_bindings.py tests: // // Definitions here are tested by importing both this module and the // relevant pybind11_tests submodule from a test_whatever.py // test_load_external bind_local<ExternalType1>(m, "ExternalType1", py::module_local()); bind_local<ExternalType2>(m, "ExternalType2", py::module_local()); // test_exceptions.py m.def("raise_runtime_error", []() { PyErr_SetString(PyExc_RuntimeError, "My runtime error"); throw py::error_already_set(); }); m.def("raise_value_error", []() { PyErr_SetString(PyExc_ValueError, "My value error"); throw py::error_already_set(); }); m.def("throw_pybind_value_error", []() { throw py::value_error("pybind11 value error"); }); m.def("throw_pybind_type_error", []() { throw py::type_error("pybind11 type error"); }); m.def("throw_stop_iteration", []() { throw py::stop_iteration(); }); // test_local_bindings.py // Local to both: bind_local<LocalType, 1>(m, "LocalType", py::module_local()) .def("get2", [](LocalType &t) { return t.i + 2; }) ; // Can only be called with our python type: m.def("local_value", [](LocalType &l) { return l.i; }); // test_nonlocal_failure // This registration will fail (global registration when LocalFail is already registered // globally in the main test module): m.def("register_nonlocal", [m]() { bind_local<NonLocalType, 0>(m, "NonLocalType"); }); // test_stl_bind_local // stl_bind.h binders defaults to py::module_local if the types are local or converting: py::bind_vector<LocalVec>(m, "LocalVec"); py::bind_map<LocalMap>(m, "LocalMap"); // test_stl_bind_global // and global if the type (or one of the types, for the map) is global (so these will fail, // assuming pybind11_tests is already loaded): m.def("register_nonlocal_vec", [m]() { py::bind_vector<NonLocalVec>(m, "NonLocalVec"); }); m.def("register_nonlocal_map", [m]() { py::bind_map<NonLocalMap>(m, "NonLocalMap"); }); // The default can, however, be overridden to global using `py::module_local()` or // `py::module_local(false)`. // Explicitly made local: py::bind_vector<NonLocalVec2>(m, "NonLocalVec2", py::module_local()); // Explicitly made global (and so will fail to bind): m.def("register_nonlocal_map2", [m]() { py::bind_map<NonLocalMap2>(m, "NonLocalMap2", py::module_local(false)); }); // test_mixed_local_global // We try this both with the global type registered first and vice versa (the order shouldn't // matter). m.def("register_mixed_global_local", [m]() { bind_local<MixedGlobalLocal, 200>(m, "MixedGlobalLocal", py::module_local()); }); m.def("register_mixed_local_global", [m]() { bind_local<MixedLocalGlobal, 2000>(m, "MixedLocalGlobal", py::module_local(false)); }); m.def("get_mixed_gl", [](int i) { return MixedGlobalLocal(i); }); m.def("get_mixed_lg", [](int i) { return MixedLocalGlobal(i); }); // test_internal_locals_differ m.def("local_cpp_types_addr", []() { return (uintptr_t) &py::detail::registered_local_types_cpp(); }); // test_stl_caster_vs_stl_bind py::bind_vector<std::vector<int>>(m, "VectorInt"); m.def("load_vector_via_binding", [](std::vector<int> &v) { return std::accumulate(v.begin(), v.end(), 0); }); // test_cross_module_calls m.def("return_self", [](LocalVec *v) { return v; }); m.def("return_copy", [](const LocalVec &v) { return LocalVec(v); }); class Dog : public pets::Pet { public: Dog(std::string name) : Pet(name) {}; }; py::class_<pets::Pet>(m, "Pet", py::module_local()) .def("name", &pets::Pet::name); // Binding for local extending class: py::class_<Dog, pets::Pet>(m, "Dog") .def(py::init<std::string>()); m.def("pet_name", [](pets::Pet &p) { return p.name(); }); py::class_<MixGL>(m, "MixGL", py::module_local()).def(py::init<int>()); m.def("get_gl_value", [](MixGL &o) { return o.i + 100; }); py::class_<MixGL2>(m, "MixGL2", py::module_local()).def(py::init<int>()); // test_vector_bool // We can't test both stl.h and stl_bind.h conversions of `std::vector<bool>` within // the same module (it would be an ODR violation). Therefore `bind_vector` of `bool` // is defined here and tested in `test_stl_binders.py`. py::bind_vector<std::vector<bool>>(m, "VectorBool"); // test_missing_header_message // The main module already includes stl.h, but we need to test the error message // which appears when this header is missing. m.def("missing_header_arg", [](std::vector<float>) { }); m.def("missing_header_return", []() { return std::vector<float>(); }); }
// socket.cpp // // -------------------------------------------------------------------------- // This file is part of the "sockpp" C++ socket library. // // Copyright (c) 2014-2017 Frank Pagliughi // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // -------------------------------------------------------------------------- #include "sockpp/stream_socket.h" #include "sockpp/exception.h" #include <algorithm> using namespace std::chrono; namespace sockpp { ///////////////////////////////////////////////////////////////////////////// // stream_socket ///////////////////////////////////////////////////////////////////////////// // Opens a TCP socket. If it was already open, it just succeeds without // doing anything. bool stream_socket::open() { if (!is_open()) { socket_t h = create(); if (check_ret_bool(h)) reset(h); else set_last_error(); } return is_open(); } // -------------------------------------------------------------------------- // Reads from the socket. Note that we use ::recv() rather then ::read() // because many non-*nix operating systems make a distinction. ssize_t stream_socket::read(void *buf, size_t n) { #if defined(_WIN32) return check_ret(::recv(handle(), reinterpret_cast<char*>(buf), int(n), 0)); #else return check_ret(::recv(handle(), buf, n, 0)); #endif } // -------------------------------------------------------------------------- // Attempts to read the requested number of bytes by repeatedly calling // read() until it has the data or an error occurs. // ssize_t stream_socket::read_n(void *buf, size_t n) { size_t nr = 0; ssize_t nx = 0; uint8_t *b = reinterpret_cast<uint8_t*>(buf); while (nr < n) { if ((nx = read(b+nr, n-nr)) <= 0) break; nr += nx; } return (nr == 0 && nx < 0) ? nx : ssize_t(nr); } // -------------------------------------------------------------------------- bool stream_socket::read_timeout(const microseconds& to) { #if !defined(_WIN32) timeval tv = to_timeval(to); return check_ret_bool(::setsockopt(handle(), SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(timeval))) == 0; #else return false; #endif } // -------------------------------------------------------------------------- ssize_t stream_socket::write(const void *buf, size_t n) { #if defined(_WIN32) return check_ret(::send(handle(), reinterpret_cast<const char*>(buf), int(n) , 0)); #else return check_ret(::send(handle(), buf, n , 0)); #endif } // -------------------------------------------------------------------------- // Attempts to write the entire buffer by repeatedly calling write() until // either all of the data is sent or an error occurs. ssize_t stream_socket::write_n(const void *buf, size_t n) { size_t nw = 0; ssize_t nx = 0; const uint8_t *b = reinterpret_cast<const uint8_t*>(buf); while (nw < n) { if ((nx = write(b+nw, n-nw)) <= 0) break; nw += nx; } return (nw == 0 && nx < 0) ? nx : ssize_t(nw); } // -------------------------------------------------------------------------- bool stream_socket::write_timeout(const microseconds& to) { #if !defined(_WIN32) timeval tv = to_timeval(to); return check_ret_bool(::setsockopt(handle(), SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(timeval))) == 0; #else return false; #endif } ///////////////////////////////////////////////////////////////////////////// // End namespace sockpp }
/* * Copyright (c) 2016 MariaDB Corporation Ab * * Use of this software is governed by the Business Source License included * in the LICENSE.TXT file and at www.mariadb.com/bsl11. * * Change Date: 2025-03-24 * * On the date above, in accordance with the Business Source License, use * of this software will be governed by version 2 or later of the General * Public License. */ /** * @file readconnroute.c - Read Connection Load Balancing Query Router * * This is the implementation of a simple query router that balances * read connections. It assumes the service is configured with a set * of slaves and that the application clients already split read and write * queries. It offers a service to balance the client read connections * over this set of slave servers. It does this once only, at the time * the connection is made. It chooses the server that currently has the least * number of connections by keeping a count for each server of how * many connections the query router has made to the server. * * When two servers have the same number of current connections the one with * the least number of connections since startup will be used. * * The router may also have options associated to it that will limit the * choice of backend server. Currently two options are supported, the "master" * option will cause the router to only connect to servers marked as masters * and the "slave" option will limit connections to routers that are marked * as slaves. If neither option is specified the router will connect to either * masters or slaves. */ #include "readconnroute.hh" #include <maxscale/protocol/mariadb/mysql.hh> #include <maxscale/modutil.hh> /** * The module entry point routine. It is this routine that * must populate the structure that is referred to as the * "module object", this is a structure with the set of * external entry points for this module. * * @return The module object */ extern "C" MXS_MODULE* MXS_CREATE_MODULE() { static MXS_MODULE info = { MXS_MODULE_API_ROUTER, MXS_MODULE_GA, MXS_ROUTER_VERSION, "A connection based router to load balance based on connections", "V2.0.0", RCAP_TYPE_RUNTIME_CONFIG, &RCR::s_object, nullptr, /* Process init. */ nullptr, /* Process finish. */ nullptr, /* Thread init. */ nullptr, /* Thread finish. */ { {MXS_END_MODULE_PARAMS} } }; return &info; } /* * This routine returns the master server from a MariaDB replication tree. The server must be * running, not in maintenance and have the master bit set. If multiple masters are found, * the one with the highest weight is chosen. * * @param servers The list of servers * * @return The Master server */ static mxs::Endpoint* get_root_master(const Endpoints& endpoints) { auto best_rank = std::numeric_limits<int64_t>::max(); mxs::Endpoint* master_host = nullptr; for (auto e : endpoints) { if (e->target()->is_master()) { auto rank = e->target()->rank(); if (!master_host) { // No master found yet master_host = e; } else if (rank < best_rank) { best_rank = rank; master_host = e; } } } return master_host; } bool RCR::configure(mxs::ConfigParameters* params) { uint64_t bitmask = 0; uint64_t bitvalue = 0; bool ok = true; for (const auto& opt : mxs::strtok(params->get_string("router_options"), ", \t")) { if (!strcasecmp(opt.c_str(), "master")) { bitmask |= (SERVER_MASTER | SERVER_SLAVE); bitvalue |= SERVER_MASTER; } else if (!strcasecmp(opt.c_str(), "slave")) { bitmask |= (SERVER_MASTER | SERVER_SLAVE); bitvalue |= SERVER_SLAVE; } else if (!strcasecmp(opt.c_str(), "running")) { bitmask |= (SERVER_RUNNING); bitvalue |= SERVER_RUNNING; } else if (!strcasecmp(opt.c_str(), "synced")) { bitmask |= (SERVER_JOINED); bitvalue |= SERVER_JOINED; } else { MXS_ERROR("Unsupported router option \'%s\' for readconnroute. " "Expected router options are [slave|master|synced|running]", opt.c_str()); ok = false; } } if (bitmask == 0 && bitvalue == 0) { /** No parameters given, use RUNNING as a valid server */ bitmask |= (SERVER_RUNNING); bitvalue |= SERVER_RUNNING; } if (ok) { uint64_t mask = bitmask | (bitvalue << 32); atomic_store_uint64(&m_bitmask_and_bitvalue, mask); } return ok; } RCR::RCR(SERVICE* service) : mxs::Router<RCR, RCRSession>(service) { } // static RCR* RCR::create(SERVICE* service, mxs::ConfigParameters* params) { RCR* inst = new(std::nothrow) RCR(service); if (inst && !inst->configure(params)) { delete inst; inst = nullptr; } return inst; } RCRSession::RCRSession(RCR* inst, MXS_SESSION* session, mxs::Endpoint* backend, const Endpoints& endpoints, uint32_t bitmask, uint32_t bitvalue) : mxs::RouterSession(session) , m_instance(inst) , m_bitmask(bitmask) , m_bitvalue(bitvalue) , m_backend(backend) , m_endpoints(endpoints) , m_session_stats(inst->session_stats(backend->target())) { } RCRSession::~RCRSession() { m_session_stats.update(m_session_timer.split(), m_query_timer.total(), m_session_queries); } RCRSession* RCR::newSession(MXS_SESSION* session, const Endpoints& endpoints) { uint64_t mask = atomic_load_uint64(&m_bitmask_and_bitvalue); uint32_t bitmask = mask; uint32_t bitvalue = mask >> 32; /** * Find the Master host from available servers */ mxs::Endpoint* master_host = get_root_master(endpoints); bool connectable_master = master_host ? master_host->target()->is_connectable() : false; /** * Find a backend server to connect to. This is the extent of the * load balancing algorithm we need to implement for this simple * connection router. */ mxs::Endpoint* candidate = nullptr; auto best_rank = std::numeric_limits<int64_t>::max(); /* * Loop over all the servers and find any that have fewer connections * than the candidate server. * * If a server has less connections than the current candidate we mark this * as the new candidate to connect to. * * If a server has the same number of connections currently as the candidate * and has had less connections over time than the candidate it will also * become the new candidate. This has the effect of spreading the * connections over different servers during periods of very low load. */ for (auto e : endpoints) { if (!e->target()->is_connectable()) { continue; } mxb_assert(e->target()->is_usable()); /* Check server status bits against bitvalue from router_options */ if (e->target()->status() & bitmask & bitvalue) { if (master_host && connectable_master) { if (e == master_host && (bitvalue & (SERVER_SLAVE | SERVER_MASTER)) == SERVER_SLAVE) { /* Skip root master here, as it could also be slave of an external server that * is not in the configuration. Intermediate masters (Relay Servers) are also * slave and will be selected as Slave(s) */ continue; } if (e == master_host && bitvalue == SERVER_MASTER) { /* If option is "master" return only the root Master as there could be * intermediate masters (Relay Servers) and they must not be selected. */ candidate = master_host; break; } } else if (bitvalue == SERVER_MASTER) { /* Master_host is nullptr, no master server. If requested router_option is 'master' * candidate will be nullptr. */ candidate = nullptr; break; } /* If no candidate set, set first running server as our initial candidate server */ if (!candidate || e->target()->rank() < best_rank) { best_rank = e->target()->rank(); candidate = e; } else if (e->target()->rank() == best_rank && e->target()->stats().n_current < candidate->target()->stats().n_current) { // This one is better candidate = e; } } } /* If we haven't found a proper candidate yet but a master server is available, we'll pick that * with the assumption that it is "better" than a slave. */ if (!candidate) { if (master_host && connectable_master) { candidate = master_host; // Even if we had 'router_options=slave' in the configuration file, we // will still end up here if there are no slaves, but a sole master. So // that the server will be considered valid in connection_is_valid(), we // turn on the SERVER_MASTER bit. // // We must do that so that readconnroute in MaxScale 2.2 will again behave // the same way as it did up until 2.1.12. if (bitvalue & SERVER_SLAVE) { bitvalue |= SERVER_MASTER; } } else { if (!master_host) { MXS_ERROR("Failed to create new routing session. Couldn't find eligible" " candidate server. Freeing allocated resources."); } else { mxb_assert(!connectable_master); MXS_ERROR("The only possible candidate server (%s) is being drained " "and thus cannot be used.", master_host->target()->name()); } return nullptr; } } else { mxb_assert(candidate->target()->is_connectable()); } if (!candidate->connect()) { /** The failure is reported in dcb_connect() */ return nullptr; } RCRSession* client_rses = new RCRSession(this, session, candidate, endpoints, bitmask, bitvalue); MXS_INFO("New session for server %s. Connections : %d", candidate->target()->name(), candidate->target()->stats().n_current); return client_rses; } /** Log routing failure due to closed session */ static void log_closed_session(uint8_t mysql_command, mxs::Target* t) { char msg[1024 + 200] = ""; // Extra space for message if (t->is_down()) { sprintf(msg, "Server '%s' is down.", t->name()); } else if (t->is_in_maint()) { sprintf(msg, "Server '%s' is in maintenance.", t->name()); } else { sprintf(msg, "Server '%s' no longer qualifies as a target server.", t->name()); } MXS_ERROR("Failed to route MySQL command %d to backend server. %s", mysql_command, msg); } /** * Check if the server we're connected to is still valid * * @param inst Router instance * @param router_cli_ses Router session * * @return True if the backend connection is still valid */ bool RCRSession::connection_is_valid() const { bool rval = false; // m_instance->bitvalue and m_bitvalue are different, if we had // 'router_options=slave' in the configuration file and there was only // the sole master available at session creation time. if (m_backend->target()->is_usable() && (m_backend->target()->status() & m_bitmask & m_bitvalue)) { // Note the use of '==' and not '|'. We must use the former to exclude a // 'router_options=slave' that uses the master due to no slave having been // available at session creation time. Its bitvalue is (SERVER_MASTER | SERVER_SLAVE). if (m_bitvalue == SERVER_MASTER && m_backend->target()->active()) { // If we're using an active master server, verify that it is still a master rval = m_backend == get_root_master(m_endpoints); } else { /** * Either we don't use master type servers or the server reference * is deactivated. We let deactivated connection close gracefully * so we simply assume it is OK. This allows a server to be taken * out of use in a manner that won't cause errors to the connected * clients. */ rval = true; } } return rval; } int RCRSession::routeQuery(GWBUF* queue) { uint8_t mysql_command = mxs_mysql_get_command(queue); if (!connection_is_valid()) { log_closed_session(mysql_command, m_backend->target()); gwbuf_free(queue); return 0; } MXS_INFO("Routed [%s] to '%s' %s", STRPACKETTYPE(mysql_command), m_backend->target()->name(), mxs::extract_sql(queue).c_str()); m_query_timer.start_interval(); m_session_stats.inc_total(); if (m_bitvalue & SERVER_MASTER) { // not necessarily a write, but explicitely routed to a master m_session_stats.inc_write(); } else { // could be a write, in which case the user has other problems m_session_stats.inc_read(); } ++m_session_queries; mxb::atomic::add(&m_backend->target()->stats().packets, 1, mxb::atomic::RELAXED); return m_backend->routeQuery(queue); } void RCRSession::clientReply(GWBUF* pPacket, const maxscale::ReplyRoute& down, const maxscale::Reply& pReply) { RouterSession::clientReply(pPacket, down, pReply); m_query_timer.end_interval(); } maxscale::SessionStats& RCR::session_stats(maxscale::Target* pTarget) { return (*m_target_stats)[pTarget]; } maxscale::TargetSessionStats RCR::combined_target_stats() const { maxscale::TargetSessionStats stats; for (const auto& a : m_target_stats.values()) { for (const auto& b : a) { if (b.first->active()) { stats[b.first] += b.second; } } } return stats; } json_t* RCR::diagnostics() const { json_t* arr = json_array(); int64_t total_packets = 0; for (const auto& a : combined_target_stats()) { maxscale::SessionStats::CurrentStats stats = a.second.current_stats(); total_packets += stats.total_queries; double active_pct = std::round(100 * stats.ave_session_active_pct) / 100; json_t* obj = json_object(); json_object_set_new(obj, "id", json_string(a.first->name())); json_object_set_new(obj, "total", json_integer(stats.total_queries)); json_object_set_new(obj, "read", json_integer(stats.total_read_queries)); json_object_set_new(obj, "write", json_integer(stats.total_write_queries)); json_object_set_new(obj, "avg_sess_duration", json_string(mxb::to_string(stats.ave_session_dur).c_str())); json_object_set_new(obj, "avg_sess_active_pct", json_real(active_pct)); json_object_set_new(obj, "avg_queries_per_session", json_integer(stats.ave_session_selects)); json_array_append_new(arr, obj); } json_t* rval = json_object(); json_object_set_new(rval, "queries", json_integer(total_packets)); json_object_set_new(rval, "server_query_statistics", arr); return rval; } uint64_t RCR::getCapabilities() { return RCAP_TYPE_RUNTIME_CONFIG; }
// $Id: PropertySeq.cpp 1861 2011-08-31 16:18:08Z mesnierp $ #include "orbsvcs/Notify/PropertySeq.h" #if ! defined (__ACE_INLINE__) #include "orbsvcs/Notify/PropertySeq.inl" #endif /* __ACE_INLINE__ */ TAO_BEGIN_VERSIONED_NAMESPACE_DECL TAO_Notify_PropertySeq::TAO_Notify_PropertySeq (void) { } TAO_Notify_PropertySeq::~TAO_Notify_PropertySeq () { } int TAO_Notify_PropertySeq::init (const CosNotification::PropertySeq& prop_seq) { ACE_CString name; for (CORBA::ULong i = 0; i < prop_seq.length (); ++i) { name = prop_seq[i].name.in (); if (this->property_map_.rebind (name, prop_seq[i].value) == -1) return -1; } // Note call to rebind. This allows to call <init> to set updates. return 0; } int TAO_Notify_PropertySeq::populate (CosNotification::PropertySeq_var& prop_seq) const { PROPERTY_MAP::CONST_ITERATOR iterator (this->property_map_); int index = prop_seq->length (); prop_seq->length (static_cast<CORBA::ULong> (index + this->property_map_.current_size ())); for (PROPERTY_MAP::ENTRY *entry = 0; iterator.next (entry) != 0; iterator.advance (), ++index) { (*prop_seq)[index].name = CORBA::string_dup (entry->ext_id_.c_str ()); (*prop_seq)[index].value = entry->int_id_; } return 0; } void TAO_Notify_PropertySeq::add(const ACE_CString& name, const CORBA::Any& val) { int ret = this->property_map_.rebind (name, val); ACE_ASSERT(ret >= 0); ACE_UNUSED_ARG (ret); // because the assert disappears in release builds } TAO_END_VERSIONED_NAMESPACE_DECL
// Optimise #include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace std; using namespace __gnu_pbds; // #define MULTI_TEST #ifdef LOCAL #define db(...) ZZ(#__VA_ARGS__, __VA_ARGS__); #define pc(...) PC(#__VA_ARGS__, __VA_ARGS__); template <typename T, typename U> ostream &operator<<(ostream &out, const pair<T, U> &p) { out << '[' << p.first << ", " << p.second << ']'; return out; } template <typename Arg> void PC(const char *name, Arg &&arg) { while (*name == ',' || *name == ' ') name++; std::cerr << name << " { "; for (const auto &v : arg) cerr << v << ' '; cerr << " }\n"; } template <typename Arg1, typename... Args> void PC(const char *names, Arg1 &&arg1, Args &&... args) { while (*names == ',' || *names == ' ') names++; const char *comma = strchr(names, ','); std::cerr.write(names, comma - names) << " { "; for (const auto &v : arg1) cerr << v << ' '; cerr << " }\n"; PC(comma, args...); } template <typename Arg1> void ZZ(const char *name, Arg1 &&arg1) { std::cerr << name << " = " << arg1 << endl; } template <typename Arg1, typename... Args> void ZZ(const char *names, Arg1 &&arg1, Args &&... args) { const char *comma = strchr(names + 1, ','); std::cerr.write(names, comma - names) << " = " << arg1; ZZ(comma, args...); } #else #define db(...) #define pc(...) #endif using ll = long long; template <typename T> using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>; #define f first #define s second #define pb push_back #define all(v) v.begin(), v.end() auto TimeStart = chrono::steady_clock::now(); auto seed = TimeStart.time_since_epoch().count(); std::mt19937 rng(seed); template <typename T> using Random = std::uniform_int_distribution<T>; const int NAX = 2e5 + 5, MOD = 1000000007; vector<int> Z_function(string S) { int n = S.size(); vector<int> z(n); int l = -1, r = -1; for (int i = 1; i < n; ++i) { z[i] = i >= r ? 0 : min(r - i, z[i - l]); while (i + z[i] < n && S[z[i]] == S[i + z[i]]) ++z[i]; if (i + z[i] - 1 > r) l = i, r = i + z[i]; } return z; } void solveCase(int caseNo) { string s; cin >> s; auto z = Z_function(s); int max_so_far = 0; int n = s.length(); for (int i = 0; i < n; ++i) { if ((z[i] == n - i) && (max_so_far >= n - i)) { cout << s.substr(0, n - i); return; } max_so_far = max(max_so_far, z[i]); } cout << "Just a legend\n"; } int main() { #ifndef LOCAL ios_base::sync_with_stdio(0); cin.tie(0); #endif int t = 1; #ifdef MULTI_TEST cin >> t; #endif for (int i = 1; i <= t; ++i) { solveCase(i); #ifdef TIME cerr << "Case #" << i << ": Time " << chrono::duration<double>(chrono::steady_clock::now() - TimeStart).count() << " s.\n"; TimeStart = chrono::steady_clock::now(); #endif } return 0; }
/* * This file is part of the Simutrans project under the Artistic License. * (see LICENSE.txt) */ /* this file has all functions for variable gui elements */ #include "gui_theme.h" #include "../world/simworld.h" #include "../simskin.h" #include "../tool/simmenu.h" #include "../sys/simsys.h" #include "../dataobj/environment.h" #include "../dataobj/tabfile.h" #include "components/gui_button.h" #include "components/gui_tab_panel.h" #include "../descriptor/skin_desc.h" #include "../descriptor/reader/obj_reader.h" /** * Colours */ PIXVAL gui_theme_t::gui_color_text; PIXVAL gui_theme_t::gui_color_text_highlight; PIXVAL gui_theme_t::gui_color_text_shadow; PIXVAL gui_theme_t::gui_color_text_title; PIXVAL gui_theme_t::gui_color_text_strong; PIXVAL gui_theme_t::gui_color_text_minus; PIXVAL gui_theme_t::gui_color_text_plus; PIXVAL gui_theme_t::gui_color_text_unused; PIXVAL gui_theme_t::gui_color_edit_text; PIXVAL gui_theme_t::gui_color_edit_text_selected; PIXVAL gui_theme_t::gui_color_edit_text_disabled; PIXVAL gui_theme_t::gui_color_edit_background_selected; PIXVAL gui_theme_t::gui_color_edit_beam; PIXVAL gui_theme_t::gui_color_chart_background; PIXVAL gui_theme_t::gui_color_chart_lines_zero; PIXVAL gui_theme_t::gui_color_chart_lines_odd; PIXVAL gui_theme_t::gui_color_chart_lines_even; PIXVAL gui_theme_t::gui_color_list_text_selected_focus; PIXVAL gui_theme_t::gui_color_list_text_selected_nofocus; PIXVAL gui_theme_t::gui_color_list_background_selected_f; PIXVAL gui_theme_t::gui_color_list_background_selected_nf; PIXVAL gui_theme_t::gui_color_button_text; PIXVAL gui_theme_t::gui_color_button_text_disabled; PIXVAL gui_theme_t::gui_color_button_text_selected; PIXVAL gui_theme_t::gui_color_colored_button_text; PIXVAL gui_theme_t::gui_color_colored_button_text_selected; PIXVAL gui_theme_t::gui_color_checkbox_text; PIXVAL gui_theme_t::gui_color_checkbox_text_disabled; PIXVAL gui_theme_t::gui_color_ticker_background; PIXVAL gui_theme_t::gui_color_ticker_divider; PIXVAL gui_theme_t::gui_color_statusbar_text; PIXVAL gui_theme_t::gui_color_statusbar_background; PIXVAL gui_theme_t::gui_color_statusbar_divider; PIXVAL gui_theme_t::gui_highlight_color; PIXVAL gui_theme_t::gui_shadow_color; PIXVAL gui_theme_t::gui_color_loadingbar_inner; PIXVAL gui_theme_t::gui_color_loadingbar_progress; PIXVAL gui_theme_t::gui_color_obsolete; PIXVAL gui_theme_t::gui_color_chat_window_network_transparency; PIXVAL gui_theme_t::gui_color_empty; /** * Max Kielland * These are the built in default theme element sizes and * are overridden by the PAK file if a new image is defined. */ scr_size gui_theme_t::gui_button_size; scr_size gui_theme_t::gui_button_text_offset; scr_size gui_theme_t::gui_color_button_size; scr_size gui_theme_t::gui_color_button_text_offset; scr_size gui_theme_t::gui_divider_size; scr_size gui_theme_t::gui_checkbox_size; scr_size gui_theme_t::gui_pos_button_size; scr_size gui_theme_t::gui_arrow_left_size; scr_size gui_theme_t::gui_arrow_right_size; scr_size gui_theme_t::gui_arrow_up_size; scr_size gui_theme_t::gui_arrow_down_size; scr_size gui_theme_t::gui_scrollbar_size; scr_size gui_theme_t::gui_min_scrollbar_size; scr_size gui_theme_t::gui_label_size; scr_size gui_theme_t::gui_edit_size; scr_size gui_theme_t::gui_gadget_size; scr_size gui_theme_t::gui_dragger_size; scr_size gui_theme_t::gui_indicator_size; scr_coord_val gui_theme_t::gui_waitingbar_width; scr_coord gui_theme_t::gui_focus_offset; scr_coord gui_theme_t::gui_button_text_offset_right; scr_coord gui_theme_t::gui_color_button_text_offset_right; scr_coord_val gui_theme_t::gui_titlebar_height; scr_coord_val gui_theme_t::gui_frame_left; scr_coord_val gui_theme_t::gui_frame_top; scr_coord_val gui_theme_t::gui_frame_right; scr_coord_val gui_theme_t::gui_frame_bottom; scr_coord_val gui_theme_t::gui_hspace; scr_coord_val gui_theme_t::gui_vspace; scr_coord_val gui_theme_t::gui_filelist_vspace; /* those are the 3x3 images which are used for stretching * also 1x3 and 3x1 subsets are possible * first entry is the normal state * second entry is the selected state * third entry is disabled state * button has a fourth one, which is the mask for the background color blending */ stretch_map_t gui_theme_t::button_tiles[3]; stretch_map_t gui_theme_t::button_color_tiles[2]; stretch_map_t gui_theme_t::round_button_tiles[3]; stretch_map_t gui_theme_t::h_scroll_back_tiles; stretch_map_t gui_theme_t::h_scroll_knob_tiles; stretch_map_t gui_theme_t::v_scroll_back_tiles; stretch_map_t gui_theme_t::v_scroll_knob_tiles; stretch_map_t gui_theme_t::divider; stretch_map_t gui_theme_t::editfield; stretch_map_t gui_theme_t::listbox; stretch_map_t gui_theme_t::windowback; // and the simple buttons image_id gui_theme_t::arrow_button_left_img[3]; image_id gui_theme_t::arrow_button_right_img[3]; image_id gui_theme_t::arrow_button_up_img[3]; image_id gui_theme_t::arrow_button_down_img[3]; image_id gui_theme_t::check_button_img[3]; image_id gui_theme_t::pos_button_img[3]; bool gui_theme_t::gui_drop_shadows; /** * Initializes theme related parameters to hard coded default values. */ void gui_theme_t::init_gui_defaults() { gui_color_text = color_idx_to_rgb(COL_BLACK); gui_color_text_highlight = color_idx_to_rgb(COL_WHITE); gui_color_text_shadow = color_idx_to_rgb(COL_BLACK); gui_color_text_title = color_idx_to_rgb(207); gui_color_text_strong = color_idx_to_rgb(COL_RED); gui_color_text_minus = color_idx_to_rgb(COL_RED); gui_color_text_plus = color_idx_to_rgb(COL_BLACK); gui_color_text_unused = color_idx_to_rgb(COL_YELLOW); gui_color_edit_text = color_idx_to_rgb(COL_WHITE); gui_color_edit_text_selected = color_idx_to_rgb(COL_GREY5); gui_color_edit_text_disabled = color_idx_to_rgb(COL_GREY3); gui_color_edit_background_selected = color_idx_to_rgb(COL_GREY2); gui_color_edit_beam = color_idx_to_rgb(COL_WHITE); gui_color_chart_background = color_idx_to_rgb(MN_GREY1); gui_color_chart_lines_zero = color_idx_to_rgb(MN_GREY4); gui_color_chart_lines_odd = color_idx_to_rgb(COL_WHITE); gui_color_chart_lines_even = color_idx_to_rgb(MN_GREY0); gui_color_list_text_selected_focus = color_idx_to_rgb(COL_WHITE); gui_color_list_text_selected_nofocus = color_idx_to_rgb(MN_GREY3); gui_color_list_background_selected_f = color_idx_to_rgb(COL_BLUE); gui_color_list_background_selected_nf = color_idx_to_rgb(COL_LIGHT_BLUE); gui_color_button_text = color_idx_to_rgb(COL_BLACK); gui_color_button_text_disabled = color_idx_to_rgb(MN_GREY0); gui_color_button_text_selected = color_idx_to_rgb(COL_BLACK); gui_color_colored_button_text = color_idx_to_rgb(COL_BLACK); gui_color_colored_button_text_selected = color_idx_to_rgb(COL_WHITE); gui_color_checkbox_text = color_idx_to_rgb(COL_BLACK); gui_color_checkbox_text_disabled = color_idx_to_rgb(MN_GREY0); gui_color_ticker_background = color_idx_to_rgb(MN_GREY2); gui_color_ticker_divider = color_idx_to_rgb(COL_BLACK); gui_color_statusbar_text = color_idx_to_rgb(COL_BLACK); gui_color_statusbar_background = color_idx_to_rgb(MN_GREY1); gui_color_statusbar_divider = color_idx_to_rgb(MN_GREY4); gui_highlight_color = color_idx_to_rgb(MN_GREY4); gui_shadow_color = color_idx_to_rgb(MN_GREY0); gui_color_loadingbar_inner = color_idx_to_rgb(COL_GREY5); gui_color_loadingbar_progress = color_idx_to_rgb(COL_BLUE); gui_color_obsolete = color_idx_to_rgb(COL_BLUE); gui_color_empty = color_idx_to_rgb(COL_WHITE); env_t::gui_player_color_bright = 4; env_t::gui_player_color_dark = 1; gui_button_size = scr_size(92,14); gui_color_button_size = scr_size(92,16); gui_button_text_offset = scr_size(0,0); gui_color_button_text_offset = scr_size(0,0); gui_divider_size = scr_size(92,2+D_V_SPACE*2); gui_checkbox_size = scr_size(10,10); gui_pos_button_size = scr_size(14,LINESPACE); gui_arrow_left_size = scr_size(14,14); gui_arrow_right_size = scr_size(14,14); gui_arrow_up_size = scr_size(14,14); gui_arrow_down_size = scr_size(14,14); gui_scrollbar_size = scr_size(14,14); gui_min_scrollbar_size = scr_size(3,3); gui_label_size = scr_size(92,LINESPACE); gui_edit_size = scr_size(92,max(LINESPACE+2, max(D_ARROW_LEFT_HEIGHT, D_ARROW_RIGHT_HEIGHT) )); gui_gadget_size = scr_size(16,16); gui_indicator_size = scr_size(20,4); gui_focus_offset = scr_coord(1,1); gui_titlebar_height = 16; gui_frame_left = 10; gui_frame_top = 10; gui_frame_right = 10; gui_frame_bottom = 10; gui_hspace = 4; gui_vspace = 4; gui_filelist_vspace = 0; gui_waitingbar_width = 4; gui_divider_size.h = D_V_SPACE*2; gui_drop_shadows = false; gui_color_chat_window_network_transparency = color_idx_to_rgb(COL_WHITE); } // helper for easier init void gui_theme_t::init_size_from_image( const image_t *image, scr_size &k ) { if( image ) { k = scr_size(image->x+image->w,image->y+image->h); } } /** * Lazy button image number init */ void gui_theme_t::init_gui_from_images() { // Calculate posbutton size if( skinverwaltung_t::divider == NULL ) { // usually there should be a default theme which would provided missing images even for outdated themes dbg->fatal( "gui_theme_t::init_gui_themes", "Wrong theme loaded" ); } init_size_from_image( skinverwaltung_t::posbutton->get_image( SKIN_BUTTON_POS ), gui_pos_button_size ); init_size_from_image( skinverwaltung_t::check_button->get_image( SKIN_BUTTON_CHECKBOX ), gui_checkbox_size ); for( int i=0; i<3; i++ ) { pos_button_img[i] = skinverwaltung_t::posbutton->get_image_id( SKIN_BUTTON_POS+i ); check_button_img[i] = skinverwaltung_t::check_button->get_image_id( SKIN_BUTTON_CHECKBOX+i ); } // Normal buttons (colorful ones) scr_coord_val y = gui_button_size.h; scr_size k; init_size_from_image( skinverwaltung_t::button->get_image( SKIN_BUTTON_SIDE_LEFT ), k ); y = max( y, k.h ); init_size_from_image( skinverwaltung_t::button->get_image( SKIN_BUTTON_SIDE_RIGHT ), k ); y = max( y, k.h ); init_size_from_image( skinverwaltung_t::button->get_image( SKIN_BUTTON_BODY ), k ); y = max( y, k.h ); for( int i=0; i<3; i++ ) { for( int j=0; j<9; j++ ) { button_tiles[i][j%3][j/3] = skinverwaltung_t::button->get_image_id( i*9+j ); } } image_id has_second_mask = 0xFFFF; for( int i=0; i<2; i++ ) { has_second_mask = 0xFFFF; for( int j=0; j<9; j++ ) { button_color_tiles[i][j%3][j/3] = skinverwaltung_t::button->get_image_id( i*9+j+27 ); has_second_mask &= button_color_tiles[i][j%3][j/3]; } } if( has_second_mask == 0xFFFF ) { // has no second mask => copy first for( int j=0; j<9; j++ ) { button_color_tiles[1][j%3][j/3] = button_color_tiles[0][j%3][j/3]; } } // Round buttons for( int i=0; i<3; i++ ) { for( int j=0; j<9; j++ ) { round_button_tiles[i][j%3][j/3] = skinverwaltung_t::round_button->get_image_id( i*9+j ); } } // background for editfields, listbuttons, and windows for( int j=0; j<9; j++ ) { editfield[j%3][j/3] = skinverwaltung_t::editfield->get_image_id( j ); listbox[j%3][j/3] = skinverwaltung_t::listbox->get_image_id( j ); windowback[j%3][j/3] = skinverwaltung_t::back->get_image_id( j ); } // Divider (vspace will be added later on) init_size_from_image( skinverwaltung_t::divider->get_image(1), gui_divider_size ); for( int i=0; i<3; i++ ) { divider[i][0] = skinverwaltung_t::divider->get_image_id( i ); divider[i][1] = IMG_EMPTY; divider[i][2] = IMG_EMPTY; } // Calculate arrow size init_size_from_image( skinverwaltung_t::scrollbar->get_image( SKIN_BUTTON_ARROW_LEFT ), gui_arrow_left_size ); init_size_from_image( skinverwaltung_t::scrollbar->get_image( SKIN_BUTTON_ARROW_RIGHT ), gui_arrow_right_size ); init_size_from_image( skinverwaltung_t::scrollbar->get_image( SKIN_BUTTON_ARROW_UP ), gui_arrow_up_size ); init_size_from_image( skinverwaltung_t::scrollbar->get_image( SKIN_BUTTON_ARROW_DOWN ), gui_arrow_down_size ); for( int i=0; i<3; i++ ) { arrow_button_left_img[i] = skinverwaltung_t::scrollbar->get_image_id( SKIN_BUTTON_ARROW_LEFT+i ); arrow_button_right_img[i] = skinverwaltung_t::scrollbar->get_image_id( SKIN_BUTTON_ARROW_RIGHT+i ); arrow_button_up_img[i] = skinverwaltung_t::scrollbar->get_image_id( SKIN_BUTTON_ARROW_UP+i ); arrow_button_down_img[i] = skinverwaltung_t::scrollbar->get_image_id( SKIN_BUTTON_ARROW_DOWN+i ); } if( gui_theme_t::gui_arrow_right_size != gui_theme_t::gui_arrow_left_size ) { dbg->warning( "gui_theme_t::themes_init()", "Size of left and right arrows differ" ); } if( gui_theme_t::gui_arrow_up_size != gui_theme_t::gui_arrow_down_size ) { dbg->warning( "gui_theme_t::themes_init()", "Size of up and down arrows differ" ); } // now init this button dependent size here too gui_edit_size = scr_size(92,max(LINESPACE+2, max(D_ARROW_LEFT_HEIGHT, D_ARROW_RIGHT_HEIGHT) )); // init horizontal scrollbar buttons for( int i=0; i<3; i++ ) { h_scroll_back_tiles[i][0] = skinverwaltung_t::scrollbar->get_image_id( SKIN_SCROLLBAR_H_BACKGROUND_LEFT+i ); h_scroll_back_tiles[i][1] = IMG_EMPTY; h_scroll_back_tiles[i][2] = IMG_EMPTY; h_scroll_knob_tiles[i][0] = skinverwaltung_t::scrollbar->get_image_id( SKIN_SCROLLBAR_H_KNOB_LEFT+i ); h_scroll_knob_tiles[i][1] = IMG_EMPTY; h_scroll_knob_tiles[i][2] = IMG_EMPTY; } // init vertical scrollbar buttons for( int i=0; i<3; i++ ) { v_scroll_back_tiles[0][i] = skinverwaltung_t::scrollbar->get_image_id( SKIN_SCROLLBAR_V_BACKGROUND_TOP+i ); v_scroll_back_tiles[1][i] = IMG_EMPTY; v_scroll_back_tiles[2][i] = IMG_EMPTY; v_scroll_knob_tiles[0][i] = skinverwaltung_t::scrollbar->get_image_id( SKIN_SCROLLBAR_V_KNOB_TOP+i ); v_scroll_knob_tiles[1][i] = IMG_EMPTY; v_scroll_knob_tiles[2][i] = IMG_EMPTY; } // Calculate V scrollbar size { scr_size back, front; init_size_from_image( skinverwaltung_t::scrollbar->get_image( SKIN_SCROLLBAR_V_BACKGROUND ), back ); init_size_from_image( skinverwaltung_t::scrollbar->get_image( SKIN_SCROLLBAR_V_KNOB_BODY ), front ); gui_scrollbar_size.w = max(front.w, back.w); // Calculate H scrollbar size init_size_from_image( skinverwaltung_t::scrollbar->get_image( SKIN_SCROLLBAR_H_BACKGROUND ), back ); init_size_from_image( skinverwaltung_t::scrollbar->get_image( SKIN_SCROLLBAR_H_KNOB_BODY ), front ); gui_scrollbar_size.h = max(front.h, back.h); // calculate minimum width init_size_from_image( skinverwaltung_t::scrollbar->get_image( SKIN_SCROLLBAR_H_KNOB_LEFT ), back ); init_size_from_image( skinverwaltung_t::scrollbar->get_image( SKIN_SCROLLBAR_H_KNOB_RIGHT ), front ); gui_min_scrollbar_size.w = back.w + front.w; // calculate minimum height init_size_from_image( skinverwaltung_t::scrollbar->get_image( SKIN_SCROLLBAR_V_KNOB_TOP ), back ); init_size_from_image( skinverwaltung_t::scrollbar->get_image( SKIN_SCROLLBAR_V_KNOB_BOTTOM ), front ); gui_min_scrollbar_size.h = back.h + front.h; } // gadgets gui_dragger_size = gui_scrollbar_size; if (skinverwaltung_t::gadget) { init_size_from_image( skinverwaltung_t::gadget->get_image( SKIN_GADGET_CLOSE ), gui_gadget_size ); } } /** * Reads theme configuration data, still not final * * Note, there will be a theme manager later on and * each gui object will find their own parameters by * themselves after registering its class to the theme * manager. This will be done as the last step in * the chain when loading a theme. */ bool gui_theme_t::themes_init(const char *file_name, bool init_fonts, bool init_tools ) { tabfile_t themesconf; // first take user data, then user global data if( !themesconf.open(file_name) ) { dbg->warning("simwin.cc themes_init()", "Can't read themes from %s", file_name ); return false; } // define a default even when stuff is missing from the table init_gui_defaults(); tabfileobj_t contents; themesconf.read(contents); // theme name to find out current theme std::string theme_name = contents.get( "name" ); // reload current font if requested size differs and we are allowed to do so uint8 new_size = contents.get_int("font_size", env_t::fontsize ); if( init_fonts && new_size!=0 && LINESPACE!=new_size ) { if( display_load_font( env_t::fontname.c_str() ) ) { env_t::fontsize = new_size; } } // first get the images ( to be able to overload default sizes) const std::string buttonpak = contents.get("themeimages"); if( buttonpak.length()>0 ) { std::string path; char *pathname = strdup(file_name); if( char *s = strrchr( pathname, '/' ) ) { *s = 0; } else if( char *s = strrchr( pathname, '\\' ) ) { *s = 0; } dr_chdir( pathname ); obj_reader_t::read_file(buttonpak.c_str()); gui_theme_t::init_gui_from_images(); free(pathname); dr_chdir(env_t::user_dir); } // first the stuff for the dialogues gui_theme_t::gui_titlebar_height = (uint32)contents.get_int("gui_titlebar_height", gui_theme_t::gui_titlebar_height ); gui_theme_t::gui_frame_left = (uint32)contents.get_int("gui_frame_left", gui_theme_t::gui_frame_left ); gui_theme_t::gui_frame_top = (uint32)contents.get_int("gui_frame_top", gui_theme_t::gui_frame_top ); gui_theme_t::gui_frame_right = (uint32)contents.get_int("gui_frame_right", gui_theme_t::gui_frame_right ); gui_theme_t::gui_frame_bottom = (uint32)contents.get_int("gui_frame_bottom", gui_theme_t::gui_frame_bottom ); gui_theme_t::gui_hspace = (uint32)contents.get_int("gui_hspace", gui_theme_t::gui_hspace ); gui_theme_t::gui_vspace = (uint32)contents.get_int("gui_vspace", gui_theme_t::gui_vspace ); gui_theme_t::gui_filelist_vspace = (uint32)contents.get_int("gui_filelist_vspace", gui_theme_t::gui_filelist_vspace ); // the divider needs the vspace added to it for know gui_divider_size.h += gui_vspace*2; gui_theme_t::gui_divider_size.h = contents.get_int("gui_divider_vsize", gui_theme_t::gui_divider_size.h ); gui_theme_t::gui_button_size.w = (uint32)contents.get_int("gui_button_width", gui_theme_t::gui_button_size.w ); gui_theme_t::gui_button_size.h = (uint32)contents.get_int("gui_button_height", gui_theme_t::gui_button_size.h ); gui_theme_t::gui_edit_size.h = (uint32)contents.get_int("gui_edit_height", gui_theme_t::gui_edit_size.h ); gui_theme_t::gui_checkbox_size.w = (uint32)contents.get_int("gui_checkbox_width", gui_theme_t::gui_checkbox_size.w ); gui_theme_t::gui_checkbox_size.h = (uint32)contents.get_int("gui_checkbox_height", gui_theme_t::gui_checkbox_size.h ); gui_theme_t::gui_gadget_size.w = (uint32)contents.get_int("gui_gadget_width", gui_theme_t::gui_gadget_size.w ); gui_theme_t::gui_gadget_size.h = (uint32)contents.get_int("gui_gadget_height", gui_theme_t::gui_gadget_size.h ); // make them fit at least the font height gui_theme_t::gui_titlebar_height = max( LINESPACE+2, gui_theme_t::gui_titlebar_height ); gui_theme_t::gui_button_size.h = max( LINESPACE+2, gui_theme_t::gui_button_size.h ); gui_theme_t::gui_edit_size.h = max( LINESPACE+2, gui_theme_t::gui_edit_size.h ); // since the arrows are used in scrollbars, the need similar sizes gui_theme_t::gui_arrow_left_size.w = (uint32)contents.get_int("gui_horizontal_arrow_width", gui_theme_t::gui_arrow_left_size.w ); gui_theme_t::gui_arrow_left_size.h = (uint32)contents.get_int("gui_horizontal_arrow_height", gui_theme_t::gui_arrow_left_size.h ); gui_theme_t::gui_arrow_right_size = gui_theme_t::gui_arrow_left_size; gui_theme_t::gui_arrow_up_size.w = (uint32)contents.get_int("gui_vertical_arrow_width", gui_theme_t::gui_arrow_up_size.w ); gui_theme_t::gui_arrow_up_size.h = (uint32)contents.get_int("gui_vertical_arrow_height", gui_theme_t::gui_arrow_up_size.h ); gui_theme_t::gui_arrow_down_size = gui_theme_t::gui_arrow_up_size; // since scrollbar must have a certain size gui_theme_t::gui_scrollbar_size.w = max( gui_min_scrollbar_size.w, (uint32)contents.get_int("gui_scrollbar_width", gui_theme_t::gui_scrollbar_size.w ) ); gui_theme_t::gui_scrollbar_size.h = max( gui_min_scrollbar_size.h, (uint32)contents.get_int("gui_scrollbar_height", gui_theme_t::gui_scrollbar_size.h ) ); // dragger size must be as large as scrollbar size if (skinverwaltung_t::gadget) { init_size_from_image( skinverwaltung_t::gadget->get_image( SKIN_WINDOW_RESIZE), gui_dragger_size ); gui_dragger_size.clip_lefttop(scr_coord(gui_scrollbar_size.w, gui_scrollbar_size.h)); } // in practice, posbutton min height better is LINESPACE gui_theme_t::gui_pos_button_size.w = (uint32)contents.get_int("gui_posbutton_width", gui_theme_t::gui_pos_button_size.w ); gui_theme_t::gui_pos_button_size.h = (uint32)contents.get_int("gui_posbutton_height", gui_theme_t::gui_pos_button_size.h ); // read ../dataobj/tabfile.h for clarification of this area vector_tpl<int> color_button_text_offsets = contents.get_ints("gui_color_button_text_offset"); if( color_button_text_offsets.get_count() > 2 ) { gui_theme_t::gui_color_button_text_offset = scr_size(color_button_text_offsets[0], color_button_text_offsets[1]); gui_theme_t::gui_color_button_text_offset_right = scr_coord(color_button_text_offsets[2], 0); } vector_tpl<int> button_text_offsets = contents.get_ints("gui_button_text_offset"); if( button_text_offsets.get_count() > 2 ) { gui_theme_t::gui_button_text_offset = scr_size(button_text_offsets[0], button_text_offsets[1]); gui_theme_t::gui_button_text_offset_right = scr_coord(button_text_offsets[2], 0); } // default iconsize (square for now) env_t::iconsize.h = env_t::iconsize.w = contents.get_int("icon_width",env_t::iconsize.w ); // maybe not the best place, rather use simwin for the static defines? gui_theme_t::gui_color_text = (PIXVAL)contents.get_color("gui_color_text", SYSCOL_TEXT); gui_theme_t::gui_color_text_highlight = (PIXVAL)contents.get_color("gui_color_text_highlight", SYSCOL_TEXT_HIGHLIGHT); gui_theme_t::gui_color_text_shadow = (PIXVAL)contents.get_color("gui_color_text_shadow", SYSCOL_TEXT_SHADOW); gui_theme_t::gui_color_text_title = (PIXVAL)contents.get_color("gui_color_text_title", SYSCOL_TEXT_TITLE); gui_theme_t::gui_color_text_strong = (PIXVAL)contents.get_color("gui_color_text_strong", SYSCOL_TEXT_STRONG); gui_theme_t::gui_color_text_minus = (PIXVAL)contents.get_color("gui_color_text_minus", MONEY_MINUS); gui_theme_t::gui_color_text_plus = (PIXVAL)contents.get_color("gui_color_text_plus", MONEY_PLUS); gui_theme_t::gui_color_text_unused = (PIXVAL)contents.get_color("gui_color_text_unused", SYSCOL_TEXT_UNUSED); gui_theme_t::gui_color_edit_text = (PIXVAL)contents.get_color("gui_color_edit_text", SYSCOL_EDIT_TEXT); gui_theme_t::gui_color_edit_text_selected = (PIXVAL)contents.get_color("gui_color_edit_text_selected", SYSCOL_EDIT_TEXT_SELECTED); gui_theme_t::gui_color_edit_text_disabled = (PIXVAL)contents.get_color("gui_color_edit_text_disabled", SYSCOL_EDIT_TEXT_DISABLED); gui_theme_t::gui_color_edit_background_selected = (PIXVAL)contents.get_color("gui_color_edit_background_selected", SYSCOL_EDIT_BACKGROUND_SELECTED); gui_theme_t::gui_color_edit_beam = (PIXVAL)contents.get_color("gui_color_edit_beam", SYSCOL_CURSOR_BEAM); gui_theme_t::gui_color_chart_background = (PIXVAL)contents.get_color("gui_color_chart_background", SYSCOL_CHART_BACKGROUND); gui_theme_t::gui_color_chart_lines_zero = (PIXVAL)contents.get_color("gui_color_chart_lines_zero", SYSCOL_CHART_LINES_ZERO); gui_theme_t::gui_color_chart_lines_odd = (PIXVAL)contents.get_color("gui_color_chart_lines_odd", SYSCOL_CHART_LINES_ODD); gui_theme_t::gui_color_chart_lines_even = (PIXVAL)contents.get_color("gui_color_chart_lines_even", SYSCOL_CHART_LINES_EVEN); gui_theme_t::gui_color_list_text_selected_focus = (PIXVAL)contents.get_color("gui_color_list_text_selected_focus", SYSCOL_LIST_TEXT_SELECTED_FOCUS); gui_theme_t::gui_color_list_text_selected_nofocus = (PIXVAL)contents.get_color("gui_color_list_text_selected_nofocus", SYSCOL_LIST_TEXT_SELECTED_NOFOCUS); gui_theme_t::gui_color_list_background_selected_f = (PIXVAL)contents.get_color("gui_color_list_background_selected_focus", SYSCOL_LIST_BACKGROUND_SELECTED_F); gui_theme_t::gui_color_list_background_selected_nf = (PIXVAL)contents.get_color("gui_color_list_background_selected_nofocus", SYSCOL_LIST_BACKGROUND_SELECTED_NF); gui_theme_t::gui_color_button_text = (PIXVAL)contents.get_color("gui_color_button_text", SYSCOL_BUTTON_TEXT); gui_theme_t::gui_color_button_text_disabled = (PIXVAL)contents.get_color("gui_color_button_text_disabled", SYSCOL_BUTTON_TEXT_DISABLED); gui_theme_t::gui_color_button_text_selected = (PIXVAL)contents.get_color("gui_color_button_text_selected", SYSCOL_BUTTON_TEXT_SELECTED); gui_theme_t::gui_color_colored_button_text = (PIXVAL)contents.get_color("gui_color_colored_button_text", SYSCOL_COLORED_BUTTON_TEXT); gui_theme_t::gui_color_colored_button_text_selected = (PIXVAL)contents.get_color("gui_color_colored_button_text_selected", SYSCOL_COLORED_BUTTON_TEXT_SELECTED); gui_theme_t::gui_color_checkbox_text = (PIXVAL)contents.get_color("gui_color_checkbox_text", SYSCOL_CHECKBOX_TEXT); gui_theme_t::gui_color_checkbox_text_disabled = (PIXVAL)contents.get_color("gui_color_checkbox_text_disabled", SYSCOL_CHECKBOX_TEXT_DISABLED); gui_theme_t::gui_color_ticker_background = (PIXVAL)contents.get_color("gui_color_ticker_background", SYSCOL_TICKER_BACKGROUND); gui_theme_t::gui_color_ticker_divider = (PIXVAL)contents.get_color("gui_color_ticker_divider", SYSCOL_TICKER_DIVIDER); gui_theme_t::gui_color_statusbar_text = (PIXVAL)contents.get_color("gui_color_statusbar_text", SYSCOL_STATUSBAR_TEXT); gui_theme_t::gui_color_statusbar_background = (PIXVAL)contents.get_color("gui_color_statusbar_background", SYSCOL_STATUSBAR_BACKGROUND); gui_theme_t::gui_color_statusbar_divider = (PIXVAL)contents.get_color("gui_color_statusbar_divider", SYSCOL_STATUSBAR_DIVIDER); gui_theme_t::gui_highlight_color = (PIXVAL)contents.get_color("gui_highlight_color", SYSCOL_HIGHLIGHT); gui_theme_t::gui_shadow_color = (PIXVAL)contents.get_color("gui_shadow_color", SYSCOL_SHADOW); gui_theme_t::gui_color_loadingbar_inner = (PIXVAL)contents.get_color("gui_color_loadingbar_inner", SYSCOL_LOADINGBAR_INNER); gui_theme_t::gui_color_loadingbar_progress = (PIXVAL)contents.get_color("gui_color_loadingbar_progress", SYSCOL_LOADINGBAR_PROGRESS); gui_theme_t::gui_color_obsolete = (PIXVAL)contents.get_color("gui_color_obsolete", SYSCOL_OBSOLETE); gui_theme_t::gui_color_empty = (PIXVAL)contents.get_color("gui_color_empty", SYSCOL_EMPTY); gui_theme_t::gui_color_chat_window_network_transparency = (PIXVAL)contents.get_color("gui_color_chat_window_network_transparency", gui_color_chat_window_network_transparency); gui_theme_t::gui_waitingbar_width = (uint32)contents.get_int("gui_waitingbar_width", gui_theme_t::gui_waitingbar_width); // those two may be rather an own control later on? gui_theme_t::gui_indicator_size = contents.get_scr_size("gui_indicator_size", gui_theme_t::gui_indicator_size ); gui_tab_panel_t::header_vsize = (uint32)contents.get_int("gui_tab_header_vsize", gui_tab_panel_t::header_vsize ); // stuff in env_t but rather GUI env_t::window_buttons_right = contents.get_int("window_buttons_right", env_t::window_buttons_right ); env_t::left_to_right_graphs = contents.get_int("left_to_right_graphs", env_t::left_to_right_graphs ); env_t::window_frame_active = contents.get_int("window_frame_active", env_t::window_frame_active ); env_t::second_open_closes_win = contents.get_int("second_open_closes_win", env_t::second_open_closes_win ); env_t::remember_window_positions = contents.get_int("remember_window_positions", env_t::remember_window_positions ); env_t::window_snap_distance = contents.get_int("window_snap_distance", env_t::window_snap_distance ); gui_theme_t::gui_drop_shadows = contents.get_int("gui_drop_shadows", gui_theme_t::gui_drop_shadows ); env_t::bottom_window_darkness = contents.get_int("bottom_window_darkness", env_t::bottom_window_darkness ); env_t::menupos = contents.get_int("menubar_position", env_t::menupos); env_t::gui_player_color_bright = contents.get_int("gui_player_color_bright", env_t::gui_player_color_bright ); env_t::gui_player_color_dark = contents.get_int("gui_player_color_dark", env_t::gui_player_color_dark ); env_t::default_window_title_color = contents.get_color("default_window_title_color", env_t::default_window_title_color, &env_t::default_window_title_color_rgb ); env_t::front_window_text_color = contents.get_color("front_window_text_color", env_t::front_window_text_color, &env_t::front_window_text_color_rgb ); env_t::bottom_window_text_color = contents.get_color("bottom_window_text_color", env_t::bottom_window_text_color, &env_t::bottom_window_text_color_rgb ); env_t::cursor_overlay_color = contents.get_color("cursor_overlay_color", env_t::cursor_overlay_color, &env_t::cursor_overlay_color_rgb ); env_t::tooltip_color = contents.get_color("tooltip_background_color", env_t::tooltip_color, &env_t::tooltip_color_rgb ); env_t::tooltip_textcolor = contents.get_color("tooltip_text_color", env_t::tooltip_textcolor, &env_t::tooltip_textcolor_rgb ); env_t::show_tooltips = contents.get_int("show_tooltips", env_t::show_tooltips ); env_t::tooltip_delay = contents.get_int("tooltip_delay", env_t::tooltip_delay ); env_t::tooltip_duration = contents.get_int("tooltip_duration", env_t::tooltip_duration ); env_t::toolbar_max_width = contents.get_int("toolbar_max_width", env_t::toolbar_max_width ); env_t::toolbar_max_height = contents.get_int("toolbar_max_height", env_t::toolbar_max_height ); env_t::chat_window_transparency = 100 - contents.get_int("gui_chat_window_network_transparency", 100 - env_t::chat_window_transparency); if( toolbar_last_used_t::last_used_tools && init_tools ) { // only re-init if already inited tool_t::update_toolbars(); } env_t::default_theme = file_name; return true; }
#pragma once #include "natalie/gc/cell.hpp" #include "tm/vector.hpp" namespace Natalie { class MarkingVisitor : public Cell::Visitor { public: virtual void visit(Cell *cell) override final { if (!cell || cell->is_marked()) return; cell->mark(); cell->visit_children(*this); } virtual void visit(const Cell *cell) override final { visit(const_cast<Cell *>(cell)); } virtual void visit(Value val) override final; }; }
#include "Precompiled.h" #include "geojson.h" #include "projection.h" int discarded = 0; #ifdef KEEP_2D //----------------------------------------------------------------------------- static inline void extractP(const rapidjson::Value& _in, Point& p, const Tile& _tile) { const Vec2d pos = LonLatToMeters(Vec2d(_in[0].GetDouble(), _in[1].GetDouble())); p.x = (pos.x - _tile.tileOrigin.x); p.y = (pos.y - _tile.tileOrigin.y); }//----------------------------------------------------------------------------- static inline bool extractPoint(const rapidjson::Value& _in, Point& p, const Tile& _tile, Point* last) { const Vec2d pos = LonLatToMeters(Vec2d(_in[0].GetDouble(), _in[1].GetDouble())); p.x = (pos.x - _tile.tileOrigin.x); p.y = (pos.y - _tile.tileOrigin.y); //return sqLength(p - *last) >= 1e-10f ? true : false; if (sqLength(p - *last) >= 0.0316f) { return true; } discarded++; return false; } #else //----------------------------------------------------------------------------- static inline void extractP(const rapidjson::Value& _in, Point& p, const Tile& _tile) { const Vec2d pos = LonLatToMeters(Vec2d(_in[0].GetDouble(), _in[1].GetDouble())); p.x = (pos.x - _tile.tileOrigin.x); p.y = (pos.y - _tile.tileOrigin.y); p.z = 0; }//----------------------------------------------------------------------------- static inline bool extractPoint(const rapidjson::Value& _in, Point& p, const Tile& _tile, Point* last) { const Vec2d pos = LonLatToMeters(Vec2d(_in[0].GetDouble(), _in[1].GetDouble())); p.x = (pos.x - _tile.tileOrigin.x); p.y = (pos.y - _tile.tileOrigin.y); p.z = 0; //return myLength(p - *last) >= 1e-5f ? true : false; //return sqLength(p - *last) >= 1e-10f ? true : false; // 1mm threshold // sqrt(0.001) ~ 0,316 //return sqLength(p - *last) >= 0.316 ? true : false; if (sqLength(p - *last) >= 0.0316f) { return true; } discarded++; return false; } #endif //----------------------------------------------------------------------------- static inline int extractLineString(const rapidjson::Value& arr, LineString& l, const Tile& _tile) { const int count = arr.Size(); l.reserve(count); l.emplace_back(); extractP(arr[0], l.back(), _tile); for (int i=1; i<count; i++) { l.emplace_back(); if (!extractPoint(arr[i], l.back(), _tile, &l[l.size() - 2])) l.pop_back(); } return l.size(); } //----------------------------------------------------------------------------- // A poly is 1 or more linestrings // First linestring can be poly, second linestring can be a hole //----------------------------------------------------------------------------- bool extractPoly(const rapidjson::Value& arr, Polygon2& poly, const Tile& _tile) { const int rings = arr.Size(); poly.reserve(rings); for(int i=0; i<rings; i++) { poly.emplace_back(); if (extractLineString(arr[i], poly.back(), _tile) < 3) // Need at least 3 points in linestring to form a polygon { poly.pop_back(); gLogger.Warning("GeoJson: invalid LineString in polygon"); } } return poly.size() == rings; } //----------------------------------------------------------------------------- bool SkipFeature(const ELayerType layerType, const Feature& f) { // Skip other geometry than lines & polygons if ((f.geometryType == GeometryType::unknown || f.geometryType == GeometryType::points)) return true; // Skip certain features drawn as lines if (f.geometryType == GeometryType::lines) { if (layerType == eLayerTransit) { if (f.kind == eKind_platform || f.kind == eKind_tram) return true; } else if (layerType == eLayerLanduse) { if (f.kind == eKind_city_wall) return true; } } // Skip water boundaries if (layerType == eLayerWater && f.boundary) return true; // Settings says skip this feature const MapGeom* g = gGeomHash.GetValuePtr((layerType << 16 | f.kind)); if (g && g->skip) return true; return false; } //----------------------------------------------------------------------------- bool GeoJson::extractFeature(const ELayerType layerType, const rapidjson::Value& _in, Feature& f, const Tile& _tile, const float defaultHeight) { const rapidjson::Value& properties = _in["properties"]; int c = properties.MemberCount(); f.height = defaultHeight; for (auto itr = properties.MemberBegin(); itr != properties.MemberEnd(); ++itr) { const auto& member = itr->name.GetString(); const rapidjson::Value& prop = properties[member]; if (strcmp(member, "height") == 0) f.height = prop.GetDouble(); else if (strcmp(member, "min_height") == 0) f.min_height = prop.GetDouble(); else if (strcmp(member, "sort_rank") == 0) f.sort_rank = prop.GetInt(); else if (strcmp(member, "name") == 0) f.name = prop.GetString(); else if (strcmp(member, "id") == 0) f.id = prop.GetInt64(); // Can be signed else if (strcmp(member, "kind") == 0) { const CStr tmpstr = prop.GetString(); f.kind = gKindHash.Get(tmpstr); if (f.kind == eKind_unknown) { if(layerType != eLayerPois) LOG("Ukn: %s - %s\n", layerNames[layerType], tmpstr.Str()); } } else if (strcmp(member, "boundary") == 0) f.boundary = prop.GetBool(); } /*if (f.min_height > f.height) { int abba = 10; }*/ // Get feature's geometry type const rapidjson::Value& geometry = _in["geometry"]; const rapidjson::Value& coords = geometry["coordinates"]; const std::string& geomType = geometry["type"].GetString(); if (geomType == "Point") f.geometryType = GeometryType::points; else if (geomType == "MultiPoint") f.geometryType = GeometryType::points; else if (geomType == "LineString") f.geometryType = GeometryType::lines; else if (geomType == "MultiLineString") f.geometryType = GeometryType::lines; else if (geomType == "Polygon") f.geometryType = GeometryType::polygons; else if (geomType == "MultiPolygon") f.geometryType = GeometryType::polygons; // Skip certain features we are not interested in if (SkipFeature(layerType, f)) { //LOG("Skipped feature (%I64d)\n", f.id); return false; } // Copy geometry into tile data if (geomType == "Point") { f.points.emplace_back(); extractP(coords, f.points.back(), _tile); } else if (geomType == "MultiPoint") { gLogger.TellUser(LOG_NOTIFY, "MultiPoint. Not sure if this might be buggy implementation?"); for (auto pointCoords = coords.Begin(); pointCoords != coords.End(); ++pointCoords) extractP(coords, f.points.back(), _tile); } else if (geomType == "LineString") { f.lineStrings.emplace_back(); if (extractLineString(coords, f.lineStrings.back(), _tile) < 2) { gLogger.Warning("GeoJson: invalid LineString"); return false; } } else if (geomType == "MultiLineString") { for (auto lineCoords = coords.Begin(); lineCoords != coords.End(); ++lineCoords) { f.lineStrings.emplace_back(); if (extractLineString(*lineCoords, f.lineStrings.back(), _tile) < 2) { f.lineStrings.pop_back(); gLogger.Warning("GeoJson: one invalid LineString in MultiLineString"); } } if (f.lineStrings.size() == 0) { gLogger.Warning("GeoJson: invalid MultiLineString"); return false; } } else if (geomType == "Polygon") { f.polygons.emplace_back(); if (!extractPoly(coords, f.polygons.back(), _tile)) { f.polygons.pop_back(); gLogger.Warning("GeoJson: invalid Polygon"); return false; } } else if (geomType == "MultiPolygon") { for (auto polyCoords = coords.Begin(); polyCoords != coords.End(); ++polyCoords) { f.polygons.emplace_back(); if (!extractPoly(*polyCoords, f.polygons.back(), _tile)) { f.polygons.pop_back(); gLogger.Warning("GeoJson: invalid MultiPolygon"); return false; } } } return true; } // Unoptimized // Parsed json in 81.7ms. Built GeoJson structures in 74.0ms // Parsed json in 80.0ms.Built GeoJson structures in 76.2ms // Parsed json in 79.2ms.Built GeoJson structures in 75.2ms // Parsed json in 2.1ms.Built GeoJson structures in 2.0ms // Parsed json in 7.0ms.Built GeoJson structures in 6.2ms // Parsed json in 2.0ms.Built GeoJson structures in 3.2ms // Reserve layers // Parsed json in 77.0ms. Built GeoJson structures in 72.5ms // Parsed json in 78.8ms.Built GeoJson structures in 75.6ms // Parsed json in 64.5ms.Built GeoJson structures in 75.4ms // Parsed json in 7.3ms.Built GeoJson structures in 8.0ms // Parsed json in 2.8ms. Built GeoJson structures in 2.1ms // Parsed json in 2.0ms. Built GeoJson structures in 1.8ms // Reserve features // Parsed json in 82.7ms. Built GeoJson structures in 53.4ms // Parsed json in 74.3ms.Built GeoJson structures in 51.0ms // Parsed json in 67.8ms.Built GeoJson structures in 48.7ms // Parsed json in 2.0ms. Built GeoJson structures in 1.3ms // Parsed json in 7.2ms. Built GeoJson structures in 5.9ms // Parsed json in 6.9ms. Built GeoJson structures in 4.7ms // ExtractP // Parsed json in 73.4ms.Built GeoJson structures in 43.5ms // Parsed json in 65.8ms.Built GeoJson structures in 42.5ms // Parsed json in 70.4ms.Built GeoJson structures in 47.1ms // Parsed json in 1.9ms.Built GeoJson structures in 1.2ms // Parsed json in 2.1ms.Built GeoJson structures in 1.1ms // Parsed json in 7.3ms.Built GeoJson structures in 3.2ms // Laptop (Reserve features) // Parsed json in 156.4ms.Built GeoJson structures in 76.6ms // Parsed json in 138.4ms.Built GeoJson structures in 66.8ms // Parsed json in 116.3ms.Built GeoJson structures in 70.7ms // ExtractP // Parsed json in 88.6ms. Built GeoJson structures in 64.1ms // Parsed json in 104.3ms.Built GeoJson structures in 56.5ms // Parsed json in 81.8ms.Built GeoJson structures in 55.6ms // Earcut // Triangulated 690 PolygonMeshes in 3480.0ms // Triangulated 690 PolygonMeshes in 3485.3ms // NUC ( Removed reserve() calls) // Triangulated 690 PolygonMeshes in 394.2ms // Triangulated 690 PolygonMeshes in 395.5ms // Replaced std::vector with TArray // Triangulated 690 PolygonMeshes in 199.9ms // Triangulated 690 PolygonMeshes in 198.6ms // More // Triangulated 690 PolygonMeshes in 190.0ms // Triangulated 690 PolygonMeshes in 193.6ms // Extrude // Triangulated 690 PolygonMeshes in 188.4ms //----------------------------------------------------------------------------- void GeoJson::extractLayer(const rapidjson::Value& _in, Layer& layer, const Tile& _tile) { const auto& featureIter = _in.FindMember("features"); if (featureIter == _in.MemberEnd()) { LOG("ERROR: GeoJSON missing 'features' member\n"); return; } // Default values float defaultHeight = layer.layerType == eLayerBuildings ? 8.0f : 0.0f; // Json array of features const auto& jsonFeatureArr = featureIter->value; const int featureCount = jsonFeatureArr.Size(); layer.features.EnsureCapacity(featureCount); //auto featureJson = features.Begin(); featureJson != features.End(); ++featureJson) for (int i=0; i<featureCount; i++) { Feature& f = layer.features.AddEmpty(); if (!extractFeature(layer.layerType, jsonFeatureArr[i], f, _tile, defaultHeight)) layer.features.RemoveLast(); } }
//===- X86ISelDAGToDAG.cpp - A DAG pattern matching inst selector for X86 -===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file defines a DAG pattern matching instruction selector for X86, // converting from a legalized dag to a X86 dag. // //===----------------------------------------------------------------------===// #include "X86.h" #include "X86MachineFunctionInfo.h" #include "X86RegisterInfo.h" #include "X86Subtarget.h" #include "X86TargetMachine.h" #include "llvm/ADT/Statistic.h" #include "llvm/CodeGen/MachineFrameInfo.h" #include "llvm/CodeGen/MachineFunction.h" #include "llvm/CodeGen/SelectionDAGISel.h" #include "llvm/Config/llvm-config.h" #include "llvm/IR/ConstantRange.h" #include "llvm/IR/Function.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/Intrinsics.h" #include "llvm/IR/IntrinsicsX86.h" #include "llvm/IR/Type.h" #include "llvm/Support/Debug.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/KnownBits.h" #include "llvm/Support/MathExtras.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Target/TargetOptions.h" #include <stdint.h> using namespace llvm; #define DEBUG_TYPE "x86-isel" STATISTIC(NumLoadMoved, "Number of loads moved below TokenFactor"); static cl::opt<bool> AndImmShrink("x86-and-imm-shrink", cl::init(true), cl::desc("Enable setting constant bits to reduce size of mask immediates"), cl::Hidden); //===----------------------------------------------------------------------===// // Pattern Matcher Implementation //===----------------------------------------------------------------------===// namespace { /// This corresponds to X86AddressMode, but uses SDValue's instead of register /// numbers for the leaves of the matched tree. struct X86ISelAddressMode { enum { RegBase, FrameIndexBase } BaseType; // This is really a union, discriminated by BaseType! SDValue Base_Reg; int Base_FrameIndex; unsigned Scale; SDValue IndexReg; int32_t Disp; SDValue Segment; const GlobalValue *GV; const Constant *CP; const BlockAddress *BlockAddr; const char *ES; MCSymbol *MCSym; int JT; unsigned Align; // CP alignment. unsigned char SymbolFlags; // X86II::MO_* bool NegateIndex = false; X86ISelAddressMode() : BaseType(RegBase), Base_FrameIndex(0), Scale(1), IndexReg(), Disp(0), Segment(), GV(nullptr), CP(nullptr), BlockAddr(nullptr), ES(nullptr), MCSym(nullptr), JT(-1), Align(0), SymbolFlags(X86II::MO_NO_FLAG) {} bool hasSymbolicDisplacement() const { return GV != nullptr || CP != nullptr || ES != nullptr || MCSym != nullptr || JT != -1 || BlockAddr != nullptr; } bool hasBaseOrIndexReg() const { return BaseType == FrameIndexBase || IndexReg.getNode() != nullptr || Base_Reg.getNode() != nullptr; } /// Return true if this addressing mode is already RIP-relative. bool isRIPRelative() const { if (BaseType != RegBase) return false; if (RegisterSDNode *RegNode = dyn_cast_or_null<RegisterSDNode>(Base_Reg.getNode())) return RegNode->getReg() == X86::RIP; return false; } void setBaseReg(SDValue Reg) { BaseType = RegBase; Base_Reg = Reg; } #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) void dump(SelectionDAG *DAG = nullptr) { dbgs() << "X86ISelAddressMode " << this << '\n'; dbgs() << "Base_Reg "; if (Base_Reg.getNode()) Base_Reg.getNode()->dump(DAG); else dbgs() << "nul\n"; if (BaseType == FrameIndexBase) dbgs() << " Base.FrameIndex " << Base_FrameIndex << '\n'; dbgs() << " Scale " << Scale << '\n' << "IndexReg "; if (NegateIndex) dbgs() << "negate "; if (IndexReg.getNode()) IndexReg.getNode()->dump(DAG); else dbgs() << "nul\n"; dbgs() << " Disp " << Disp << '\n' << "GV "; if (GV) GV->dump(); else dbgs() << "nul"; dbgs() << " CP "; if (CP) CP->dump(); else dbgs() << "nul"; dbgs() << '\n' << "ES "; if (ES) dbgs() << ES; else dbgs() << "nul"; dbgs() << " MCSym "; if (MCSym) dbgs() << MCSym; else dbgs() << "nul"; dbgs() << " JT" << JT << " Align" << Align << '\n'; } #endif }; } namespace { //===--------------------------------------------------------------------===// /// ISel - X86-specific code to select X86 machine instructions for /// SelectionDAG operations. /// class X86DAGToDAGISel final : public SelectionDAGISel { /// Keep a pointer to the X86Subtarget around so that we can /// make the right decision when generating code for different targets. const X86Subtarget *Subtarget; /// If true, selector should try to optimize for code size instead of /// performance. bool OptForSize; /// If true, selector should try to optimize for minimum code size. bool OptForMinSize; /// Disable direct TLS access through segment registers. bool IndirectTlsSegRefs; public: explicit X86DAGToDAGISel(X86TargetMachine &tm, CodeGenOpt::Level OptLevel) : SelectionDAGISel(tm, OptLevel), Subtarget(nullptr), OptForSize(false), OptForMinSize(false), IndirectTlsSegRefs(false) {} StringRef getPassName() const override { return "X86 DAG->DAG Instruction Selection"; } bool runOnMachineFunction(MachineFunction &MF) override { // Reset the subtarget each time through. Subtarget = &MF.getSubtarget<X86Subtarget>(); IndirectTlsSegRefs = MF.getFunction().hasFnAttribute( "indirect-tls-seg-refs"); // OptFor[Min]Size are used in pattern predicates that isel is matching. OptForSize = MF.getFunction().hasOptSize(); OptForMinSize = MF.getFunction().hasMinSize(); assert((!OptForMinSize || OptForSize) && "OptForMinSize implies OptForSize"); SelectionDAGISel::runOnMachineFunction(MF); return true; } void emitFunctionEntryCode() override; bool IsProfitableToFold(SDValue N, SDNode *U, SDNode *Root) const override; void PreprocessISelDAG() override; void PostprocessISelDAG() override; // Include the pieces autogenerated from the target description. #include "X86GenDAGISel.inc" private: void Select(SDNode *N) override; bool foldOffsetIntoAddress(uint64_t Offset, X86ISelAddressMode &AM); bool matchLoadInAddress(LoadSDNode *N, X86ISelAddressMode &AM); bool matchWrapper(SDValue N, X86ISelAddressMode &AM); bool matchAddress(SDValue N, X86ISelAddressMode &AM); bool matchVectorAddress(SDValue N, X86ISelAddressMode &AM); bool matchAdd(SDValue &N, X86ISelAddressMode &AM, unsigned Depth); bool matchAddressRecursively(SDValue N, X86ISelAddressMode &AM, unsigned Depth); bool matchAddressBase(SDValue N, X86ISelAddressMode &AM); bool selectAddr(SDNode *Parent, SDValue N, SDValue &Base, SDValue &Scale, SDValue &Index, SDValue &Disp, SDValue &Segment); bool selectVectorAddr(MemSDNode *Parent, SDValue BasePtr, SDValue IndexOp, SDValue ScaleOp, SDValue &Base, SDValue &Scale, SDValue &Index, SDValue &Disp, SDValue &Segment); bool selectMOV64Imm32(SDValue N, SDValue &Imm); bool selectLEAAddr(SDValue N, SDValue &Base, SDValue &Scale, SDValue &Index, SDValue &Disp, SDValue &Segment); bool selectLEA64_32Addr(SDValue N, SDValue &Base, SDValue &Scale, SDValue &Index, SDValue &Disp, SDValue &Segment); bool selectTLSADDRAddr(SDValue N, SDValue &Base, SDValue &Scale, SDValue &Index, SDValue &Disp, SDValue &Segment); bool selectScalarSSELoad(SDNode *Root, SDNode *Parent, SDValue N, SDValue &Base, SDValue &Scale, SDValue &Index, SDValue &Disp, SDValue &Segment, SDValue &NodeWithChain); bool selectRelocImm(SDValue N, SDValue &Op); bool tryFoldLoad(SDNode *Root, SDNode *P, SDValue N, SDValue &Base, SDValue &Scale, SDValue &Index, SDValue &Disp, SDValue &Segment); // Convenience method where P is also root. bool tryFoldLoad(SDNode *P, SDValue N, SDValue &Base, SDValue &Scale, SDValue &Index, SDValue &Disp, SDValue &Segment) { return tryFoldLoad(P, P, N, Base, Scale, Index, Disp, Segment); } bool tryFoldBroadcast(SDNode *Root, SDNode *P, SDValue N, SDValue &Base, SDValue &Scale, SDValue &Index, SDValue &Disp, SDValue &Segment); /// Implement addressing mode selection for inline asm expressions. bool SelectInlineAsmMemoryOperand(const SDValue &Op, unsigned ConstraintID, std::vector<SDValue> &OutOps) override; void emitSpecialCodeForMain(); inline void getAddressOperands(X86ISelAddressMode &AM, const SDLoc &DL, MVT VT, SDValue &Base, SDValue &Scale, SDValue &Index, SDValue &Disp, SDValue &Segment) { if (AM.BaseType == X86ISelAddressMode::FrameIndexBase) Base = CurDAG->getTargetFrameIndex( AM.Base_FrameIndex, TLI->getPointerTy(CurDAG->getDataLayout())); else if (AM.Base_Reg.getNode()) Base = AM.Base_Reg; else Base = CurDAG->getRegister(0, VT); Scale = getI8Imm(AM.Scale, DL); // Negate the index if needed. if (AM.NegateIndex) { unsigned NegOpc = VT == MVT::i64 ? X86::NEG64r : X86::NEG32r; SDValue Neg = SDValue(CurDAG->getMachineNode(NegOpc, DL, VT, MVT::i32, AM.IndexReg), 0); AM.IndexReg = Neg; } if (AM.IndexReg.getNode()) Index = AM.IndexReg; else Index = CurDAG->getRegister(0, VT); // These are 32-bit even in 64-bit mode since RIP-relative offset // is 32-bit. if (AM.GV) Disp = CurDAG->getTargetGlobalAddress(AM.GV, SDLoc(), MVT::i32, AM.Disp, AM.SymbolFlags); else if (AM.CP) Disp = CurDAG->getTargetConstantPool(AM.CP, MVT::i32, AM.Align, AM.Disp, AM.SymbolFlags); else if (AM.ES) { assert(!AM.Disp && "Non-zero displacement is ignored with ES."); Disp = CurDAG->getTargetExternalSymbol(AM.ES, MVT::i32, AM.SymbolFlags); } else if (AM.MCSym) { assert(!AM.Disp && "Non-zero displacement is ignored with MCSym."); assert(AM.SymbolFlags == 0 && "oo"); Disp = CurDAG->getMCSymbol(AM.MCSym, MVT::i32); } else if (AM.JT != -1) { assert(!AM.Disp && "Non-zero displacement is ignored with JT."); Disp = CurDAG->getTargetJumpTable(AM.JT, MVT::i32, AM.SymbolFlags); } else if (AM.BlockAddr) Disp = CurDAG->getTargetBlockAddress(AM.BlockAddr, MVT::i32, AM.Disp, AM.SymbolFlags); else Disp = CurDAG->getTargetConstant(AM.Disp, DL, MVT::i32); if (AM.Segment.getNode()) Segment = AM.Segment; else Segment = CurDAG->getRegister(0, MVT::i16); } // Utility function to determine whether we should avoid selecting // immediate forms of instructions for better code size or not. // At a high level, we'd like to avoid such instructions when // we have similar constants used within the same basic block // that can be kept in a register. // bool shouldAvoidImmediateInstFormsForSize(SDNode *N) const { uint32_t UseCount = 0; // Do not want to hoist if we're not optimizing for size. // TODO: We'd like to remove this restriction. // See the comment in X86InstrInfo.td for more info. if (!CurDAG->shouldOptForSize()) return false; // Walk all the users of the immediate. for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); (UI != UE) && (UseCount < 2); ++UI) { SDNode *User = *UI; // This user is already selected. Count it as a legitimate use and // move on. if (User->isMachineOpcode()) { UseCount++; continue; } // We want to count stores of immediates as real uses. if (User->getOpcode() == ISD::STORE && User->getOperand(1).getNode() == N) { UseCount++; continue; } // We don't currently match users that have > 2 operands (except // for stores, which are handled above) // Those instruction won't match in ISEL, for now, and would // be counted incorrectly. // This may change in the future as we add additional instruction // types. if (User->getNumOperands() != 2) continue; // If this can match to INC/DEC, don't count it as a use. if (User->getOpcode() == ISD::ADD && (isOneConstant(SDValue(N, 0)) || isAllOnesConstant(SDValue(N, 0)))) continue; // Immediates that are used for offsets as part of stack // manipulation should be left alone. These are typically // used to indicate SP offsets for argument passing and // will get pulled into stores/pushes (implicitly). if (User->getOpcode() == X86ISD::ADD || User->getOpcode() == ISD::ADD || User->getOpcode() == X86ISD::SUB || User->getOpcode() == ISD::SUB) { // Find the other operand of the add/sub. SDValue OtherOp = User->getOperand(0); if (OtherOp.getNode() == N) OtherOp = User->getOperand(1); // Don't count if the other operand is SP. RegisterSDNode *RegNode; if (OtherOp->getOpcode() == ISD::CopyFromReg && (RegNode = dyn_cast_or_null<RegisterSDNode>( OtherOp->getOperand(1).getNode()))) if ((RegNode->getReg() == X86::ESP) || (RegNode->getReg() == X86::RSP)) continue; } // ... otherwise, count this and move on. UseCount++; } // If we have more than 1 use, then recommend for hoisting. return (UseCount > 1); } /// Return a target constant with the specified value of type i8. inline SDValue getI8Imm(unsigned Imm, const SDLoc &DL) { return CurDAG->getTargetConstant(Imm, DL, MVT::i8); } /// Return a target constant with the specified value, of type i32. inline SDValue getI32Imm(unsigned Imm, const SDLoc &DL) { return CurDAG->getTargetConstant(Imm, DL, MVT::i32); } /// Return a target constant with the specified value, of type i64. inline SDValue getI64Imm(uint64_t Imm, const SDLoc &DL) { return CurDAG->getTargetConstant(Imm, DL, MVT::i64); } SDValue getExtractVEXTRACTImmediate(SDNode *N, unsigned VecWidth, const SDLoc &DL) { assert((VecWidth == 128 || VecWidth == 256) && "Unexpected vector width"); uint64_t Index = N->getConstantOperandVal(1); MVT VecVT = N->getOperand(0).getSimpleValueType(); return getI8Imm((Index * VecVT.getScalarSizeInBits()) / VecWidth, DL); } SDValue getInsertVINSERTImmediate(SDNode *N, unsigned VecWidth, const SDLoc &DL) { assert((VecWidth == 128 || VecWidth == 256) && "Unexpected vector width"); uint64_t Index = N->getConstantOperandVal(2); MVT VecVT = N->getSimpleValueType(0); return getI8Imm((Index * VecVT.getScalarSizeInBits()) / VecWidth, DL); } // Helper to detect unneeded and instructions on shift amounts. Called // from PatFrags in tablegen. bool isUnneededShiftMask(SDNode *N, unsigned Width) const { assert(N->getOpcode() == ISD::AND && "Unexpected opcode"); const APInt &Val = cast<ConstantSDNode>(N->getOperand(1))->getAPIntValue(); if (Val.countTrailingOnes() >= Width) return true; APInt Mask = Val | CurDAG->computeKnownBits(N->getOperand(0)).Zero; return Mask.countTrailingOnes() >= Width; } /// Return an SDNode that returns the value of the global base register. /// Output instructions required to initialize the global base register, /// if necessary. SDNode *getGlobalBaseReg(); /// Return a reference to the TargetMachine, casted to the target-specific /// type. const X86TargetMachine &getTargetMachine() const { return static_cast<const X86TargetMachine &>(TM); } /// Return a reference to the TargetInstrInfo, casted to the target-specific /// type. const X86InstrInfo *getInstrInfo() const { return Subtarget->getInstrInfo(); } /// Address-mode matching performs shift-of-and to and-of-shift /// reassociation in order to expose more scaled addressing /// opportunities. bool ComplexPatternFuncMutatesDAG() const override { return true; } bool isSExtAbsoluteSymbolRef(unsigned Width, SDNode *N) const; /// Returns whether this is a relocatable immediate in the range /// [-2^Width .. 2^Width-1]. template <unsigned Width> bool isSExtRelocImm(SDNode *N) const { if (auto *CN = dyn_cast<ConstantSDNode>(N)) return isInt<Width>(CN->getSExtValue()); return isSExtAbsoluteSymbolRef(Width, N); } // Indicates we should prefer to use a non-temporal load for this load. bool useNonTemporalLoad(LoadSDNode *N) const { if (!N->isNonTemporal()) return false; unsigned StoreSize = N->getMemoryVT().getStoreSize(); if (N->getAlignment() < StoreSize) return false; switch (StoreSize) { default: llvm_unreachable("Unsupported store size"); case 4: case 8: return false; case 16: return Subtarget->hasSSE41(); case 32: return Subtarget->hasAVX2(); case 64: return Subtarget->hasAVX512(); } } bool foldLoadStoreIntoMemOperand(SDNode *Node); MachineSDNode *matchBEXTRFromAndImm(SDNode *Node); bool matchBitExtract(SDNode *Node); bool shrinkAndImmediate(SDNode *N); bool isMaskZeroExtended(SDNode *N) const; bool tryShiftAmountMod(SDNode *N); bool tryShrinkShlLogicImm(SDNode *N); bool tryVPTESTM(SDNode *Root, SDValue Setcc, SDValue Mask); bool tryMatchBitSelect(SDNode *N); MachineSDNode *emitPCMPISTR(unsigned ROpc, unsigned MOpc, bool MayFoldLoad, const SDLoc &dl, MVT VT, SDNode *Node); MachineSDNode *emitPCMPESTR(unsigned ROpc, unsigned MOpc, bool MayFoldLoad, const SDLoc &dl, MVT VT, SDNode *Node, SDValue &InFlag); bool tryOptimizeRem8Extend(SDNode *N); bool onlyUsesZeroFlag(SDValue Flags) const; bool hasNoSignFlagUses(SDValue Flags) const; bool hasNoCarryFlagUses(SDValue Flags) const; }; } // Returns true if this masked compare can be implemented legally with this // type. static bool isLegalMaskCompare(SDNode *N, const X86Subtarget *Subtarget) { unsigned Opcode = N->getOpcode(); if (Opcode == X86ISD::CMPM || Opcode == X86ISD::STRICT_CMPM || Opcode == ISD::SETCC || Opcode == X86ISD::CMPM_SAE || Opcode == X86ISD::VFPCLASS) { // We can get 256-bit 8 element types here without VLX being enabled. When // this happens we will use 512-bit operations and the mask will not be // zero extended. EVT OpVT = N->getOperand(0).getValueType(); // The first operand of X86ISD::STRICT_CMPM is chain, so we need to get the // second operand. if (Opcode == X86ISD::STRICT_CMPM) OpVT = N->getOperand(1).getValueType(); if (OpVT.is256BitVector() || OpVT.is128BitVector()) return Subtarget->hasVLX(); return true; } // Scalar opcodes use 128 bit registers, but aren't subject to the VLX check. if (Opcode == X86ISD::VFPCLASSS || Opcode == X86ISD::FSETCCM || Opcode == X86ISD::FSETCCM_SAE) return true; return false; } // Returns true if we can assume the writer of the mask has zero extended it // for us. bool X86DAGToDAGISel::isMaskZeroExtended(SDNode *N) const { // If this is an AND, check if we have a compare on either side. As long as // one side guarantees the mask is zero extended, the AND will preserve those // zeros. if (N->getOpcode() == ISD::AND) return isLegalMaskCompare(N->getOperand(0).getNode(), Subtarget) || isLegalMaskCompare(N->getOperand(1).getNode(), Subtarget); return isLegalMaskCompare(N, Subtarget); } bool X86DAGToDAGISel::IsProfitableToFold(SDValue N, SDNode *U, SDNode *Root) const { if (OptLevel == CodeGenOpt::None) return false; if (!N.hasOneUse()) return false; if (N.getOpcode() != ISD::LOAD) return true; // Don't fold non-temporal loads if we have an instruction for them. if (useNonTemporalLoad(cast<LoadSDNode>(N))) return false; // If N is a load, do additional profitability checks. if (U == Root) { switch (U->getOpcode()) { default: break; case X86ISD::ADD: case X86ISD::ADC: case X86ISD::SUB: case X86ISD::SBB: case X86ISD::AND: case X86ISD::XOR: case X86ISD::OR: case ISD::ADD: case ISD::ADDCARRY: case ISD::AND: case ISD::OR: case ISD::XOR: { SDValue Op1 = U->getOperand(1); // If the other operand is a 8-bit immediate we should fold the immediate // instead. This reduces code size. // e.g. // movl 4(%esp), %eax // addl $4, %eax // vs. // movl $4, %eax // addl 4(%esp), %eax // The former is 2 bytes shorter. In case where the increment is 1, then // the saving can be 4 bytes (by using incl %eax). if (ConstantSDNode *Imm = dyn_cast<ConstantSDNode>(Op1)) { if (Imm->getAPIntValue().isSignedIntN(8)) return false; // If this is a 64-bit AND with an immediate that fits in 32-bits, // prefer using the smaller and over folding the load. This is needed to // make sure immediates created by shrinkAndImmediate are always folded. // Ideally we would narrow the load during DAG combine and get the // best of both worlds. if (U->getOpcode() == ISD::AND && Imm->getAPIntValue().getBitWidth() == 64 && Imm->getAPIntValue().isIntN(32)) return false; // If this really a zext_inreg that can be represented with a movzx // instruction, prefer that. // TODO: We could shrink the load and fold if it is non-volatile. if (U->getOpcode() == ISD::AND && (Imm->getAPIntValue() == UINT8_MAX || Imm->getAPIntValue() == UINT16_MAX || Imm->getAPIntValue() == UINT32_MAX)) return false; // ADD/SUB with can negate the immediate and use the opposite operation // to fit 128 into a sign extended 8 bit immediate. if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB) && (-Imm->getAPIntValue()).isSignedIntN(8)) return false; if ((U->getOpcode() == X86ISD::ADD || U->getOpcode() == X86ISD::SUB) && (-Imm->getAPIntValue()).isSignedIntN(8) && hasNoCarryFlagUses(SDValue(U, 1))) return false; } // If the other operand is a TLS address, we should fold it instead. // This produces // movl %gs:0, %eax // leal i@NTPOFF(%eax), %eax // instead of // movl $i@NTPOFF, %eax // addl %gs:0, %eax // if the block also has an access to a second TLS address this will save // a load. // FIXME: This is probably also true for non-TLS addresses. if (Op1.getOpcode() == X86ISD::Wrapper) { SDValue Val = Op1.getOperand(0); if (Val.getOpcode() == ISD::TargetGlobalTLSAddress) return false; } // Don't fold load if this matches the BTS/BTR/BTC patterns. // BTS: (or X, (shl 1, n)) // BTR: (and X, (rotl -2, n)) // BTC: (xor X, (shl 1, n)) if (U->getOpcode() == ISD::OR || U->getOpcode() == ISD::XOR) { if (U->getOperand(0).getOpcode() == ISD::SHL && isOneConstant(U->getOperand(0).getOperand(0))) return false; if (U->getOperand(1).getOpcode() == ISD::SHL && isOneConstant(U->getOperand(1).getOperand(0))) return false; } if (U->getOpcode() == ISD::AND) { SDValue U0 = U->getOperand(0); SDValue U1 = U->getOperand(1); if (U0.getOpcode() == ISD::ROTL) { auto *C = dyn_cast<ConstantSDNode>(U0.getOperand(0)); if (C && C->getSExtValue() == -2) return false; } if (U1.getOpcode() == ISD::ROTL) { auto *C = dyn_cast<ConstantSDNode>(U1.getOperand(0)); if (C && C->getSExtValue() == -2) return false; } } break; } case ISD::SHL: case ISD::SRA: case ISD::SRL: // Don't fold a load into a shift by immediate. The BMI2 instructions // support folding a load, but not an immediate. The legacy instructions // support folding an immediate, but can't fold a load. Folding an // immediate is preferable to folding a load. if (isa<ConstantSDNode>(U->getOperand(1))) return false; break; } } // Prevent folding a load if this can implemented with an insert_subreg or // a move that implicitly zeroes. if (Root->getOpcode() == ISD::INSERT_SUBVECTOR && isNullConstant(Root->getOperand(2)) && (Root->getOperand(0).isUndef() || ISD::isBuildVectorAllZeros(Root->getOperand(0).getNode()))) return false; return true; } /// Replace the original chain operand of the call with /// load's chain operand and move load below the call's chain operand. static void moveBelowOrigChain(SelectionDAG *CurDAG, SDValue Load, SDValue Call, SDValue OrigChain) { SmallVector<SDValue, 8> Ops; SDValue Chain = OrigChain.getOperand(0); if (Chain.getNode() == Load.getNode()) Ops.push_back(Load.getOperand(0)); else { assert(Chain.getOpcode() == ISD::TokenFactor && "Unexpected chain operand"); for (unsigned i = 0, e = Chain.getNumOperands(); i != e; ++i) if (Chain.getOperand(i).getNode() == Load.getNode()) Ops.push_back(Load.getOperand(0)); else Ops.push_back(Chain.getOperand(i)); SDValue NewChain = CurDAG->getNode(ISD::TokenFactor, SDLoc(Load), MVT::Other, Ops); Ops.clear(); Ops.push_back(NewChain); } Ops.append(OrigChain->op_begin() + 1, OrigChain->op_end()); CurDAG->UpdateNodeOperands(OrigChain.getNode(), Ops); CurDAG->UpdateNodeOperands(Load.getNode(), Call.getOperand(0), Load.getOperand(1), Load.getOperand(2)); Ops.clear(); Ops.push_back(SDValue(Load.getNode(), 1)); Ops.append(Call->op_begin() + 1, Call->op_end()); CurDAG->UpdateNodeOperands(Call.getNode(), Ops); } /// Return true if call address is a load and it can be /// moved below CALLSEQ_START and the chains leading up to the call. /// Return the CALLSEQ_START by reference as a second output. /// In the case of a tail call, there isn't a callseq node between the call /// chain and the load. static bool isCalleeLoad(SDValue Callee, SDValue &Chain, bool HasCallSeq) { // The transformation is somewhat dangerous if the call's chain was glued to // the call. After MoveBelowOrigChain the load is moved between the call and // the chain, this can create a cycle if the load is not folded. So it is // *really* important that we are sure the load will be folded. if (Callee.getNode() == Chain.getNode() || !Callee.hasOneUse()) return false; LoadSDNode *LD = dyn_cast<LoadSDNode>(Callee.getNode()); if (!LD || !LD->isSimple() || LD->getAddressingMode() != ISD::UNINDEXED || LD->getExtensionType() != ISD::NON_EXTLOAD) return false; // Now let's find the callseq_start. while (HasCallSeq && Chain.getOpcode() != ISD::CALLSEQ_START) { if (!Chain.hasOneUse()) return false; Chain = Chain.getOperand(0); } if (!Chain.getNumOperands()) return false; // Since we are not checking for AA here, conservatively abort if the chain // writes to memory. It's not safe to move the callee (a load) across a store. if (isa<MemSDNode>(Chain.getNode()) && cast<MemSDNode>(Chain.getNode())->writeMem()) return false; if (Chain.getOperand(0).getNode() == Callee.getNode()) return true; if (Chain.getOperand(0).getOpcode() == ISD::TokenFactor && Callee.getValue(1).isOperandOf(Chain.getOperand(0).getNode()) && Callee.getValue(1).hasOneUse()) return true; return false; } void X86DAGToDAGISel::PreprocessISelDAG() { for (SelectionDAG::allnodes_iterator I = CurDAG->allnodes_begin(), E = CurDAG->allnodes_end(); I != E; ) { SDNode *N = &*I++; // Preincrement iterator to avoid invalidation issues. // If this is a target specific AND node with no flag usages, turn it back // into ISD::AND to enable test instruction matching. if (N->getOpcode() == X86ISD::AND && !N->hasAnyUseOfValue(1)) { SDValue Res = CurDAG->getNode(ISD::AND, SDLoc(N), N->getValueType(0), N->getOperand(0), N->getOperand(1)); --I; CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Res); ++I; CurDAG->DeleteNode(N); continue; } /// Convert vector increment or decrement to sub/add with an all-ones /// constant: /// add X, <1, 1...> --> sub X, <-1, -1...> /// sub X, <1, 1...> --> add X, <-1, -1...> /// The all-ones vector constant can be materialized using a pcmpeq /// instruction that is commonly recognized as an idiom (has no register /// dependency), so that's better/smaller than loading a splat 1 constant. if ((N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) && N->getSimpleValueType(0).isVector()) { APInt SplatVal; if (X86::isConstantSplat(N->getOperand(1), SplatVal) && SplatVal.isOneValue()) { SDLoc DL(N); MVT VT = N->getSimpleValueType(0); unsigned NumElts = VT.getSizeInBits() / 32; SDValue AllOnes = CurDAG->getAllOnesConstant(DL, MVT::getVectorVT(MVT::i32, NumElts)); AllOnes = CurDAG->getBitcast(VT, AllOnes); unsigned NewOpcode = N->getOpcode() == ISD::ADD ? ISD::SUB : ISD::ADD; SDValue Res = CurDAG->getNode(NewOpcode, DL, VT, N->getOperand(0), AllOnes); --I; CurDAG->ReplaceAllUsesWith(N, Res.getNode()); ++I; CurDAG->DeleteNode(N); continue; } } switch (N->getOpcode()) { case ISD::FP_ROUND: case ISD::STRICT_FP_ROUND: case ISD::FP_TO_SINT: case ISD::FP_TO_UINT: case ISD::STRICT_FP_TO_SINT: case ISD::STRICT_FP_TO_UINT: { // Replace vector fp_to_s/uint with their X86 specific equivalent so we // don't need 2 sets of patterns. if (!N->getSimpleValueType(0).isVector()) break; unsigned NewOpc; switch (N->getOpcode()) { default: llvm_unreachable("Unexpected opcode!"); case ISD::FP_ROUND: NewOpc = X86ISD::VFPROUND; break; case ISD::STRICT_FP_ROUND: NewOpc = X86ISD::STRICT_VFPROUND; break; case ISD::STRICT_FP_TO_SINT: NewOpc = X86ISD::STRICT_CVTTP2SI; break; case ISD::FP_TO_SINT: NewOpc = X86ISD::CVTTP2SI; break; case ISD::STRICT_FP_TO_UINT: NewOpc = X86ISD::STRICT_CVTTP2UI; break; case ISD::FP_TO_UINT: NewOpc = X86ISD::CVTTP2UI; break; } SDValue Res; if (N->isStrictFPOpcode()) Res = CurDAG->getNode(NewOpc, SDLoc(N), {N->getValueType(0), MVT::Other}, {N->getOperand(0), N->getOperand(1)}); else Res = CurDAG->getNode(NewOpc, SDLoc(N), N->getValueType(0), N->getOperand(0)); --I; CurDAG->ReplaceAllUsesWith(N, Res.getNode()); ++I; CurDAG->DeleteNode(N); continue; } case ISD::SHL: case ISD::SRA: case ISD::SRL: { // Replace vector shifts with their X86 specific equivalent so we don't // need 2 sets of patterns. if (!N->getValueType(0).isVector()) break; unsigned NewOpc; switch (N->getOpcode()) { default: llvm_unreachable("Unexpected opcode!"); case ISD::SHL: NewOpc = X86ISD::VSHLV; break; case ISD::SRA: NewOpc = X86ISD::VSRAV; break; case ISD::SRL: NewOpc = X86ISD::VSRLV; break; } SDValue Res = CurDAG->getNode(NewOpc, SDLoc(N), N->getValueType(0), N->getOperand(0), N->getOperand(1)); --I; CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Res); ++I; CurDAG->DeleteNode(N); continue; } case ISD::ANY_EXTEND: case ISD::ANY_EXTEND_VECTOR_INREG: { // Replace vector any extend with the zero extend equivalents so we don't // need 2 sets of patterns. Ignore vXi1 extensions. if (!N->getValueType(0).isVector()) break; unsigned NewOpc; if (N->getOperand(0).getScalarValueSizeInBits() == 1) { assert(N->getOpcode() == ISD::ANY_EXTEND && "Unexpected opcode for mask vector!"); NewOpc = ISD::SIGN_EXTEND; } else { NewOpc = N->getOpcode() == ISD::ANY_EXTEND ? ISD::ZERO_EXTEND : ISD::ZERO_EXTEND_VECTOR_INREG; } SDValue Res = CurDAG->getNode(NewOpc, SDLoc(N), N->getValueType(0), N->getOperand(0)); --I; CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Res); ++I; CurDAG->DeleteNode(N); continue; } case ISD::FCEIL: case ISD::STRICT_FCEIL: case ISD::FFLOOR: case ISD::STRICT_FFLOOR: case ISD::FTRUNC: case ISD::STRICT_FTRUNC: case ISD::FNEARBYINT: case ISD::STRICT_FNEARBYINT: case ISD::FRINT: case ISD::STRICT_FRINT: { // Replace fp rounding with their X86 specific equivalent so we don't // need 2 sets of patterns. unsigned Imm; switch (N->getOpcode()) { default: llvm_unreachable("Unexpected opcode!"); case ISD::STRICT_FCEIL: case ISD::FCEIL: Imm = 0xA; break; case ISD::STRICT_FFLOOR: case ISD::FFLOOR: Imm = 0x9; break; case ISD::STRICT_FTRUNC: case ISD::FTRUNC: Imm = 0xB; break; case ISD::STRICT_FNEARBYINT: case ISD::FNEARBYINT: Imm = 0xC; break; case ISD::STRICT_FRINT: case ISD::FRINT: Imm = 0x4; break; } SDLoc dl(N); bool IsStrict = N->isStrictFPOpcode(); SDValue Res; if (IsStrict) Res = CurDAG->getNode(X86ISD::STRICT_VRNDSCALE, dl, {N->getValueType(0), MVT::Other}, {N->getOperand(0), N->getOperand(1), CurDAG->getTargetConstant(Imm, dl, MVT::i8)}); else Res = CurDAG->getNode(X86ISD::VRNDSCALE, dl, N->getValueType(0), N->getOperand(0), CurDAG->getTargetConstant(Imm, dl, MVT::i8)); --I; CurDAG->ReplaceAllUsesWith(N, Res.getNode()); ++I; CurDAG->DeleteNode(N); continue; } case X86ISD::FANDN: case X86ISD::FAND: case X86ISD::FOR: case X86ISD::FXOR: { // Widen scalar fp logic ops to vector to reduce isel patterns. // FIXME: Can we do this during lowering/combine. MVT VT = N->getSimpleValueType(0); if (VT.isVector() || VT == MVT::f128) break; MVT VecVT = VT == MVT::f64 ? MVT::v2f64 : MVT::v4f32; SDLoc dl(N); SDValue Op0 = CurDAG->getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, N->getOperand(0)); SDValue Op1 = CurDAG->getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, N->getOperand(1)); SDValue Res; if (Subtarget->hasSSE2()) { EVT IntVT = EVT(VecVT).changeVectorElementTypeToInteger(); Op0 = CurDAG->getNode(ISD::BITCAST, dl, IntVT, Op0); Op1 = CurDAG->getNode(ISD::BITCAST, dl, IntVT, Op1); unsigned Opc; switch (N->getOpcode()) { default: llvm_unreachable("Unexpected opcode!"); case X86ISD::FANDN: Opc = X86ISD::ANDNP; break; case X86ISD::FAND: Opc = ISD::AND; break; case X86ISD::FOR: Opc = ISD::OR; break; case X86ISD::FXOR: Opc = ISD::XOR; break; } Res = CurDAG->getNode(Opc, dl, IntVT, Op0, Op1); Res = CurDAG->getNode(ISD::BITCAST, dl, VecVT, Res); } else { Res = CurDAG->getNode(N->getOpcode(), dl, VecVT, Op0, Op1); } Res = CurDAG->getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Res, CurDAG->getIntPtrConstant(0, dl)); --I; CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Res); ++I; CurDAG->DeleteNode(N); continue; } } if (OptLevel != CodeGenOpt::None && // Only do this when the target can fold the load into the call or // jmp. !Subtarget->useRetpolineIndirectCalls() && ((N->getOpcode() == X86ISD::CALL && !Subtarget->slowTwoMemOps()) || (N->getOpcode() == X86ISD::TC_RETURN && (Subtarget->is64Bit() || !getTargetMachine().isPositionIndependent())))) { /// Also try moving call address load from outside callseq_start to just /// before the call to allow it to be folded. /// /// [Load chain] /// ^ /// | /// [Load] /// ^ ^ /// | | /// / \-- /// / | ///[CALLSEQ_START] | /// ^ | /// | | /// [LOAD/C2Reg] | /// | | /// \ / /// \ / /// [CALL] bool HasCallSeq = N->getOpcode() == X86ISD::CALL; SDValue Chain = N->getOperand(0); SDValue Load = N->getOperand(1); if (!isCalleeLoad(Load, Chain, HasCallSeq)) continue; moveBelowOrigChain(CurDAG, Load, SDValue(N, 0), Chain); ++NumLoadMoved; continue; } // Lower fpround and fpextend nodes that target the FP stack to be store and // load to the stack. This is a gross hack. We would like to simply mark // these as being illegal, but when we do that, legalize produces these when // it expands calls, then expands these in the same legalize pass. We would // like dag combine to be able to hack on these between the call expansion // and the node legalization. As such this pass basically does "really // late" legalization of these inline with the X86 isel pass. // FIXME: This should only happen when not compiled with -O0. switch (N->getOpcode()) { default: continue; case ISD::FP_ROUND: case ISD::FP_EXTEND: { MVT SrcVT = N->getOperand(0).getSimpleValueType(); MVT DstVT = N->getSimpleValueType(0); // If any of the sources are vectors, no fp stack involved. if (SrcVT.isVector() || DstVT.isVector()) continue; // If the source and destination are SSE registers, then this is a legal // conversion that should not be lowered. const X86TargetLowering *X86Lowering = static_cast<const X86TargetLowering *>(TLI); bool SrcIsSSE = X86Lowering->isScalarFPTypeInSSEReg(SrcVT); bool DstIsSSE = X86Lowering->isScalarFPTypeInSSEReg(DstVT); if (SrcIsSSE && DstIsSSE) continue; if (!SrcIsSSE && !DstIsSSE) { // If this is an FPStack extension, it is a noop. if (N->getOpcode() == ISD::FP_EXTEND) continue; // If this is a value-preserving FPStack truncation, it is a noop. if (N->getConstantOperandVal(1)) continue; } // Here we could have an FP stack truncation or an FPStack <-> SSE convert. // FPStack has extload and truncstore. SSE can fold direct loads into other // operations. Based on this, decide what we want to do. MVT MemVT = (N->getOpcode() == ISD::FP_ROUND) ? DstVT : SrcVT; SDValue MemTmp = CurDAG->CreateStackTemporary(MemVT); int SPFI = cast<FrameIndexSDNode>(MemTmp)->getIndex(); MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(CurDAG->getMachineFunction(), SPFI); SDLoc dl(N); // FIXME: optimize the case where the src/dest is a load or store? SDValue Store = CurDAG->getTruncStore( CurDAG->getEntryNode(), dl, N->getOperand(0), MemTmp, MPI, MemVT); SDValue Result = CurDAG->getExtLoad(ISD::EXTLOAD, dl, DstVT, Store, MemTmp, MPI, MemVT); // We're about to replace all uses of the FP_ROUND/FP_EXTEND with the // extload we created. This will cause general havok on the dag because // anything below the conversion could be folded into other existing nodes. // To avoid invalidating 'I', back it up to the convert node. --I; CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Result); break; } //The sequence of events for lowering STRICT_FP versions of these nodes requires //dealing with the chain differently, as there is already a preexisting chain. case ISD::STRICT_FP_ROUND: case ISD::STRICT_FP_EXTEND: { MVT SrcVT = N->getOperand(1).getSimpleValueType(); MVT DstVT = N->getSimpleValueType(0); // If any of the sources are vectors, no fp stack involved. if (SrcVT.isVector() || DstVT.isVector()) continue; // If the source and destination are SSE registers, then this is a legal // conversion that should not be lowered. const X86TargetLowering *X86Lowering = static_cast<const X86TargetLowering *>(TLI); bool SrcIsSSE = X86Lowering->isScalarFPTypeInSSEReg(SrcVT); bool DstIsSSE = X86Lowering->isScalarFPTypeInSSEReg(DstVT); if (SrcIsSSE && DstIsSSE) continue; if (!SrcIsSSE && !DstIsSSE) { // If this is an FPStack extension, it is a noop. if (N->getOpcode() == ISD::STRICT_FP_EXTEND) continue; // If this is a value-preserving FPStack truncation, it is a noop. if (N->getConstantOperandVal(2)) continue; } // Here we could have an FP stack truncation or an FPStack <-> SSE convert. // FPStack has extload and truncstore. SSE can fold direct loads into other // operations. Based on this, decide what we want to do. MVT MemVT = (N->getOpcode() == ISD::STRICT_FP_ROUND) ? DstVT : SrcVT; SDValue MemTmp = CurDAG->CreateStackTemporary(MemVT); int SPFI = cast<FrameIndexSDNode>(MemTmp)->getIndex(); MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(CurDAG->getMachineFunction(), SPFI); SDLoc dl(N); // FIXME: optimize the case where the src/dest is a load or store? //Since the operation is StrictFP, use the preexisting chain. SDValue Store, Result; if (!SrcIsSSE) { SDVTList VTs = CurDAG->getVTList(MVT::Other); SDValue Ops[] = {N->getOperand(0), N->getOperand(1), MemTmp}; Store = CurDAG->getMemIntrinsicNode(X86ISD::FST, dl, VTs, Ops, MemVT, MPI, /*Align*/ 0, MachineMemOperand::MOStore); if (N->getFlags().hasNoFPExcept()) { SDNodeFlags Flags = Store->getFlags(); Flags.setNoFPExcept(true); Store->setFlags(Flags); } } else { assert(SrcVT == MemVT && "Unexpected VT!"); Store = CurDAG->getStore(N->getOperand(0), dl, N->getOperand(1), MemTmp, MPI); } if (!DstIsSSE) { SDVTList VTs = CurDAG->getVTList(DstVT, MVT::Other); SDValue Ops[] = {Store, MemTmp}; Result = CurDAG->getMemIntrinsicNode(X86ISD::FLD, dl, VTs, Ops, MemVT, MPI, /*Align*/ 0, MachineMemOperand::MOLoad); if (N->getFlags().hasNoFPExcept()) { SDNodeFlags Flags = Result->getFlags(); Flags.setNoFPExcept(true); Result->setFlags(Flags); } } else { assert(DstVT == MemVT && "Unexpected VT!"); Result = CurDAG->getLoad(DstVT, dl, Store, MemTmp, MPI); } // We're about to replace all uses of the FP_ROUND/FP_EXTEND with the // extload we created. This will cause general havok on the dag because // anything below the conversion could be folded into other existing nodes. // To avoid invalidating 'I', back it up to the convert node. --I; CurDAG->ReplaceAllUsesWith(N, Result.getNode()); break; } } // Now that we did that, the node is dead. Increment the iterator to the // next node to process, then delete N. ++I; CurDAG->DeleteNode(N); } // The load+call transform above can leave some dead nodes in the graph. Make // sure we remove them. Its possible some of the other transforms do to so // just remove dead nodes unconditionally. CurDAG->RemoveDeadNodes(); } // Look for a redundant movzx/movsx that can occur after an 8-bit divrem. bool X86DAGToDAGISel::tryOptimizeRem8Extend(SDNode *N) { unsigned Opc = N->getMachineOpcode(); if (Opc != X86::MOVZX32rr8 && Opc != X86::MOVSX32rr8 && Opc != X86::MOVSX64rr8) return false; SDValue N0 = N->getOperand(0); // We need to be extracting the lower bit of an extend. if (!N0.isMachineOpcode() || N0.getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG || N0.getConstantOperandVal(1) != X86::sub_8bit) return false; // We're looking for either a movsx or movzx to match the original opcode. unsigned ExpectedOpc = Opc == X86::MOVZX32rr8 ? X86::MOVZX32rr8_NOREX : X86::MOVSX32rr8_NOREX; SDValue N00 = N0.getOperand(0); if (!N00.isMachineOpcode() || N00.getMachineOpcode() != ExpectedOpc) return false; if (Opc == X86::MOVSX64rr8) { // If we had a sign extend from 8 to 64 bits. We still need to go from 32 // to 64. MachineSDNode *Extend = CurDAG->getMachineNode(X86::MOVSX64rr32, SDLoc(N), MVT::i64, N00); ReplaceUses(N, Extend); } else { // Ok we can drop this extend and just use the original extend. ReplaceUses(N, N00.getNode()); } return true; } void X86DAGToDAGISel::PostprocessISelDAG() { // Skip peepholes at -O0. if (TM.getOptLevel() == CodeGenOpt::None) return; SelectionDAG::allnodes_iterator Position = CurDAG->allnodes_end(); bool MadeChange = false; while (Position != CurDAG->allnodes_begin()) { SDNode *N = &*--Position; // Skip dead nodes and any non-machine opcodes. if (N->use_empty() || !N->isMachineOpcode()) continue; if (tryOptimizeRem8Extend(N)) { MadeChange = true; continue; } // Look for a TESTrr+ANDrr pattern where both operands of the test are // the same. Rewrite to remove the AND. unsigned Opc = N->getMachineOpcode(); if ((Opc == X86::TEST8rr || Opc == X86::TEST16rr || Opc == X86::TEST32rr || Opc == X86::TEST64rr) && N->getOperand(0) == N->getOperand(1) && N->isOnlyUserOf(N->getOperand(0).getNode()) && N->getOperand(0).isMachineOpcode()) { SDValue And = N->getOperand(0); unsigned N0Opc = And.getMachineOpcode(); if (N0Opc == X86::AND8rr || N0Opc == X86::AND16rr || N0Opc == X86::AND32rr || N0Opc == X86::AND64rr) { MachineSDNode *Test = CurDAG->getMachineNode(Opc, SDLoc(N), MVT::i32, And.getOperand(0), And.getOperand(1)); ReplaceUses(N, Test); MadeChange = true; continue; } if (N0Opc == X86::AND8rm || N0Opc == X86::AND16rm || N0Opc == X86::AND32rm || N0Opc == X86::AND64rm) { unsigned NewOpc; switch (N0Opc) { case X86::AND8rm: NewOpc = X86::TEST8mr; break; case X86::AND16rm: NewOpc = X86::TEST16mr; break; case X86::AND32rm: NewOpc = X86::TEST32mr; break; case X86::AND64rm: NewOpc = X86::TEST64mr; break; } // Need to swap the memory and register operand. SDValue Ops[] = { And.getOperand(1), And.getOperand(2), And.getOperand(3), And.getOperand(4), And.getOperand(5), And.getOperand(0), And.getOperand(6) /* Chain */ }; MachineSDNode *Test = CurDAG->getMachineNode(NewOpc, SDLoc(N), MVT::i32, MVT::Other, Ops); ReplaceUses(N, Test); MadeChange = true; continue; } } // Look for a KAND+KORTEST and turn it into KTEST if only the zero flag is // used. We're doing this late so we can prefer to fold the AND into masked // comparisons. Doing that can be better for the live range of the mask // register. if ((Opc == X86::KORTESTBrr || Opc == X86::KORTESTWrr || Opc == X86::KORTESTDrr || Opc == X86::KORTESTQrr) && N->getOperand(0) == N->getOperand(1) && N->isOnlyUserOf(N->getOperand(0).getNode()) && N->getOperand(0).isMachineOpcode() && onlyUsesZeroFlag(SDValue(N, 0))) { SDValue And = N->getOperand(0); unsigned N0Opc = And.getMachineOpcode(); // KANDW is legal with AVX512F, but KTESTW requires AVX512DQ. The other // KAND instructions and KTEST use the same ISA feature. if (N0Opc == X86::KANDBrr || (N0Opc == X86::KANDWrr && Subtarget->hasDQI()) || N0Opc == X86::KANDDrr || N0Opc == X86::KANDQrr) { unsigned NewOpc; switch (Opc) { default: llvm_unreachable("Unexpected opcode!"); case X86::KORTESTBrr: NewOpc = X86::KTESTBrr; break; case X86::KORTESTWrr: NewOpc = X86::KTESTWrr; break; case X86::KORTESTDrr: NewOpc = X86::KTESTDrr; break; case X86::KORTESTQrr: NewOpc = X86::KTESTQrr; break; } MachineSDNode *KTest = CurDAG->getMachineNode(NewOpc, SDLoc(N), MVT::i32, And.getOperand(0), And.getOperand(1)); ReplaceUses(N, KTest); MadeChange = true; continue; } } // Attempt to remove vectors moves that were inserted to zero upper bits. if (Opc != TargetOpcode::SUBREG_TO_REG) continue; unsigned SubRegIdx = N->getConstantOperandVal(2); if (SubRegIdx != X86::sub_xmm && SubRegIdx != X86::sub_ymm) continue; SDValue Move = N->getOperand(1); if (!Move.isMachineOpcode()) continue; // Make sure its one of the move opcodes we recognize. switch (Move.getMachineOpcode()) { default: continue; case X86::VMOVAPDrr: case X86::VMOVUPDrr: case X86::VMOVAPSrr: case X86::VMOVUPSrr: case X86::VMOVDQArr: case X86::VMOVDQUrr: case X86::VMOVAPDYrr: case X86::VMOVUPDYrr: case X86::VMOVAPSYrr: case X86::VMOVUPSYrr: case X86::VMOVDQAYrr: case X86::VMOVDQUYrr: case X86::VMOVAPDZ128rr: case X86::VMOVUPDZ128rr: case X86::VMOVAPSZ128rr: case X86::VMOVUPSZ128rr: case X86::VMOVDQA32Z128rr: case X86::VMOVDQU32Z128rr: case X86::VMOVDQA64Z128rr: case X86::VMOVDQU64Z128rr: case X86::VMOVAPDZ256rr: case X86::VMOVUPDZ256rr: case X86::VMOVAPSZ256rr: case X86::VMOVUPSZ256rr: case X86::VMOVDQA32Z256rr: case X86::VMOVDQU32Z256rr: case X86::VMOVDQA64Z256rr: case X86::VMOVDQU64Z256rr: break; } SDValue In = Move.getOperand(0); if (!In.isMachineOpcode() || In.getMachineOpcode() <= TargetOpcode::GENERIC_OP_END) continue; // Make sure the instruction has a VEX, XOP, or EVEX prefix. This covers // the SHA instructions which use a legacy encoding. uint64_t TSFlags = getInstrInfo()->get(In.getMachineOpcode()).TSFlags; if ((TSFlags & X86II::EncodingMask) != X86II::VEX && (TSFlags & X86II::EncodingMask) != X86II::EVEX && (TSFlags & X86II::EncodingMask) != X86II::XOP) continue; // Producing instruction is another vector instruction. We can drop the // move. CurDAG->UpdateNodeOperands(N, N->getOperand(0), In, N->getOperand(2)); MadeChange = true; } if (MadeChange) CurDAG->RemoveDeadNodes(); } /// Emit any code that needs to be executed only in the main function. void X86DAGToDAGISel::emitSpecialCodeForMain() { if (Subtarget->isTargetCygMing()) { TargetLowering::ArgListTy Args; auto &DL = CurDAG->getDataLayout(); TargetLowering::CallLoweringInfo CLI(*CurDAG); CLI.setChain(CurDAG->getRoot()) .setCallee(CallingConv::C, Type::getVoidTy(*CurDAG->getContext()), CurDAG->getExternalSymbol("__main", TLI->getPointerTy(DL)), std::move(Args)); const TargetLowering &TLI = CurDAG->getTargetLoweringInfo(); std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); CurDAG->setRoot(Result.second); } } void X86DAGToDAGISel::emitFunctionEntryCode() { // If this is main, emit special code for main. const Function &F = MF->getFunction(); if (F.hasExternalLinkage() && F.getName() == "main") emitSpecialCodeForMain(); } static bool isDispSafeForFrameIndex(int64_t Val) { // On 64-bit platforms, we can run into an issue where a frame index // includes a displacement that, when added to the explicit displacement, // will overflow the displacement field. Assuming that the frame index // displacement fits into a 31-bit integer (which is only slightly more // aggressive than the current fundamental assumption that it fits into // a 32-bit integer), a 31-bit disp should always be safe. return isInt<31>(Val); } bool X86DAGToDAGISel::foldOffsetIntoAddress(uint64_t Offset, X86ISelAddressMode &AM) { // We may have already matched a displacement and the caller just added the // symbolic displacement. So we still need to do the checks even if Offset // is zero. int64_t Val = AM.Disp + Offset; // Cannot combine ExternalSymbol displacements with integer offsets. if (Val != 0 && (AM.ES || AM.MCSym)) return true; CodeModel::Model M = TM.getCodeModel(); if (Subtarget->is64Bit()) { if (Val != 0 && !X86::isOffsetSuitableForCodeModel(Val, M, AM.hasSymbolicDisplacement())) return true; // In addition to the checks required for a register base, check that // we do not try to use an unsafe Disp with a frame index. if (AM.BaseType == X86ISelAddressMode::FrameIndexBase && !isDispSafeForFrameIndex(Val)) return true; } AM.Disp = Val; return false; } bool X86DAGToDAGISel::matchLoadInAddress(LoadSDNode *N, X86ISelAddressMode &AM){ SDValue Address = N->getOperand(1); // load gs:0 -> GS segment register. // load fs:0 -> FS segment register. // // This optimization is valid because the GNU TLS model defines that // gs:0 (or fs:0 on X86-64) contains its own address. // For more information see http://people.redhat.com/drepper/tls.pdf if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Address)) if (C->getSExtValue() == 0 && AM.Segment.getNode() == nullptr && !IndirectTlsSegRefs && (Subtarget->isTargetGlibc() || Subtarget->isTargetAndroid() || Subtarget->isTargetFuchsia())) switch (N->getPointerInfo().getAddrSpace()) { case 256: AM.Segment = CurDAG->getRegister(X86::GS, MVT::i16); return false; case 257: AM.Segment = CurDAG->getRegister(X86::FS, MVT::i16); return false; // Address space 258 is not handled here, because it is not used to // address TLS areas. } return true; } /// Try to match X86ISD::Wrapper and X86ISD::WrapperRIP nodes into an addressing /// mode. These wrap things that will resolve down into a symbol reference. /// If no match is possible, this returns true, otherwise it returns false. bool X86DAGToDAGISel::matchWrapper(SDValue N, X86ISelAddressMode &AM) { // If the addressing mode already has a symbol as the displacement, we can // never match another symbol. if (AM.hasSymbolicDisplacement()) return true; bool IsRIPRelTLS = false; bool IsRIPRel = N.getOpcode() == X86ISD::WrapperRIP; if (IsRIPRel) { SDValue Val = N.getOperand(0); if (Val.getOpcode() == ISD::TargetGlobalTLSAddress) IsRIPRelTLS = true; } // We can't use an addressing mode in the 64-bit large code model. // Global TLS addressing is an exception. In the medium code model, // we use can use a mode when RIP wrappers are present. // That signifies access to globals that are known to be "near", // such as the GOT itself. CodeModel::Model M = TM.getCodeModel(); if (Subtarget->is64Bit() && ((M == CodeModel::Large && !IsRIPRelTLS) || (M == CodeModel::Medium && !IsRIPRel))) return true; // Base and index reg must be 0 in order to use %rip as base. if (IsRIPRel && AM.hasBaseOrIndexReg()) return true; // Make a local copy in case we can't do this fold. X86ISelAddressMode Backup = AM; int64_t Offset = 0; SDValue N0 = N.getOperand(0); if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) { AM.GV = G->getGlobal(); AM.SymbolFlags = G->getTargetFlags(); Offset = G->getOffset(); } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) { AM.CP = CP->getConstVal(); AM.Align = CP->getAlignment(); AM.SymbolFlags = CP->getTargetFlags(); Offset = CP->getOffset(); } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(N0)) { AM.ES = S->getSymbol(); AM.SymbolFlags = S->getTargetFlags(); } else if (auto *S = dyn_cast<MCSymbolSDNode>(N0)) { AM.MCSym = S->getMCSymbol(); } else if (JumpTableSDNode *J = dyn_cast<JumpTableSDNode>(N0)) { AM.JT = J->getIndex(); AM.SymbolFlags = J->getTargetFlags(); } else if (BlockAddressSDNode *BA = dyn_cast<BlockAddressSDNode>(N0)) { AM.BlockAddr = BA->getBlockAddress(); AM.SymbolFlags = BA->getTargetFlags(); Offset = BA->getOffset(); } else llvm_unreachable("Unhandled symbol reference node."); if (foldOffsetIntoAddress(Offset, AM)) { AM = Backup; return true; } if (IsRIPRel) AM.setBaseReg(CurDAG->getRegister(X86::RIP, MVT::i64)); // Commit the changes now that we know this fold is safe. return false; } /// Add the specified node to the specified addressing mode, returning true if /// it cannot be done. This just pattern matches for the addressing mode. bool X86DAGToDAGISel::matchAddress(SDValue N, X86ISelAddressMode &AM) { if (matchAddressRecursively(N, AM, 0)) return true; // Post-processing: Convert lea(,%reg,2) to lea(%reg,%reg), which has // a smaller encoding and avoids a scaled-index. if (AM.Scale == 2 && AM.BaseType == X86ISelAddressMode::RegBase && AM.Base_Reg.getNode() == nullptr) { AM.Base_Reg = AM.IndexReg; AM.Scale = 1; } // Post-processing: Convert foo to foo(%rip), even in non-PIC mode, // because it has a smaller encoding. // TODO: Which other code models can use this? switch (TM.getCodeModel()) { default: break; case CodeModel::Small: case CodeModel::Kernel: if (Subtarget->is64Bit() && AM.Scale == 1 && AM.BaseType == X86ISelAddressMode::RegBase && AM.Base_Reg.getNode() == nullptr && AM.IndexReg.getNode() == nullptr && AM.SymbolFlags == X86II::MO_NO_FLAG && AM.hasSymbolicDisplacement()) AM.Base_Reg = CurDAG->getRegister(X86::RIP, MVT::i64); break; } return false; } bool X86DAGToDAGISel::matchAdd(SDValue &N, X86ISelAddressMode &AM, unsigned Depth) { // Add an artificial use to this node so that we can keep track of // it if it gets CSE'd with a different node. HandleSDNode Handle(N); X86ISelAddressMode Backup = AM; if (!matchAddressRecursively(N.getOperand(0), AM, Depth+1) && !matchAddressRecursively(Handle.getValue().getOperand(1), AM, Depth+1)) return false; AM = Backup; // Try again after commutating the operands. if (!matchAddressRecursively(Handle.getValue().getOperand(1), AM, Depth + 1) && !matchAddressRecursively(Handle.getValue().getOperand(0), AM, Depth + 1)) return false; AM = Backup; // If we couldn't fold both operands into the address at the same time, // see if we can just put each operand into a register and fold at least // the add. if (AM.BaseType == X86ISelAddressMode::RegBase && !AM.Base_Reg.getNode() && !AM.IndexReg.getNode()) { N = Handle.getValue(); AM.Base_Reg = N.getOperand(0); AM.IndexReg = N.getOperand(1); AM.Scale = 1; return false; } N = Handle.getValue(); return true; } // Insert a node into the DAG at least before the Pos node's position. This // will reposition the node as needed, and will assign it a node ID that is <= // the Pos node's ID. Note that this does *not* preserve the uniqueness of node // IDs! The selection DAG must no longer depend on their uniqueness when this // is used. static void insertDAGNode(SelectionDAG &DAG, SDValue Pos, SDValue N) { if (N->getNodeId() == -1 || (SelectionDAGISel::getUninvalidatedNodeId(N.getNode()) > SelectionDAGISel::getUninvalidatedNodeId(Pos.getNode()))) { DAG.RepositionNode(Pos->getIterator(), N.getNode()); // Mark Node as invalid for pruning as after this it may be a successor to a // selected node but otherwise be in the same position of Pos. // Conservatively mark it with the same -abs(Id) to assure node id // invariant is preserved. N->setNodeId(Pos->getNodeId()); SelectionDAGISel::InvalidateNodeId(N.getNode()); } } // Transform "(X >> (8-C1)) & (0xff << C1)" to "((X >> 8) & 0xff) << C1" if // safe. This allows us to convert the shift and and into an h-register // extract and a scaled index. Returns false if the simplification is // performed. static bool foldMaskAndShiftToExtract(SelectionDAG &DAG, SDValue N, uint64_t Mask, SDValue Shift, SDValue X, X86ISelAddressMode &AM) { if (Shift.getOpcode() != ISD::SRL || !isa<ConstantSDNode>(Shift.getOperand(1)) || !Shift.hasOneUse()) return true; int ScaleLog = 8 - Shift.getConstantOperandVal(1); if (ScaleLog <= 0 || ScaleLog >= 4 || Mask != (0xffu << ScaleLog)) return true; MVT VT = N.getSimpleValueType(); SDLoc DL(N); SDValue Eight = DAG.getConstant(8, DL, MVT::i8); SDValue NewMask = DAG.getConstant(0xff, DL, VT); SDValue Srl = DAG.getNode(ISD::SRL, DL, VT, X, Eight); SDValue And = DAG.getNode(ISD::AND, DL, VT, Srl, NewMask); SDValue ShlCount = DAG.getConstant(ScaleLog, DL, MVT::i8); SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, And, ShlCount); // Insert the new nodes into the topological ordering. We must do this in // a valid topological ordering as nothing is going to go back and re-sort // these nodes. We continually insert before 'N' in sequence as this is // essentially a pre-flattened and pre-sorted sequence of nodes. There is no // hierarchy left to express. insertDAGNode(DAG, N, Eight); insertDAGNode(DAG, N, Srl); insertDAGNode(DAG, N, NewMask); insertDAGNode(DAG, N, And); insertDAGNode(DAG, N, ShlCount); insertDAGNode(DAG, N, Shl); DAG.ReplaceAllUsesWith(N, Shl); DAG.RemoveDeadNode(N.getNode()); AM.IndexReg = And; AM.Scale = (1 << ScaleLog); return false; } // Transforms "(X << C1) & C2" to "(X & (C2>>C1)) << C1" if safe and if this // allows us to fold the shift into this addressing mode. Returns false if the // transform succeeded. static bool foldMaskedShiftToScaledMask(SelectionDAG &DAG, SDValue N, X86ISelAddressMode &AM) { SDValue Shift = N.getOperand(0); // Use a signed mask so that shifting right will insert sign bits. These // bits will be removed when we shift the result left so it doesn't matter // what we use. This might allow a smaller immediate encoding. int64_t Mask = cast<ConstantSDNode>(N->getOperand(1))->getSExtValue(); // If we have an any_extend feeding the AND, look through it to see if there // is a shift behind it. But only if the AND doesn't use the extended bits. // FIXME: Generalize this to other ANY_EXTEND than i32 to i64? bool FoundAnyExtend = false; if (Shift.getOpcode() == ISD::ANY_EXTEND && Shift.hasOneUse() && Shift.getOperand(0).getSimpleValueType() == MVT::i32 && isUInt<32>(Mask)) { FoundAnyExtend = true; Shift = Shift.getOperand(0); } if (Shift.getOpcode() != ISD::SHL || !isa<ConstantSDNode>(Shift.getOperand(1))) return true; SDValue X = Shift.getOperand(0); // Not likely to be profitable if either the AND or SHIFT node has more // than one use (unless all uses are for address computation). Besides, // isel mechanism requires their node ids to be reused. if (!N.hasOneUse() || !Shift.hasOneUse()) return true; // Verify that the shift amount is something we can fold. unsigned ShiftAmt = Shift.getConstantOperandVal(1); if (ShiftAmt != 1 && ShiftAmt != 2 && ShiftAmt != 3) return true; MVT VT = N.getSimpleValueType(); SDLoc DL(N); if (FoundAnyExtend) { SDValue NewX = DAG.getNode(ISD::ANY_EXTEND, DL, VT, X); insertDAGNode(DAG, N, NewX); X = NewX; } SDValue NewMask = DAG.getConstant(Mask >> ShiftAmt, DL, VT); SDValue NewAnd = DAG.getNode(ISD::AND, DL, VT, X, NewMask); SDValue NewShift = DAG.getNode(ISD::SHL, DL, VT, NewAnd, Shift.getOperand(1)); // Insert the new nodes into the topological ordering. We must do this in // a valid topological ordering as nothing is going to go back and re-sort // these nodes. We continually insert before 'N' in sequence as this is // essentially a pre-flattened and pre-sorted sequence of nodes. There is no // hierarchy left to express. insertDAGNode(DAG, N, NewMask); insertDAGNode(DAG, N, NewAnd); insertDAGNode(DAG, N, NewShift); DAG.ReplaceAllUsesWith(N, NewShift); DAG.RemoveDeadNode(N.getNode()); AM.Scale = 1 << ShiftAmt; AM.IndexReg = NewAnd; return false; } // Implement some heroics to detect shifts of masked values where the mask can // be replaced by extending the shift and undoing that in the addressing mode // scale. Patterns such as (shl (srl x, c1), c2) are canonicalized into (and // (srl x, SHIFT), MASK) by DAGCombines that don't know the shl can be done in // the addressing mode. This results in code such as: // // int f(short *y, int *lookup_table) { // ... // return *y + lookup_table[*y >> 11]; // } // // Turning into: // movzwl (%rdi), %eax // movl %eax, %ecx // shrl $11, %ecx // addl (%rsi,%rcx,4), %eax // // Instead of: // movzwl (%rdi), %eax // movl %eax, %ecx // shrl $9, %ecx // andl $124, %rcx // addl (%rsi,%rcx), %eax // // Note that this function assumes the mask is provided as a mask *after* the // value is shifted. The input chain may or may not match that, but computing // such a mask is trivial. static bool foldMaskAndShiftToScale(SelectionDAG &DAG, SDValue N, uint64_t Mask, SDValue Shift, SDValue X, X86ISelAddressMode &AM) { if (Shift.getOpcode() != ISD::SRL || !Shift.hasOneUse() || !isa<ConstantSDNode>(Shift.getOperand(1))) return true; unsigned ShiftAmt = Shift.getConstantOperandVal(1); unsigned MaskLZ = countLeadingZeros(Mask); unsigned MaskTZ = countTrailingZeros(Mask); // The amount of shift we're trying to fit into the addressing mode is taken // from the trailing zeros of the mask. unsigned AMShiftAmt = MaskTZ; // There is nothing we can do here unless the mask is removing some bits. // Also, the addressing mode can only represent shifts of 1, 2, or 3 bits. if (AMShiftAmt == 0 || AMShiftAmt > 3) return true; // We also need to ensure that mask is a continuous run of bits. if (countTrailingOnes(Mask >> MaskTZ) + MaskTZ + MaskLZ != 64) return true; // Scale the leading zero count down based on the actual size of the value. // Also scale it down based on the size of the shift. unsigned ScaleDown = (64 - X.getSimpleValueType().getSizeInBits()) + ShiftAmt; if (MaskLZ < ScaleDown) return true; MaskLZ -= ScaleDown; // The final check is to ensure that any masked out high bits of X are // already known to be zero. Otherwise, the mask has a semantic impact // other than masking out a couple of low bits. Unfortunately, because of // the mask, zero extensions will be removed from operands in some cases. // This code works extra hard to look through extensions because we can // replace them with zero extensions cheaply if necessary. bool ReplacingAnyExtend = false; if (X.getOpcode() == ISD::ANY_EXTEND) { unsigned ExtendBits = X.getSimpleValueType().getSizeInBits() - X.getOperand(0).getSimpleValueType().getSizeInBits(); // Assume that we'll replace the any-extend with a zero-extend, and // narrow the search to the extended value. X = X.getOperand(0); MaskLZ = ExtendBits > MaskLZ ? 0 : MaskLZ - ExtendBits; ReplacingAnyExtend = true; } APInt MaskedHighBits = APInt::getHighBitsSet(X.getSimpleValueType().getSizeInBits(), MaskLZ); KnownBits Known = DAG.computeKnownBits(X); if (MaskedHighBits != Known.Zero) return true; // We've identified a pattern that can be transformed into a single shift // and an addressing mode. Make it so. MVT VT = N.getSimpleValueType(); if (ReplacingAnyExtend) { assert(X.getValueType() != VT); // We looked through an ANY_EXTEND node, insert a ZERO_EXTEND. SDValue NewX = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(X), VT, X); insertDAGNode(DAG, N, NewX); X = NewX; } SDLoc DL(N); SDValue NewSRLAmt = DAG.getConstant(ShiftAmt + AMShiftAmt, DL, MVT::i8); SDValue NewSRL = DAG.getNode(ISD::SRL, DL, VT, X, NewSRLAmt); SDValue NewSHLAmt = DAG.getConstant(AMShiftAmt, DL, MVT::i8); SDValue NewSHL = DAG.getNode(ISD::SHL, DL, VT, NewSRL, NewSHLAmt); // Insert the new nodes into the topological ordering. We must do this in // a valid topological ordering as nothing is going to go back and re-sort // these nodes. We continually insert before 'N' in sequence as this is // essentially a pre-flattened and pre-sorted sequence of nodes. There is no // hierarchy left to express. insertDAGNode(DAG, N, NewSRLAmt); insertDAGNode(DAG, N, NewSRL); insertDAGNode(DAG, N, NewSHLAmt); insertDAGNode(DAG, N, NewSHL); DAG.ReplaceAllUsesWith(N, NewSHL); DAG.RemoveDeadNode(N.getNode()); AM.Scale = 1 << AMShiftAmt; AM.IndexReg = NewSRL; return false; } // Transform "(X >> SHIFT) & (MASK << C1)" to // "((X >> (SHIFT + C1)) & (MASK)) << C1". Everything before the SHL will be // matched to a BEXTR later. Returns false if the simplification is performed. static bool foldMaskedShiftToBEXTR(SelectionDAG &DAG, SDValue N, uint64_t Mask, SDValue Shift, SDValue X, X86ISelAddressMode &AM, const X86Subtarget &Subtarget) { if (Shift.getOpcode() != ISD::SRL || !isa<ConstantSDNode>(Shift.getOperand(1)) || !Shift.hasOneUse() || !N.hasOneUse()) return true; // Only do this if BEXTR will be matched by matchBEXTRFromAndImm. if (!Subtarget.hasTBM() && !(Subtarget.hasBMI() && Subtarget.hasFastBEXTR())) return true; // We need to ensure that mask is a continuous run of bits. if (!isShiftedMask_64(Mask)) return true; unsigned ShiftAmt = Shift.getConstantOperandVal(1); // The amount of shift we're trying to fit into the addressing mode is taken // from the trailing zeros of the mask. unsigned AMShiftAmt = countTrailingZeros(Mask); // There is nothing we can do here unless the mask is removing some bits. // Also, the addressing mode can only represent shifts of 1, 2, or 3 bits. if (AMShiftAmt == 0 || AMShiftAmt > 3) return true; MVT VT = N.getSimpleValueType(); SDLoc DL(N); SDValue NewSRLAmt = DAG.getConstant(ShiftAmt + AMShiftAmt, DL, MVT::i8); SDValue NewSRL = DAG.getNode(ISD::SRL, DL, VT, X, NewSRLAmt); SDValue NewMask = DAG.getConstant(Mask >> AMShiftAmt, DL, VT); SDValue NewAnd = DAG.getNode(ISD::AND, DL, VT, NewSRL, NewMask); SDValue NewSHLAmt = DAG.getConstant(AMShiftAmt, DL, MVT::i8); SDValue NewSHL = DAG.getNode(ISD::SHL, DL, VT, NewAnd, NewSHLAmt); // Insert the new nodes into the topological ordering. We must do this in // a valid topological ordering as nothing is going to go back and re-sort // these nodes. We continually insert before 'N' in sequence as this is // essentially a pre-flattened and pre-sorted sequence of nodes. There is no // hierarchy left to express. insertDAGNode(DAG, N, NewSRLAmt); insertDAGNode(DAG, N, NewSRL); insertDAGNode(DAG, N, NewMask); insertDAGNode(DAG, N, NewAnd); insertDAGNode(DAG, N, NewSHLAmt); insertDAGNode(DAG, N, NewSHL); DAG.ReplaceAllUsesWith(N, NewSHL); DAG.RemoveDeadNode(N.getNode()); AM.Scale = 1 << AMShiftAmt; AM.IndexReg = NewAnd; return false; } bool X86DAGToDAGISel::matchAddressRecursively(SDValue N, X86ISelAddressMode &AM, unsigned Depth) { SDLoc dl(N); LLVM_DEBUG({ dbgs() << "MatchAddress: "; AM.dump(CurDAG); }); // Limit recursion. if (Depth > 5) return matchAddressBase(N, AM); // If this is already a %rip relative address, we can only merge immediates // into it. Instead of handling this in every case, we handle it here. // RIP relative addressing: %rip + 32-bit displacement! if (AM.isRIPRelative()) { // FIXME: JumpTable and ExternalSymbol address currently don't like // displacements. It isn't very important, but this should be fixed for // consistency. if (!(AM.ES || AM.MCSym) && AM.JT != -1) return true; if (ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(N)) if (!foldOffsetIntoAddress(Cst->getSExtValue(), AM)) return false; return true; } switch (N.getOpcode()) { default: break; case ISD::LOCAL_RECOVER: { if (!AM.hasSymbolicDisplacement() && AM.Disp == 0) if (const auto *ESNode = dyn_cast<MCSymbolSDNode>(N.getOperand(0))) { // Use the symbol and don't prefix it. AM.MCSym = ESNode->getMCSymbol(); return false; } break; } case ISD::Constant: { uint64_t Val = cast<ConstantSDNode>(N)->getSExtValue(); if (!foldOffsetIntoAddress(Val, AM)) return false; break; } case X86ISD::Wrapper: case X86ISD::WrapperRIP: if (!matchWrapper(N, AM)) return false; break; case ISD::LOAD: if (!matchLoadInAddress(cast<LoadSDNode>(N), AM)) return false; break; case ISD::FrameIndex: if (AM.BaseType == X86ISelAddressMode::RegBase && AM.Base_Reg.getNode() == nullptr && (!Subtarget->is64Bit() || isDispSafeForFrameIndex(AM.Disp))) { AM.BaseType = X86ISelAddressMode::FrameIndexBase; AM.Base_FrameIndex = cast<FrameIndexSDNode>(N)->getIndex(); return false; } break; case ISD::SHL: if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1) break; if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) { unsigned Val = CN->getZExtValue(); // Note that we handle x<<1 as (,x,2) rather than (x,x) here so // that the base operand remains free for further matching. If // the base doesn't end up getting used, a post-processing step // in MatchAddress turns (,x,2) into (x,x), which is cheaper. if (Val == 1 || Val == 2 || Val == 3) { AM.Scale = 1 << Val; SDValue ShVal = N.getOperand(0); // Okay, we know that we have a scale by now. However, if the scaled // value is an add of something and a constant, we can fold the // constant into the disp field here. if (CurDAG->isBaseWithConstantOffset(ShVal)) { AM.IndexReg = ShVal.getOperand(0); ConstantSDNode *AddVal = cast<ConstantSDNode>(ShVal.getOperand(1)); uint64_t Disp = (uint64_t)AddVal->getSExtValue() << Val; if (!foldOffsetIntoAddress(Disp, AM)) return false; } AM.IndexReg = ShVal; return false; } } break; case ISD::SRL: { // Scale must not be used already. if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1) break; // We only handle up to 64-bit values here as those are what matter for // addressing mode optimizations. assert(N.getSimpleValueType().getSizeInBits() <= 64 && "Unexpected value size!"); SDValue And = N.getOperand(0); if (And.getOpcode() != ISD::AND) break; SDValue X = And.getOperand(0); // The mask used for the transform is expected to be post-shift, but we // found the shift first so just apply the shift to the mask before passing // it down. if (!isa<ConstantSDNode>(N.getOperand(1)) || !isa<ConstantSDNode>(And.getOperand(1))) break; uint64_t Mask = And.getConstantOperandVal(1) >> N.getConstantOperandVal(1); // Try to fold the mask and shift into the scale, and return false if we // succeed. if (!foldMaskAndShiftToScale(*CurDAG, N, Mask, N, X, AM)) return false; break; } case ISD::SMUL_LOHI: case ISD::UMUL_LOHI: // A mul_lohi where we need the low part can be folded as a plain multiply. if (N.getResNo() != 0) break; LLVM_FALLTHROUGH; case ISD::MUL: case X86ISD::MUL_IMM: // X*[3,5,9] -> X+X*[2,4,8] if (AM.BaseType == X86ISelAddressMode::RegBase && AM.Base_Reg.getNode() == nullptr && AM.IndexReg.getNode() == nullptr) { if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) if (CN->getZExtValue() == 3 || CN->getZExtValue() == 5 || CN->getZExtValue() == 9) { AM.Scale = unsigned(CN->getZExtValue())-1; SDValue MulVal = N.getOperand(0); SDValue Reg; // Okay, we know that we have a scale by now. However, if the scaled // value is an add of something and a constant, we can fold the // constant into the disp field here. if (MulVal.getNode()->getOpcode() == ISD::ADD && MulVal.hasOneUse() && isa<ConstantSDNode>(MulVal.getOperand(1))) { Reg = MulVal.getOperand(0); ConstantSDNode *AddVal = cast<ConstantSDNode>(MulVal.getOperand(1)); uint64_t Disp = AddVal->getSExtValue() * CN->getZExtValue(); if (foldOffsetIntoAddress(Disp, AM)) Reg = N.getOperand(0); } else { Reg = N.getOperand(0); } AM.IndexReg = AM.Base_Reg = Reg; return false; } } break; case ISD::SUB: { // Given A-B, if A can be completely folded into the address and // the index field with the index field unused, use -B as the index. // This is a win if a has multiple parts that can be folded into // the address. Also, this saves a mov if the base register has // other uses, since it avoids a two-address sub instruction, however // it costs an additional mov if the index register has other uses. // Add an artificial use to this node so that we can keep track of // it if it gets CSE'd with a different node. HandleSDNode Handle(N); // Test if the LHS of the sub can be folded. X86ISelAddressMode Backup = AM; if (matchAddressRecursively(N.getOperand(0), AM, Depth+1)) { N = Handle.getValue(); AM = Backup; break; } N = Handle.getValue(); // Test if the index field is free for use. if (AM.IndexReg.getNode() || AM.isRIPRelative()) { AM = Backup; break; } int Cost = 0; SDValue RHS = N.getOperand(1); // If the RHS involves a register with multiple uses, this // transformation incurs an extra mov, due to the neg instruction // clobbering its operand. if (!RHS.getNode()->hasOneUse() || RHS.getNode()->getOpcode() == ISD::CopyFromReg || RHS.getNode()->getOpcode() == ISD::TRUNCATE || RHS.getNode()->getOpcode() == ISD::ANY_EXTEND || (RHS.getNode()->getOpcode() == ISD::ZERO_EXTEND && RHS.getOperand(0).getValueType() == MVT::i32)) ++Cost; // If the base is a register with multiple uses, this // transformation may save a mov. if ((AM.BaseType == X86ISelAddressMode::RegBase && AM.Base_Reg.getNode() && !AM.Base_Reg.getNode()->hasOneUse()) || AM.BaseType == X86ISelAddressMode::FrameIndexBase) --Cost; // If the folded LHS was interesting, this transformation saves // address arithmetic. if ((AM.hasSymbolicDisplacement() && !Backup.hasSymbolicDisplacement()) + ((AM.Disp != 0) && (Backup.Disp == 0)) + (AM.Segment.getNode() && !Backup.Segment.getNode()) >= 2) --Cost; // If it doesn't look like it may be an overall win, don't do it. if (Cost >= 0) { AM = Backup; break; } // Ok, the transformation is legal and appears profitable. Go for it. // Negation will be emitted later to avoid creating dangling nodes if this // was an unprofitable LEA. AM.IndexReg = RHS; AM.NegateIndex = true; AM.Scale = 1; return false; } case ISD::ADD: if (!matchAdd(N, AM, Depth)) return false; break; case ISD::OR: // We want to look through a transform in InstCombine and DAGCombiner that // turns 'add' into 'or', so we can treat this 'or' exactly like an 'add'. // Example: (or (and x, 1), (shl y, 3)) --> (add (and x, 1), (shl y, 3)) // An 'lea' can then be used to match the shift (multiply) and add: // and $1, %esi // lea (%rsi, %rdi, 8), %rax if (CurDAG->haveNoCommonBitsSet(N.getOperand(0), N.getOperand(1)) && !matchAdd(N, AM, Depth)) return false; break; case ISD::AND: { // Perform some heroic transforms on an and of a constant-count shift // with a constant to enable use of the scaled offset field. // Scale must not be used already. if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1) break; // We only handle up to 64-bit values here as those are what matter for // addressing mode optimizations. assert(N.getSimpleValueType().getSizeInBits() <= 64 && "Unexpected value size!"); if (!isa<ConstantSDNode>(N.getOperand(1))) break; if (N.getOperand(0).getOpcode() == ISD::SRL) { SDValue Shift = N.getOperand(0); SDValue X = Shift.getOperand(0); uint64_t Mask = N.getConstantOperandVal(1); // Try to fold the mask and shift into an extract and scale. if (!foldMaskAndShiftToExtract(*CurDAG, N, Mask, Shift, X, AM)) return false; // Try to fold the mask and shift directly into the scale. if (!foldMaskAndShiftToScale(*CurDAG, N, Mask, Shift, X, AM)) return false; // Try to fold the mask and shift into BEXTR and scale. if (!foldMaskedShiftToBEXTR(*CurDAG, N, Mask, Shift, X, AM, *Subtarget)) return false; } // Try to swap the mask and shift to place shifts which can be done as // a scale on the outside of the mask. if (!foldMaskedShiftToScaledMask(*CurDAG, N, AM)) return false; break; } case ISD::ZERO_EXTEND: { // Try to widen a zexted shift left to the same size as its use, so we can // match the shift as a scale factor. if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1) break; if (N.getOperand(0).getOpcode() != ISD::SHL || !N.getOperand(0).hasOneUse()) break; // Give up if the shift is not a valid scale factor [1,2,3]. SDValue Shl = N.getOperand(0); auto *ShAmtC = dyn_cast<ConstantSDNode>(Shl.getOperand(1)); if (!ShAmtC || ShAmtC->getZExtValue() > 3) break; // The narrow shift must only shift out zero bits (it must be 'nuw'). // That makes it safe to widen to the destination type. APInt HighZeros = APInt::getHighBitsSet(Shl.getValueSizeInBits(), ShAmtC->getZExtValue()); if (!CurDAG->MaskedValueIsZero(Shl.getOperand(0), HighZeros)) break; // zext (shl nuw i8 %x, C) to i32 --> shl (zext i8 %x to i32), (zext C) MVT VT = N.getSimpleValueType(); SDLoc DL(N); SDValue Zext = CurDAG->getNode(ISD::ZERO_EXTEND, DL, VT, Shl.getOperand(0)); SDValue NewShl = CurDAG->getNode(ISD::SHL, DL, VT, Zext, Shl.getOperand(1)); // Convert the shift to scale factor. AM.Scale = 1 << ShAmtC->getZExtValue(); AM.IndexReg = Zext; insertDAGNode(*CurDAG, N, Zext); insertDAGNode(*CurDAG, N, NewShl); CurDAG->ReplaceAllUsesWith(N, NewShl); CurDAG->RemoveDeadNode(N.getNode()); return false; } } return matchAddressBase(N, AM); } /// Helper for MatchAddress. Add the specified node to the /// specified addressing mode without any further recursion. bool X86DAGToDAGISel::matchAddressBase(SDValue N, X86ISelAddressMode &AM) { // Is the base register already occupied? if (AM.BaseType != X86ISelAddressMode::RegBase || AM.Base_Reg.getNode()) { // If so, check to see if the scale index register is set. if (!AM.IndexReg.getNode()) { AM.IndexReg = N; AM.Scale = 1; return false; } // Otherwise, we cannot select it. return true; } // Default, generate it as a register. AM.BaseType = X86ISelAddressMode::RegBase; AM.Base_Reg = N; return false; } /// Helper for selectVectorAddr. Handles things that can be folded into a /// gather scatter address. The index register and scale should have already /// been handled. bool X86DAGToDAGISel::matchVectorAddress(SDValue N, X86ISelAddressMode &AM) { // TODO: Support other operations. switch (N.getOpcode()) { case ISD::Constant: { uint64_t Val = cast<ConstantSDNode>(N)->getSExtValue(); if (!foldOffsetIntoAddress(Val, AM)) return false; break; } case X86ISD::Wrapper: if (!matchWrapper(N, AM)) return false; break; } return matchAddressBase(N, AM); } bool X86DAGToDAGISel::selectVectorAddr(MemSDNode *Parent, SDValue BasePtr, SDValue IndexOp, SDValue ScaleOp, SDValue &Base, SDValue &Scale, SDValue &Index, SDValue &Disp, SDValue &Segment) { X86ISelAddressMode AM; AM.IndexReg = IndexOp; AM.Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue(); unsigned AddrSpace = Parent->getPointerInfo().getAddrSpace(); if (AddrSpace == X86AS::GS) AM.Segment = CurDAG->getRegister(X86::GS, MVT::i16); if (AddrSpace == X86AS::FS) AM.Segment = CurDAG->getRegister(X86::FS, MVT::i16); if (AddrSpace == X86AS::SS) AM.Segment = CurDAG->getRegister(X86::SS, MVT::i16); SDLoc DL(BasePtr); MVT VT = BasePtr.getSimpleValueType(); // Try to match into the base and displacement fields. if (matchVectorAddress(BasePtr, AM)) return false; getAddressOperands(AM, DL, VT, Base, Scale, Index, Disp, Segment); return true; } /// Returns true if it is able to pattern match an addressing mode. /// It returns the operands which make up the maximal addressing mode it can /// match by reference. /// /// Parent is the parent node of the addr operand that is being matched. It /// is always a load, store, atomic node, or null. It is only null when /// checking memory operands for inline asm nodes. bool X86DAGToDAGISel::selectAddr(SDNode *Parent, SDValue N, SDValue &Base, SDValue &Scale, SDValue &Index, SDValue &Disp, SDValue &Segment) { X86ISelAddressMode AM; if (Parent && // This list of opcodes are all the nodes that have an "addr:$ptr" operand // that are not a MemSDNode, and thus don't have proper addrspace info. Parent->getOpcode() != ISD::INTRINSIC_W_CHAIN && // unaligned loads, fixme Parent->getOpcode() != ISD::INTRINSIC_VOID && // nontemporal stores Parent->getOpcode() != X86ISD::TLSCALL && // Fixme Parent->getOpcode() != X86ISD::ENQCMD && // Fixme Parent->getOpcode() != X86ISD::ENQCMDS && // Fixme Parent->getOpcode() != X86ISD::EH_SJLJ_SETJMP && // setjmp Parent->getOpcode() != X86ISD::EH_SJLJ_LONGJMP) { // longjmp unsigned AddrSpace = cast<MemSDNode>(Parent)->getPointerInfo().getAddrSpace(); // AddrSpace 256 -> GS, 257 -> FS, 258 -> SS. if (AddrSpace == 256) AM.Segment = CurDAG->getRegister(X86::GS, MVT::i16); if (AddrSpace == 257) AM.Segment = CurDAG->getRegister(X86::FS, MVT::i16); if (AddrSpace == 258) AM.Segment = CurDAG->getRegister(X86::SS, MVT::i16); } // Save the DL and VT before calling matchAddress, it can invalidate N. SDLoc DL(N); MVT VT = N.getSimpleValueType(); if (matchAddress(N, AM)) return false; getAddressOperands(AM, DL, VT, Base, Scale, Index, Disp, Segment); return true; } // We can only fold a load if all nodes between it and the root node have a // single use. If there are additional uses, we could end up duplicating the // load. static bool hasSingleUsesFromRoot(SDNode *Root, SDNode *User) { while (User != Root) { if (!User->hasOneUse()) return false; User = *User->use_begin(); } return true; } /// Match a scalar SSE load. In particular, we want to match a load whose top /// elements are either undef or zeros. The load flavor is derived from the /// type of N, which is either v4f32 or v2f64. /// /// We also return: /// PatternChainNode: this is the matched node that has a chain input and /// output. bool X86DAGToDAGISel::selectScalarSSELoad(SDNode *Root, SDNode *Parent, SDValue N, SDValue &Base, SDValue &Scale, SDValue &Index, SDValue &Disp, SDValue &Segment, SDValue &PatternNodeWithChain) { if (!hasSingleUsesFromRoot(Root, Parent)) return false; // We can allow a full vector load here since narrowing a load is ok unless // it's volatile or atomic. if (ISD::isNON_EXTLoad(N.getNode())) { LoadSDNode *LD = cast<LoadSDNode>(N); if (LD->isSimple() && IsProfitableToFold(N, LD, Root) && IsLegalToFold(N, Parent, Root, OptLevel)) { PatternNodeWithChain = N; return selectAddr(LD, LD->getBasePtr(), Base, Scale, Index, Disp, Segment); } } // We can also match the special zero extended load opcode. if (N.getOpcode() == X86ISD::VZEXT_LOAD) { PatternNodeWithChain = N; if (IsProfitableToFold(PatternNodeWithChain, N.getNode(), Root) && IsLegalToFold(PatternNodeWithChain, Parent, Root, OptLevel)) { auto *MI = cast<MemIntrinsicSDNode>(PatternNodeWithChain); return selectAddr(MI, MI->getBasePtr(), Base, Scale, Index, Disp, Segment); } } // Need to make sure that the SCALAR_TO_VECTOR and load are both only used // once. Otherwise the load might get duplicated and the chain output of the // duplicate load will not be observed by all dependencies. if (N.getOpcode() == ISD::SCALAR_TO_VECTOR && N.getNode()->hasOneUse()) { PatternNodeWithChain = N.getOperand(0); if (ISD::isNON_EXTLoad(PatternNodeWithChain.getNode()) && IsProfitableToFold(PatternNodeWithChain, N.getNode(), Root) && IsLegalToFold(PatternNodeWithChain, N.getNode(), Root, OptLevel)) { LoadSDNode *LD = cast<LoadSDNode>(PatternNodeWithChain); return selectAddr(LD, LD->getBasePtr(), Base, Scale, Index, Disp, Segment); } } return false; } bool X86DAGToDAGISel::selectMOV64Imm32(SDValue N, SDValue &Imm) { if (const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) { uint64_t ImmVal = CN->getZExtValue(); if (!isUInt<32>(ImmVal)) return false; Imm = CurDAG->getTargetConstant(ImmVal, SDLoc(N), MVT::i64); return true; } // In static codegen with small code model, we can get the address of a label // into a register with 'movl' if (N->getOpcode() != X86ISD::Wrapper) return false; N = N.getOperand(0); // At least GNU as does not accept 'movl' for TPOFF relocations. // FIXME: We could use 'movl' when we know we are targeting MC. if (N->getOpcode() == ISD::TargetGlobalTLSAddress) return false; Imm = N; if (N->getOpcode() != ISD::TargetGlobalAddress) return TM.getCodeModel() == CodeModel::Small; Optional<ConstantRange> CR = cast<GlobalAddressSDNode>(N)->getGlobal()->getAbsoluteSymbolRange(); if (!CR) return TM.getCodeModel() == CodeModel::Small; return CR->getUnsignedMax().ult(1ull << 32); } bool X86DAGToDAGISel::selectLEA64_32Addr(SDValue N, SDValue &Base, SDValue &Scale, SDValue &Index, SDValue &Disp, SDValue &Segment) { // Save the debug loc before calling selectLEAAddr, in case it invalidates N. SDLoc DL(N); if (!selectLEAAddr(N, Base, Scale, Index, Disp, Segment)) return false; RegisterSDNode *RN = dyn_cast<RegisterSDNode>(Base); if (RN && RN->getReg() == 0) Base = CurDAG->getRegister(0, MVT::i64); else if (Base.getValueType() == MVT::i32 && !isa<FrameIndexSDNode>(Base)) { // Base could already be %rip, particularly in the x32 ABI. SDValue ImplDef = SDValue(CurDAG->getMachineNode(X86::IMPLICIT_DEF, DL, MVT::i64), 0); Base = CurDAG->getTargetInsertSubreg(X86::sub_32bit, DL, MVT::i64, ImplDef, Base); } RN = dyn_cast<RegisterSDNode>(Index); if (RN && RN->getReg() == 0) Index = CurDAG->getRegister(0, MVT::i64); else { assert(Index.getValueType() == MVT::i32 && "Expect to be extending 32-bit registers for use in LEA"); SDValue ImplDef = SDValue(CurDAG->getMachineNode(X86::IMPLICIT_DEF, DL, MVT::i64), 0); Index = CurDAG->getTargetInsertSubreg(X86::sub_32bit, DL, MVT::i64, ImplDef, Index); } return true; } /// Calls SelectAddr and determines if the maximal addressing /// mode it matches can be cost effectively emitted as an LEA instruction. bool X86DAGToDAGISel::selectLEAAddr(SDValue N, SDValue &Base, SDValue &Scale, SDValue &Index, SDValue &Disp, SDValue &Segment) { X86ISelAddressMode AM; // Save the DL and VT before calling matchAddress, it can invalidate N. SDLoc DL(N); MVT VT = N.getSimpleValueType(); // Set AM.Segment to prevent MatchAddress from using one. LEA doesn't support // segments. SDValue Copy = AM.Segment; SDValue T = CurDAG->getRegister(0, MVT::i32); AM.Segment = T; if (matchAddress(N, AM)) return false; assert (T == AM.Segment); AM.Segment = Copy; unsigned Complexity = 0; if (AM.BaseType == X86ISelAddressMode::RegBase && AM.Base_Reg.getNode()) Complexity = 1; else if (AM.BaseType == X86ISelAddressMode::FrameIndexBase) Complexity = 4; if (AM.IndexReg.getNode()) Complexity++; // Don't match just leal(,%reg,2). It's cheaper to do addl %reg, %reg, or with // a simple shift. if (AM.Scale > 1) Complexity++; // FIXME: We are artificially lowering the criteria to turn ADD %reg, $GA // to a LEA. This is determined with some experimentation but is by no means // optimal (especially for code size consideration). LEA is nice because of // its three-address nature. Tweak the cost function again when we can run // convertToThreeAddress() at register allocation time. if (AM.hasSymbolicDisplacement()) { // For X86-64, always use LEA to materialize RIP-relative addresses. if (Subtarget->is64Bit()) Complexity = 4; else Complexity += 2; } // Heuristic: try harder to form an LEA from ADD if the operands set flags. // Unlike ADD, LEA does not affect flags, so we will be less likely to require // duplicating flag-producing instructions later in the pipeline. if (N.getOpcode() == ISD::ADD) { auto isMathWithFlags = [](SDValue V) { switch (V.getOpcode()) { case X86ISD::ADD: case X86ISD::SUB: case X86ISD::ADC: case X86ISD::SBB: /* TODO: These opcodes can be added safely, but we may want to justify their inclusion for different reasons (better for reg-alloc). case X86ISD::SMUL: case X86ISD::UMUL: case X86ISD::OR: case X86ISD::XOR: case X86ISD::AND: */ // Value 1 is the flag output of the node - verify it's not dead. return !SDValue(V.getNode(), 1).use_empty(); default: return false; } }; // TODO: This could be an 'or' rather than 'and' to make the transform more // likely to happen. We might want to factor in whether there's a // load folding opportunity for the math op that disappears with LEA. if (isMathWithFlags(N.getOperand(0)) && isMathWithFlags(N.getOperand(1))) Complexity++; } if (AM.Disp) Complexity++; // If it isn't worth using an LEA, reject it. if (Complexity <= 2) return false; getAddressOperands(AM, DL, VT, Base, Scale, Index, Disp, Segment); return true; } /// This is only run on TargetGlobalTLSAddress nodes. bool X86DAGToDAGISel::selectTLSADDRAddr(SDValue N, SDValue &Base, SDValue &Scale, SDValue &Index, SDValue &Disp, SDValue &Segment) { assert(N.getOpcode() == ISD::TargetGlobalTLSAddress); const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N); X86ISelAddressMode AM; AM.GV = GA->getGlobal(); AM.Disp += GA->getOffset(); AM.SymbolFlags = GA->getTargetFlags(); MVT VT = N.getSimpleValueType(); if (VT == MVT::i32) { AM.Scale = 1; AM.IndexReg = CurDAG->getRegister(X86::EBX, MVT::i32); } getAddressOperands(AM, SDLoc(N), VT, Base, Scale, Index, Disp, Segment); return true; } bool X86DAGToDAGISel::selectRelocImm(SDValue N, SDValue &Op) { if (auto *CN = dyn_cast<ConstantSDNode>(N)) { Op = CurDAG->getTargetConstant(CN->getAPIntValue(), SDLoc(CN), N.getValueType()); return true; } // Keep track of the original value type and whether this value was // truncated. If we see a truncation from pointer type to VT that truncates // bits that are known to be zero, we can use a narrow reference. EVT VT = N.getValueType(); bool WasTruncated = false; if (N.getOpcode() == ISD::TRUNCATE) { WasTruncated = true; N = N.getOperand(0); } if (N.getOpcode() != X86ISD::Wrapper) return false; // We can only use non-GlobalValues as immediates if they were not truncated, // as we do not have any range information. If we have a GlobalValue and the // address was not truncated, we can select it as an operand directly. unsigned Opc = N.getOperand(0)->getOpcode(); if (Opc != ISD::TargetGlobalAddress || !WasTruncated) { Op = N.getOperand(0); // We can only select the operand directly if we didn't have to look past a // truncate. return !WasTruncated; } // Check that the global's range fits into VT. auto *GA = cast<GlobalAddressSDNode>(N.getOperand(0)); Optional<ConstantRange> CR = GA->getGlobal()->getAbsoluteSymbolRange(); if (!CR || CR->getUnsignedMax().uge(1ull << VT.getSizeInBits())) return false; // Okay, we can use a narrow reference. Op = CurDAG->getTargetGlobalAddress(GA->getGlobal(), SDLoc(N), VT, GA->getOffset(), GA->getTargetFlags()); return true; } bool X86DAGToDAGISel::tryFoldLoad(SDNode *Root, SDNode *P, SDValue N, SDValue &Base, SDValue &Scale, SDValue &Index, SDValue &Disp, SDValue &Segment) { assert(Root && P && "Unknown root/parent nodes"); if (!ISD::isNON_EXTLoad(N.getNode()) || !IsProfitableToFold(N, P, Root) || !IsLegalToFold(N, P, Root, OptLevel)) return false; return selectAddr(N.getNode(), N.getOperand(1), Base, Scale, Index, Disp, Segment); } bool X86DAGToDAGISel::tryFoldBroadcast(SDNode *Root, SDNode *P, SDValue N, SDValue &Base, SDValue &Scale, SDValue &Index, SDValue &Disp, SDValue &Segment) { assert(Root && P && "Unknown root/parent nodes"); if (N->getOpcode() != X86ISD::VBROADCAST_LOAD || !IsProfitableToFold(N, P, Root) || !IsLegalToFold(N, P, Root, OptLevel)) return false; return selectAddr(N.getNode(), N.getOperand(1), Base, Scale, Index, Disp, Segment); } /// Return an SDNode that returns the value of the global base register. /// Output instructions required to initialize the global base register, /// if necessary. SDNode *X86DAGToDAGISel::getGlobalBaseReg() { unsigned GlobalBaseReg = getInstrInfo()->getGlobalBaseReg(MF); auto &DL = MF->getDataLayout(); return CurDAG->getRegister(GlobalBaseReg, TLI->getPointerTy(DL)).getNode(); } bool X86DAGToDAGISel::isSExtAbsoluteSymbolRef(unsigned Width, SDNode *N) const { if (N->getOpcode() == ISD::TRUNCATE) N = N->getOperand(0).getNode(); if (N->getOpcode() != X86ISD::Wrapper) return false; auto *GA = dyn_cast<GlobalAddressSDNode>(N->getOperand(0)); if (!GA) return false; Optional<ConstantRange> CR = GA->getGlobal()->getAbsoluteSymbolRange(); return CR && CR->getSignedMin().sge(-1ull << Width) && CR->getSignedMax().slt(1ull << Width); } static X86::CondCode getCondFromNode(SDNode *N) { assert(N->isMachineOpcode() && "Unexpected node"); X86::CondCode CC = X86::COND_INVALID; unsigned Opc = N->getMachineOpcode(); if (Opc == X86::JCC_1) CC = static_cast<X86::CondCode>(N->getConstantOperandVal(1)); else if (Opc == X86::SETCCr) CC = static_cast<X86::CondCode>(N->getConstantOperandVal(0)); else if (Opc == X86::SETCCm) CC = static_cast<X86::CondCode>(N->getConstantOperandVal(5)); else if (Opc == X86::CMOV16rr || Opc == X86::CMOV32rr || Opc == X86::CMOV64rr) CC = static_cast<X86::CondCode>(N->getConstantOperandVal(2)); else if (Opc == X86::CMOV16rm || Opc == X86::CMOV32rm || Opc == X86::CMOV64rm) CC = static_cast<X86::CondCode>(N->getConstantOperandVal(6)); return CC; } /// Test whether the given X86ISD::CMP node has any users that use a flag /// other than ZF. bool X86DAGToDAGISel::onlyUsesZeroFlag(SDValue Flags) const { // Examine each user of the node. for (SDNode::use_iterator UI = Flags->use_begin(), UE = Flags->use_end(); UI != UE; ++UI) { // Only check things that use the flags. if (UI.getUse().getResNo() != Flags.getResNo()) continue; // Only examine CopyToReg uses that copy to EFLAGS. if (UI->getOpcode() != ISD::CopyToReg || cast<RegisterSDNode>(UI->getOperand(1))->getReg() != X86::EFLAGS) return false; // Examine each user of the CopyToReg use. for (SDNode::use_iterator FlagUI = UI->use_begin(), FlagUE = UI->use_end(); FlagUI != FlagUE; ++FlagUI) { // Only examine the Flag result. if (FlagUI.getUse().getResNo() != 1) continue; // Anything unusual: assume conservatively. if (!FlagUI->isMachineOpcode()) return false; // Examine the condition code of the user. X86::CondCode CC = getCondFromNode(*FlagUI); switch (CC) { // Comparisons which only use the zero flag. case X86::COND_E: case X86::COND_NE: continue; // Anything else: assume conservatively. default: return false; } } } return true; } /// Test whether the given X86ISD::CMP node has any uses which require the SF /// flag to be accurate. bool X86DAGToDAGISel::hasNoSignFlagUses(SDValue Flags) const { // Examine each user of the node. for (SDNode::use_iterator UI = Flags->use_begin(), UE = Flags->use_end(); UI != UE; ++UI) { // Only check things that use the flags. if (UI.getUse().getResNo() != Flags.getResNo()) continue; // Only examine CopyToReg uses that copy to EFLAGS. if (UI->getOpcode() != ISD::CopyToReg || cast<RegisterSDNode>(UI->getOperand(1))->getReg() != X86::EFLAGS) return false; // Examine each user of the CopyToReg use. for (SDNode::use_iterator FlagUI = UI->use_begin(), FlagUE = UI->use_end(); FlagUI != FlagUE; ++FlagUI) { // Only examine the Flag result. if (FlagUI.getUse().getResNo() != 1) continue; // Anything unusual: assume conservatively. if (!FlagUI->isMachineOpcode()) return false; // Examine the condition code of the user. X86::CondCode CC = getCondFromNode(*FlagUI); switch (CC) { // Comparisons which don't examine the SF flag. case X86::COND_A: case X86::COND_AE: case X86::COND_B: case X86::COND_BE: case X86::COND_E: case X86::COND_NE: case X86::COND_O: case X86::COND_NO: case X86::COND_P: case X86::COND_NP: continue; // Anything else: assume conservatively. default: return false; } } } return true; } static bool mayUseCarryFlag(X86::CondCode CC) { switch (CC) { // Comparisons which don't examine the CF flag. case X86::COND_O: case X86::COND_NO: case X86::COND_E: case X86::COND_NE: case X86::COND_S: case X86::COND_NS: case X86::COND_P: case X86::COND_NP: case X86::COND_L: case X86::COND_GE: case X86::COND_G: case X86::COND_LE: return false; // Anything else: assume conservatively. default: return true; } } /// Test whether the given node which sets flags has any uses which require the /// CF flag to be accurate. bool X86DAGToDAGISel::hasNoCarryFlagUses(SDValue Flags) const { // Examine each user of the node. for (SDNode::use_iterator UI = Flags->use_begin(), UE = Flags->use_end(); UI != UE; ++UI) { // Only check things that use the flags. if (UI.getUse().getResNo() != Flags.getResNo()) continue; unsigned UIOpc = UI->getOpcode(); if (UIOpc == ISD::CopyToReg) { // Only examine CopyToReg uses that copy to EFLAGS. if (cast<RegisterSDNode>(UI->getOperand(1))->getReg() != X86::EFLAGS) return false; // Examine each user of the CopyToReg use. for (SDNode::use_iterator FlagUI = UI->use_begin(), FlagUE = UI->use_end(); FlagUI != FlagUE; ++FlagUI) { // Only examine the Flag result. if (FlagUI.getUse().getResNo() != 1) continue; // Anything unusual: assume conservatively. if (!FlagUI->isMachineOpcode()) return false; // Examine the condition code of the user. X86::CondCode CC = getCondFromNode(*FlagUI); if (mayUseCarryFlag(CC)) return false; } // This CopyToReg is ok. Move on to the next user. continue; } // This might be an unselected node. So look for the pre-isel opcodes that // use flags. unsigned CCOpNo; switch (UIOpc) { default: // Something unusual. Be conservative. return false; case X86ISD::SETCC: CCOpNo = 0; break; case X86ISD::SETCC_CARRY: CCOpNo = 0; break; case X86ISD::CMOV: CCOpNo = 2; break; case X86ISD::BRCOND: CCOpNo = 2; break; } X86::CondCode CC = (X86::CondCode)UI->getConstantOperandVal(CCOpNo); if (mayUseCarryFlag(CC)) return false; } return true; } /// Check whether or not the chain ending in StoreNode is suitable for doing /// the {load; op; store} to modify transformation. static bool isFusableLoadOpStorePattern(StoreSDNode *StoreNode, SDValue StoredVal, SelectionDAG *CurDAG, unsigned LoadOpNo, LoadSDNode *&LoadNode, SDValue &InputChain) { // Is the stored value result 0 of the operation? if (StoredVal.getResNo() != 0) return false; // Are there other uses of the operation other than the store? if (!StoredVal.getNode()->hasNUsesOfValue(1, 0)) return false; // Is the store non-extending and non-indexed? if (!ISD::isNormalStore(StoreNode) || StoreNode->isNonTemporal()) return false; SDValue Load = StoredVal->getOperand(LoadOpNo); // Is the stored value a non-extending and non-indexed load? if (!ISD::isNormalLoad(Load.getNode())) return false; // Return LoadNode by reference. LoadNode = cast<LoadSDNode>(Load); // Is store the only read of the loaded value? if (!Load.hasOneUse()) return false; // Is the address of the store the same as the load? if (LoadNode->getBasePtr() != StoreNode->getBasePtr() || LoadNode->getOffset() != StoreNode->getOffset()) return false; bool FoundLoad = false; SmallVector<SDValue, 4> ChainOps; SmallVector<const SDNode *, 4> LoopWorklist; SmallPtrSet<const SDNode *, 16> Visited; const unsigned int Max = 1024; // Visualization of Load-Op-Store fusion: // ------------------------- // Legend: // *-lines = Chain operand dependencies. // |-lines = Normal operand dependencies. // Dependencies flow down and right. n-suffix references multiple nodes. // // C Xn C // * * * // * * * // Xn A-LD Yn TF Yn // * * \ | * | // * * \ | * | // * * \ | => A--LD_OP_ST // * * \| \ // TF OP \ // * | \ Zn // * | \ // A-ST Zn // // This merge induced dependences from: #1: Xn -> LD, OP, Zn // #2: Yn -> LD // #3: ST -> Zn // Ensure the transform is safe by checking for the dual // dependencies to make sure we do not induce a loop. // As LD is a predecessor to both OP and ST we can do this by checking: // a). if LD is a predecessor to a member of Xn or Yn. // b). if a Zn is a predecessor to ST. // However, (b) can only occur through being a chain predecessor to // ST, which is the same as Zn being a member or predecessor of Xn, // which is a subset of LD being a predecessor of Xn. So it's // subsumed by check (a). SDValue Chain = StoreNode->getChain(); // Gather X elements in ChainOps. if (Chain == Load.getValue(1)) { FoundLoad = true; ChainOps.push_back(Load.getOperand(0)); } else if (Chain.getOpcode() == ISD::TokenFactor) { for (unsigned i = 0, e = Chain.getNumOperands(); i != e; ++i) { SDValue Op = Chain.getOperand(i); if (Op == Load.getValue(1)) { FoundLoad = true; // Drop Load, but keep its chain. No cycle check necessary. ChainOps.push_back(Load.getOperand(0)); continue; } LoopWorklist.push_back(Op.getNode()); ChainOps.push_back(Op); } } if (!FoundLoad) return false; // Worklist is currently Xn. Add Yn to worklist. for (SDValue Op : StoredVal->ops()) if (Op.getNode() != LoadNode) LoopWorklist.push_back(Op.getNode()); // Check (a) if Load is a predecessor to Xn + Yn if (SDNode::hasPredecessorHelper(Load.getNode(), Visited, LoopWorklist, Max, true)) return false; InputChain = CurDAG->getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ChainOps); return true; } // Change a chain of {load; op; store} of the same value into a simple op // through memory of that value, if the uses of the modified value and its // address are suitable. // // The tablegen pattern memory operand pattern is currently not able to match // the case where the EFLAGS on the original operation are used. // // To move this to tablegen, we'll need to improve tablegen to allow flags to // be transferred from a node in the pattern to the result node, probably with // a new keyword. For example, we have this // def DEC64m : RI<0xFF, MRM1m, (outs), (ins i64mem:$dst), "dec{q}\t$dst", // [(store (add (loadi64 addr:$dst), -1), addr:$dst), // (implicit EFLAGS)]>; // but maybe need something like this // def DEC64m : RI<0xFF, MRM1m, (outs), (ins i64mem:$dst), "dec{q}\t$dst", // [(store (add (loadi64 addr:$dst), -1), addr:$dst), // (transferrable EFLAGS)]>; // // Until then, we manually fold these and instruction select the operation // here. bool X86DAGToDAGISel::foldLoadStoreIntoMemOperand(SDNode *Node) { StoreSDNode *StoreNode = cast<StoreSDNode>(Node); SDValue StoredVal = StoreNode->getOperand(1); unsigned Opc = StoredVal->getOpcode(); // Before we try to select anything, make sure this is memory operand size // and opcode we can handle. Note that this must match the code below that // actually lowers the opcodes. EVT MemVT = StoreNode->getMemoryVT(); if (MemVT != MVT::i64 && MemVT != MVT::i32 && MemVT != MVT::i16 && MemVT != MVT::i8) return false; bool IsCommutable = false; bool IsNegate = false; switch (Opc) { default: return false; case X86ISD::SUB: IsNegate = isNullConstant(StoredVal.getOperand(0)); break; case X86ISD::SBB: break; case X86ISD::ADD: case X86ISD::ADC: case X86ISD::AND: case X86ISD::OR: case X86ISD::XOR: IsCommutable = true; break; } unsigned LoadOpNo = IsNegate ? 1 : 0; LoadSDNode *LoadNode = nullptr; SDValue InputChain; if (!isFusableLoadOpStorePattern(StoreNode, StoredVal, CurDAG, LoadOpNo, LoadNode, InputChain)) { if (!IsCommutable) return false; // This operation is commutable, try the other operand. LoadOpNo = 1; if (!isFusableLoadOpStorePattern(StoreNode, StoredVal, CurDAG, LoadOpNo, LoadNode, InputChain)) return false; } SDValue Base, Scale, Index, Disp, Segment; if (!selectAddr(LoadNode, LoadNode->getBasePtr(), Base, Scale, Index, Disp, Segment)) return false; auto SelectOpcode = [&](unsigned Opc64, unsigned Opc32, unsigned Opc16, unsigned Opc8) { switch (MemVT.getSimpleVT().SimpleTy) { case MVT::i64: return Opc64; case MVT::i32: return Opc32; case MVT::i16: return Opc16; case MVT::i8: return Opc8; default: llvm_unreachable("Invalid size!"); } }; MachineSDNode *Result; switch (Opc) { case X86ISD::SUB: // Handle negate. if (IsNegate) { unsigned NewOpc = SelectOpcode(X86::NEG64m, X86::NEG32m, X86::NEG16m, X86::NEG8m); const SDValue Ops[] = {Base, Scale, Index, Disp, Segment, InputChain}; Result = CurDAG->getMachineNode(NewOpc, SDLoc(Node), MVT::i32, MVT::Other, Ops); break; } LLVM_FALLTHROUGH; case X86ISD::ADD: // Try to match inc/dec. if (!Subtarget->slowIncDec() || CurDAG->shouldOptForSize()) { bool IsOne = isOneConstant(StoredVal.getOperand(1)); bool IsNegOne = isAllOnesConstant(StoredVal.getOperand(1)); // ADD/SUB with 1/-1 and carry flag isn't used can use inc/dec. if ((IsOne || IsNegOne) && hasNoCarryFlagUses(StoredVal.getValue(1))) { unsigned NewOpc = ((Opc == X86ISD::ADD) == IsOne) ? SelectOpcode(X86::INC64m, X86::INC32m, X86::INC16m, X86::INC8m) : SelectOpcode(X86::DEC64m, X86::DEC32m, X86::DEC16m, X86::DEC8m); const SDValue Ops[] = {Base, Scale, Index, Disp, Segment, InputChain}; Result = CurDAG->getMachineNode(NewOpc, SDLoc(Node), MVT::i32, MVT::Other, Ops); break; } } LLVM_FALLTHROUGH; case X86ISD::ADC: case X86ISD::SBB: case X86ISD::AND: case X86ISD::OR: case X86ISD::XOR: { auto SelectRegOpcode = [SelectOpcode](unsigned Opc) { switch (Opc) { case X86ISD::ADD: return SelectOpcode(X86::ADD64mr, X86::ADD32mr, X86::ADD16mr, X86::ADD8mr); case X86ISD::ADC: return SelectOpcode(X86::ADC64mr, X86::ADC32mr, X86::ADC16mr, X86::ADC8mr); case X86ISD::SUB: return SelectOpcode(X86::SUB64mr, X86::SUB32mr, X86::SUB16mr, X86::SUB8mr); case X86ISD::SBB: return SelectOpcode(X86::SBB64mr, X86::SBB32mr, X86::SBB16mr, X86::SBB8mr); case X86ISD::AND: return SelectOpcode(X86::AND64mr, X86::AND32mr, X86::AND16mr, X86::AND8mr); case X86ISD::OR: return SelectOpcode(X86::OR64mr, X86::OR32mr, X86::OR16mr, X86::OR8mr); case X86ISD::XOR: return SelectOpcode(X86::XOR64mr, X86::XOR32mr, X86::XOR16mr, X86::XOR8mr); default: llvm_unreachable("Invalid opcode!"); } }; auto SelectImm8Opcode = [SelectOpcode](unsigned Opc) { switch (Opc) { case X86ISD::ADD: return SelectOpcode(X86::ADD64mi8, X86::ADD32mi8, X86::ADD16mi8, 0); case X86ISD::ADC: return SelectOpcode(X86::ADC64mi8, X86::ADC32mi8, X86::ADC16mi8, 0); case X86ISD::SUB: return SelectOpcode(X86::SUB64mi8, X86::SUB32mi8, X86::SUB16mi8, 0); case X86ISD::SBB: return SelectOpcode(X86::SBB64mi8, X86::SBB32mi8, X86::SBB16mi8, 0); case X86ISD::AND: return SelectOpcode(X86::AND64mi8, X86::AND32mi8, X86::AND16mi8, 0); case X86ISD::OR: return SelectOpcode(X86::OR64mi8, X86::OR32mi8, X86::OR16mi8, 0); case X86ISD::XOR: return SelectOpcode(X86::XOR64mi8, X86::XOR32mi8, X86::XOR16mi8, 0); default: llvm_unreachable("Invalid opcode!"); } }; auto SelectImmOpcode = [SelectOpcode](unsigned Opc) { switch (Opc) { case X86ISD::ADD: return SelectOpcode(X86::ADD64mi32, X86::ADD32mi, X86::ADD16mi, X86::ADD8mi); case X86ISD::ADC: return SelectOpcode(X86::ADC64mi32, X86::ADC32mi, X86::ADC16mi, X86::ADC8mi); case X86ISD::SUB: return SelectOpcode(X86::SUB64mi32, X86::SUB32mi, X86::SUB16mi, X86::SUB8mi); case X86ISD::SBB: return SelectOpcode(X86::SBB64mi32, X86::SBB32mi, X86::SBB16mi, X86::SBB8mi); case X86ISD::AND: return SelectOpcode(X86::AND64mi32, X86::AND32mi, X86::AND16mi, X86::AND8mi); case X86ISD::OR: return SelectOpcode(X86::OR64mi32, X86::OR32mi, X86::OR16mi, X86::OR8mi); case X86ISD::XOR: return SelectOpcode(X86::XOR64mi32, X86::XOR32mi, X86::XOR16mi, X86::XOR8mi); default: llvm_unreachable("Invalid opcode!"); } }; unsigned NewOpc = SelectRegOpcode(Opc); SDValue Operand = StoredVal->getOperand(1-LoadOpNo); // See if the operand is a constant that we can fold into an immediate // operand. if (auto *OperandC = dyn_cast<ConstantSDNode>(Operand)) { int64_t OperandV = OperandC->getSExtValue(); // Check if we can shrink the operand enough to fit in an immediate (or // fit into a smaller immediate) by negating it and switching the // operation. if ((Opc == X86ISD::ADD || Opc == X86ISD::SUB) && ((MemVT != MVT::i8 && !isInt<8>(OperandV) && isInt<8>(-OperandV)) || (MemVT == MVT::i64 && !isInt<32>(OperandV) && isInt<32>(-OperandV))) && hasNoCarryFlagUses(StoredVal.getValue(1))) { OperandV = -OperandV; Opc = Opc == X86ISD::ADD ? X86ISD::SUB : X86ISD::ADD; } // First try to fit this into an Imm8 operand. If it doesn't fit, then try // the larger immediate operand. if (MemVT != MVT::i8 && isInt<8>(OperandV)) { Operand = CurDAG->getTargetConstant(OperandV, SDLoc(Node), MemVT); NewOpc = SelectImm8Opcode(Opc); } else if (MemVT != MVT::i64 || isInt<32>(OperandV)) { Operand = CurDAG->getTargetConstant(OperandV, SDLoc(Node), MemVT); NewOpc = SelectImmOpcode(Opc); } } if (Opc == X86ISD::ADC || Opc == X86ISD::SBB) { SDValue CopyTo = CurDAG->getCopyToReg(InputChain, SDLoc(Node), X86::EFLAGS, StoredVal.getOperand(2), SDValue()); const SDValue Ops[] = {Base, Scale, Index, Disp, Segment, Operand, CopyTo, CopyTo.getValue(1)}; Result = CurDAG->getMachineNode(NewOpc, SDLoc(Node), MVT::i32, MVT::Other, Ops); } else { const SDValue Ops[] = {Base, Scale, Index, Disp, Segment, Operand, InputChain}; Result = CurDAG->getMachineNode(NewOpc, SDLoc(Node), MVT::i32, MVT::Other, Ops); } break; } default: llvm_unreachable("Invalid opcode!"); } MachineMemOperand *MemOps[] = {StoreNode->getMemOperand(), LoadNode->getMemOperand()}; CurDAG->setNodeMemRefs(Result, MemOps); // Update Load Chain uses as well. ReplaceUses(SDValue(LoadNode, 1), SDValue(Result, 1)); ReplaceUses(SDValue(StoreNode, 0), SDValue(Result, 1)); ReplaceUses(SDValue(StoredVal.getNode(), 1), SDValue(Result, 0)); CurDAG->RemoveDeadNode(Node); return true; } // See if this is an X & Mask that we can match to BEXTR/BZHI. // Where Mask is one of the following patterns: // a) x & (1 << nbits) - 1 // b) x & ~(-1 << nbits) // c) x & (-1 >> (32 - y)) // d) x << (32 - y) >> (32 - y) bool X86DAGToDAGISel::matchBitExtract(SDNode *Node) { assert( (Node->getOpcode() == ISD::AND || Node->getOpcode() == ISD::SRL) && "Should be either an and-mask, or right-shift after clearing high bits."); // BEXTR is BMI instruction, BZHI is BMI2 instruction. We need at least one. if (!Subtarget->hasBMI() && !Subtarget->hasBMI2()) return false; MVT NVT = Node->getSimpleValueType(0); // Only supported for 32 and 64 bits. if (NVT != MVT::i32 && NVT != MVT::i64) return false; SDValue NBits; // If we have BMI2's BZHI, we are ok with muti-use patterns. // Else, if we only have BMI1's BEXTR, we require one-use. const bool CanHaveExtraUses = Subtarget->hasBMI2(); auto checkUses = [CanHaveExtraUses](SDValue Op, unsigned NUses) { return CanHaveExtraUses || Op.getNode()->hasNUsesOfValue(NUses, Op.getResNo()); }; auto checkOneUse = [checkUses](SDValue Op) { return checkUses(Op, 1); }; auto checkTwoUse = [checkUses](SDValue Op) { return checkUses(Op, 2); }; auto peekThroughOneUseTruncation = [checkOneUse](SDValue V) { if (V->getOpcode() == ISD::TRUNCATE && checkOneUse(V)) { assert(V.getSimpleValueType() == MVT::i32 && V.getOperand(0).getSimpleValueType() == MVT::i64 && "Expected i64 -> i32 truncation"); V = V.getOperand(0); } return V; }; // a) x & ((1 << nbits) + (-1)) auto matchPatternA = [checkOneUse, peekThroughOneUseTruncation, &NBits](SDValue Mask) -> bool { // Match `add`. Must only have one use! if (Mask->getOpcode() != ISD::ADD || !checkOneUse(Mask)) return false; // We should be adding all-ones constant (i.e. subtracting one.) if (!isAllOnesConstant(Mask->getOperand(1))) return false; // Match `1 << nbits`. Might be truncated. Must only have one use! SDValue M0 = peekThroughOneUseTruncation(Mask->getOperand(0)); if (M0->getOpcode() != ISD::SHL || !checkOneUse(M0)) return false; if (!isOneConstant(M0->getOperand(0))) return false; NBits = M0->getOperand(1); return true; }; auto isAllOnes = [this, peekThroughOneUseTruncation, NVT](SDValue V) { V = peekThroughOneUseTruncation(V); return CurDAG->MaskedValueIsAllOnes( V, APInt::getLowBitsSet(V.getSimpleValueType().getSizeInBits(), NVT.getSizeInBits())); }; // b) x & ~(-1 << nbits) auto matchPatternB = [checkOneUse, isAllOnes, peekThroughOneUseTruncation, &NBits](SDValue Mask) -> bool { // Match `~()`. Must only have one use! if (Mask.getOpcode() != ISD::XOR || !checkOneUse(Mask)) return false; // The -1 only has to be all-ones for the final Node's NVT. if (!isAllOnes(Mask->getOperand(1))) return false; // Match `-1 << nbits`. Might be truncated. Must only have one use! SDValue M0 = peekThroughOneUseTruncation(Mask->getOperand(0)); if (M0->getOpcode() != ISD::SHL || !checkOneUse(M0)) return false; // The -1 only has to be all-ones for the final Node's NVT. if (!isAllOnes(M0->getOperand(0))) return false; NBits = M0->getOperand(1); return true; }; // Match potentially-truncated (bitwidth - y) auto matchShiftAmt = [checkOneUse, &NBits](SDValue ShiftAmt, unsigned Bitwidth) { // Skip over a truncate of the shift amount. if (ShiftAmt.getOpcode() == ISD::TRUNCATE) { ShiftAmt = ShiftAmt.getOperand(0); // The trunc should have been the only user of the real shift amount. if (!checkOneUse(ShiftAmt)) return false; } // Match the shift amount as: (bitwidth - y). It should go away, too. if (ShiftAmt.getOpcode() != ISD::SUB) return false; auto V0 = dyn_cast<ConstantSDNode>(ShiftAmt.getOperand(0)); if (!V0 || V0->getZExtValue() != Bitwidth) return false; NBits = ShiftAmt.getOperand(1); return true; }; // c) x & (-1 >> (32 - y)) auto matchPatternC = [checkOneUse, peekThroughOneUseTruncation, matchShiftAmt](SDValue Mask) -> bool { // The mask itself may be truncated. Mask = peekThroughOneUseTruncation(Mask); unsigned Bitwidth = Mask.getSimpleValueType().getSizeInBits(); // Match `l>>`. Must only have one use! if (Mask.getOpcode() != ISD::SRL || !checkOneUse(Mask)) return false; // We should be shifting truly all-ones constant. if (!isAllOnesConstant(Mask.getOperand(0))) return false; SDValue M1 = Mask.getOperand(1); // The shift amount should not be used externally. if (!checkOneUse(M1)) return false; return matchShiftAmt(M1, Bitwidth); }; SDValue X; // d) x << (32 - y) >> (32 - y) auto matchPatternD = [checkOneUse, checkTwoUse, matchShiftAmt, &X](SDNode *Node) -> bool { if (Node->getOpcode() != ISD::SRL) return false; SDValue N0 = Node->getOperand(0); if (N0->getOpcode() != ISD::SHL || !checkOneUse(N0)) return false; unsigned Bitwidth = N0.getSimpleValueType().getSizeInBits(); SDValue N1 = Node->getOperand(1); SDValue N01 = N0->getOperand(1); // Both of the shifts must be by the exact same value. // There should not be any uses of the shift amount outside of the pattern. if (N1 != N01 || !checkTwoUse(N1)) return false; if (!matchShiftAmt(N1, Bitwidth)) return false; X = N0->getOperand(0); return true; }; auto matchLowBitMask = [matchPatternA, matchPatternB, matchPatternC](SDValue Mask) -> bool { return matchPatternA(Mask) || matchPatternB(Mask) || matchPatternC(Mask); }; if (Node->getOpcode() == ISD::AND) { X = Node->getOperand(0); SDValue Mask = Node->getOperand(1); if (matchLowBitMask(Mask)) { // Great. } else { std::swap(X, Mask); if (!matchLowBitMask(Mask)) return false; } } else if (!matchPatternD(Node)) return false; SDLoc DL(Node); // Truncate the shift amount. NBits = CurDAG->getNode(ISD::TRUNCATE, DL, MVT::i8, NBits); insertDAGNode(*CurDAG, SDValue(Node, 0), NBits); // Insert 8-bit NBits into lowest 8 bits of 32-bit register. // All the other bits are undefined, we do not care about them. SDValue ImplDef = SDValue( CurDAG->getMachineNode(TargetOpcode::IMPLICIT_DEF, DL, MVT::i32), 0); insertDAGNode(*CurDAG, SDValue(Node, 0), ImplDef); SDValue SRIdxVal = CurDAG->getTargetConstant(X86::sub_8bit, DL, MVT::i32); insertDAGNode(*CurDAG, SDValue(Node, 0), SRIdxVal); NBits = SDValue( CurDAG->getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::i32, ImplDef, NBits, SRIdxVal), 0); insertDAGNode(*CurDAG, SDValue(Node, 0), NBits); if (Subtarget->hasBMI2()) { // Great, just emit the the BZHI.. if (NVT != MVT::i32) { // But have to place the bit count into the wide-enough register first. NBits = CurDAG->getNode(ISD::ANY_EXTEND, DL, NVT, NBits); insertDAGNode(*CurDAG, SDValue(Node, 0), NBits); } SDValue Extract = CurDAG->getNode(X86ISD::BZHI, DL, NVT, X, NBits); ReplaceNode(Node, Extract.getNode()); SelectCode(Extract.getNode()); return true; } // Else, if we do *NOT* have BMI2, let's find out if the if the 'X' is // *logically* shifted (potentially with one-use trunc inbetween), // and the truncation was the only use of the shift, // and if so look past one-use truncation. { SDValue RealX = peekThroughOneUseTruncation(X); // FIXME: only if the shift is one-use? if (RealX != X && RealX.getOpcode() == ISD::SRL) X = RealX; } MVT XVT = X.getSimpleValueType(); // Else, emitting BEXTR requires one more step. // The 'control' of BEXTR has the pattern of: // [15...8 bit][ 7...0 bit] location // [ bit count][ shift] name // I.e. 0b000000011'00000001 means (x >> 0b1) & 0b11 // Shift NBits left by 8 bits, thus producing 'control'. // This makes the low 8 bits to be zero. SDValue C8 = CurDAG->getConstant(8, DL, MVT::i8); SDValue Control = CurDAG->getNode(ISD::SHL, DL, MVT::i32, NBits, C8); insertDAGNode(*CurDAG, SDValue(Node, 0), Control); // If the 'X' is *logically* shifted, we can fold that shift into 'control'. // FIXME: only if the shift is one-use? if (X.getOpcode() == ISD::SRL) { SDValue ShiftAmt = X.getOperand(1); X = X.getOperand(0); assert(ShiftAmt.getValueType() == MVT::i8 && "Expected shift amount to be i8"); // Now, *zero*-extend the shift amount. The bits 8...15 *must* be zero! // We could zext to i16 in some form, but we intentionally don't do that. SDValue OrigShiftAmt = ShiftAmt; ShiftAmt = CurDAG->getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShiftAmt); insertDAGNode(*CurDAG, OrigShiftAmt, ShiftAmt); // And now 'or' these low 8 bits of shift amount into the 'control'. Control = CurDAG->getNode(ISD::OR, DL, MVT::i32, Control, ShiftAmt); insertDAGNode(*CurDAG, SDValue(Node, 0), Control); } // But have to place the 'control' into the wide-enough register first. if (XVT != MVT::i32) { Control = CurDAG->getNode(ISD::ANY_EXTEND, DL, XVT, Control); insertDAGNode(*CurDAG, SDValue(Node, 0), Control); } // And finally, form the BEXTR itself. SDValue Extract = CurDAG->getNode(X86ISD::BEXTR, DL, XVT, X, Control); // The 'X' was originally truncated. Do that now. if (XVT != NVT) { insertDAGNode(*CurDAG, SDValue(Node, 0), Extract); Extract = CurDAG->getNode(ISD::TRUNCATE, DL, NVT, Extract); } ReplaceNode(Node, Extract.getNode()); SelectCode(Extract.getNode()); return true; } // See if this is an (X >> C1) & C2 that we can match to BEXTR/BEXTRI. MachineSDNode *X86DAGToDAGISel::matchBEXTRFromAndImm(SDNode *Node) { MVT NVT = Node->getSimpleValueType(0); SDLoc dl(Node); SDValue N0 = Node->getOperand(0); SDValue N1 = Node->getOperand(1); // If we have TBM we can use an immediate for the control. If we have BMI // we should only do this if the BEXTR instruction is implemented well. // Otherwise moving the control into a register makes this more costly. // TODO: Maybe load folding, greater than 32-bit masks, or a guarantee of LICM // hoisting the move immediate would make it worthwhile with a less optimal // BEXTR? bool PreferBEXTR = Subtarget->hasTBM() || (Subtarget->hasBMI() && Subtarget->hasFastBEXTR()); if (!PreferBEXTR && !Subtarget->hasBMI2()) return nullptr; // Must have a shift right. if (N0->getOpcode() != ISD::SRL && N0->getOpcode() != ISD::SRA) return nullptr; // Shift can't have additional users. if (!N0->hasOneUse()) return nullptr; // Only supported for 32 and 64 bits. if (NVT != MVT::i32 && NVT != MVT::i64) return nullptr; // Shift amount and RHS of and must be constant. ConstantSDNode *MaskCst = dyn_cast<ConstantSDNode>(N1); ConstantSDNode *ShiftCst = dyn_cast<ConstantSDNode>(N0->getOperand(1)); if (!MaskCst || !ShiftCst) return nullptr; // And RHS must be a mask. uint64_t Mask = MaskCst->getZExtValue(); if (!isMask_64(Mask)) return nullptr; uint64_t Shift = ShiftCst->getZExtValue(); uint64_t MaskSize = countPopulation(Mask); // Don't interfere with something that can be handled by extracting AH. // TODO: If we are able to fold a load, BEXTR might still be better than AH. if (Shift == 8 && MaskSize == 8) return nullptr; // Make sure we are only using bits that were in the original value, not // shifted in. if (Shift + MaskSize > NVT.getSizeInBits()) return nullptr; // BZHI, if available, is always fast, unlike BEXTR. But even if we decide // that we can't use BEXTR, it is only worthwhile using BZHI if the mask // does not fit into 32 bits. Load folding is not a sufficient reason. if (!PreferBEXTR && MaskSize <= 32) return nullptr; SDValue Control; unsigned ROpc, MOpc; if (!PreferBEXTR) { assert(Subtarget->hasBMI2() && "We must have BMI2's BZHI then."); // If we can't make use of BEXTR then we can't fuse shift+mask stages. // Let's perform the mask first, and apply shift later. Note that we need to // widen the mask to account for the fact that we'll apply shift afterwards! Control = CurDAG->getTargetConstant(Shift + MaskSize, dl, NVT); ROpc = NVT == MVT::i64 ? X86::BZHI64rr : X86::BZHI32rr; MOpc = NVT == MVT::i64 ? X86::BZHI64rm : X86::BZHI32rm; unsigned NewOpc = NVT == MVT::i64 ? X86::MOV32ri64 : X86::MOV32ri; Control = SDValue(CurDAG->getMachineNode(NewOpc, dl, NVT, Control), 0); } else { // The 'control' of BEXTR has the pattern of: // [15...8 bit][ 7...0 bit] location // [ bit count][ shift] name // I.e. 0b000000011'00000001 means (x >> 0b1) & 0b11 Control = CurDAG->getTargetConstant(Shift | (MaskSize << 8), dl, NVT); if (Subtarget->hasTBM()) { ROpc = NVT == MVT::i64 ? X86::BEXTRI64ri : X86::BEXTRI32ri; MOpc = NVT == MVT::i64 ? X86::BEXTRI64mi : X86::BEXTRI32mi; } else { assert(Subtarget->hasBMI() && "We must have BMI1's BEXTR then."); // BMI requires the immediate to placed in a register. ROpc = NVT == MVT::i64 ? X86::BEXTR64rr : X86::BEXTR32rr; MOpc = NVT == MVT::i64 ? X86::BEXTR64rm : X86::BEXTR32rm; unsigned NewOpc = NVT == MVT::i64 ? X86::MOV32ri64 : X86::MOV32ri; Control = SDValue(CurDAG->getMachineNode(NewOpc, dl, NVT, Control), 0); } } MachineSDNode *NewNode; SDValue Input = N0->getOperand(0); SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4; if (tryFoldLoad(Node, N0.getNode(), Input, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) { SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Control, Input.getOperand(0)}; SDVTList VTs = CurDAG->getVTList(NVT, MVT::i32, MVT::Other); NewNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops); // Update the chain. ReplaceUses(Input.getValue(1), SDValue(NewNode, 2)); // Record the mem-refs CurDAG->setNodeMemRefs(NewNode, {cast<LoadSDNode>(Input)->getMemOperand()}); } else { NewNode = CurDAG->getMachineNode(ROpc, dl, NVT, MVT::i32, Input, Control); } if (!PreferBEXTR) { // We still need to apply the shift. SDValue ShAmt = CurDAG->getTargetConstant(Shift, dl, NVT); unsigned NewOpc = NVT == MVT::i64 ? X86::SHR64ri : X86::SHR32ri; NewNode = CurDAG->getMachineNode(NewOpc, dl, NVT, SDValue(NewNode, 0), ShAmt); } return NewNode; } // Emit a PCMISTR(I/M) instruction. MachineSDNode *X86DAGToDAGISel::emitPCMPISTR(unsigned ROpc, unsigned MOpc, bool MayFoldLoad, const SDLoc &dl, MVT VT, SDNode *Node) { SDValue N0 = Node->getOperand(0); SDValue N1 = Node->getOperand(1); SDValue Imm = Node->getOperand(2); const ConstantInt *Val = cast<ConstantSDNode>(Imm)->getConstantIntValue(); Imm = CurDAG->getTargetConstant(*Val, SDLoc(Node), Imm.getValueType()); // Try to fold a load. No need to check alignment. SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4; if (MayFoldLoad && tryFoldLoad(Node, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) { SDValue Ops[] = { N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Imm, N1.getOperand(0) }; SDVTList VTs = CurDAG->getVTList(VT, MVT::i32, MVT::Other); MachineSDNode *CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops); // Update the chain. ReplaceUses(N1.getValue(1), SDValue(CNode, 2)); // Record the mem-refs CurDAG->setNodeMemRefs(CNode, {cast<LoadSDNode>(N1)->getMemOperand()}); return CNode; } SDValue Ops[] = { N0, N1, Imm }; SDVTList VTs = CurDAG->getVTList(VT, MVT::i32); MachineSDNode *CNode = CurDAG->getMachineNode(ROpc, dl, VTs, Ops); return CNode; } // Emit a PCMESTR(I/M) instruction. Also return the Glue result in case we need // to emit a second instruction after this one. This is needed since we have two // copyToReg nodes glued before this and we need to continue that glue through. MachineSDNode *X86DAGToDAGISel::emitPCMPESTR(unsigned ROpc, unsigned MOpc, bool MayFoldLoad, const SDLoc &dl, MVT VT, SDNode *Node, SDValue &InFlag) { SDValue N0 = Node->getOperand(0); SDValue N2 = Node->getOperand(2); SDValue Imm = Node->getOperand(4); const ConstantInt *Val = cast<ConstantSDNode>(Imm)->getConstantIntValue(); Imm = CurDAG->getTargetConstant(*Val, SDLoc(Node), Imm.getValueType()); // Try to fold a load. No need to check alignment. SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4; if (MayFoldLoad && tryFoldLoad(Node, N2, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) { SDValue Ops[] = { N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Imm, N2.getOperand(0), InFlag }; SDVTList VTs = CurDAG->getVTList(VT, MVT::i32, MVT::Other, MVT::Glue); MachineSDNode *CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops); InFlag = SDValue(CNode, 3); // Update the chain. ReplaceUses(N2.getValue(1), SDValue(CNode, 2)); // Record the mem-refs CurDAG->setNodeMemRefs(CNode, {cast<LoadSDNode>(N2)->getMemOperand()}); return CNode; } SDValue Ops[] = { N0, N2, Imm, InFlag }; SDVTList VTs = CurDAG->getVTList(VT, MVT::i32, MVT::Glue); MachineSDNode *CNode = CurDAG->getMachineNode(ROpc, dl, VTs, Ops); InFlag = SDValue(CNode, 2); return CNode; } bool X86DAGToDAGISel::tryShiftAmountMod(SDNode *N) { EVT VT = N->getValueType(0); // Only handle scalar shifts. if (VT.isVector()) return false; // Narrower shifts only mask to 5 bits in hardware. unsigned Size = VT == MVT::i64 ? 64 : 32; SDValue OrigShiftAmt = N->getOperand(1); SDValue ShiftAmt = OrigShiftAmt; SDLoc DL(N); // Skip over a truncate of the shift amount. if (ShiftAmt->getOpcode() == ISD::TRUNCATE) ShiftAmt = ShiftAmt->getOperand(0); // This function is called after X86DAGToDAGISel::matchBitExtract(), // so we are not afraid that we might mess up BZHI/BEXTR pattern. SDValue NewShiftAmt; if (ShiftAmt->getOpcode() == ISD::ADD || ShiftAmt->getOpcode() == ISD::SUB) { SDValue Add0 = ShiftAmt->getOperand(0); SDValue Add1 = ShiftAmt->getOperand(1); // If we are shifting by X+/-N where N == 0 mod Size, then just shift by X // to avoid the ADD/SUB. if (isa<ConstantSDNode>(Add1) && cast<ConstantSDNode>(Add1)->getZExtValue() % Size == 0) { NewShiftAmt = Add0; // If we are shifting by N-X where N == 0 mod Size, then just shift by -X to // generate a NEG instead of a SUB of a constant. } else if (ShiftAmt->getOpcode() == ISD::SUB && isa<ConstantSDNode>(Add0) && cast<ConstantSDNode>(Add0)->getZExtValue() != 0 && cast<ConstantSDNode>(Add0)->getZExtValue() % Size == 0) { // Insert a negate op. // TODO: This isn't guaranteed to replace the sub if there is a logic cone // that uses it that's not a shift. EVT SubVT = ShiftAmt.getValueType(); SDValue Zero = CurDAG->getConstant(0, DL, SubVT); SDValue Neg = CurDAG->getNode(ISD::SUB, DL, SubVT, Zero, Add1); NewShiftAmt = Neg; // Insert these operands into a valid topological order so they can // get selected independently. insertDAGNode(*CurDAG, OrigShiftAmt, Zero); insertDAGNode(*CurDAG, OrigShiftAmt, Neg); } else return false; } else return false; if (NewShiftAmt.getValueType() != MVT::i8) { // Need to truncate the shift amount. NewShiftAmt = CurDAG->getNode(ISD::TRUNCATE, DL, MVT::i8, NewShiftAmt); // Add to a correct topological ordering. insertDAGNode(*CurDAG, OrigShiftAmt, NewShiftAmt); } // Insert a new mask to keep the shift amount legal. This should be removed // by isel patterns. NewShiftAmt = CurDAG->getNode(ISD::AND, DL, MVT::i8, NewShiftAmt, CurDAG->getConstant(Size - 1, DL, MVT::i8)); // Place in a correct topological ordering. insertDAGNode(*CurDAG, OrigShiftAmt, NewShiftAmt); SDNode *UpdatedNode = CurDAG->UpdateNodeOperands(N, N->getOperand(0), NewShiftAmt); if (UpdatedNode != N) { // If we found an existing node, we should replace ourselves with that node // and wait for it to be selected after its other users. ReplaceNode(N, UpdatedNode); return true; } // If the original shift amount is now dead, delete it so that we don't run // it through isel. if (OrigShiftAmt.getNode()->use_empty()) CurDAG->RemoveDeadNode(OrigShiftAmt.getNode()); // Now that we've optimized the shift amount, defer to normal isel to get // load folding and legacy vs BMI2 selection without repeating it here. SelectCode(N); return true; } bool X86DAGToDAGISel::tryShrinkShlLogicImm(SDNode *N) { MVT NVT = N->getSimpleValueType(0); unsigned Opcode = N->getOpcode(); SDLoc dl(N); // For operations of the form (x << C1) op C2, check if we can use a smaller // encoding for C2 by transforming it into (x op (C2>>C1)) << C1. SDValue Shift = N->getOperand(0); SDValue N1 = N->getOperand(1); ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(N1); if (!Cst) return false; int64_t Val = Cst->getSExtValue(); // If we have an any_extend feeding the AND, look through it to see if there // is a shift behind it. But only if the AND doesn't use the extended bits. // FIXME: Generalize this to other ANY_EXTEND than i32 to i64? bool FoundAnyExtend = false; if (Shift.getOpcode() == ISD::ANY_EXTEND && Shift.hasOneUse() && Shift.getOperand(0).getSimpleValueType() == MVT::i32 && isUInt<32>(Val)) { FoundAnyExtend = true; Shift = Shift.getOperand(0); } if (Shift.getOpcode() != ISD::SHL || !Shift.hasOneUse()) return false; // i8 is unshrinkable, i16 should be promoted to i32. if (NVT != MVT::i32 && NVT != MVT::i64) return false; ConstantSDNode *ShlCst = dyn_cast<ConstantSDNode>(Shift.getOperand(1)); if (!ShlCst) return false; uint64_t ShAmt = ShlCst->getZExtValue(); // Make sure that we don't change the operation by removing bits. // This only matters for OR and XOR, AND is unaffected. uint64_t RemovedBitsMask = (1ULL << ShAmt) - 1; if (Opcode != ISD::AND && (Val & RemovedBitsMask) != 0) return false; // Check the minimum bitwidth for the new constant. // TODO: Using 16 and 8 bit operations is also possible for or32 & xor32. auto CanShrinkImmediate = [&](int64_t &ShiftedVal) { if (Opcode == ISD::AND) { // AND32ri is the same as AND64ri32 with zext imm. // Try this before sign extended immediates below. ShiftedVal = (uint64_t)Val >> ShAmt; if (NVT == MVT::i64 && !isUInt<32>(Val) && isUInt<32>(ShiftedVal)) return true; // Also swap order when the AND can become MOVZX. if (ShiftedVal == UINT8_MAX || ShiftedVal == UINT16_MAX) return true; } ShiftedVal = Val >> ShAmt; if ((!isInt<8>(Val) && isInt<8>(ShiftedVal)) || (!isInt<32>(Val) && isInt<32>(ShiftedVal))) return true; if (Opcode != ISD::AND) { // MOV32ri+OR64r/XOR64r is cheaper than MOV64ri64+OR64rr/XOR64rr ShiftedVal = (uint64_t)Val >> ShAmt; if (NVT == MVT::i64 && !isUInt<32>(Val) && isUInt<32>(ShiftedVal)) return true; } return false; }; int64_t ShiftedVal; if (!CanShrinkImmediate(ShiftedVal)) return false; // Ok, we can reorder to get a smaller immediate. // But, its possible the original immediate allowed an AND to become MOVZX. // Doing this late due to avoid the MakedValueIsZero call as late as // possible. if (Opcode == ISD::AND) { // Find the smallest zext this could possibly be. unsigned ZExtWidth = Cst->getAPIntValue().getActiveBits(); ZExtWidth = PowerOf2Ceil(std::max(ZExtWidth, 8U)); // Figure out which bits need to be zero to achieve that mask. APInt NeededMask = APInt::getLowBitsSet(NVT.getSizeInBits(), ZExtWidth); NeededMask &= ~Cst->getAPIntValue(); if (CurDAG->MaskedValueIsZero(N->getOperand(0), NeededMask)) return false; } SDValue X = Shift.getOperand(0); if (FoundAnyExtend) { SDValue NewX = CurDAG->getNode(ISD::ANY_EXTEND, dl, NVT, X); insertDAGNode(*CurDAG, SDValue(N, 0), NewX); X = NewX; } SDValue NewCst = CurDAG->getConstant(ShiftedVal, dl, NVT); insertDAGNode(*CurDAG, SDValue(N, 0), NewCst); SDValue NewBinOp = CurDAG->getNode(Opcode, dl, NVT, X, NewCst); insertDAGNode(*CurDAG, SDValue(N, 0), NewBinOp); SDValue NewSHL = CurDAG->getNode(ISD::SHL, dl, NVT, NewBinOp, Shift.getOperand(1)); ReplaceNode(N, NewSHL.getNode()); SelectCode(NewSHL.getNode()); return true; } /// If the high bits of an 'and' operand are known zero, try setting the /// high bits of an 'and' constant operand to produce a smaller encoding by /// creating a small, sign-extended negative immediate rather than a large /// positive one. This reverses a transform in SimplifyDemandedBits that /// shrinks mask constants by clearing bits. There is also a possibility that /// the 'and' mask can be made -1, so the 'and' itself is unnecessary. In that /// case, just replace the 'and'. Return 'true' if the node is replaced. bool X86DAGToDAGISel::shrinkAndImmediate(SDNode *And) { // i8 is unshrinkable, i16 should be promoted to i32, and vector ops don't // have immediate operands. MVT VT = And->getSimpleValueType(0); if (VT != MVT::i32 && VT != MVT::i64) return false; auto *And1C = dyn_cast<ConstantSDNode>(And->getOperand(1)); if (!And1C) return false; // Bail out if the mask constant is already negative. It's can't shrink more. // If the upper 32 bits of a 64 bit mask are all zeros, we have special isel // patterns to use a 32-bit and instead of a 64-bit and by relying on the // implicit zeroing of 32 bit ops. So we should check if the lower 32 bits // are negative too. APInt MaskVal = And1C->getAPIntValue(); unsigned MaskLZ = MaskVal.countLeadingZeros(); if (!MaskLZ || (VT == MVT::i64 && MaskLZ == 32)) return false; // Don't extend into the upper 32 bits of a 64 bit mask. if (VT == MVT::i64 && MaskLZ >= 32) { MaskLZ -= 32; MaskVal = MaskVal.trunc(32); } SDValue And0 = And->getOperand(0); APInt HighZeros = APInt::getHighBitsSet(MaskVal.getBitWidth(), MaskLZ); APInt NegMaskVal = MaskVal | HighZeros; // If a negative constant would not allow a smaller encoding, there's no need // to continue. Only change the constant when we know it's a win. unsigned MinWidth = NegMaskVal.getMinSignedBits(); if (MinWidth > 32 || (MinWidth > 8 && MaskVal.getMinSignedBits() <= 32)) return false; // Extend masks if we truncated above. if (VT == MVT::i64 && MaskVal.getBitWidth() < 64) { NegMaskVal = NegMaskVal.zext(64); HighZeros = HighZeros.zext(64); } // The variable operand must be all zeros in the top bits to allow using the // new, negative constant as the mask. if (!CurDAG->MaskedValueIsZero(And0, HighZeros)) return false; // Check if the mask is -1. In that case, this is an unnecessary instruction // that escaped earlier analysis. if (NegMaskVal.isAllOnesValue()) { ReplaceNode(And, And0.getNode()); return true; } // A negative mask allows a smaller encoding. Create a new 'and' node. SDValue NewMask = CurDAG->getConstant(NegMaskVal, SDLoc(And), VT); SDValue NewAnd = CurDAG->getNode(ISD::AND, SDLoc(And), VT, And0, NewMask); ReplaceNode(And, NewAnd.getNode()); SelectCode(NewAnd.getNode()); return true; } static unsigned getVPTESTMOpc(MVT TestVT, bool IsTestN, bool FoldedLoad, bool FoldedBCast, bool Masked) { if (Masked) { if (FoldedLoad) { switch (TestVT.SimpleTy) { default: llvm_unreachable("Unexpected VT!"); case MVT::v16i8: return IsTestN ? X86::VPTESTNMBZ128rmk : X86::VPTESTMBZ128rmk; case MVT::v8i16: return IsTestN ? X86::VPTESTNMWZ128rmk : X86::VPTESTMWZ128rmk; case MVT::v4i32: return IsTestN ? X86::VPTESTNMDZ128rmk : X86::VPTESTMDZ128rmk; case MVT::v2i64: return IsTestN ? X86::VPTESTNMQZ128rmk : X86::VPTESTMQZ128rmk; case MVT::v32i8: return IsTestN ? X86::VPTESTNMBZ256rmk : X86::VPTESTMBZ256rmk; case MVT::v16i16: return IsTestN ? X86::VPTESTNMWZ256rmk : X86::VPTESTMWZ256rmk; case MVT::v8i32: return IsTestN ? X86::VPTESTNMDZ256rmk : X86::VPTESTMDZ256rmk; case MVT::v4i64: return IsTestN ? X86::VPTESTNMQZ256rmk : X86::VPTESTMQZ256rmk; case MVT::v64i8: return IsTestN ? X86::VPTESTNMBZrmk : X86::VPTESTMBZrmk; case MVT::v32i16: return IsTestN ? X86::VPTESTNMWZrmk : X86::VPTESTMWZrmk; case MVT::v16i32: return IsTestN ? X86::VPTESTNMDZrmk : X86::VPTESTMDZrmk; case MVT::v8i64: return IsTestN ? X86::VPTESTNMQZrmk : X86::VPTESTMQZrmk; } } if (FoldedBCast) { switch (TestVT.SimpleTy) { default: llvm_unreachable("Unexpected VT!"); case MVT::v4i32: return IsTestN ? X86::VPTESTNMDZ128rmbk : X86::VPTESTMDZ128rmbk; case MVT::v2i64: return IsTestN ? X86::VPTESTNMQZ128rmbk : X86::VPTESTMQZ128rmbk; case MVT::v8i32: return IsTestN ? X86::VPTESTNMDZ256rmbk : X86::VPTESTMDZ256rmbk; case MVT::v4i64: return IsTestN ? X86::VPTESTNMQZ256rmbk : X86::VPTESTMQZ256rmbk; case MVT::v16i32: return IsTestN ? X86::VPTESTNMDZrmbk : X86::VPTESTMDZrmbk; case MVT::v8i64: return IsTestN ? X86::VPTESTNMQZrmbk : X86::VPTESTMQZrmbk; } } switch (TestVT.SimpleTy) { default: llvm_unreachable("Unexpected VT!"); case MVT::v16i8: return IsTestN ? X86::VPTESTNMBZ128rrk : X86::VPTESTMBZ128rrk; case MVT::v8i16: return IsTestN ? X86::VPTESTNMWZ128rrk : X86::VPTESTMWZ128rrk; case MVT::v4i32: return IsTestN ? X86::VPTESTNMDZ128rrk : X86::VPTESTMDZ128rrk; case MVT::v2i64: return IsTestN ? X86::VPTESTNMQZ128rrk : X86::VPTESTMQZ128rrk; case MVT::v32i8: return IsTestN ? X86::VPTESTNMBZ256rrk : X86::VPTESTMBZ256rrk; case MVT::v16i16: return IsTestN ? X86::VPTESTNMWZ256rrk : X86::VPTESTMWZ256rrk; case MVT::v8i32: return IsTestN ? X86::VPTESTNMDZ256rrk : X86::VPTESTMDZ256rrk; case MVT::v4i64: return IsTestN ? X86::VPTESTNMQZ256rrk : X86::VPTESTMQZ256rrk; case MVT::v64i8: return IsTestN ? X86::VPTESTNMBZrrk : X86::VPTESTMBZrrk; case MVT::v32i16: return IsTestN ? X86::VPTESTNMWZrrk : X86::VPTESTMWZrrk; case MVT::v16i32: return IsTestN ? X86::VPTESTNMDZrrk : X86::VPTESTMDZrrk; case MVT::v8i64: return IsTestN ? X86::VPTESTNMQZrrk : X86::VPTESTMQZrrk; } } if (FoldedLoad) { switch (TestVT.SimpleTy) { default: llvm_unreachable("Unexpected VT!"); case MVT::v16i8: return IsTestN ? X86::VPTESTNMBZ128rm : X86::VPTESTMBZ128rm; case MVT::v8i16: return IsTestN ? X86::VPTESTNMWZ128rm : X86::VPTESTMWZ128rm; case MVT::v4i32: return IsTestN ? X86::VPTESTNMDZ128rm : X86::VPTESTMDZ128rm; case MVT::v2i64: return IsTestN ? X86::VPTESTNMQZ128rm : X86::VPTESTMQZ128rm; case MVT::v32i8: return IsTestN ? X86::VPTESTNMBZ256rm : X86::VPTESTMBZ256rm; case MVT::v16i16: return IsTestN ? X86::VPTESTNMWZ256rm : X86::VPTESTMWZ256rm; case MVT::v8i32: return IsTestN ? X86::VPTESTNMDZ256rm : X86::VPTESTMDZ256rm; case MVT::v4i64: return IsTestN ? X86::VPTESTNMQZ256rm : X86::VPTESTMQZ256rm; case MVT::v64i8: return IsTestN ? X86::VPTESTNMBZrm : X86::VPTESTMBZrm; case MVT::v32i16: return IsTestN ? X86::VPTESTNMWZrm : X86::VPTESTMWZrm; case MVT::v16i32: return IsTestN ? X86::VPTESTNMDZrm : X86::VPTESTMDZrm; case MVT::v8i64: return IsTestN ? X86::VPTESTNMQZrm : X86::VPTESTMQZrm; } } if (FoldedBCast) { switch (TestVT.SimpleTy) { default: llvm_unreachable("Unexpected VT!"); case MVT::v4i32: return IsTestN ? X86::VPTESTNMDZ128rmb : X86::VPTESTMDZ128rmb; case MVT::v2i64: return IsTestN ? X86::VPTESTNMQZ128rmb : X86::VPTESTMQZ128rmb; case MVT::v8i32: return IsTestN ? X86::VPTESTNMDZ256rmb : X86::VPTESTMDZ256rmb; case MVT::v4i64: return IsTestN ? X86::VPTESTNMQZ256rmb : X86::VPTESTMQZ256rmb; case MVT::v16i32: return IsTestN ? X86::VPTESTNMDZrmb : X86::VPTESTMDZrmb; case MVT::v8i64: return IsTestN ? X86::VPTESTNMQZrmb : X86::VPTESTMQZrmb; } } switch (TestVT.SimpleTy) { default: llvm_unreachable("Unexpected VT!"); case MVT::v16i8: return IsTestN ? X86::VPTESTNMBZ128rr : X86::VPTESTMBZ128rr; case MVT::v8i16: return IsTestN ? X86::VPTESTNMWZ128rr : X86::VPTESTMWZ128rr; case MVT::v4i32: return IsTestN ? X86::VPTESTNMDZ128rr : X86::VPTESTMDZ128rr; case MVT::v2i64: return IsTestN ? X86::VPTESTNMQZ128rr : X86::VPTESTMQZ128rr; case MVT::v32i8: return IsTestN ? X86::VPTESTNMBZ256rr : X86::VPTESTMBZ256rr; case MVT::v16i16: return IsTestN ? X86::VPTESTNMWZ256rr : X86::VPTESTMWZ256rr; case MVT::v8i32: return IsTestN ? X86::VPTESTNMDZ256rr : X86::VPTESTMDZ256rr; case MVT::v4i64: return IsTestN ? X86::VPTESTNMQZ256rr : X86::VPTESTMQZ256rr; case MVT::v64i8: return IsTestN ? X86::VPTESTNMBZrr : X86::VPTESTMBZrr; case MVT::v32i16: return IsTestN ? X86::VPTESTNMWZrr : X86::VPTESTMWZrr; case MVT::v16i32: return IsTestN ? X86::VPTESTNMDZrr : X86::VPTESTMDZrr; case MVT::v8i64: return IsTestN ? X86::VPTESTNMQZrr : X86::VPTESTMQZrr; } } // Try to create VPTESTM instruction. If InMask is not null, it will be used // to form a masked operation. bool X86DAGToDAGISel::tryVPTESTM(SDNode *Root, SDValue Setcc, SDValue InMask) { assert(Subtarget->hasAVX512() && "Expected AVX512!"); assert(Setcc.getSimpleValueType().getVectorElementType() == MVT::i1 && "Unexpected VT!"); // Look for equal and not equal compares. ISD::CondCode CC = cast<CondCodeSDNode>(Setcc.getOperand(2))->get(); if (CC != ISD::SETEQ && CC != ISD::SETNE) return false; SDValue SetccOp0 = Setcc.getOperand(0); SDValue SetccOp1 = Setcc.getOperand(1); // Canonicalize the all zero vector to the RHS. if (ISD::isBuildVectorAllZeros(SetccOp0.getNode())) std::swap(SetccOp0, SetccOp1); // See if we're comparing against zero. if (!ISD::isBuildVectorAllZeros(SetccOp1.getNode())) return false; SDValue N0 = SetccOp0; MVT CmpVT = N0.getSimpleValueType(); MVT CmpSVT = CmpVT.getVectorElementType(); // Start with both operands the same. We'll try to refine this. SDValue Src0 = N0; SDValue Src1 = N0; { // Look through single use bitcasts. SDValue N0Temp = N0; if (N0Temp.getOpcode() == ISD::BITCAST && N0Temp.hasOneUse()) N0Temp = N0.getOperand(0); // Look for single use AND. if (N0Temp.getOpcode() == ISD::AND && N0Temp.hasOneUse()) { Src0 = N0Temp.getOperand(0); Src1 = N0Temp.getOperand(1); } } // Without VLX we need to widen the load. bool Widen = !Subtarget->hasVLX() && !CmpVT.is512BitVector(); // We can only fold loads if the sources are unique. bool CanFoldLoads = Src0 != Src1; // Try to fold loads unless we need to widen. bool FoldedLoad = false; SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Load; if (!Widen && CanFoldLoads) { Load = Src1; FoldedLoad = tryFoldLoad(Root, N0.getNode(), Load, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4); if (!FoldedLoad) { // And is computative. Load = Src0; FoldedLoad = tryFoldLoad(Root, N0.getNode(), Load, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4); if (FoldedLoad) std::swap(Src0, Src1); } } auto findBroadcastedOp = [](SDValue Src, MVT CmpSVT, SDNode *&Parent) { // Look through single use bitcasts. if (Src.getOpcode() == ISD::BITCAST && Src.hasOneUse()) { Parent = Src.getNode(); Src = Src.getOperand(0); } if (Src.getOpcode() == X86ISD::VBROADCAST_LOAD && Src.hasOneUse()) { auto *MemIntr = cast<MemIntrinsicSDNode>(Src); if (MemIntr->getMemoryVT().getSizeInBits() == CmpSVT.getSizeInBits()) return Src; } return SDValue(); }; // If we didn't fold a load, try to match broadcast. No widening limitation // for this. But only 32 and 64 bit types are supported. bool FoldedBCast = false; if (!FoldedLoad && CanFoldLoads && (CmpSVT == MVT::i32 || CmpSVT == MVT::i64)) { SDNode *ParentNode = N0.getNode(); if ((Load = findBroadcastedOp(Src1, CmpSVT, ParentNode))) { FoldedBCast = tryFoldBroadcast(Root, ParentNode, Load, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4); } // Try the other operand. if (!FoldedBCast) { SDNode *ParentNode = N0.getNode(); if ((Load = findBroadcastedOp(Src0, CmpSVT, ParentNode))) { FoldedBCast = tryFoldBroadcast(Root, ParentNode, Load, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4); if (FoldedBCast) std::swap(Src0, Src1); } } } auto getMaskRC = [](MVT MaskVT) { switch (MaskVT.SimpleTy) { default: llvm_unreachable("Unexpected VT!"); case MVT::v2i1: return X86::VK2RegClassID; case MVT::v4i1: return X86::VK4RegClassID; case MVT::v8i1: return X86::VK8RegClassID; case MVT::v16i1: return X86::VK16RegClassID; case MVT::v32i1: return X86::VK32RegClassID; case MVT::v64i1: return X86::VK64RegClassID; } }; bool IsMasked = InMask.getNode() != nullptr; SDLoc dl(Root); MVT ResVT = Setcc.getSimpleValueType(); MVT MaskVT = ResVT; if (Widen) { // Widen the inputs using insert_subreg or copy_to_regclass. unsigned Scale = CmpVT.is128BitVector() ? 4 : 2; unsigned SubReg = CmpVT.is128BitVector() ? X86::sub_xmm : X86::sub_ymm; unsigned NumElts = CmpVT.getVectorNumElements() * Scale; CmpVT = MVT::getVectorVT(CmpSVT, NumElts); MaskVT = MVT::getVectorVT(MVT::i1, NumElts); SDValue ImplDef = SDValue(CurDAG->getMachineNode(X86::IMPLICIT_DEF, dl, CmpVT), 0); Src0 = CurDAG->getTargetInsertSubreg(SubReg, dl, CmpVT, ImplDef, Src0); assert(!FoldedLoad && "Shouldn't have folded the load"); if (!FoldedBCast) Src1 = CurDAG->getTargetInsertSubreg(SubReg, dl, CmpVT, ImplDef, Src1); if (IsMasked) { // Widen the mask. unsigned RegClass = getMaskRC(MaskVT); SDValue RC = CurDAG->getTargetConstant(RegClass, dl, MVT::i32); InMask = SDValue(CurDAG->getMachineNode(TargetOpcode::COPY_TO_REGCLASS, dl, MaskVT, InMask, RC), 0); } } bool IsTestN = CC == ISD::SETEQ; unsigned Opc = getVPTESTMOpc(CmpVT, IsTestN, FoldedLoad, FoldedBCast, IsMasked); MachineSDNode *CNode; if (FoldedLoad || FoldedBCast) { SDVTList VTs = CurDAG->getVTList(MaskVT, MVT::Other); if (IsMasked) { SDValue Ops[] = { InMask, Src0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Load.getOperand(0) }; CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops); } else { SDValue Ops[] = { Src0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Load.getOperand(0) }; CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops); } // Update the chain. ReplaceUses(Load.getValue(1), SDValue(CNode, 1)); // Record the mem-refs CurDAG->setNodeMemRefs(CNode, {cast<MemSDNode>(Load)->getMemOperand()}); } else { if (IsMasked) CNode = CurDAG->getMachineNode(Opc, dl, MaskVT, InMask, Src0, Src1); else CNode = CurDAG->getMachineNode(Opc, dl, MaskVT, Src0, Src1); } // If we widened, we need to shrink the mask VT. if (Widen) { unsigned RegClass = getMaskRC(ResVT); SDValue RC = CurDAG->getTargetConstant(RegClass, dl, MVT::i32); CNode = CurDAG->getMachineNode(TargetOpcode::COPY_TO_REGCLASS, dl, ResVT, SDValue(CNode, 0), RC); } ReplaceUses(SDValue(Root, 0), SDValue(CNode, 0)); CurDAG->RemoveDeadNode(Root); return true; } // Try to match the bitselect pattern (or (and A, B), (andn A, C)). Turn it // into vpternlog. bool X86DAGToDAGISel::tryMatchBitSelect(SDNode *N) { assert(N->getOpcode() == ISD::OR && "Unexpected opcode!"); MVT NVT = N->getSimpleValueType(0); // Make sure we support VPTERNLOG. if (!NVT.isVector() || !Subtarget->hasAVX512()) return false; // We need VLX for 128/256-bit. if (!(Subtarget->hasVLX() || NVT.is512BitVector())) return false; SDValue N0 = N->getOperand(0); SDValue N1 = N->getOperand(1); // Canonicalize AND to LHS. if (N1.getOpcode() == ISD::AND) std::swap(N0, N1); if (N0.getOpcode() != ISD::AND || N1.getOpcode() != X86ISD::ANDNP || !N0.hasOneUse() || !N1.hasOneUse()) return false; // ANDN is not commutable, use it to pick down A and C. SDValue A = N1.getOperand(0); SDValue C = N1.getOperand(1); // AND is commutable, if one operand matches A, the other operand is B. // Otherwise this isn't a match. SDValue B; if (N0.getOperand(0) == A) B = N0.getOperand(1); else if (N0.getOperand(1) == A) B = N0.getOperand(0); else return false; SDLoc dl(N); SDValue Imm = CurDAG->getTargetConstant(0xCA, dl, MVT::i8); SDValue Ternlog = CurDAG->getNode(X86ISD::VPTERNLOG, dl, NVT, A, B, C, Imm); ReplaceNode(N, Ternlog.getNode()); SelectCode(Ternlog.getNode()); return true; } void X86DAGToDAGISel::Select(SDNode *Node) { MVT NVT = Node->getSimpleValueType(0); unsigned Opcode = Node->getOpcode(); SDLoc dl(Node); if (Node->isMachineOpcode()) { LLVM_DEBUG(dbgs() << "== "; Node->dump(CurDAG); dbgs() << '\n'); Node->setNodeId(-1); return; // Already selected. } switch (Opcode) { default: break; case ISD::INTRINSIC_VOID: { unsigned IntNo = Node->getConstantOperandVal(1); switch (IntNo) { default: break; case Intrinsic::x86_sse3_monitor: case Intrinsic::x86_monitorx: case Intrinsic::x86_clzero: { bool Use64BitPtr = Node->getOperand(2).getValueType() == MVT::i64; unsigned Opc = 0; switch (IntNo) { default: llvm_unreachable("Unexpected intrinsic!"); case Intrinsic::x86_sse3_monitor: if (!Subtarget->hasSSE3()) break; Opc = Use64BitPtr ? X86::MONITOR64rrr : X86::MONITOR32rrr; break; case Intrinsic::x86_monitorx: if (!Subtarget->hasMWAITX()) break; Opc = Use64BitPtr ? X86::MONITORX64rrr : X86::MONITORX32rrr; break; case Intrinsic::x86_clzero: if (!Subtarget->hasCLZERO()) break; Opc = Use64BitPtr ? X86::CLZERO64r : X86::CLZERO32r; break; } if (Opc) { unsigned PtrReg = Use64BitPtr ? X86::RAX : X86::EAX; SDValue Chain = CurDAG->getCopyToReg(Node->getOperand(0), dl, PtrReg, Node->getOperand(2), SDValue()); SDValue InFlag = Chain.getValue(1); if (IntNo == Intrinsic::x86_sse3_monitor || IntNo == Intrinsic::x86_monitorx) { // Copy the other two operands to ECX and EDX. Chain = CurDAG->getCopyToReg(Chain, dl, X86::ECX, Node->getOperand(3), InFlag); InFlag = Chain.getValue(1); Chain = CurDAG->getCopyToReg(Chain, dl, X86::EDX, Node->getOperand(4), InFlag); InFlag = Chain.getValue(1); } MachineSDNode *CNode = CurDAG->getMachineNode(Opc, dl, MVT::Other, { Chain, InFlag}); ReplaceNode(Node, CNode); return; } break; } } break; } case ISD::BRIND: { if (Subtarget->isTargetNaCl()) // NaCl has its own pass where jmp %r32 are converted to jmp %r64. We // leave the instruction alone. break; if (Subtarget->isTarget64BitILP32()) { // Converts a 32-bit register to a 64-bit, zero-extended version of // it. This is needed because x86-64 can do many things, but jmp %r32 // ain't one of them. const SDValue &Target = Node->getOperand(1); assert(Target.getSimpleValueType() == llvm::MVT::i32); SDValue ZextTarget = CurDAG->getZExtOrTrunc(Target, dl, EVT(MVT::i64)); SDValue Brind = CurDAG->getNode(ISD::BRIND, dl, MVT::Other, Node->getOperand(0), ZextTarget); ReplaceNode(Node, Brind.getNode()); SelectCode(ZextTarget.getNode()); SelectCode(Brind.getNode()); return; } break; } case X86ISD::GlobalBaseReg: ReplaceNode(Node, getGlobalBaseReg()); return; case ISD::BITCAST: // Just drop all 128/256/512-bit bitcasts. if (NVT.is512BitVector() || NVT.is256BitVector() || NVT.is128BitVector() || NVT == MVT::f128) { ReplaceUses(SDValue(Node, 0), Node->getOperand(0)); CurDAG->RemoveDeadNode(Node); return; } break; case ISD::VSELECT: { // Replace VSELECT with non-mask conditions with with BLENDV. if (Node->getOperand(0).getValueType().getVectorElementType() == MVT::i1) break; assert(Subtarget->hasSSE41() && "Expected SSE4.1 support!"); SDValue Blendv = CurDAG->getNode( X86ISD::BLENDV, SDLoc(Node), Node->getValueType(0), Node->getOperand(0), Node->getOperand(1), Node->getOperand(2)); ReplaceNode(Node, Blendv.getNode()); SelectCode(Blendv.getNode()); // We already called ReplaceUses. return; } case ISD::SRL: if (matchBitExtract(Node)) return; LLVM_FALLTHROUGH; case ISD::SRA: case ISD::SHL: if (tryShiftAmountMod(Node)) return; break; case ISD::AND: if (NVT.isVector() && NVT.getVectorElementType() == MVT::i1) { // Try to form a masked VPTESTM. Operands can be in either order. SDValue N0 = Node->getOperand(0); SDValue N1 = Node->getOperand(1); if (N0.getOpcode() == ISD::SETCC && N0.hasOneUse() && tryVPTESTM(Node, N0, N1)) return; if (N1.getOpcode() == ISD::SETCC && N1.hasOneUse() && tryVPTESTM(Node, N1, N0)) return; } if (MachineSDNode *NewNode = matchBEXTRFromAndImm(Node)) { ReplaceUses(SDValue(Node, 0), SDValue(NewNode, 0)); CurDAG->RemoveDeadNode(Node); return; } if (matchBitExtract(Node)) return; if (AndImmShrink && shrinkAndImmediate(Node)) return; LLVM_FALLTHROUGH; case ISD::OR: case ISD::XOR: if (tryShrinkShlLogicImm(Node)) return; if (Opcode == ISD::OR && tryMatchBitSelect(Node)) return; LLVM_FALLTHROUGH; case ISD::ADD: case ISD::SUB: { // Try to avoid folding immediates with multiple uses for optsize. // This code tries to select to register form directly to avoid going // through the isel table which might fold the immediate. We can't change // the patterns on the add/sub/and/or/xor with immediate paterns in the // tablegen files to check immediate use count without making the patterns // unavailable to the fast-isel table. if (!OptForSize) break; // Only handle i8/i16/i32/i64. if (NVT != MVT::i8 && NVT != MVT::i16 && NVT != MVT::i32 && NVT != MVT::i64) break; SDValue N0 = Node->getOperand(0); SDValue N1 = Node->getOperand(1); ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(N1); if (!Cst) break; int64_t Val = Cst->getSExtValue(); // Make sure its an immediate that is considered foldable. // FIXME: Handle unsigned 32 bit immediates for 64-bit AND. if (!isInt<8>(Val) && !isInt<32>(Val)) break; // If this can match to INC/DEC, let it go. if (Opcode == ISD::ADD && (Val == 1 || Val == -1)) break; // Check if we should avoid folding this immediate. if (!shouldAvoidImmediateInstFormsForSize(N1.getNode())) break; // We should not fold the immediate. So we need a register form instead. unsigned ROpc, MOpc; switch (NVT.SimpleTy) { default: llvm_unreachable("Unexpected VT!"); case MVT::i8: switch (Opcode) { default: llvm_unreachable("Unexpected opcode!"); case ISD::ADD: ROpc = X86::ADD8rr; MOpc = X86::ADD8rm; break; case ISD::SUB: ROpc = X86::SUB8rr; MOpc = X86::SUB8rm; break; case ISD::AND: ROpc = X86::AND8rr; MOpc = X86::AND8rm; break; case ISD::OR: ROpc = X86::OR8rr; MOpc = X86::OR8rm; break; case ISD::XOR: ROpc = X86::XOR8rr; MOpc = X86::XOR8rm; break; } break; case MVT::i16: switch (Opcode) { default: llvm_unreachable("Unexpected opcode!"); case ISD::ADD: ROpc = X86::ADD16rr; MOpc = X86::ADD16rm; break; case ISD::SUB: ROpc = X86::SUB16rr; MOpc = X86::SUB16rm; break; case ISD::AND: ROpc = X86::AND16rr; MOpc = X86::AND16rm; break; case ISD::OR: ROpc = X86::OR16rr; MOpc = X86::OR16rm; break; case ISD::XOR: ROpc = X86::XOR16rr; MOpc = X86::XOR16rm; break; } break; case MVT::i32: switch (Opcode) { default: llvm_unreachable("Unexpected opcode!"); case ISD::ADD: ROpc = X86::ADD32rr; MOpc = X86::ADD32rm; break; case ISD::SUB: ROpc = X86::SUB32rr; MOpc = X86::SUB32rm; break; case ISD::AND: ROpc = X86::AND32rr; MOpc = X86::AND32rm; break; case ISD::OR: ROpc = X86::OR32rr; MOpc = X86::OR32rm; break; case ISD::XOR: ROpc = X86::XOR32rr; MOpc = X86::XOR32rm; break; } break; case MVT::i64: switch (Opcode) { default: llvm_unreachable("Unexpected opcode!"); case ISD::ADD: ROpc = X86::ADD64rr; MOpc = X86::ADD64rm; break; case ISD::SUB: ROpc = X86::SUB64rr; MOpc = X86::SUB64rm; break; case ISD::AND: ROpc = X86::AND64rr; MOpc = X86::AND64rm; break; case ISD::OR: ROpc = X86::OR64rr; MOpc = X86::OR64rm; break; case ISD::XOR: ROpc = X86::XOR64rr; MOpc = X86::XOR64rm; break; } break; } // Ok this is a AND/OR/XOR/ADD/SUB with constant. // If this is a not a subtract, we can still try to fold a load. if (Opcode != ISD::SUB) { SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4; if (tryFoldLoad(Node, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) { SDValue Ops[] = { N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N0.getOperand(0) }; SDVTList VTs = CurDAG->getVTList(NVT, MVT::i32, MVT::Other); MachineSDNode *CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops); // Update the chain. ReplaceUses(N0.getValue(1), SDValue(CNode, 2)); // Record the mem-refs CurDAG->setNodeMemRefs(CNode, {cast<LoadSDNode>(N0)->getMemOperand()}); ReplaceUses(SDValue(Node, 0), SDValue(CNode, 0)); CurDAG->RemoveDeadNode(Node); return; } } CurDAG->SelectNodeTo(Node, ROpc, NVT, MVT::i32, N0, N1); return; } case X86ISD::SMUL: // i16/i32/i64 are handled with isel patterns. if (NVT != MVT::i8) break; LLVM_FALLTHROUGH; case X86ISD::UMUL: { SDValue N0 = Node->getOperand(0); SDValue N1 = Node->getOperand(1); unsigned LoReg, ROpc, MOpc; switch (NVT.SimpleTy) { default: llvm_unreachable("Unsupported VT!"); case MVT::i8: LoReg = X86::AL; ROpc = Opcode == X86ISD::SMUL ? X86::IMUL8r : X86::MUL8r; MOpc = Opcode == X86ISD::SMUL ? X86::IMUL8m : X86::MUL8m; break; case MVT::i16: LoReg = X86::AX; ROpc = X86::MUL16r; MOpc = X86::MUL16m; break; case MVT::i32: LoReg = X86::EAX; ROpc = X86::MUL32r; MOpc = X86::MUL32m; break; case MVT::i64: LoReg = X86::RAX; ROpc = X86::MUL64r; MOpc = X86::MUL64m; break; } SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4; bool FoldedLoad = tryFoldLoad(Node, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4); // Multiply is commmutative. if (!FoldedLoad) { FoldedLoad = tryFoldLoad(Node, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4); if (FoldedLoad) std::swap(N0, N1); } SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, LoReg, N0, SDValue()).getValue(1); MachineSDNode *CNode; if (FoldedLoad) { // i16/i32/i64 use an instruction that produces a low and high result even // though only the low result is used. SDVTList VTs; if (NVT == MVT::i8) VTs = CurDAG->getVTList(NVT, MVT::i32, MVT::Other); else VTs = CurDAG->getVTList(NVT, NVT, MVT::i32, MVT::Other); SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N1.getOperand(0), InFlag }; CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops); // Update the chain. ReplaceUses(N1.getValue(1), SDValue(CNode, NVT == MVT::i8 ? 2 : 3)); // Record the mem-refs CurDAG->setNodeMemRefs(CNode, {cast<LoadSDNode>(N1)->getMemOperand()}); } else { // i16/i32/i64 use an instruction that produces a low and high result even // though only the low result is used. SDVTList VTs; if (NVT == MVT::i8) VTs = CurDAG->getVTList(NVT, MVT::i32); else VTs = CurDAG->getVTList(NVT, NVT, MVT::i32); CNode = CurDAG->getMachineNode(ROpc, dl, VTs, {N1, InFlag}); } ReplaceUses(SDValue(Node, 0), SDValue(CNode, 0)); ReplaceUses(SDValue(Node, 1), SDValue(CNode, NVT == MVT::i8 ? 1 : 2)); CurDAG->RemoveDeadNode(Node); return; } case ISD::SMUL_LOHI: case ISD::UMUL_LOHI: { SDValue N0 = Node->getOperand(0); SDValue N1 = Node->getOperand(1); unsigned Opc, MOpc; unsigned LoReg, HiReg; bool IsSigned = Opcode == ISD::SMUL_LOHI; switch (NVT.SimpleTy) { default: llvm_unreachable("Unsupported VT!"); case MVT::i32: Opc = IsSigned ? X86::IMUL32r : X86::MUL32r; MOpc = IsSigned ? X86::IMUL32m : X86::MUL32m; LoReg = X86::EAX; HiReg = X86::EDX; break; case MVT::i64: Opc = IsSigned ? X86::IMUL64r : X86::MUL64r; MOpc = IsSigned ? X86::IMUL64m : X86::MUL64m; LoReg = X86::RAX; HiReg = X86::RDX; break; } SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4; bool foldedLoad = tryFoldLoad(Node, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4); // Multiply is commmutative. if (!foldedLoad) { foldedLoad = tryFoldLoad(Node, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4); if (foldedLoad) std::swap(N0, N1); } SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, LoReg, N0, SDValue()).getValue(1); if (foldedLoad) { SDValue Chain; MachineSDNode *CNode = nullptr; SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N1.getOperand(0), InFlag }; SDVTList VTs = CurDAG->getVTList(MVT::Other, MVT::Glue); CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops); Chain = SDValue(CNode, 0); InFlag = SDValue(CNode, 1); // Update the chain. ReplaceUses(N1.getValue(1), Chain); // Record the mem-refs CurDAG->setNodeMemRefs(CNode, {cast<LoadSDNode>(N1)->getMemOperand()}); } else { SDValue Ops[] = { N1, InFlag }; SDVTList VTs = CurDAG->getVTList(MVT::Glue); SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops); InFlag = SDValue(CNode, 0); } // Copy the low half of the result, if it is needed. if (!SDValue(Node, 0).use_empty()) { assert(LoReg && "Register for low half is not defined!"); SDValue ResLo = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl, LoReg, NVT, InFlag); InFlag = ResLo.getValue(2); ReplaceUses(SDValue(Node, 0), ResLo); LLVM_DEBUG(dbgs() << "=> "; ResLo.getNode()->dump(CurDAG); dbgs() << '\n'); } // Copy the high half of the result, if it is needed. if (!SDValue(Node, 1).use_empty()) { assert(HiReg && "Register for high half is not defined!"); SDValue ResHi = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl, HiReg, NVT, InFlag); InFlag = ResHi.getValue(2); ReplaceUses(SDValue(Node, 1), ResHi); LLVM_DEBUG(dbgs() << "=> "; ResHi.getNode()->dump(CurDAG); dbgs() << '\n'); } CurDAG->RemoveDeadNode(Node); return; } case ISD::SDIVREM: case ISD::UDIVREM: { SDValue N0 = Node->getOperand(0); SDValue N1 = Node->getOperand(1); unsigned ROpc, MOpc; bool isSigned = Opcode == ISD::SDIVREM; if (!isSigned) { switch (NVT.SimpleTy) { default: llvm_unreachable("Unsupported VT!"); case MVT::i8: ROpc = X86::DIV8r; MOpc = X86::DIV8m; break; case MVT::i16: ROpc = X86::DIV16r; MOpc = X86::DIV16m; break; case MVT::i32: ROpc = X86::DIV32r; MOpc = X86::DIV32m; break; case MVT::i64: ROpc = X86::DIV64r; MOpc = X86::DIV64m; break; } } else { switch (NVT.SimpleTy) { default: llvm_unreachable("Unsupported VT!"); case MVT::i8: ROpc = X86::IDIV8r; MOpc = X86::IDIV8m; break; case MVT::i16: ROpc = X86::IDIV16r; MOpc = X86::IDIV16m; break; case MVT::i32: ROpc = X86::IDIV32r; MOpc = X86::IDIV32m; break; case MVT::i64: ROpc = X86::IDIV64r; MOpc = X86::IDIV64m; break; } } unsigned LoReg, HiReg, ClrReg; unsigned SExtOpcode; switch (NVT.SimpleTy) { default: llvm_unreachable("Unsupported VT!"); case MVT::i8: LoReg = X86::AL; ClrReg = HiReg = X86::AH; SExtOpcode = 0; // Not used. break; case MVT::i16: LoReg = X86::AX; HiReg = X86::DX; ClrReg = X86::DX; SExtOpcode = X86::CWD; break; case MVT::i32: LoReg = X86::EAX; ClrReg = HiReg = X86::EDX; SExtOpcode = X86::CDQ; break; case MVT::i64: LoReg = X86::RAX; ClrReg = HiReg = X86::RDX; SExtOpcode = X86::CQO; break; } SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4; bool foldedLoad = tryFoldLoad(Node, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4); bool signBitIsZero = CurDAG->SignBitIsZero(N0); SDValue InFlag; if (NVT == MVT::i8) { // Special case for div8, just use a move with zero extension to AX to // clear the upper 8 bits (AH). SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Chain; MachineSDNode *Move; if (tryFoldLoad(Node, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) { SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N0.getOperand(0) }; unsigned Opc = (isSigned && !signBitIsZero) ? X86::MOVSX16rm8 : X86::MOVZX16rm8; Move = CurDAG->getMachineNode(Opc, dl, MVT::i16, MVT::Other, Ops); Chain = SDValue(Move, 1); ReplaceUses(N0.getValue(1), Chain); // Record the mem-refs CurDAG->setNodeMemRefs(Move, {cast<LoadSDNode>(N0)->getMemOperand()}); } else { unsigned Opc = (isSigned && !signBitIsZero) ? X86::MOVSX16rr8 : X86::MOVZX16rr8; Move = CurDAG->getMachineNode(Opc, dl, MVT::i16, N0); Chain = CurDAG->getEntryNode(); } Chain = CurDAG->getCopyToReg(Chain, dl, X86::AX, SDValue(Move, 0), SDValue()); InFlag = Chain.getValue(1); } else { InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, LoReg, N0, SDValue()).getValue(1); if (isSigned && !signBitIsZero) { // Sign extend the low part into the high part. InFlag = SDValue(CurDAG->getMachineNode(SExtOpcode, dl, MVT::Glue, InFlag),0); } else { // Zero out the high part, effectively zero extending the input. SDVTList VTs = CurDAG->getVTList(MVT::i32, MVT::i32); SDValue ClrNode = SDValue(CurDAG->getMachineNode(X86::MOV32r0, dl, VTs, None), 0); switch (NVT.SimpleTy) { case MVT::i16: ClrNode = SDValue(CurDAG->getMachineNode( TargetOpcode::EXTRACT_SUBREG, dl, MVT::i16, ClrNode, CurDAG->getTargetConstant(X86::sub_16bit, dl, MVT::i32)), 0); break; case MVT::i32: break; case MVT::i64: ClrNode = SDValue(CurDAG->getMachineNode( TargetOpcode::SUBREG_TO_REG, dl, MVT::i64, CurDAG->getTargetConstant(0, dl, MVT::i64), ClrNode, CurDAG->getTargetConstant(X86::sub_32bit, dl, MVT::i32)), 0); break; default: llvm_unreachable("Unexpected division source"); } InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, ClrReg, ClrNode, InFlag).getValue(1); } } if (foldedLoad) { SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N1.getOperand(0), InFlag }; MachineSDNode *CNode = CurDAG->getMachineNode(MOpc, dl, MVT::Other, MVT::Glue, Ops); InFlag = SDValue(CNode, 1); // Update the chain. ReplaceUses(N1.getValue(1), SDValue(CNode, 0)); // Record the mem-refs CurDAG->setNodeMemRefs(CNode, {cast<LoadSDNode>(N1)->getMemOperand()}); } else { InFlag = SDValue(CurDAG->getMachineNode(ROpc, dl, MVT::Glue, N1, InFlag), 0); } // Prevent use of AH in a REX instruction by explicitly copying it to // an ABCD_L register. // // The current assumption of the register allocator is that isel // won't generate explicit references to the GR8_ABCD_H registers. If // the allocator and/or the backend get enhanced to be more robust in // that regard, this can be, and should be, removed. if (HiReg == X86::AH && !SDValue(Node, 1).use_empty()) { SDValue AHCopy = CurDAG->getRegister(X86::AH, MVT::i8); unsigned AHExtOpcode = isSigned ? X86::MOVSX32rr8_NOREX : X86::MOVZX32rr8_NOREX; SDNode *RNode = CurDAG->getMachineNode(AHExtOpcode, dl, MVT::i32, MVT::Glue, AHCopy, InFlag); SDValue Result(RNode, 0); InFlag = SDValue(RNode, 1); Result = CurDAG->getTargetExtractSubreg(X86::sub_8bit, dl, MVT::i8, Result); ReplaceUses(SDValue(Node, 1), Result); LLVM_DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG); dbgs() << '\n'); } // Copy the division (low) result, if it is needed. if (!SDValue(Node, 0).use_empty()) { SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl, LoReg, NVT, InFlag); InFlag = Result.getValue(2); ReplaceUses(SDValue(Node, 0), Result); LLVM_DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG); dbgs() << '\n'); } // Copy the remainder (high) result, if it is needed. if (!SDValue(Node, 1).use_empty()) { SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl, HiReg, NVT, InFlag); InFlag = Result.getValue(2); ReplaceUses(SDValue(Node, 1), Result); LLVM_DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG); dbgs() << '\n'); } CurDAG->RemoveDeadNode(Node); return; } case X86ISD::FCMP: case X86ISD::STRICT_FCMP: case X86ISD::STRICT_FCMPS: { bool IsStrictCmp = Node->getOpcode() == X86ISD::STRICT_FCMP || Node->getOpcode() == X86ISD::STRICT_FCMPS; SDValue N0 = Node->getOperand(IsStrictCmp ? 1 : 0); SDValue N1 = Node->getOperand(IsStrictCmp ? 2 : 1); // Save the original VT of the compare. MVT CmpVT = N0.getSimpleValueType(); // Floating point needs special handling if we don't have FCOMI. if (Subtarget->hasCMov()) break; bool IsSignaling = Node->getOpcode() == X86ISD::STRICT_FCMPS; unsigned Opc; switch (CmpVT.SimpleTy) { default: llvm_unreachable("Unexpected type!"); case MVT::f32: Opc = IsSignaling ? X86::COM_Fpr32 : X86::UCOM_Fpr32; break; case MVT::f64: Opc = IsSignaling ? X86::COM_Fpr64 : X86::UCOM_Fpr64; break; case MVT::f80: Opc = IsSignaling ? X86::COM_Fpr80 : X86::UCOM_Fpr80; break; } SDValue Cmp; SDValue Chain = IsStrictCmp ? Node->getOperand(0) : CurDAG->getEntryNode(); if (IsStrictCmp) { SDVTList VTs = CurDAG->getVTList(MVT::i16, MVT::Other); Cmp = SDValue(CurDAG->getMachineNode(Opc, dl, VTs, {N0, N1, Chain}), 0); Chain = Cmp.getValue(1); } else { Cmp = SDValue(CurDAG->getMachineNode(Opc, dl, MVT::i16, N0, N1), 0); } // Move FPSW to AX. SDValue FPSW = CurDAG->getCopyToReg(Chain, dl, X86::FPSW, Cmp, SDValue()); Chain = FPSW; SDValue FNSTSW = SDValue(CurDAG->getMachineNode(X86::FNSTSW16r, dl, MVT::i16, FPSW, FPSW.getValue(1)), 0); // Extract upper 8-bits of AX. SDValue Extract = CurDAG->getTargetExtractSubreg(X86::sub_8bit_hi, dl, MVT::i8, FNSTSW); // Move AH into flags. // Some 64-bit targets lack SAHF support, but they do support FCOMI. assert(Subtarget->hasLAHFSAHF() && "Target doesn't support SAHF or FCOMI?"); SDValue AH = CurDAG->getCopyToReg(Chain, dl, X86::AH, Extract, SDValue()); Chain = AH; SDValue SAHF = SDValue( CurDAG->getMachineNode(X86::SAHF, dl, MVT::i32, AH.getValue(1)), 0); if (IsStrictCmp) ReplaceUses(SDValue(Node, 1), Chain); ReplaceUses(SDValue(Node, 0), SAHF); CurDAG->RemoveDeadNode(Node); return; } case X86ISD::CMP: { SDValue N0 = Node->getOperand(0); SDValue N1 = Node->getOperand(1); // Optimizations for TEST compares. if (!isNullConstant(N1)) break; // Save the original VT of the compare. MVT CmpVT = N0.getSimpleValueType(); // If we are comparing (and (shr X, C, Mask) with 0, emit a BEXTR followed // by a test instruction. The test should be removed later by // analyzeCompare if we are using only the zero flag. // TODO: Should we check the users and use the BEXTR flags directly? if (N0.getOpcode() == ISD::AND && N0.hasOneUse()) { if (MachineSDNode *NewNode = matchBEXTRFromAndImm(N0.getNode())) { unsigned TestOpc = CmpVT == MVT::i64 ? X86::TEST64rr : X86::TEST32rr; SDValue BEXTR = SDValue(NewNode, 0); NewNode = CurDAG->getMachineNode(TestOpc, dl, MVT::i32, BEXTR, BEXTR); ReplaceUses(SDValue(Node, 0), SDValue(NewNode, 0)); CurDAG->RemoveDeadNode(Node); return; } } // We can peek through truncates, but we need to be careful below. if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse()) N0 = N0.getOperand(0); // Look for (X86cmp (and $op, $imm), 0) and see if we can convert it to // use a smaller encoding. // Look past the truncate if CMP is the only use of it. if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() && N0.getValueType() != MVT::i8) { ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); if (!C) break; uint64_t Mask = C->getZExtValue(); // Check if we can replace AND+IMM64 with a shift. This is possible for // masks/ like 0xFF000000 or 0x00FFFFFF and if we care only about the zero // flag. if (CmpVT == MVT::i64 && !isInt<32>(Mask) && onlyUsesZeroFlag(SDValue(Node, 0))) { if (isMask_64(~Mask)) { unsigned TrailingZeros = countTrailingZeros(Mask); SDValue Imm = CurDAG->getTargetConstant(TrailingZeros, dl, MVT::i64); SDValue Shift = SDValue(CurDAG->getMachineNode(X86::SHR64ri, dl, MVT::i64, MVT::i32, N0.getOperand(0), Imm), 0); MachineSDNode *Test = CurDAG->getMachineNode(X86::TEST64rr, dl, MVT::i32, Shift, Shift); ReplaceNode(Node, Test); return; } if (isMask_64(Mask)) { unsigned LeadingZeros = countLeadingZeros(Mask); SDValue Imm = CurDAG->getTargetConstant(LeadingZeros, dl, MVT::i64); SDValue Shift = SDValue(CurDAG->getMachineNode(X86::SHL64ri, dl, MVT::i64, MVT::i32, N0.getOperand(0), Imm), 0); MachineSDNode *Test = CurDAG->getMachineNode(X86::TEST64rr, dl, MVT::i32, Shift, Shift); ReplaceNode(Node, Test); return; } } MVT VT; int SubRegOp; unsigned ROpc, MOpc; // For each of these checks we need to be careful if the sign flag is // being used. It is only safe to use the sign flag in two conditions, // either the sign bit in the shrunken mask is zero or the final test // size is equal to the original compare size. if (isUInt<8>(Mask) && (!(Mask & 0x80) || CmpVT == MVT::i8 || hasNoSignFlagUses(SDValue(Node, 0)))) { // For example, convert "testl %eax, $8" to "testb %al, $8" VT = MVT::i8; SubRegOp = X86::sub_8bit; ROpc = X86::TEST8ri; MOpc = X86::TEST8mi; } else if (OptForMinSize && isUInt<16>(Mask) && (!(Mask & 0x8000) || CmpVT == MVT::i16 || hasNoSignFlagUses(SDValue(Node, 0)))) { // For example, "testl %eax, $32776" to "testw %ax, $32776". // NOTE: We only want to form TESTW instructions if optimizing for // min size. Otherwise we only save one byte and possibly get a length // changing prefix penalty in the decoders. VT = MVT::i16; SubRegOp = X86::sub_16bit; ROpc = X86::TEST16ri; MOpc = X86::TEST16mi; } else if (isUInt<32>(Mask) && N0.getValueType() != MVT::i16 && ((!(Mask & 0x80000000) && // Without minsize 16-bit Cmps can get here so we need to // be sure we calculate the correct sign flag if needed. (CmpVT != MVT::i16 || !(Mask & 0x8000))) || CmpVT == MVT::i32 || hasNoSignFlagUses(SDValue(Node, 0)))) { // For example, "testq %rax, $268468232" to "testl %eax, $268468232". // NOTE: We only want to run that transform if N0 is 32 or 64 bits. // Otherwize, we find ourselves in a position where we have to do // promotion. If previous passes did not promote the and, we assume // they had a good reason not to and do not promote here. VT = MVT::i32; SubRegOp = X86::sub_32bit; ROpc = X86::TEST32ri; MOpc = X86::TEST32mi; } else { // No eligible transformation was found. break; } SDValue Imm = CurDAG->getTargetConstant(Mask, dl, VT); SDValue Reg = N0.getOperand(0); // Emit a testl or testw. MachineSDNode *NewNode; SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4; if (tryFoldLoad(Node, N0.getNode(), Reg, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) { if (auto *LoadN = dyn_cast<LoadSDNode>(N0.getOperand(0).getNode())) { if (!LoadN->isSimple()) { unsigned NumVolBits = LoadN->getValueType(0).getSizeInBits(); if (MOpc == X86::TEST8mi && NumVolBits != 8) break; else if (MOpc == X86::TEST16mi && NumVolBits != 16) break; else if (MOpc == X86::TEST32mi && NumVolBits != 32) break; } } SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Imm, Reg.getOperand(0) }; NewNode = CurDAG->getMachineNode(MOpc, dl, MVT::i32, MVT::Other, Ops); // Update the chain. ReplaceUses(Reg.getValue(1), SDValue(NewNode, 1)); // Record the mem-refs CurDAG->setNodeMemRefs(NewNode, {cast<LoadSDNode>(Reg)->getMemOperand()}); } else { // Extract the subregister if necessary. if (N0.getValueType() != VT) Reg = CurDAG->getTargetExtractSubreg(SubRegOp, dl, VT, Reg); NewNode = CurDAG->getMachineNode(ROpc, dl, MVT::i32, Reg, Imm); } // Replace CMP with TEST. ReplaceNode(Node, NewNode); return; } break; } case X86ISD::PCMPISTR: { if (!Subtarget->hasSSE42()) break; bool NeedIndex = !SDValue(Node, 0).use_empty(); bool NeedMask = !SDValue(Node, 1).use_empty(); // We can't fold a load if we are going to make two instructions. bool MayFoldLoad = !NeedIndex || !NeedMask; MachineSDNode *CNode; if (NeedMask) { unsigned ROpc = Subtarget->hasAVX() ? X86::VPCMPISTRMrr : X86::PCMPISTRMrr; unsigned MOpc = Subtarget->hasAVX() ? X86::VPCMPISTRMrm : X86::PCMPISTRMrm; CNode = emitPCMPISTR(ROpc, MOpc, MayFoldLoad, dl, MVT::v16i8, Node); ReplaceUses(SDValue(Node, 1), SDValue(CNode, 0)); } if (NeedIndex || !NeedMask) { unsigned ROpc = Subtarget->hasAVX() ? X86::VPCMPISTRIrr : X86::PCMPISTRIrr; unsigned MOpc = Subtarget->hasAVX() ? X86::VPCMPISTRIrm : X86::PCMPISTRIrm; CNode = emitPCMPISTR(ROpc, MOpc, MayFoldLoad, dl, MVT::i32, Node); ReplaceUses(SDValue(Node, 0), SDValue(CNode, 0)); } // Connect the flag usage to the last instruction created. ReplaceUses(SDValue(Node, 2), SDValue(CNode, 1)); CurDAG->RemoveDeadNode(Node); return; } case X86ISD::PCMPESTR: { if (!Subtarget->hasSSE42()) break; // Copy the two implicit register inputs. SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, X86::EAX, Node->getOperand(1), SDValue()).getValue(1); InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, X86::EDX, Node->getOperand(3), InFlag).getValue(1); bool NeedIndex = !SDValue(Node, 0).use_empty(); bool NeedMask = !SDValue(Node, 1).use_empty(); // We can't fold a load if we are going to make two instructions. bool MayFoldLoad = !NeedIndex || !NeedMask; MachineSDNode *CNode; if (NeedMask) { unsigned ROpc = Subtarget->hasAVX() ? X86::VPCMPESTRMrr : X86::PCMPESTRMrr; unsigned MOpc = Subtarget->hasAVX() ? X86::VPCMPESTRMrm : X86::PCMPESTRMrm; CNode = emitPCMPESTR(ROpc, MOpc, MayFoldLoad, dl, MVT::v16i8, Node, InFlag); ReplaceUses(SDValue(Node, 1), SDValue(CNode, 0)); } if (NeedIndex || !NeedMask) { unsigned ROpc = Subtarget->hasAVX() ? X86::VPCMPESTRIrr : X86::PCMPESTRIrr; unsigned MOpc = Subtarget->hasAVX() ? X86::VPCMPESTRIrm : X86::PCMPESTRIrm; CNode = emitPCMPESTR(ROpc, MOpc, MayFoldLoad, dl, MVT::i32, Node, InFlag); ReplaceUses(SDValue(Node, 0), SDValue(CNode, 0)); } // Connect the flag usage to the last instruction created. ReplaceUses(SDValue(Node, 2), SDValue(CNode, 1)); CurDAG->RemoveDeadNode(Node); return; } case ISD::SETCC: { if (NVT.isVector() && tryVPTESTM(Node, SDValue(Node, 0), SDValue())) return; break; } case ISD::STORE: if (foldLoadStoreIntoMemOperand(Node)) return; break; case X86ISD::SETCC_CARRY: { // We have to do this manually because tblgen will put the eflags copy in // the wrong place if we use an extract_subreg in the pattern. MVT VT = Node->getSimpleValueType(0); // Copy flags to the EFLAGS register and glue it to next node. SDValue EFLAGS = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, X86::EFLAGS, Node->getOperand(1), SDValue()); // Create a 64-bit instruction if the result is 64-bits otherwise use the // 32-bit version. unsigned Opc = VT == MVT::i64 ? X86::SETB_C64r : X86::SETB_C32r; MVT SetVT = VT == MVT::i64 ? MVT::i64 : MVT::i32; SDValue Result = SDValue( CurDAG->getMachineNode(Opc, dl, SetVT, EFLAGS, EFLAGS.getValue(1)), 0); // For less than 32-bits we need to extract from the 32-bit node. if (VT == MVT::i8 || VT == MVT::i16) { int SubIndex = VT == MVT::i16 ? X86::sub_16bit : X86::sub_8bit; Result = CurDAG->getTargetExtractSubreg(SubIndex, dl, VT, Result); } ReplaceUses(SDValue(Node, 0), Result); CurDAG->RemoveDeadNode(Node); return; } case X86ISD::SBB: { if (isNullConstant(Node->getOperand(0)) && isNullConstant(Node->getOperand(1))) { MVT VT = Node->getSimpleValueType(0); // Create zero. SDVTList VTs = CurDAG->getVTList(MVT::i32, MVT::i32); SDValue Zero = SDValue(CurDAG->getMachineNode(X86::MOV32r0, dl, VTs, None), 0); if (VT == MVT::i64) { Zero = SDValue( CurDAG->getMachineNode( TargetOpcode::SUBREG_TO_REG, dl, MVT::i64, CurDAG->getTargetConstant(0, dl, MVT::i64), Zero, CurDAG->getTargetConstant(X86::sub_32bit, dl, MVT::i32)), 0); } // Copy flags to the EFLAGS register and glue it to next node. SDValue EFLAGS = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, X86::EFLAGS, Node->getOperand(2), SDValue()); // Create a 64-bit instruction if the result is 64-bits otherwise use the // 32-bit version. unsigned Opc = VT == MVT::i64 ? X86::SBB64rr : X86::SBB32rr; MVT SBBVT = VT == MVT::i64 ? MVT::i64 : MVT::i32; VTs = CurDAG->getVTList(SBBVT, MVT::i32); SDValue Result = SDValue(CurDAG->getMachineNode(Opc, dl, VTs, {Zero, Zero, EFLAGS, EFLAGS.getValue(1)}), 0); // Replace the flag use. ReplaceUses(SDValue(Node, 1), Result.getValue(1)); // Replace the result use. if (!SDValue(Node, 0).use_empty()) { // For less than 32-bits we need to extract from the 32-bit node. if (VT == MVT::i8 || VT == MVT::i16) { int SubIndex = VT == MVT::i16 ? X86::sub_16bit : X86::sub_8bit; Result = CurDAG->getTargetExtractSubreg(SubIndex, dl, VT, Result); } ReplaceUses(SDValue(Node, 0), Result); } CurDAG->RemoveDeadNode(Node); return; } break; } case X86ISD::MGATHER: { auto *Mgt = cast<X86MaskedGatherSDNode>(Node); SDValue IndexOp = Mgt->getIndex(); SDValue Mask = Mgt->getMask(); MVT IndexVT = IndexOp.getSimpleValueType(); MVT ValueVT = Node->getSimpleValueType(0); MVT MaskVT = Mask.getSimpleValueType(); // This is just to prevent crashes if the nodes are malformed somehow. We're // otherwise only doing loose type checking in here based on type what // a type constraint would say just like table based isel. if (!ValueVT.isVector() || !MaskVT.isVector()) break; unsigned NumElts = ValueVT.getVectorNumElements(); MVT ValueSVT = ValueVT.getVectorElementType(); bool IsFP = ValueSVT.isFloatingPoint(); unsigned EltSize = ValueSVT.getSizeInBits(); unsigned Opc = 0; bool AVX512Gather = MaskVT.getVectorElementType() == MVT::i1; if (AVX512Gather) { if (IndexVT == MVT::v4i32 && NumElts == 4 && EltSize == 32) Opc = IsFP ? X86::VGATHERDPSZ128rm : X86::VPGATHERDDZ128rm; else if (IndexVT == MVT::v8i32 && NumElts == 8 && EltSize == 32) Opc = IsFP ? X86::VGATHERDPSZ256rm : X86::VPGATHERDDZ256rm; else if (IndexVT == MVT::v16i32 && NumElts == 16 && EltSize == 32) Opc = IsFP ? X86::VGATHERDPSZrm : X86::VPGATHERDDZrm; else if (IndexVT == MVT::v4i32 && NumElts == 2 && EltSize == 64) Opc = IsFP ? X86::VGATHERDPDZ128rm : X86::VPGATHERDQZ128rm; else if (IndexVT == MVT::v4i32 && NumElts == 4 && EltSize == 64) Opc = IsFP ? X86::VGATHERDPDZ256rm : X86::VPGATHERDQZ256rm; else if (IndexVT == MVT::v8i32 && NumElts == 8 && EltSize == 64) Opc = IsFP ? X86::VGATHERDPDZrm : X86::VPGATHERDQZrm; else if (IndexVT == MVT::v2i64 && NumElts == 4 && EltSize == 32) Opc = IsFP ? X86::VGATHERQPSZ128rm : X86::VPGATHERQDZ128rm; else if (IndexVT == MVT::v4i64 && NumElts == 4 && EltSize == 32) Opc = IsFP ? X86::VGATHERQPSZ256rm : X86::VPGATHERQDZ256rm; else if (IndexVT == MVT::v8i64 && NumElts == 8 && EltSize == 32) Opc = IsFP ? X86::VGATHERQPSZrm : X86::VPGATHERQDZrm; else if (IndexVT == MVT::v2i64 && NumElts == 2 && EltSize == 64) Opc = IsFP ? X86::VGATHERQPDZ128rm : X86::VPGATHERQQZ128rm; else if (IndexVT == MVT::v4i64 && NumElts == 4 && EltSize == 64) Opc = IsFP ? X86::VGATHERQPDZ256rm : X86::VPGATHERQQZ256rm; else if (IndexVT == MVT::v8i64 && NumElts == 8 && EltSize == 64) Opc = IsFP ? X86::VGATHERQPDZrm : X86::VPGATHERQQZrm; } else { assert(EVT(MaskVT) == EVT(ValueVT).changeVectorElementTypeToInteger() && "Unexpected mask VT!"); if (IndexVT == MVT::v4i32 && NumElts == 4 && EltSize == 32) Opc = IsFP ? X86::VGATHERDPSrm : X86::VPGATHERDDrm; else if (IndexVT == MVT::v8i32 && NumElts == 8 && EltSize == 32) Opc = IsFP ? X86::VGATHERDPSYrm : X86::VPGATHERDDYrm; else if (IndexVT == MVT::v4i32 && NumElts == 2 && EltSize == 64) Opc = IsFP ? X86::VGATHERDPDrm : X86::VPGATHERDQrm; else if (IndexVT == MVT::v4i32 && NumElts == 4 && EltSize == 64) Opc = IsFP ? X86::VGATHERDPDYrm : X86::VPGATHERDQYrm; else if (IndexVT == MVT::v2i64 && NumElts == 4 && EltSize == 32) Opc = IsFP ? X86::VGATHERQPSrm : X86::VPGATHERQDrm; else if (IndexVT == MVT::v4i64 && NumElts == 4 && EltSize == 32) Opc = IsFP ? X86::VGATHERQPSYrm : X86::VPGATHERQDYrm; else if (IndexVT == MVT::v2i64 && NumElts == 2 && EltSize == 64) Opc = IsFP ? X86::VGATHERQPDrm : X86::VPGATHERQQrm; else if (IndexVT == MVT::v4i64 && NumElts == 4 && EltSize == 64) Opc = IsFP ? X86::VGATHERQPDYrm : X86::VPGATHERQQYrm; } if (!Opc) break; SDValue Base, Scale, Index, Disp, Segment; if (!selectVectorAddr(Mgt, Mgt->getBasePtr(), IndexOp, Mgt->getScale(), Base, Scale, Index, Disp, Segment)) break; SDValue PassThru = Mgt->getPassThru(); SDValue Chain = Mgt->getChain(); // Gather instructions have a mask output not in the ISD node. SDVTList VTs = CurDAG->getVTList(ValueVT, MaskVT, MVT::Other); MachineSDNode *NewNode; if (AVX512Gather) { SDValue Ops[] = {PassThru, Mask, Base, Scale, Index, Disp, Segment, Chain}; NewNode = CurDAG->getMachineNode(Opc, SDLoc(dl), VTs, Ops); } else { SDValue Ops[] = {PassThru, Base, Scale, Index, Disp, Segment, Mask, Chain}; NewNode = CurDAG->getMachineNode(Opc, SDLoc(dl), VTs, Ops); } CurDAG->setNodeMemRefs(NewNode, {Mgt->getMemOperand()}); ReplaceUses(SDValue(Node, 0), SDValue(NewNode, 0)); ReplaceUses(SDValue(Node, 1), SDValue(NewNode, 2)); CurDAG->RemoveDeadNode(Node); return; } case X86ISD::MSCATTER: { auto *Sc = cast<X86MaskedScatterSDNode>(Node); SDValue Value = Sc->getValue(); SDValue IndexOp = Sc->getIndex(); MVT IndexVT = IndexOp.getSimpleValueType(); MVT ValueVT = Value.getSimpleValueType(); // This is just to prevent crashes if the nodes are malformed somehow. We're // otherwise only doing loose type checking in here based on type what // a type constraint would say just like table based isel. if (!ValueVT.isVector()) break; unsigned NumElts = ValueVT.getVectorNumElements(); MVT ValueSVT = ValueVT.getVectorElementType(); bool IsFP = ValueSVT.isFloatingPoint(); unsigned EltSize = ValueSVT.getSizeInBits(); unsigned Opc; if (IndexVT == MVT::v4i32 && NumElts == 4 && EltSize == 32) Opc = IsFP ? X86::VSCATTERDPSZ128mr : X86::VPSCATTERDDZ128mr; else if (IndexVT == MVT::v8i32 && NumElts == 8 && EltSize == 32) Opc = IsFP ? X86::VSCATTERDPSZ256mr : X86::VPSCATTERDDZ256mr; else if (IndexVT == MVT::v16i32 && NumElts == 16 && EltSize == 32) Opc = IsFP ? X86::VSCATTERDPSZmr : X86::VPSCATTERDDZmr; else if (IndexVT == MVT::v4i32 && NumElts == 2 && EltSize == 64) Opc = IsFP ? X86::VSCATTERDPDZ128mr : X86::VPSCATTERDQZ128mr; else if (IndexVT == MVT::v4i32 && NumElts == 4 && EltSize == 64) Opc = IsFP ? X86::VSCATTERDPDZ256mr : X86::VPSCATTERDQZ256mr; else if (IndexVT == MVT::v8i32 && NumElts == 8 && EltSize == 64) Opc = IsFP ? X86::VSCATTERDPDZmr : X86::VPSCATTERDQZmr; else if (IndexVT == MVT::v2i64 && NumElts == 4 && EltSize == 32) Opc = IsFP ? X86::VSCATTERQPSZ128mr : X86::VPSCATTERQDZ128mr; else if (IndexVT == MVT::v4i64 && NumElts == 4 && EltSize == 32) Opc = IsFP ? X86::VSCATTERQPSZ256mr : X86::VPSCATTERQDZ256mr; else if (IndexVT == MVT::v8i64 && NumElts == 8 && EltSize == 32) Opc = IsFP ? X86::VSCATTERQPSZmr : X86::VPSCATTERQDZmr; else if (IndexVT == MVT::v2i64 && NumElts == 2 && EltSize == 64) Opc = IsFP ? X86::VSCATTERQPDZ128mr : X86::VPSCATTERQQZ128mr; else if (IndexVT == MVT::v4i64 && NumElts == 4 && EltSize == 64) Opc = IsFP ? X86::VSCATTERQPDZ256mr : X86::VPSCATTERQQZ256mr; else if (IndexVT == MVT::v8i64 && NumElts == 8 && EltSize == 64) Opc = IsFP ? X86::VSCATTERQPDZmr : X86::VPSCATTERQQZmr; else break; SDValue Base, Scale, Index, Disp, Segment; if (!selectVectorAddr(Sc, Sc->getBasePtr(), IndexOp, Sc->getScale(), Base, Scale, Index, Disp, Segment)) break; SDValue Mask = Sc->getMask(); SDValue Chain = Sc->getChain(); // Scatter instructions have a mask output not in the ISD node. SDVTList VTs = CurDAG->getVTList(Mask.getValueType(), MVT::Other); SDValue Ops[] = {Base, Scale, Index, Disp, Segment, Mask, Value, Chain}; MachineSDNode *NewNode = CurDAG->getMachineNode(Opc, SDLoc(dl), VTs, Ops); CurDAG->setNodeMemRefs(NewNode, {Sc->getMemOperand()}); ReplaceUses(SDValue(Node, 0), SDValue(NewNode, 1)); CurDAG->RemoveDeadNode(Node); return; } } SelectCode(Node); } bool X86DAGToDAGISel:: SelectInlineAsmMemoryOperand(const SDValue &Op, unsigned ConstraintID, std::vector<SDValue> &OutOps) { SDValue Op0, Op1, Op2, Op3, Op4; switch (ConstraintID) { default: llvm_unreachable("Unexpected asm memory constraint"); case InlineAsm::Constraint_o: // offsetable ?? case InlineAsm::Constraint_v: // not offsetable ?? case InlineAsm::Constraint_m: // memory case InlineAsm::Constraint_X: if (!selectAddr(nullptr, Op, Op0, Op1, Op2, Op3, Op4)) return true; break; } OutOps.push_back(Op0); OutOps.push_back(Op1); OutOps.push_back(Op2); OutOps.push_back(Op3); OutOps.push_back(Op4); return false; } /// This pass converts a legalized DAG into a X86-specific DAG, /// ready for instruction scheduling. FunctionPass *llvm::createX86ISelDag(X86TargetMachine &TM, CodeGenOpt::Level OptLevel) { return new X86DAGToDAGISel(TM, OptLevel); }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated by the Codegen C++ plugin. // If you make any local changes, they will be lost. // source: google/bigtable/admin/v2/bigtable_instance_admin.proto #include "google/cloud/bigtable/admin/bigtable_instance_admin_client.h" #include "google/cloud/bigtable/admin/bigtable_instance_admin_options.h" #include "google/cloud/bigtable/admin/internal/bigtable_instance_admin_option_defaults.h" #include <memory> #include <thread> namespace google { namespace cloud { namespace bigtable_admin { GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN BigtableInstanceAdminClient::BigtableInstanceAdminClient( std::shared_ptr<BigtableInstanceAdminConnection> connection, Options options) : connection_(std::move(connection)), options_(bigtable_admin_internal::BigtableInstanceAdminDefaultOptions( std::move(options))) {} BigtableInstanceAdminClient::~BigtableInstanceAdminClient() = default; future<StatusOr<google::bigtable::admin::v2::Instance>> BigtableInstanceAdminClient::CreateInstance( std::string const& parent, std::string const& instance_id, google::bigtable::admin::v2::Instance const& instance, std::map<std::string, google::bigtable::admin::v2::Cluster> const& clusters, Options options) { internal::OptionsSpan span( internal::MergeOptions(std::move(options), options_)); google::bigtable::admin::v2::CreateInstanceRequest request; request.set_parent(parent); request.set_instance_id(instance_id); *request.mutable_instance() = instance; *request.mutable_clusters() = {clusters.begin(), clusters.end()}; return connection_->CreateInstance(request); } future<StatusOr<google::bigtable::admin::v2::Instance>> BigtableInstanceAdminClient::CreateInstance( google::bigtable::admin::v2::CreateInstanceRequest const& request, Options options) { internal::OptionsSpan span( internal::MergeOptions(std::move(options), options_)); return connection_->CreateInstance(request); } StatusOr<google::bigtable::admin::v2::Instance> BigtableInstanceAdminClient::GetInstance(std::string const& name, Options options) { internal::OptionsSpan span( internal::MergeOptions(std::move(options), options_)); google::bigtable::admin::v2::GetInstanceRequest request; request.set_name(name); return connection_->GetInstance(request); } StatusOr<google::bigtable::admin::v2::Instance> BigtableInstanceAdminClient::GetInstance( google::bigtable::admin::v2::GetInstanceRequest const& request, Options options) { internal::OptionsSpan span( internal::MergeOptions(std::move(options), options_)); return connection_->GetInstance(request); } StatusOr<google::bigtable::admin::v2::ListInstancesResponse> BigtableInstanceAdminClient::ListInstances(std::string const& parent, Options options) { internal::OptionsSpan span( internal::MergeOptions(std::move(options), options_)); google::bigtable::admin::v2::ListInstancesRequest request; request.set_parent(parent); return connection_->ListInstances(request); } StatusOr<google::bigtable::admin::v2::ListInstancesResponse> BigtableInstanceAdminClient::ListInstances( google::bigtable::admin::v2::ListInstancesRequest const& request, Options options) { internal::OptionsSpan span( internal::MergeOptions(std::move(options), options_)); return connection_->ListInstances(request); } StatusOr<google::bigtable::admin::v2::Instance> BigtableInstanceAdminClient::UpdateInstance( google::bigtable::admin::v2::Instance const& request, Options options) { internal::OptionsSpan span( internal::MergeOptions(std::move(options), options_)); return connection_->UpdateInstance(request); } future<StatusOr<google::bigtable::admin::v2::Instance>> BigtableInstanceAdminClient::PartialUpdateInstance( google::bigtable::admin::v2::Instance const& instance, google::protobuf::FieldMask const& update_mask, Options options) { internal::OptionsSpan span( internal::MergeOptions(std::move(options), options_)); google::bigtable::admin::v2::PartialUpdateInstanceRequest request; *request.mutable_instance() = instance; *request.mutable_update_mask() = update_mask; return connection_->PartialUpdateInstance(request); } future<StatusOr<google::bigtable::admin::v2::Instance>> BigtableInstanceAdminClient::PartialUpdateInstance( google::bigtable::admin::v2::PartialUpdateInstanceRequest const& request, Options options) { internal::OptionsSpan span( internal::MergeOptions(std::move(options), options_)); return connection_->PartialUpdateInstance(request); } Status BigtableInstanceAdminClient::DeleteInstance(std::string const& name, Options options) { internal::OptionsSpan span( internal::MergeOptions(std::move(options), options_)); google::bigtable::admin::v2::DeleteInstanceRequest request; request.set_name(name); return connection_->DeleteInstance(request); } Status BigtableInstanceAdminClient::DeleteInstance( google::bigtable::admin::v2::DeleteInstanceRequest const& request, Options options) { internal::OptionsSpan span( internal::MergeOptions(std::move(options), options_)); return connection_->DeleteInstance(request); } future<StatusOr<google::bigtable::admin::v2::Cluster>> BigtableInstanceAdminClient::CreateCluster( std::string const& parent, std::string const& cluster_id, google::bigtable::admin::v2::Cluster const& cluster, Options options) { internal::OptionsSpan span( internal::MergeOptions(std::move(options), options_)); google::bigtable::admin::v2::CreateClusterRequest request; request.set_parent(parent); request.set_cluster_id(cluster_id); *request.mutable_cluster() = cluster; return connection_->CreateCluster(request); } future<StatusOr<google::bigtable::admin::v2::Cluster>> BigtableInstanceAdminClient::CreateCluster( google::bigtable::admin::v2::CreateClusterRequest const& request, Options options) { internal::OptionsSpan span( internal::MergeOptions(std::move(options), options_)); return connection_->CreateCluster(request); } StatusOr<google::bigtable::admin::v2::Cluster> BigtableInstanceAdminClient::GetCluster(std::string const& name, Options options) { internal::OptionsSpan span( internal::MergeOptions(std::move(options), options_)); google::bigtable::admin::v2::GetClusterRequest request; request.set_name(name); return connection_->GetCluster(request); } StatusOr<google::bigtable::admin::v2::Cluster> BigtableInstanceAdminClient::GetCluster( google::bigtable::admin::v2::GetClusterRequest const& request, Options options) { internal::OptionsSpan span( internal::MergeOptions(std::move(options), options_)); return connection_->GetCluster(request); } StatusOr<google::bigtable::admin::v2::ListClustersResponse> BigtableInstanceAdminClient::ListClusters(std::string const& parent, Options options) { internal::OptionsSpan span( internal::MergeOptions(std::move(options), options_)); google::bigtable::admin::v2::ListClustersRequest request; request.set_parent(parent); return connection_->ListClusters(request); } StatusOr<google::bigtable::admin::v2::ListClustersResponse> BigtableInstanceAdminClient::ListClusters( google::bigtable::admin::v2::ListClustersRequest const& request, Options options) { internal::OptionsSpan span( internal::MergeOptions(std::move(options), options_)); return connection_->ListClusters(request); } future<StatusOr<google::bigtable::admin::v2::Cluster>> BigtableInstanceAdminClient::UpdateCluster( google::bigtable::admin::v2::Cluster const& request, Options options) { internal::OptionsSpan span( internal::MergeOptions(std::move(options), options_)); return connection_->UpdateCluster(request); } future<StatusOr<google::bigtable::admin::v2::Cluster>> BigtableInstanceAdminClient::PartialUpdateCluster( google::bigtable::admin::v2::Cluster const& cluster, google::protobuf::FieldMask const& update_mask, Options options) { internal::OptionsSpan span( internal::MergeOptions(std::move(options), options_)); google::bigtable::admin::v2::PartialUpdateClusterRequest request; *request.mutable_cluster() = cluster; *request.mutable_update_mask() = update_mask; return connection_->PartialUpdateCluster(request); } future<StatusOr<google::bigtable::admin::v2::Cluster>> BigtableInstanceAdminClient::PartialUpdateCluster( google::bigtable::admin::v2::PartialUpdateClusterRequest const& request, Options options) { internal::OptionsSpan span( internal::MergeOptions(std::move(options), options_)); return connection_->PartialUpdateCluster(request); } Status BigtableInstanceAdminClient::DeleteCluster(std::string const& name, Options options) { internal::OptionsSpan span( internal::MergeOptions(std::move(options), options_)); google::bigtable::admin::v2::DeleteClusterRequest request; request.set_name(name); return connection_->DeleteCluster(request); } Status BigtableInstanceAdminClient::DeleteCluster( google::bigtable::admin::v2::DeleteClusterRequest const& request, Options options) { internal::OptionsSpan span( internal::MergeOptions(std::move(options), options_)); return connection_->DeleteCluster(request); } StatusOr<google::bigtable::admin::v2::AppProfile> BigtableInstanceAdminClient::CreateAppProfile( std::string const& parent, std::string const& app_profile_id, google::bigtable::admin::v2::AppProfile const& app_profile, Options options) { internal::OptionsSpan span( internal::MergeOptions(std::move(options), options_)); google::bigtable::admin::v2::CreateAppProfileRequest request; request.set_parent(parent); request.set_app_profile_id(app_profile_id); *request.mutable_app_profile() = app_profile; return connection_->CreateAppProfile(request); } StatusOr<google::bigtable::admin::v2::AppProfile> BigtableInstanceAdminClient::CreateAppProfile( google::bigtable::admin::v2::CreateAppProfileRequest const& request, Options options) { internal::OptionsSpan span( internal::MergeOptions(std::move(options), options_)); return connection_->CreateAppProfile(request); } StatusOr<google::bigtable::admin::v2::AppProfile> BigtableInstanceAdminClient::GetAppProfile(std::string const& name, Options options) { internal::OptionsSpan span( internal::MergeOptions(std::move(options), options_)); google::bigtable::admin::v2::GetAppProfileRequest request; request.set_name(name); return connection_->GetAppProfile(request); } StatusOr<google::bigtable::admin::v2::AppProfile> BigtableInstanceAdminClient::GetAppProfile( google::bigtable::admin::v2::GetAppProfileRequest const& request, Options options) { internal::OptionsSpan span( internal::MergeOptions(std::move(options), options_)); return connection_->GetAppProfile(request); } StreamRange<google::bigtable::admin::v2::AppProfile> BigtableInstanceAdminClient::ListAppProfiles(std::string const& parent, Options options) { internal::OptionsSpan span( internal::MergeOptions(std::move(options), options_)); google::bigtable::admin::v2::ListAppProfilesRequest request; request.set_parent(parent); return connection_->ListAppProfiles(request); } StreamRange<google::bigtable::admin::v2::AppProfile> BigtableInstanceAdminClient::ListAppProfiles( google::bigtable::admin::v2::ListAppProfilesRequest request, Options options) { internal::OptionsSpan span( internal::MergeOptions(std::move(options), options_)); return connection_->ListAppProfiles(std::move(request)); } future<StatusOr<google::bigtable::admin::v2::AppProfile>> BigtableInstanceAdminClient::UpdateAppProfile( google::bigtable::admin::v2::AppProfile const& app_profile, google::protobuf::FieldMask const& update_mask, Options options) { internal::OptionsSpan span( internal::MergeOptions(std::move(options), options_)); google::bigtable::admin::v2::UpdateAppProfileRequest request; *request.mutable_app_profile() = app_profile; *request.mutable_update_mask() = update_mask; return connection_->UpdateAppProfile(request); } future<StatusOr<google::bigtable::admin::v2::AppProfile>> BigtableInstanceAdminClient::UpdateAppProfile( google::bigtable::admin::v2::UpdateAppProfileRequest const& request, Options options) { internal::OptionsSpan span( internal::MergeOptions(std::move(options), options_)); return connection_->UpdateAppProfile(request); } Status BigtableInstanceAdminClient::DeleteAppProfile(std::string const& name, Options options) { internal::OptionsSpan span( internal::MergeOptions(std::move(options), options_)); google::bigtable::admin::v2::DeleteAppProfileRequest request; request.set_name(name); return connection_->DeleteAppProfile(request); } Status BigtableInstanceAdminClient::DeleteAppProfile( google::bigtable::admin::v2::DeleteAppProfileRequest const& request, Options options) { internal::OptionsSpan span( internal::MergeOptions(std::move(options), options_)); return connection_->DeleteAppProfile(request); } StatusOr<google::iam::v1::Policy> BigtableInstanceAdminClient::GetIamPolicy( std::string const& resource, Options options) { internal::OptionsSpan span( internal::MergeOptions(std::move(options), options_)); google::iam::v1::GetIamPolicyRequest request; request.set_resource(resource); return connection_->GetIamPolicy(request); } StatusOr<google::iam::v1::Policy> BigtableInstanceAdminClient::GetIamPolicy( google::iam::v1::GetIamPolicyRequest const& request, Options options) { internal::OptionsSpan span( internal::MergeOptions(std::move(options), options_)); return connection_->GetIamPolicy(request); } StatusOr<google::iam::v1::Policy> BigtableInstanceAdminClient::SetIamPolicy( std::string const& resource, google::iam::v1::Policy const& policy, Options options) { internal::OptionsSpan span( internal::MergeOptions(std::move(options), options_)); google::iam::v1::SetIamPolicyRequest request; request.set_resource(resource); *request.mutable_policy() = policy; return connection_->SetIamPolicy(request); } StatusOr<google::iam::v1::Policy> BigtableInstanceAdminClient::SetIamPolicy( std::string const& resource, IamUpdater const& updater, Options options) { internal::CheckExpectedOptions<BigtableInstanceAdminBackoffPolicyOption>( options, __func__); internal::OptionsSpan span( internal::MergeOptions(std::move(options), options_)); auto backoff_policy = internal::CurrentOptions() .get<BigtableInstanceAdminBackoffPolicyOption>() ->clone(); for (;;) { auto recent = GetIamPolicy(resource); if (!recent) { return recent.status(); } auto policy = updater(*std::move(recent)); if (!policy) { return Status(StatusCode::kCancelled, "updater did not yield a policy"); } auto result = SetIamPolicy(resource, *std::move(policy)); if (result || result.status().code() != StatusCode::kAborted) { return result; } std::this_thread::sleep_for(backoff_policy->OnCompletion()); } } StatusOr<google::iam::v1::Policy> BigtableInstanceAdminClient::SetIamPolicy( google::iam::v1::SetIamPolicyRequest const& request, Options options) { internal::OptionsSpan span( internal::MergeOptions(std::move(options), options_)); return connection_->SetIamPolicy(request); } StatusOr<google::iam::v1::TestIamPermissionsResponse> BigtableInstanceAdminClient::TestIamPermissions( std::string const& resource, std::vector<std::string> const& permissions, Options options) { internal::OptionsSpan span( internal::MergeOptions(std::move(options), options_)); google::iam::v1::TestIamPermissionsRequest request; request.set_resource(resource); *request.mutable_permissions() = {permissions.begin(), permissions.end()}; return connection_->TestIamPermissions(request); } StatusOr<google::iam::v1::TestIamPermissionsResponse> BigtableInstanceAdminClient::TestIamPermissions( google::iam::v1::TestIamPermissionsRequest const& request, Options options) { internal::OptionsSpan span( internal::MergeOptions(std::move(options), options_)); return connection_->TestIamPermissions(request); } GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END } // namespace bigtable_admin } // namespace cloud } // namespace google
/*! @file Defines `boost::hana::maximum`. @copyright Louis Dionne 2013-2017 Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) */ #ifndef BOOST_HANA_MAXIMUM_HPP #define BOOST_HANA_MAXIMUM_HPP #include <boost/hana/fwd/maximum.hpp> #include <boost/hana/concept/foldable.hpp> #include <boost/hana/config.hpp> #include <boost/hana/core/dispatch.hpp> #include <boost/hana/detail/nested_by.hpp> // required by fwd decl #include <boost/hana/fold_left.hpp> #include <boost/hana/if.hpp> #include <boost/hana/less.hpp> BOOST_HANA_NAMESPACE_BEGIN //! @cond template <typename Xs> constexpr decltype(auto) maximum_t::operator()(Xs&& xs) const { using S = typename hana::tag_of<Xs>::type; using Maximum = BOOST_HANA_DISPATCH_IF(maximum_impl<S>, hana::Foldable<S>::value ); #ifndef BOOST_HANA_CONFIG_DISABLE_CONCEPT_CHECKS static_assert(hana::Foldable<S>::value, "hana::maximum(xs) requires 'xs' to be Foldable"); #endif return Maximum::apply(static_cast<Xs&&>(xs)); } template <typename Xs, typename Predicate> constexpr decltype(auto) maximum_t::operator()(Xs&& xs, Predicate&& pred) const { using S = typename hana::tag_of<Xs>::type; using Maximum = BOOST_HANA_DISPATCH_IF(maximum_pred_impl<S>, hana::Foldable<S>::value ); #ifndef BOOST_HANA_CONFIG_DISABLE_CONCEPT_CHECKS static_assert(hana::Foldable<S>::value, "hana::maximum(xs, predicate) requires 'xs' to be Foldable"); #endif return Maximum::apply(static_cast<Xs&&>(xs), static_cast<Predicate&&>(pred)); } //! @endcond ////////////////////////////////////////////////////////////////////////// // maximum (with a custom predicate) ////////////////////////////////////////////////////////////////////////// namespace detail { template <typename Pred> struct max_by { Pred pred; template <typename X, typename Y> constexpr decltype(auto) operator()(X&& x, Y&& y) const { auto result = (*pred)(x, y); return hana::if_(result, static_cast<Y&&>(y), static_cast<X&&>(x)); } }; } template <typename T, bool condition> struct maximum_pred_impl<T, when<condition>> : default_ { template <typename Xs, typename Pred> static constexpr decltype(auto) apply(Xs&& xs, Pred&& pred) { // We use a pointer instead of a reference to avoid a Clang ICE. return hana::fold_left(static_cast<Xs&&>(xs), detail::max_by<decltype(&pred)>{&pred} ); } }; ////////////////////////////////////////////////////////////////////////// // maximum (without a custom predicate) ////////////////////////////////////////////////////////////////////////// template <typename T, bool condition> struct maximum_impl<T, when<condition>> : default_ { template <typename Xs> static constexpr decltype(auto) apply(Xs&& xs) { return hana::maximum(static_cast<Xs&&>(xs), hana::less); } }; BOOST_HANA_NAMESPACE_END #endif // !BOOST_HANA_MAXIMUM_HPP
#include <iostream> #include "../include/nyx_solver.hpp" int main() { #if 0 #if 0 Pose firstPose(2,0,0); Pose secondPose(1,1,0); //Pose secondPose(-0.330083,1.972496,0); //Pose secondPose(0.8,0,0); //Pose secondPose(0,2,0); std::vector<Link> chain = std::vector<Link>(); chain.push_back(Link(1, 1, -15,15, 0,180)); chain.push_back(Link(1, 1, -15,15, 0,180)); std::cout << "Creating state" << std::endl; State s = State(chain, firstPose, secondPose); //std::cout << "State created" << std::endl; //std::cout << "Current state" << std::endl; //std::cout << s.print(); #else Pose firstPose(40,0,0); //Pose secondPose(3,1,0); //Pose secondPose(0.964322,3.807231,0); //Pose secondPose(20,34.6, 0); //Pose secondPose(20.6,34.26, 0); //Pose secondPose(50, 0,0); //Pose secondPose(-30, 10, 0); //Pose secondPose(10,30,0); //Pose secondPose(0,30,10); //Pose secondPose(30,0,10); Pose secondPose(21.21, 21.21, 10); std::vector<Link> chain = std::vector<Link>(); chain.push_back(Link(10, 1, -90,90, 0,180)); chain.push_back(Link(10, 2, -90,90, 0,180)); chain.push_back(Link(10, 2, -90,90, 0,180)); chain.push_back(Link(10, 2, -90,90, 0,180)); #endif Solver nyx_solver = Solver(chain, firstPose); nyx_solver.updateTargetPose(secondPose); /*std::cout << "\n\nAttempting to get next state\n"; std::vector<State> nextStates = s.getNext(); for (int i=0; i<nextStates.size(); i++) { std::cout << "\nI: " << i << "\n"; nextStates[i].print(); } std::cout << "second level states, based off of index 0\n"; for (int j=0; j<10; j++) { nextStates = nextStates[0].getNext(); for (int i=0; i<nextStates.size(); i++) { std::cout << "\nI: " << i << "\n"; nextStates[i].print(); } } */ #endif // Initialize solver std::vector<Link> chain; // DOF 0 chain.push_back(Link(6.16, 1, 0,170, 50,120)); // Vertical offset chain.push_back(Link(6.38, 2, 90,90, 0,0)); // DOF 1 chain.push_back(Link(17.63, 2, -94,9, 57,140)); // DOF 2 chain.push_back(Link(16.12, 2, -36,-158, 52,115)); // DOF 3 chain.push_back(Link(8.9, 2, -45,47, 95,134)); /*chain[0].setCurrentAngle(85); chain[2].setCurrentAngle(-50); chain[3].setCurrentAngle(-90); chain[4].setCurrentAngle(0); */ Pose dest (35.611878, 3.115636, -1.454086); Solver solver (chain); std::cout << "Angles: " << std::endl; solver.getState().print(); std::cout << "Solved state:" << std::endl; solver.updateTargetPose(dest).print(); }
// Copyright Epic Games, Inc. All Rights Reserved. #include "ConnectFourGameModeBase.h"
#include "envoy/common/platform.h" #include "envoy/config/core/v3/base.pb.h" #include "common/api/os_sys_calls_impl.h" #include "common/network/io_socket_handle_impl.h" #include "common/network/listen_socket_impl.h" #include "common/network/utility.h" #include "test/mocks/network/mocks.h" #include "test/test_common/environment.h" #include "test/test_common/network_utility.h" #include "test/test_common/utility.h" #include "gtest/gtest.h" using testing::_; using testing::Return; namespace Envoy { namespace Network { namespace { template <Network::Address::SocketType Type> class ListenSocketImplTest : public testing::TestWithParam<Address::IpVersion> { protected: ListenSocketImplTest() : version_(GetParam()) {} const Address::IpVersion version_; template <typename... Args> std::unique_ptr<ListenSocketImpl> createListenSocketPtr(Args&&... args) { using NetworkSocketTraitType = NetworkSocketTrait<Type>; return std::make_unique<NetworkListenSocket<NetworkSocketTraitType>>( std::forward<Args>(args)...); } void testBindSpecificPort() { // This test has a small but real risk of flaky behavior if another thread or process should // bind to our assigned port during the interval between closing the fd and re-binding. In an // attempt to avoid this, we allow for retrying by placing the core of the test in a loop with // a catch of the SocketBindException, indicating we couldn't bind, at which point we retry. const int kLoopLimit = 20; int loop_number = 0; while (true) { ++loop_number; auto addr_fd = Network::Test::bindFreeLoopbackPort(version_, Address::SocketType::Stream); auto addr = addr_fd.first; Network::IoHandlePtr& io_handle = addr_fd.second; EXPECT_TRUE(SOCKET_VALID(io_handle->fd())); // Confirm that we got a reasonable address and port. ASSERT_EQ(Address::Type::Ip, addr->type()); ASSERT_EQ(version_, addr->ip()->version()); ASSERT_LT(0U, addr->ip()->port()); // Release the socket and re-bind it. EXPECT_EQ(nullptr, io_handle->close().err_); auto option = std::make_unique<MockSocketOption>(); auto options = std::make_shared<std::vector<Network::Socket::OptionConstSharedPtr>>(); EXPECT_CALL(*option, setOption(_, envoy::config::core::v3::SocketOption::STATE_PREBIND)) .WillOnce(Return(true)); options->emplace_back(std::move(option)); std::unique_ptr<ListenSocketImpl> socket1; try { socket1 = createListenSocketPtr(addr, options, true); } catch (SocketBindException& e) { if (e.errorNumber() != EADDRINUSE) { ADD_FAILURE() << "Unexpected failure (" << e.errorNumber() << ") to bind a free port: " << e.what(); throw; } else if (loop_number >= kLoopLimit) { ADD_FAILURE() << "Too many failures (" << loop_number << ") to bind a specific port: " << e.what(); return; } continue; } // TODO (conqerAtapple): This is unfortunate. We should be able to templatize this // instead of if block. auto os_sys_calls = Api::OsSysCallsSingleton::get(); if (NetworkSocketTrait<Type>::type == Address::SocketType::Stream) { EXPECT_EQ(0, os_sys_calls.listen(socket1->ioHandle().fd(), 0).rc_); } EXPECT_EQ(addr->ip()->port(), socket1->localAddress()->ip()->port()); EXPECT_EQ(addr->ip()->addressAsString(), socket1->localAddress()->ip()->addressAsString()); EXPECT_EQ(Type, socket1->socketType()); auto option2 = std::make_unique<MockSocketOption>(); auto options2 = std::make_shared<std::vector<Network::Socket::OptionConstSharedPtr>>(); EXPECT_CALL(*option2, setOption(_, envoy::config::core::v3::SocketOption::STATE_PREBIND)) .WillOnce(Return(true)); options2->emplace_back(std::move(option2)); // The address and port are bound already, should throw exception. EXPECT_THROW(createListenSocketPtr(addr, options2, true), SocketBindException); // Release socket and re-bind it. socket1->close(); // Test createListenSocketPtr from IoHandlePtr's os_fd_t constructor int domain = version_ == Address::IpVersion::v4 ? AF_INET : AF_INET6; auto socket_result = os_sys_calls.socket(domain, SOCK_STREAM, 0); EXPECT_TRUE(SOCKET_VALID(socket_result.rc_)); io_handle = std::make_unique<IoSocketHandleImpl>(socket_result.rc_); auto socket3 = createListenSocketPtr(std::move(io_handle), addr, nullptr); EXPECT_EQ(socket3->localAddress()->asString(), addr->asString()); // Test successful. return; } } void testBindPortZero() { auto loopback = Network::Test::getCanonicalLoopbackAddress(version_); auto socket = createListenSocketPtr(loopback, nullptr, true); EXPECT_EQ(Address::Type::Ip, socket->localAddress()->type()); EXPECT_EQ(version_, socket->localAddress()->ip()->version()); EXPECT_EQ(loopback->ip()->addressAsString(), socket->localAddress()->ip()->addressAsString()); EXPECT_GT(socket->localAddress()->ip()->port(), 0U); EXPECT_EQ(Type, socket->socketType()); } }; using ListenSocketImplTestTcp = ListenSocketImplTest<Network::Address::SocketType::Stream>; using ListenSocketImplTestUdp = ListenSocketImplTest<Network::Address::SocketType::Datagram>; INSTANTIATE_TEST_SUITE_P(IpVersions, ListenSocketImplTestTcp, testing::ValuesIn(TestEnvironment::getIpVersionsForTest()), TestUtility::ipTestParamsToString); INSTANTIATE_TEST_SUITE_P(IpVersions, ListenSocketImplTestUdp, testing::ValuesIn(TestEnvironment::getIpVersionsForTest()), TestUtility::ipTestParamsToString); TEST_P(ListenSocketImplTestTcp, BindSpecificPort) { testBindSpecificPort(); } /* * A simple implementation to test some of ListenSocketImpl's accessors without requiring * stack interaction. */ class TestListenSocket : public ListenSocketImpl { public: TestListenSocket(Address::InstanceConstSharedPtr address) : ListenSocketImpl(std::make_unique<Network::IoSocketHandleImpl>(), address) {} Address::SocketType socketType() const override { return Address::SocketType::Stream; } }; TEST_P(ListenSocketImplTestTcp, SetLocalAddress) { std::string address_str = "10.1.2.3"; if (version_ == Address::IpVersion::v6) { address_str = "1::2"; } Address::InstanceConstSharedPtr address = Network::Utility::parseInternetAddress(address_str); TestListenSocket socket(Utility::getIpv4AnyAddress()); socket.setLocalAddress(address); EXPECT_EQ(socket.localAddress(), address); } TEST_P(ListenSocketImplTestUdp, BindSpecificPort) { testBindSpecificPort(); } // Validate that we get port allocation when binding to port zero. TEST_P(ListenSocketImplTestTcp, BindPortZero) { testBindPortZero(); } TEST_P(ListenSocketImplTestUdp, BindPortZero) { testBindPortZero(); } } // namespace } // namespace Network } // namespace Envoy
/* * CommandFlashLock.cpp * * Created on: Sep 10, 2021 * Author: djek-sweng */ #include "CommandFlashLock.h" #include "global.h" namespace Bootloader { CommandFlashLock::CommandFlashLock( const char* device, uint32_t baudRate ) : Command { device, baudRate } { } CommandFlashLock::~CommandFlashLock() { Command::Close(); } int32_t CommandFlashLock::Execute() { BLDR_CommandMessage_t commandMessageTx; BLDR_CommandMessage_t commandMessageRx; BLDR_InitCommandMessageStruct(&commandMessageTx); BLDR_InitCommandMessageStruct(&commandMessageRx); commandMessageTx.Id = BLDR_IDC_FLASH_LOCK; commandMessageTx.Length = 0; Command::Transmit(&commandMessageTx); Command::Receive(&commandMessageRx); Command::Print(&commandMessageTx, "----TX----"); Command::Print(&commandMessageRx, "----RX----"); return NO_FAILURE; } }
// Electroslag Interactive Graphics System // Copyright 2018 Joshua Buckman // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma once #include "electroslag/event.hpp" #include "electroslag/ui/ui_interface.hpp" #include "electroslag/threading/mutex.hpp" #include "electroslag/graphics/graphics_interface.hpp" #include "electroslag/graphics/context_interface.hpp" #include "electroslag/renderer/renderer_interface.hpp" #include "electroslag/renderer/field_source_interface.hpp" #include "electroslag/renderer/pass_interface.hpp" #include "electroslag/renderer/uniform_buffer_manager.hpp" #include "electroslag/renderer/primitive_stream_manager.hpp" #include "electroslag/renderer/texture_manager.hpp" #include "electroslag/renderer/shader_program_manager.hpp" #include "electroslag/renderer/pipeline_manager.hpp" namespace electroslag { namespace renderer { class renderer : public renderer_interface , public field_source_interface { private: typedef std::vector<pass_interface::ref> pass_vector; public: typedef pass_vector::const_iterator const_pass_iterator; typedef pass_vector::iterator pass_iterator; renderer(); virtual ~renderer() {} // Implement field_source_interface virtual bool locate_field_source(graphics::shader_field const* field, void const** field_source) const; // Implement renderer_interface methods. virtual void initialize(); virtual void shutdown(); virtual bool is_initialized() const; virtual scene::ref create_instances(instance_descriptor::ref const& desc); typedef event<void, scene::ref const&> scene_created_event; typedef scene_created_event::bound_delegate scene_created_delegate; mutable scene_created_event scene_created; // renderer internal methods. // The list of passes is built at initialization time and is constant afterwards, // so no mutex required for iteration. const_pass_iterator begin_passes() const { return (m_passes.begin()); } pass_iterator begin_passes() { return (m_passes.begin()); } const_pass_iterator end_passes() const { return (m_passes.end()); } pass_iterator end_passes() { return (m_passes.end()); } int get_pass_count() const { return (static_cast<int>(m_passes.size())); } int get_geometry_pass_count() const { return (m_geometry_pass_count); } // Each manager object needs to do it's own thread synchronization. uniform_buffer_manager* get_ubo_manager() { return (&m_ubo_manager); } primitive_stream_manager* get_primitive_stream_manager() { return (&m_primitive_stream_manager); } texture_manager* get_texture_manager() { return (&m_texture_manager); } shader_program_manager* get_shader_program_manager() { return (&m_shader_program_manager); } pipeline_manager* get_pipeline_manager() { return (&m_pipeline_manager); } // Called by mesh rendering work item. void finish_rendering_mesh(frame_details* this_frame_details); private: class finish_drawing_command : public graphics::command { public: explicit finish_drawing_command(frame_details* this_frame_details) : m_this_frame_details(this_frame_details) {} virtual void execute(graphics::context_interface* context); private: frame_details* m_this_frame_details; }; void on_window_destroyed(); void on_window_size_changed(ui::window_dimensions const* dimensions); void on_window_paused_changed(bool paused); void on_window_frame(int millisec_elapsed); mutable threading::mutex m_mutex; ui::window_interface::destroyed_delegate* m_destroyed_delegate; ui::window_interface::size_changed_delegate* m_size_changed_delegate; ui::window_interface::paused_changed_delegate* m_paused_changed_delegate; ui::window_interface::frame_delegate* m_frame_delegate; graphics::command_queue_interface::ref m_pre_frame_queue; graphics::command_queue_interface::ref m_post_frame_queue; typedef std::vector<scene::ref> scene_vector; scene_vector m_scenes; pass_vector m_passes; int m_geometry_pass_count; uniform_buffer_manager m_ubo_manager; primitive_stream_manager m_primitive_stream_manager; texture_manager m_texture_manager; shader_program_manager m_shader_program_manager; pipeline_manager m_pipeline_manager; static constexpr int const per_frame_count = graphics::context_interface::display_buffer_count + 1; frame_details m_per_frame_details[per_frame_count]; int m_current_frame_index; bool m_initialized; // Disallowed operations: explicit renderer(renderer const&); renderer& operator =(renderer const&); }; renderer* get_renderer_internal(); } }
// MusicXML Class Library // Copyright (c) by Matthew James Briggs // Distributed under the MIT License #include "mx/core/elements/KeyStep.h" #include "mx/core/FromXElement.h" #include <iostream> namespace mx { namespace core { KeyStep::KeyStep() :myValue( StepEnum::a ) {} KeyStep::KeyStep( const StepEnum& value ) :myValue( value ) {} bool KeyStep::hasAttributes() const { return false; } bool KeyStep::hasContents() const { return true; } std::ostream& KeyStep::streamAttributes( std::ostream& os ) const { return os; } std::ostream& KeyStep::streamName( std::ostream& os ) const { os << "key-step"; return os; } std::ostream& KeyStep::streamContents( std::ostream& os, const int indentLevel, bool& isOneLineOnly ) const { MX_UNUSED( indentLevel ); isOneLineOnly = true; os << myValue; return os; } StepEnum KeyStep::getValue() const { return myValue; } void KeyStep::setValue( const StepEnum& value ) { myValue = value; } bool KeyStep::fromXElementImpl( std::ostream& message, ::ezxml::XElement& xelement ) { MX_UNUSED( message ); MX_UNUSED( xelement ); myValue = parseStepEnum( xelement.getValue() ); return true; } } }
#include <gossip/dispatcher.hpp> using gossip::Dispatcher; Dispatcher::Dispatcher() { } Dispatcher::~Dispatcher() noexcept { }
/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "paddle/fluid/framework/ir/subgraph_detector.h" #include <string> #include <unordered_map> #include <unordered_set> #include <utility> #include "paddle/fluid/framework/ir/graph_helper.h" #include "paddle/fluid/framework/ir/graph_pattern_detector.h" #include "paddle/fluid/framework/ir/node.h" DECLARE_bool(use_ngraph); namespace paddle { namespace framework { namespace ir { std::pair<std::vector<Node *>, std::vector<Node *>> ExtractInputAndOutputOfSubGraph(std::vector<Node *> &graph) { // NOLINT std::unordered_set<Node *> nodes(graph.begin(), graph.end()); std::unordered_set<Node *> inputs; std::unordered_set<Node *> outputs; // Input a Value, check whether its inlink is in the subgraph. auto inlink_in_subgraph = [&](Node *n) { for (auto *in : n->inputs) { if (nodes.count(in)) return true; } return false; }; for (auto &node : graph) { for (auto *in : node->inputs) { // The Value that is written by nodes inside a sub-graph shouldn't be the // input of the sub-graph. if (!nodes.count(in) && in->IsVar() && !inlink_in_subgraph(in)) { inputs.insert(in); } } for (auto *out : node->outputs) { if (!nodes.count(out) && out->IsVar()) { outputs.insert(out); } } } return std::make_pair(std::vector<Node *>(inputs.begin(), inputs.end()), std::vector<Node *>(outputs.begin(), outputs.end())); } // Filter the Intermediate results of the subgraph node. void FilterRedundantOutputOfSubGraph(Graph *graph) { std::vector<Node *> op_nodes; for (auto &node : TopologicalSort(*graph)) { if (node.IsVar() || Agent(&node).deleted()) { continue; } op_nodes.push_back(&node); } size_t op_num = op_nodes.size(); for (size_t i = 0; i < op_num; i++) { if (op_nodes[i]->IsOp()) continue; std::unordered_set<std::string> follow_up_input_names; for (size_t j = i + 1; j < op_num; j++) { for (auto *in : op_nodes[j]->inputs) { follow_up_input_names.insert(in->Name()); } } std::vector<Node *> filtered_subgraph_outlinks; for (auto *out : op_nodes[i]->outputs) { if (follow_up_input_names.count(out->Name())) { filtered_subgraph_outlinks.push_back(out); } else { Agent(out).set_deleted(true); } } // The filtered_subgraph_outlinks may be empty. op_nodes[i]->outputs = filtered_subgraph_outlinks; } } std::vector<std::vector<Node *>> SubgraphDetector::operator()() { MarkNodesInsideSubGraph(); return ExtractSubGraphs(); } // Mark the output variables inside a subgraph with the func. inline void MarkOutLinksInSubGraph(const Node *func) { for (auto *var : func->outputs) { Agent(var).set_marked(true); } } void SubgraphDetector::MarkNodesInsideSubGraph() { for (auto &node : framework::ir::GraphTraits::DFS(*graph_)) { if (node_inside_subgraph_teller_(&node)) { Agent(&node).set_marked(true); if (node.IsOp()) { // If a function is inside the sub-graph, mark all the output variables // to be inside too, so that two marked functions will be inside a same // sub-graph, lets take a example: A_function->var->B_function, if // A_function is marked, var should also be marked, so that B_function // will be in the same sub-graph with A_function if B_function is // marked. MarkOutLinksInSubGraph(&node); } } } } // Use the Union Find(UF) algorithm to find fully connected sub-graphs, if node // a's output is node b, that is a and b is in the same sub-graph. The UF // algorithm will group them to the same cluster. using node_map_t = std::unordered_map<int, Node *>; // Find the ancestor id of a node. int UnionFindGetAncestor(const node_map_t &node_map, size_t id) { int tmp = id; do { tmp = Agent(node_map.at(tmp)).union_find_parent(); } while (Agent(node_map.at(tmp)).union_find_parent() != tmp); return tmp; } // Make this two node share the same ancestor. // TODO(Superjom) bad performance, make a balanced tree latter. void UnionFindCombine(const node_map_t &node_map, size_t a, size_t b) { int a_ancestor = UnionFindGetAncestor(node_map, a); int b_ancestor = UnionFindGetAncestor(node_map, b); Agent(node_map.at(b_ancestor)).set_union_find_parent(a_ancestor); Agent(node_map.at(a)).set_union_find_parent(a_ancestor); Agent(node_map.at(b)).set_union_find_parent(a_ancestor); } // This is a simple representation of a graph. // The BriefNode hold the pointer of the Node. // This is to avoid changing the original graph // in the process of trt graph analysis. struct BriefNode { explicit BriefNode(Node *n) { node = n; } Node *node; std::vector<BriefNode *> inlinks; std::vector<BriefNode *> outlinks; }; // Union two adjacent BriefNode. // Suppose we have two adjacent nodes src and dst. // We will perform the following operations: // 1. add all inputs(except src) of dst to src inlinks. // 2. add all outputs of dst to src outlinks. // 3. change all the dst's inputs and outputs // corresponding inlinks and outlinks to src node. // 4. delete all dst's inlinks and outlinks. void UnionContractedNodes(const std::unordered_map<int, BriefNode *> &node_map, int src_id, int dst_id) { // merge the two adjacent nodes into one node. BriefNode *src_node = node_map.at(src_id); BriefNode *dst_node = node_map.at(dst_id); std::unordered_set<BriefNode *> inputs(src_node->inlinks.begin(), src_node->inlinks.end()); std::unordered_set<BriefNode *> outputs; for (auto *n : src_node->outlinks) { if (n != dst_node) outputs.insert(n); } // Add the inlinks and outlinks of dst node to src node. std::vector<BriefNode *> dst_in_nodes = dst_node->inlinks; for (BriefNode *node : dst_in_nodes) { if (node != src_node) { inputs.insert(node); } } std::vector<BriefNode *> dst_out_nodes = dst_node->outlinks; for (BriefNode *node : dst_out_nodes) { outputs.insert(node); } // update the dst and src node's inlinks and outlinks. #ifdef __clang__ src_node->inlinks = std::vector<BriefNode *>(inputs.begin(), inputs.end()); src_node->outlinks = std::vector<BriefNode *>(outputs.begin(), outputs.end()); dst_node->inlinks.clear(); dst_node->outlinks.clear(); #else src_node->inlinks = std::move(std::vector<BriefNode *>(inputs.begin(), inputs.end())); src_node->outlinks = std::move(std::vector<BriefNode *>(outputs.begin(), outputs.end())); dst_node->inlinks.clear(); dst_node->outlinks.clear(); #endif auto inlink_or_outlink_cleaner = [&](std::vector<BriefNode *> &nodes) { for (auto *&n : nodes) { if (n == src_node || n == dst_node) { n = src_node; } } }; // Change all the dst inputs and outputs corresponding inlink and // outlink to the src node. for (auto *node : src_node->inlinks) { inlink_or_outlink_cleaner(node->outlinks); } for (auto *node : src_node->outlinks) { inlink_or_outlink_cleaner(node->inlinks); } } // FlexibleDFS // If reverse is true, do reverse dfs. // If enter func is not nullptr, calls enter(node) before visiting any children // of node. // If leave func not nullptr, calls leave(node) after visiting all parents of // node. void FlexibleDFS(const std::vector<BriefNode *> &source, bool reverse, const std::function<bool(const BriefNode *)> &enter, const std::function<bool(const BriefNode *)> &leave) { typedef struct { const BriefNode *node; bool leave; } FNode; std::vector<FNode> stack; for (auto &node : source) { stack.push_back(FNode{node, false}); } std::unordered_set<const BriefNode *> visited; while (!stack.empty()) { auto fnode = stack.back(); stack.pop_back(); if (fnode.leave) { if (leave && !leave(fnode.node)) return; } if (visited.count(fnode.node)) continue; visited.insert(fnode.node); if (enter && !enter(fnode.node)) return; if (leave) stack.push_back(FNode{fnode.node, true}); const std::vector<BriefNode *> iter_nodes = reverse == true ? fnode.node->inlinks : fnode.node->outlinks; for (const BriefNode *node : iter_nodes) { if (!visited.count(node)) { stack.push_back(FNode{node, false}); } } } } std::vector<std::vector<Node *>> SubgraphDetector::ExtractSubGraphs() { // Run the Extract algorithm to find all subgraphs. std::vector<Node *> marked_nodes; // We use brief_node_map to represent the original graph in order to avoid // changing the original graph. std::unordered_map<int, BriefNode *> brief_node_map; std::unordered_set<int32_t> valid_node_ids; for (auto *node : graph_->Nodes()) { valid_node_ids.insert(node->id()); } for (auto &node : framework::ir::GraphTraits::TS(*graph_)) { brief_node_map[node.id()] = new BriefNode(&node); if (Agent(&node).marked()) { marked_nodes.push_back(&node); } } // extract sub-graphs in the marked node set, use Union Find algorithm. node_map_t node_map; // id to ptr for (auto *n : marked_nodes) { // n's parent == n.id means it is the ancestor Agent(n).set_union_find_parent(n->id()); node_map[n->id()] = n; } // create breif node map for (auto &itr : brief_node_map) { for (Node *node : itr.second->node->inputs) { if (!valid_node_ids.count(node->id())) { LOG(INFO) << "invalid node id " << node->id(); continue; } itr.second->inlinks.push_back(brief_node_map.at(node->id())); } for (Node *node : itr.second->node->outputs) { if (!valid_node_ids.count(node->id())) { LOG(INFO) << "invalid node id " << node->id(); continue; } itr.second->outlinks.push_back(brief_node_map.at(node->id())); } } for (auto &itr : brief_node_map) { BriefNode *brief_node = itr.second; if (!Agent(brief_node->node).marked()) { VLOG(4) << brief_node->node->id() << " node not a trt candidate."; continue; } // Our algorithm must guarantee that: // 1. The graph is always directed acyclic graph(DAG). // 2. If there is a path in the subgraph from X to Y (X and Y are both // nodes in the subgraph), then all paths from X to Y are in the // subgraph. // // In order to achieve the above guarantee. // For adjacent nodes src -> dst. // 1. Get all dst input nodes except src. // 2. Reverse DFS from those input nodes // 3. If there is a path from input nodes to src, // then the src and dst nodes can not be fused into one node, // otherwise it can be done. while (true) { std::unordered_set<BriefNode *> contract_nodes; for (auto *out : brief_node->outlinks) { // must be an trt candidate if (!Agent(out->node).marked()) continue; // get all dst input nodes except src. std::vector<BriefNode *> source_nodes; for (auto *n : out->inlinks) { if (n != brief_node) { source_nodes.push_back(n); } } // Reverse DFS from the source_nodes. bool have_excess_path = false; FlexibleDFS(source_nodes, true, nullptr, [&have_excess_path, brief_node](const BriefNode *n) { if (n == brief_node) { have_excess_path = true; return false; } return true; }); if (have_excess_path) continue; contract_nodes.insert(out); } if (contract_nodes.empty()) break; for (auto dst_node : contract_nodes) { UnionFindCombine(node_map, brief_node->node->id(), dst_node->node->id()); UnionContractedNodes(brief_node_map, brief_node->node->id(), dst_node->node->id()); } } } std::unordered_map<int /*ancestor*/, std::vector<Node *>> clusters; for (auto *n : marked_nodes) { if (n->IsOp()) { clusters[UnionFindGetAncestor(node_map, Agent(n).union_find_parent())] .push_back(n); } } std::vector<std::vector<Node *>> result; std::for_each(clusters.begin(), clusters.end(), [&](const decltype(clusters)::value_type &it) { result.push_back(it.second); }); return result; } void SubGraphFuser::operator()() { ReplaceNodesWithSubGraphs(); } void RemoveIntermediateOutputInSubgraph(const std::vector<Node *> &subgraph, Graph *graph, std::vector<Node *> *outputs) { std::unordered_set<Node *> subgraph_set(subgraph.begin(), subgraph.end()); std::unordered_set<Node *> valid_output; for (auto *output : *outputs) { int num_used = 0; for (auto *node : output->outputs) { if (!subgraph_set.count(node)) ++num_used; if (num_used > 0) valid_output.insert(output); } } // In use for ngraph subgraph pass for parallel executor, // this will remove all nodes, bypass this and let ngraph // subgraph pass to process outputs if (FLAGS_use_ngraph && valid_output.size() == 0) return; outputs->assign(valid_output.begin(), valid_output.end()); } void DetachDeletedNodes(framework::ir::Graph *graph) { std::unordered_set<const Node *> nodes; for (auto *node : graph->Nodes()) { if (Agent(node).deleted()) { node->inputs.clear(); node->outputs.clear(); } } } void SubGraphFuser::ReplaceNodesWithSubGraphs() { auto subgraphs = SubgraphDetector(graph_, node_inside_subgraph_teller_)(); for (auto &subgraph : subgraphs) { if (subgraph.size() <= (size_t)min_subgraph_size_) continue; std::unordered_set<Node *> subgraph_uniq(subgraph.begin(), subgraph.end()); // replace this sub-graph with the first node. Two steps: 1. Create a Block // Node that contains this subgraph 2. Mark the nodes inside the sub-graph // as deleted. 3. Replace the deleted node with the new Block Node. framework::OpDesc empty_desc; empty_desc.SetType(name_); auto *block_node = graph_->CreateOpNode(&empty_desc); Agent(block_node).set_subgraph({}); auto io = ExtractInputAndOutputOfSubGraph(subgraph); block_node->inputs = std::move(io.first); block_node->outputs = std::move(io.second); RemoveIntermediateOutputInSubgraph(subgraph, graph_, &block_node->outputs); for (auto *node : subgraph) { // TODO(Superjomn) need a unified mechanism to treat deleted node in each // pass. Agent(node).set_deleted(true); Agent(block_node).subgraph()->push_back(node); } // Change all the sub-graph's inputs and outputs corresponding inlink and // outlink to this sub-graph node. auto inlink_or_outlink_cleaner = [&](std::vector<Node *> &nodes) { for (auto *&n : nodes) { if (subgraph_uniq.count(n)) { n = block_node; } } std::unordered_set<Node *> uniq(nodes.begin(), nodes.end()); nodes.assign(uniq.begin(), uniq.end()); }; for (auto *i : block_node->inputs) { inlink_or_outlink_cleaner(i->outputs); } for (auto *&o : block_node->outputs) { inlink_or_outlink_cleaner(o->inputs); } } // DetachDeletedNodes(graph_); FilterRedundantOutputOfSubGraph(graph_); } inline bool CheckNodeIndegreeEquals(const Node &node, size_t n) { return node.inputs.size() == n; } } // namespace ir } // namespace framework } // namespace paddle
/********************************************************************** * Copyright (c) 2008-2014, Alliance for Sustainable Energy. * All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA **********************************************************************/ #include <utilities/data/Attribute.hpp> #include <utilities/data/Attribute_Impl.hpp> #include <utilities/core/Assert.hpp> #include <utilities/core/Containers.hpp> #include <utilities/core/Json.hpp> #include <utilities/units/UnitFactory.hpp> #include <utilities/units/Quantity.hpp> #include <utilities/units/QuantityFactory.hpp> #include <utilities/units/OSOptionalQuantity.hpp> #include <boost/foreach.hpp> #include <boost/regex.hpp> #include <boost/lexical_cast.hpp> #include <boost/bind.hpp> #include <sstream> #include <limits> #include <QDomElement> #include <QDomDocument> #include <QFile> namespace openstudio { namespace detail{ //int __attribute_type__ = qRegisterMetaType<openstudio::Attribute>("openstudio::Attribute"); int __attribute_optional_type__ = qRegisterMetaType<boost::optional<openstudio::Attribute> >("boost::optional<openstudio::Attribute>"); int __attribute_vector_type__ = qRegisterMetaType<std::vector<openstudio::Attribute> >("std::vector<openstudio::Attribute>"); // constructors Attribute_Impl::Attribute_Impl(const std::string& name, bool value, const boost::optional<std::string>& units) : m_uuid(createUUID()), m_versionUUID(createUUID()), m_name(name), m_valueType(AttributeValueType::Boolean), m_value(value), m_units(units) { } Attribute_Impl::Attribute_Impl(const openstudio::UUID& uuid, const openstudio::UUID& versionUUID, const std::string& name, const boost::optional<std::string>& displayName, bool value, const boost::optional<std::string>& units) : m_uuid(uuid), m_versionUUID(versionUUID), m_name(name), m_displayName(displayName), m_valueType(AttributeValueType::Boolean), m_value(value), m_units(units) { } Attribute_Impl::Attribute_Impl(const std::string& name, double value, const boost::optional<std::string>& units) : m_uuid(createUUID()), m_versionUUID(createUUID()), m_name(name), m_valueType(AttributeValueType::Double), m_value(value), m_units(units) { } Attribute_Impl::Attribute_Impl(const openstudio::UUID& uuid, const openstudio::UUID& versionUUID, const std::string& name, const boost::optional<std::string>& displayName, double value, const boost::optional<std::string>& units) : m_uuid(uuid), m_versionUUID(versionUUID), m_name(name), m_displayName(displayName), m_valueType(AttributeValueType::Double), m_value(value), m_units(units) { } Attribute_Impl::Attribute_Impl(const std::string& name, const OSOptionalQuantity& value) : m_uuid(createUUID()), m_versionUUID(createUUID()), m_name(name) { if (value.isSet()) { m_valueType = AttributeValueType::Quantity; m_value = QVariant::fromValue(value.get()); } else { m_valueType = AttributeValueType::Unit; m_value = QVariant::fromValue(value); } } Attribute_Impl::Attribute_Impl(const std::string& name, const Quantity& value) : m_uuid(createUUID()), m_versionUUID(createUUID()), m_name(name), m_valueType(AttributeValueType::Quantity), m_value(QVariant::fromValue(value)) { } Attribute_Impl::Attribute_Impl(const openstudio::UUID& uuid, const openstudio::UUID& versionUUID, const std::string& name, const boost::optional<std::string>& displayName, const Quantity& value) : m_uuid(uuid), m_versionUUID(versionUUID), m_name(name), m_displayName(displayName), m_valueType(AttributeValueType::Quantity), m_value(QVariant::fromValue(value)) { } Attribute_Impl::Attribute_Impl(const std::string& name, const Unit& value) : m_uuid(createUUID()), m_versionUUID(createUUID()), m_name(name), m_valueType(AttributeValueType::Unit), m_value(QVariant::fromValue(OSOptionalQuantity(value))) { } Attribute_Impl::Attribute_Impl(const openstudio::UUID& uuid, const openstudio::UUID& versionUUID, const std::string& name, const boost::optional<std::string>& displayName, const Unit& value) : m_uuid(uuid), m_versionUUID(versionUUID), m_name(name), m_displayName(displayName), m_valueType(AttributeValueType::Unit), m_value(QVariant::fromValue(OSOptionalQuantity(value))) { } Attribute_Impl::Attribute_Impl(const std::string& name, int value, const boost::optional<std::string>& units) : m_uuid(createUUID()), m_versionUUID(createUUID()), m_name(name), m_valueType(AttributeValueType::Integer), m_value(value), m_units(units) { } Attribute_Impl::Attribute_Impl(const openstudio::UUID& uuid, const openstudio::UUID& versionUUID, const std::string& name, const boost::optional<std::string>& displayName, int value, const boost::optional<std::string>& units) : m_uuid(uuid), m_versionUUID(versionUUID), m_name(name), m_displayName(displayName), m_valueType(AttributeValueType::Integer), m_value(value), m_units(units) { } Attribute_Impl::Attribute_Impl(const std::string& name, unsigned value, const boost::optional<std::string>& units) : m_uuid(createUUID()), m_versionUUID(createUUID()), m_name(name), m_valueType(AttributeValueType::Unsigned), m_value(value), m_units(units) { } Attribute_Impl::Attribute_Impl(const openstudio::UUID& uuid, const openstudio::UUID& versionUUID, const std::string& name, const boost::optional<std::string>& displayName, unsigned value, const boost::optional<std::string>& units) : m_uuid(uuid), m_versionUUID(versionUUID), m_name(name), m_displayName(displayName), m_valueType(AttributeValueType::Unsigned), m_value(value), m_units(units) { } Attribute_Impl::Attribute_Impl(const std::string& name, const char* value, const boost::optional<std::string>& units) : m_uuid(createUUID()), m_versionUUID(createUUID()), m_name(name), m_valueType(AttributeValueType::String), m_value(), m_units(units) { m_value.setValue(std::string(value)); } Attribute_Impl::Attribute_Impl(const openstudio::UUID& uuid, const openstudio::UUID& versionUUID, const std::string& name, const boost::optional<std::string>& displayName, const char* value, const boost::optional<std::string>& units) : m_uuid(uuid), m_versionUUID(versionUUID), m_name(name), m_displayName(displayName), m_valueType(AttributeValueType::String), m_value(), m_units(units) { m_value.setValue(std::string(value)); } Attribute_Impl::Attribute_Impl(const std::string& name, const std::string& value, const boost::optional<std::string>& units) : m_uuid(createUUID()), m_versionUUID(createUUID()), m_name(name), m_valueType(AttributeValueType::String), m_value(), m_units(units) { m_value.setValue(value); } Attribute_Impl::Attribute_Impl(const openstudio::UUID& uuid, const openstudio::UUID& versionUUID, const std::string& name, const boost::optional<std::string>& displayName, const std::string& value, const boost::optional<std::string>& units) : m_uuid(uuid), m_versionUUID(versionUUID), m_name(name), m_displayName(displayName), m_valueType(AttributeValueType::String), m_value(), m_units(units) { m_value.setValue(value); } Attribute_Impl::Attribute_Impl(const std::string& name, const std::vector<openstudio::Attribute>& value, const boost::optional<std::string>& units) : m_uuid(createUUID()), m_versionUUID(createUUID()), m_name(name), m_valueType(AttributeValueType::AttributeVector), m_value(), m_units(units) { m_value.setValue(value); } Attribute_Impl::Attribute_Impl(const openstudio::UUID& uuid, const openstudio::UUID& versionUUID, const std::string& name, const boost::optional<std::string>& displayName, const std::vector<openstudio::Attribute>& value, const boost::optional<std::string>& units) : m_uuid(uuid), m_versionUUID(versionUUID), m_name(name), m_displayName(displayName), m_valueType(AttributeValueType::AttributeVector), m_value(), m_units(units) { m_value.setValue(value); } Attribute_Impl::Attribute_Impl(const QDomElement& element) { if(element.isNull()){ LOG_AND_THROW("Cannot construct Attribute from null QDomElement"); } QDomElement uuidElement = element.firstChildElement(QString::fromStdString("UUID")); QDomElement versionUUIDElement = element.firstChildElement(QString::fromStdString("VersionUUID")); QDomElement nameElement = element.firstChildElement(QString::fromStdString("Name")); QDomElement displayNameElement = element.firstChildElement(QString::fromStdString("DisplayName")); QDomElement valueTypeElement = element.firstChildElement(QString::fromStdString("ValueType")); QDomElement valueElement = element.firstChildElement(QString::fromStdString("Value")); QDomElement unitsElement = element.firstChildElement(QString::fromStdString("Units")); QDomElement unitSystemElement = element.firstChildElement(QString::fromStdString("UnitSystem")); if(uuidElement.isNull()){ LOG_AND_THROW("uuidElement is null"); } if(versionUUIDElement.isNull()){ LOG_AND_THROW("versionUUIDElement is null"); } if(nameElement.isNull()){ LOG_AND_THROW("nameElement is null"); } if(valueTypeElement.isNull()){ LOG_AND_THROW("valueTypeElement is null"); } if(valueElement.isNull()){ LOG_AND_THROW("valueElement is null"); } m_uuid = toUUID(uuidElement.firstChild().nodeValue().toStdString()); m_versionUUID = toUUID(versionUUIDElement.firstChild().nodeValue().toStdString()); m_name = nameElement.firstChild().nodeValue().toStdString(); if (!displayNameElement.isNull()){ m_displayName = displayNameElement.firstChild().nodeValue().toStdString(); } m_valueType = AttributeValueType(valueTypeElement.firstChild().nodeValue().toStdString()); if (!unitsElement.isNull()) { m_units = unitsElement.firstChild().nodeValue().toStdString(); } OptionalUnitSystem sys; if (!unitSystemElement.isNull()) { sys = UnitSystem(unitSystemElement.firstChild().nodeValue().toStdString()); } std::vector<Attribute> children; QDomNodeList childNodes = valueElement.childNodes(); switch(m_valueType.value()){ case AttributeValueType::Boolean: if (valueElement.firstChild().nodeValue() == "true"){ m_value = true; }else{ m_value = false; } break; case AttributeValueType::Integer: m_value = valueElement.firstChild().nodeValue().toInt(); break; case AttributeValueType::Unsigned: m_value = valueElement.firstChild().nodeValue().toUInt(); break; case AttributeValueType::Double: m_value = valueElement.firstChild().nodeValue().toDouble(); break; case AttributeValueType::Quantity : OS_ASSERT(m_units); OS_ASSERT(sys); m_value = QVariant::fromValue(Quantity(valueElement.firstChild().nodeValue().toDouble(),createUnit(*m_units,*sys).get())); m_units.reset(); break; case AttributeValueType::Unit : OS_ASSERT(m_units); OS_ASSERT(sys); m_value = QVariant::fromValue(OSOptionalQuantity(createUnit(*m_units,*sys).get())); m_units.reset(); break; case AttributeValueType::String: m_value.setValue(valueElement.firstChild().nodeValue().toStdString()); break; case AttributeValueType::AttributeVector: for (int i = 0; i < childNodes.count(); i++){ QDomElement childElement = childNodes.at(i).toElement(); children.push_back(Attribute(childElement)); } m_value.setValue(children); break; default: OS_ASSERT(false); break; } } Attribute_Impl::Attribute_Impl(const Attribute_Impl& other) : m_uuid(createUUID()), m_versionUUID(createUUID()), m_name(other.name()), m_displayName(other.displayName()), m_valueType(other.valueType()), m_value(other.valueAsQVariant()), m_units(other.units()) {} openstudio::UUID Attribute_Impl::uuid() const { return m_uuid; } openstudio::UUID Attribute_Impl::versionUUID() const { return m_versionUUID; } std::string Attribute_Impl::name() const { return m_name; } boost::optional<std::string> Attribute_Impl::displayName() const { return m_displayName; } bool Attribute_Impl::setDisplayName(const std::string& displayName) { m_displayName = displayName; m_versionUUID = createUUID(); return true; } AttributeValueType Attribute_Impl::valueType() const { return m_valueType; } bool Attribute_Impl::valueAsBoolean() const { if(!m_value.isValid() || m_value.isNull() || m_valueType != AttributeValueType::Boolean){ LOG_AND_THROW("Cannot convert attribute '" << name() << "' of type " << valueType().valueDescription() << " to Boolean."); } return m_value.value<bool>(); } void Attribute_Impl::setValue(bool value) { if (m_valueType != AttributeValueType::Boolean) { LOG_AND_THROW("Attribute is '" << name() << "' is of type " << valueType().valueDescription() << ", not Boolean."); } m_value = value; m_versionUUID = createUUID(); } int Attribute_Impl::valueAsInteger() const { if(!m_value.isValid() || m_value.isNull() || m_valueType != AttributeValueType::Integer){ LOG_AND_THROW("Cannot convert attribute '" << name() << "' of type " << valueType().valueDescription() << " to Integer."); } return m_value.value<int>(); } void Attribute_Impl::setValue(int value) { if (m_valueType != AttributeValueType::Integer) { LOG_AND_THROW("Attribute is '" << name() << "' is of type " << valueType().valueDescription() << ", not Integer."); } m_value = value; m_versionUUID = createUUID(); } unsigned Attribute_Impl::valueAsUnsigned() const { if(!m_value.isValid() || m_value.isNull() || m_valueType != AttributeValueType::Unsigned){ LOG_AND_THROW("Cannot convert attribute '" << name() << "' of type " << valueType().valueDescription() << " to Unsigned."); } return m_value.value<unsigned>(); } void Attribute_Impl::setValue(unsigned value) { if (m_valueType != AttributeValueType::Unsigned) { LOG_AND_THROW("Attribute is '" << name() << "' is of type " << valueType().valueDescription() << ", not Unsigned."); } m_value = value; m_versionUUID = createUUID(); } double Attribute_Impl::valueAsDouble() const { if(!m_value.isValid() || m_value.isNull() || m_valueType != AttributeValueType::Double){ LOG_AND_THROW("Cannot convert attribute '" << name() << "' of type " << valueType().valueDescription() << " to Double."); } return m_value.value<double>(); } void Attribute_Impl::setValue(double value) { if (m_valueType != AttributeValueType::Double) { LOG_AND_THROW("Attribute is '" << name() << "' is of type " << valueType().valueDescription() << ", not Double."); } m_value = value; m_versionUUID = createUUID(); } Quantity Attribute_Impl::valueAsQuantity() const { if(!m_value.isValid() || m_value.isNull() || m_valueType != AttributeValueType::Quantity){ LOG_AND_THROW("Cannot convert attribute '" << name() << "' of type " << valueType().valueDescription() << " to Quantity."); } return m_value.value<openstudio::Quantity>(); } void Attribute_Impl::setValue(const Quantity& value) { if (m_valueType != AttributeValueType::Quantity) { LOG_AND_THROW("Attribute is '" << name() << "' is of type " << valueType().valueDescription() << ", not Quantity."); } m_value.setValue(value); m_versionUUID = createUUID(); } Unit Attribute_Impl::valueAsUnit() const { if(!m_value.isValid() || m_value.isNull() || m_valueType != AttributeValueType::Unit){ LOG_AND_THROW("Cannot convert attribute '" << name() << "' of type " << valueType().valueDescription() << " to Unit."); } return m_value.value<openstudio::OSOptionalQuantity>().units(); } void Attribute_Impl::setValue(const Unit& value) { if (m_valueType != AttributeValueType::Unit) { LOG_AND_THROW("Attribute is '" << name() << "' is of type " << valueType().valueDescription() << ", not Unit."); } m_value.setValue(OSOptionalQuantity(value)); m_versionUUID = createUUID(); } std::string Attribute_Impl::valueAsString() const { if(!m_value.isValid() || m_value.isNull() || m_valueType != AttributeValueType::String){ LOG_AND_THROW("Cannot convert attribute '" << name() << "' of type " << valueType().valueDescription() << " to String."); } return m_value.value<std::string>(); } void Attribute_Impl::setValue(const char* value) { if (m_valueType != AttributeValueType::String) { LOG_AND_THROW("Attribute is '" << name() << "' is of type " << valueType().valueDescription() << ", not String."); } m_value.setValue(std::string(value)); m_versionUUID = createUUID(); } void Attribute_Impl::setValue(const std::string& value) { if (m_valueType != AttributeValueType::String) { LOG_AND_THROW("Attribute is '" << name() << "' is of type " << valueType().valueDescription() << ", not String."); } m_value.setValue(value); m_versionUUID = createUUID(); } std::vector<Attribute> Attribute_Impl::valueAsAttributeVector() const { if(!m_value.isValid() || m_value.isNull() || m_valueType != AttributeValueType::AttributeVector){ LOG_AND_THROW("Cannot convert attribute '" << name() << "' of type " << valueType().valueDescription() << " to AttributeVector."); } return m_value.value<std::vector<Attribute> >(); } void Attribute_Impl::setValue(const std::vector<Attribute>& value) { if (m_valueType != AttributeValueType::AttributeVector) { LOG_AND_THROW("Attribute is '" << name() << "' is of type " << valueType().valueDescription() << ", not AttributeVector."); } m_value.setValue(value); m_versionUUID = createUUID(); } QVariant Attribute_Impl::valueAsQVariant() const { return m_value; } struct FindChildByName { FindChildByName(const std::string& name) : m_name(name) {} bool operator()(const Attribute& attribute) { return m_name == attribute.name(); } std::string m_name; }; boost::optional<Attribute> Attribute_Impl::findChildByName(const std::string& name) const { boost::optional<Attribute> result; if (m_value.isValid() && !m_value.isNull() && m_valueType == AttributeValueType::AttributeVector){ std::vector<Attribute> children = this->valueAsAttributeVector(); std::vector<Attribute>::const_iterator it = std::find_if(children.begin(), children.end(), FindChildByName(name)); if (it != children.end()){ result = *it; } } return result; } boost::optional<std::string> Attribute_Impl::units() const { return m_units; } bool Attribute_Impl::setUnits(const std::string& units) { m_units = units; m_versionUUID = createUUID(); return true; } std::string Attribute_Impl::toString() const { std::string result; std::stringstream ss; QString str; QTextStream qts(&str); switch(this->valueType().value()) { case AttributeValueType::Boolean: if (this->valueAsBoolean()) { result = "true"; } else { result = "false"; } break; case AttributeValueType::Integer: result = boost::lexical_cast<std::string>(this->valueAsInteger()); break; case AttributeValueType::Unsigned: result = boost::lexical_cast<std::string>(this->valueAsUnsigned()); break; case AttributeValueType::Double: result = openstudio::toString(this->valueAsDouble()); break; case AttributeValueType::Quantity : ss << this->valueAsQuantity(); result = ss.str(); break; case AttributeValueType::Unit : ss << this->valueAsUnit(); result = ss.str(); break; case AttributeValueType::String : result = this->valueAsString(); break; case AttributeValueType::AttributeVector: this->toXml().save(qts, 2); result = str.toStdString(); break; default: OS_ASSERT(false); break; } return result; } QDomDocument Attribute_Impl::toXml() const { QDomDocument doc; QDomElement element = doc.createElement(QString("Attribute")); OS_ASSERT(!element.isNull()); this->writeValues(doc, element); doc.appendChild(element); return doc; } bool Attribute_Impl::operator==(const Attribute& other) const { bool result = false; QVariant otherValue = other.valueAsQVariant(); if (this->valueType() == AttributeValueType::Quantity) { if (otherValue.canConvert<openstudio::Quantity>()) { result = (this->valueAsQuantity() == otherValue.value<openstudio::Quantity>()); } }else if (this->valueType() == AttributeValueType::Unit) { if (otherValue.canConvert<openstudio::OSOptionalQuantity>()) { result = (this->valueAsUnit() == otherValue.value<openstudio::OSOptionalQuantity>().units()); } }else if (this->valueType() == AttributeValueType::String){ if (otherValue.canConvert<std::string>()){ result = (this->valueAsString() == otherValue.value<std::string>()); } }else if (this->valueType() == AttributeValueType::AttributeVector){ if (otherValue.canConvert<std::vector<Attribute> >()){ std::vector<Attribute> thisAttributes = this->valueAsAttributeVector(); std::vector<Attribute> otherAttributes = other.valueAsAttributeVector(); if (thisAttributes.size() == otherAttributes.size()){ result = true; for (unsigned i = 0; i < thisAttributes.size(); ++i){ result = result && (thisAttributes[i] == otherAttributes[i]); if (!result){ break; } } } } }else{ result = (m_value == otherValue); } if (m_units){ result = result && other.units() && (*m_units == other.units().get()); }else{ result = result && !other.units(); } return result; } void Attribute_Impl::writeValues(QDomDocument& doc, QDomElement& element) const { QDomElement childElement; QDomText text; childElement = doc.createElement(QString::fromStdString("UUID")); text = doc.createTextNode(m_uuid.toString()); childElement.appendChild(text); element.appendChild(childElement); childElement = doc.createElement(QString::fromStdString("VersionUUID")); text = doc.createTextNode(m_versionUUID.toString()); childElement.appendChild(text); element.appendChild(childElement); childElement = doc.createElement(QString::fromStdString("Name")); text = doc.createTextNode(toQString(m_name)); childElement.appendChild(text); element.appendChild(childElement); if (m_displayName){ childElement = doc.createElement(QString::fromStdString("DisplayName")); text = doc.createTextNode(toQString(*m_displayName)); childElement.appendChild(text); element.appendChild(childElement); } childElement = doc.createElement(QString::fromStdString("ValueType")); text = doc.createTextNode(toQString(m_valueType.valueName())); childElement.appendChild(text); element.appendChild(childElement); std::string temp; childElement = doc.createElement(QString::fromStdString("Value")); switch(m_valueType.value()){ case AttributeValueType::Boolean: text = doc.createTextNode(this->valueAsBoolean() ? QString::fromStdString("true") : QString::fromStdString("false")); childElement.appendChild(text); break; case AttributeValueType::Integer: text = doc.createTextNode(QString::number(this->valueAsInteger())); childElement.appendChild(text); break; case AttributeValueType::Unsigned: text = doc.createTextNode(QString::number(this->valueAsUnsigned())); childElement.appendChild(text); break; case AttributeValueType::Double: temp = boost::regex_replace(openstudio::toString(QString::number(this->valueAsDouble(), 'G', std::numeric_limits<double>::digits10)), boost::regex("\\+"),""); text = doc.createTextNode(toQString(temp)); childElement.appendChild(text); break; case AttributeValueType::Quantity: temp = boost::regex_replace(openstudio::toString(QString::number(this->valueAsQuantity().value(), 'G', std::numeric_limits<double>::digits10)), boost::regex("\\+"),""); text = doc.createTextNode(toQString(temp)); childElement.appendChild(text); break; case AttributeValueType::Unit: text = doc.createTextNode(QString()); childElement.appendChild(text); break; case AttributeValueType::String: text = doc.createTextNode(QString::fromStdString(this->valueAsString())); childElement.appendChild(text); break; case AttributeValueType::AttributeVector: BOOST_FOREACH(const Attribute& Attribute, this->valueAsAttributeVector()){ childElement.appendChild(Attribute.toXml().documentElement()); } break; default: OS_ASSERT(false); break; } element.appendChild(childElement); if ((m_valueType.value() == AttributeValueType::Quantity) || (m_valueType.value() == AttributeValueType::Unit)) { OptionalUnit units; if (m_valueType.value() == AttributeValueType::Quantity) { units = this->valueAsQuantity().units(); } else { units = this->valueAsUnit(); } childElement = doc.createElement(QString::fromStdString("Units")); text = doc.createTextNode(QString::fromStdString(units->standardString())); childElement.appendChild(text); element.appendChild(childElement); childElement = doc.createElement(QString::fromStdString("UnitSystem")); text = doc.createTextNode(QString::fromStdString(units->system().valueName())); childElement.appendChild(text); element.appendChild(childElement); }else if(m_units){ childElement = doc.createElement(QString::fromStdString("Units")); text = doc.createTextNode(QString::fromStdString(*m_units)); childElement.appendChild(text); element.appendChild(childElement); } } void Attribute_Impl::setValue(const QVariant& value, bool check) { if (check) { if (OptionalAttribute validator = Attribute::fromQVariant(name(),value)) { if (validator->valueType() != valueType()) { LOG_AND_THROW("QVariant value of type " << value.typeName() << " does not convert to AttributeValueType " << valueType().valueDescription() << "."); } } else { LOG_AND_THROW("Unable to construct Attribute using QVariant value of type " << value.typeName() << "."); } } m_value = value; } } // detail AttributeDescription::AttributeDescription(const std::string& t_name, const std::string& t_displayName, const std::string& t_description, const AttributeValueType& t_validValueType, bool t_required) : name(t_name), displayName(t_displayName), description(t_description), validValueTypes(1u,t_validValueType), required(t_required) {} AttributeDescription::AttributeDescription(const std::string& t_name, const std::string& t_displayName, const std::string& t_description, const AttributeValueType& t_validValueType, bool t_required, QVariant t_defaultValue) : name(t_name), displayName(t_displayName), description(t_description), validValueTypes(1u,t_validValueType), required(t_required), defaultValue(t_defaultValue) {} AttributeDescription::AttributeDescription(const std::string& t_name, const std::string& t_displayName, const std::string& t_description, const std::vector<AttributeValueType>& t_validValueTypes, bool t_required) : name(t_name), displayName(t_displayName), description(t_description), validValueTypes(t_validValueTypes), required(t_required) {} AttributeDescription::AttributeDescription(const std::string& t_name, const std::string& t_displayName, const std::string& t_description, const std::vector<AttributeValueType>& t_validValueTypes, bool t_required, QVariant t_defaultValue) : name(t_name), displayName(t_displayName), description(t_description), validValueTypes(t_validValueTypes), required(t_required), defaultValue(t_defaultValue) {} Attribute::Attribute(const std::string& name, bool value) : m_impl(boost::shared_ptr<detail::Attribute_Impl>( new detail::Attribute_Impl(name, value, boost::none))) { OS_ASSERT(m_impl); } Attribute::Attribute(const std::string& name, bool value, const std::string& units) : m_impl(boost::shared_ptr<detail::Attribute_Impl>( new detail::Attribute_Impl(name, value, units))) { OS_ASSERT(m_impl); } Attribute::Attribute(const std::string& name, bool value, const boost::optional<std::string>& units) : m_impl(boost::shared_ptr<detail::Attribute_Impl>( new detail::Attribute_Impl(name, value, units))) { OS_ASSERT(m_impl); } Attribute::Attribute(const openstudio::UUID& uuid, const openstudio::UUID& versionUUID, const std::string& name, const boost::optional<std::string>& displayName, bool value, const boost::optional<std::string>& units) : m_impl(boost::shared_ptr<detail::Attribute_Impl>( new detail::Attribute_Impl(uuid, versionUUID, name, displayName, value, units))) { OS_ASSERT(m_impl); } Attribute::Attribute(const std::string& name, double value) : m_impl(boost::shared_ptr<detail::Attribute_Impl>( new detail::Attribute_Impl(name, value, boost::none))) { OS_ASSERT(m_impl); } Attribute::Attribute(const std::string& name, double value, const std::string& units) : m_impl(boost::shared_ptr<detail::Attribute_Impl>( new detail::Attribute_Impl(name, value, units))) { OS_ASSERT(m_impl); } Attribute::Attribute(const std::string& name, double value, const boost::optional<std::string>& units) : m_impl(boost::shared_ptr<detail::Attribute_Impl>( new detail::Attribute_Impl(name, value, units))) { OS_ASSERT(m_impl); } Attribute::Attribute(const openstudio::UUID& uuid, const openstudio::UUID& versionUUID, const std::string& name, const boost::optional<std::string>& displayName, double value, const boost::optional<std::string>& units) : m_impl(boost::shared_ptr<detail::Attribute_Impl>( new detail::Attribute_Impl(uuid, versionUUID, name, displayName, value, units))) { OS_ASSERT(m_impl); } Attribute::Attribute(const std::string& name, const OSOptionalQuantity& value) : m_impl(boost::shared_ptr<detail::Attribute_Impl>( new detail::Attribute_Impl(name,value))) { OS_ASSERT(m_impl); } Attribute::Attribute(const std::string& name, const Quantity& value) : m_impl(boost::shared_ptr<detail::Attribute_Impl>( new detail::Attribute_Impl(name, value))) { OS_ASSERT(m_impl); } Attribute::Attribute(const openstudio::UUID& uuid, const openstudio::UUID& versionUUID, const std::string& name, const boost::optional<std::string>& displayName, const Quantity& value) : m_impl(boost::shared_ptr<detail::Attribute_Impl>( new detail::Attribute_Impl(uuid, versionUUID, name, displayName, value))) { OS_ASSERT(m_impl); } Attribute::Attribute(const std::string& name, const Unit& value) : m_impl(boost::shared_ptr<detail::Attribute_Impl>( new detail::Attribute_Impl(name,value))) { OS_ASSERT(m_impl); } Attribute::Attribute(const openstudio::UUID& uuid, const openstudio::UUID& versionUUID, const std::string& name, const boost::optional<std::string>& displayName, const Unit& value) : m_impl(boost::shared_ptr<detail::Attribute_Impl>( new detail::Attribute_Impl(uuid, versionUUID, name, displayName, value))) { OS_ASSERT(m_impl); } Attribute::Attribute(const std::string& name, int value) : m_impl(boost::shared_ptr<detail::Attribute_Impl>( new detail::Attribute_Impl(name, value, boost::none))) { OS_ASSERT(m_impl); } Attribute::Attribute(const std::string& name, int value, const std::string& units) : m_impl(boost::shared_ptr<detail::Attribute_Impl>( new detail::Attribute_Impl(name, value, units))) { OS_ASSERT(m_impl); } Attribute::Attribute(const std::string& name, int value, const boost::optional<std::string>& units) : m_impl(boost::shared_ptr<detail::Attribute_Impl>( new detail::Attribute_Impl(name, value, units))) { OS_ASSERT(m_impl); } Attribute::Attribute(const openstudio::UUID& uuid, const openstudio::UUID& versionUUID, const std::string& name, const boost::optional<std::string>& displayName, int value, const boost::optional<std::string>& units) : m_impl(boost::shared_ptr<detail::Attribute_Impl>( new detail::Attribute_Impl(uuid, versionUUID, name, displayName, value, units))) { OS_ASSERT(m_impl); } Attribute::Attribute(const std::string& name, unsigned value) : m_impl(boost::shared_ptr<detail::Attribute_Impl>( new detail::Attribute_Impl(name, value, boost::none))) { OS_ASSERT(m_impl); } Attribute::Attribute(const std::string& name, unsigned value, const std::string& units) : m_impl(boost::shared_ptr<detail::Attribute_Impl>( new detail::Attribute_Impl(name, value, units))) { OS_ASSERT(m_impl); } Attribute::Attribute(const std::string& name, unsigned value, const boost::optional<std::string>& units) : m_impl(boost::shared_ptr<detail::Attribute_Impl>( new detail::Attribute_Impl(name, value, units))) { OS_ASSERT(m_impl); } Attribute::Attribute(const openstudio::UUID& uuid, const openstudio::UUID& versionUUID, const std::string& name, const boost::optional<std::string>& displayName, unsigned value, const boost::optional<std::string>& units) : m_impl(boost::shared_ptr<detail::Attribute_Impl>( new detail::Attribute_Impl(uuid, versionUUID, name, displayName, value, units))) { OS_ASSERT(m_impl); } Attribute::Attribute(const std::string& name, const char* value) : m_impl(boost::shared_ptr<detail::Attribute_Impl>( new detail::Attribute_Impl(name, value, boost::none))) { OS_ASSERT(m_impl); } Attribute::Attribute(const std::string& name, const char* value, const std::string& units) : m_impl(boost::shared_ptr<detail::Attribute_Impl>( new detail::Attribute_Impl(name, value, units))) { OS_ASSERT(m_impl); } Attribute::Attribute(const std::string& name, const char* value, const boost::optional<std::string>& units) : m_impl(boost::shared_ptr<detail::Attribute_Impl>( new detail::Attribute_Impl(name, value, units))) { OS_ASSERT(m_impl); } Attribute::Attribute(const openstudio::UUID& uuid, const openstudio::UUID& versionUUID, const std::string& name, const boost::optional<std::string>& displayName, const char* value, const boost::optional<std::string>& units) : m_impl(boost::shared_ptr<detail::Attribute_Impl>( new detail::Attribute_Impl(uuid, versionUUID, name, displayName, value, units))) { OS_ASSERT(m_impl); } Attribute::Attribute(const std::string& name, const std::string& value) : m_impl(boost::shared_ptr<detail::Attribute_Impl>( new detail::Attribute_Impl(name, value, boost::none))) { OS_ASSERT(m_impl); } Attribute::Attribute(const std::string& name, const std::string& value, const std::string& units) : m_impl(boost::shared_ptr<detail::Attribute_Impl>( new detail::Attribute_Impl(name, value, units))) { OS_ASSERT(m_impl); } Attribute::Attribute(const std::string& name, const std::string& value, const boost::optional<std::string>& units) : m_impl(boost::shared_ptr<detail::Attribute_Impl>( new detail::Attribute_Impl(name, value, units))) { OS_ASSERT(m_impl); } Attribute::Attribute(const openstudio::UUID& uuid, const openstudio::UUID& versionUUID, const std::string& name, const boost::optional<std::string>& displayName, const std::string& value, const boost::optional<std::string>& units) : m_impl(boost::shared_ptr<detail::Attribute_Impl>( new detail::Attribute_Impl(uuid, versionUUID, name, displayName, value, units))) { OS_ASSERT(m_impl); } Attribute::Attribute(const std::string& name, const std::vector<openstudio::Attribute>& value) : m_impl(boost::shared_ptr<detail::Attribute_Impl>( new detail::Attribute_Impl(name, value, boost::none))) { OS_ASSERT(m_impl); } Attribute::Attribute(const std::string& name, const std::vector<openstudio::Attribute>& value, const std::string& units) : m_impl(boost::shared_ptr<detail::Attribute_Impl>( new detail::Attribute_Impl(name, value, units))) { OS_ASSERT(m_impl); } Attribute::Attribute(const std::string& name, const std::vector<openstudio::Attribute>& value, const boost::optional<std::string>& units) : m_impl(boost::shared_ptr<detail::Attribute_Impl>(new detail::Attribute_Impl(name, value, units))) { OS_ASSERT(m_impl); } Attribute::Attribute(const openstudio::UUID& uuid, const openstudio::UUID& versionUUID, const std::string& name, const boost::optional<std::string>& displayName, const std::vector<openstudio::Attribute>& value, const boost::optional<std::string>& units) : m_impl(boost::shared_ptr<detail::Attribute_Impl>( new detail::Attribute_Impl(uuid, versionUUID, name, displayName, value, units))) { OS_ASSERT(m_impl); } Attribute::Attribute(const QDomElement& element) : m_impl(boost::shared_ptr<detail::Attribute_Impl>(new detail::Attribute_Impl(element))) { OS_ASSERT(m_impl); } Attribute::Attribute(const Attribute& other) : m_impl(other.m_impl) { OS_ASSERT(m_impl); } Attribute Attribute::clone() const { Attribute result(boost::shared_ptr<detail::Attribute_Impl>(new detail::Attribute_Impl(*m_impl))); return result; } Attribute::Attribute(const boost::shared_ptr<detail::Attribute_Impl>& impl) : m_impl(impl) { OS_ASSERT(m_impl); } boost::optional<Attribute> Attribute::fromQVariant(const std::string& name, const QVariant& value, const boost::optional<std::string>& units) { boost::optional<Attribute> result; std::string typeName = value.typeName(); switch (value.type()) { case QVariant::Bool : result = Attribute(name, value.toBool(), units); break; case QVariant::Int : result = Attribute(name, value.toInt(), units); break; case QVariant::UInt : result = Attribute(name, value.toUInt(), units); break; case QVariant::Double : result = Attribute(name, value.toDouble(), units); break; case QVariant::UserType : if (typeName == "std::string") { result = Attribute(name, value.value<std::string>(), units); }else if (typeName == "openstudio::Attribute") { LOG(Error, "openstudio::Attribute is not yet registered with QMetaType"); //result = value.value<openstudio::Attribute>(); }else if (typeName == "boost::optional<int>") { boost::optional<int> test = value.value<boost::optional<int> >(); if (test){ result = Attribute(name, *test, units); } }else if (typeName == "boost::optional<unsigned>") { boost::optional<unsigned> test = value.value<boost::optional<unsigned> >(); if (test){ result = Attribute(name, *test, units); } }else if (typeName == "boost::optional<double>") { boost::optional<double> test = value.value<boost::optional<double> >(); if (test){ result = Attribute(name, *test, units); } }else if (typeName == "openstudio::Quantity") { result = Attribute(name,value.value<openstudio::Quantity>()); }else if (typeName == "openstudio::OSOptionalQuantity") { result = Attribute(name,value.value<openstudio::OSOptionalQuantity>()); }else if (typeName == "boost::optional<std::string>") { boost::optional<std::string> test = value.value<boost::optional<std::string> >(); if (test){ result = Attribute(name, *test, units); } }else if (typeName == "boost::optional<openstudio::Attribute>") { boost::optional<openstudio::Attribute> test = value.value<boost::optional<openstudio::Attribute> >(); if (test){ result = *test; } }else if (typeName == "std::vector<openstudio::Attribute>") { result = Attribute(name,value.value<std::vector<openstudio::Attribute> >(),units); } break; default: ; }; return result; } boost::optional<Attribute> Attribute::loadFromXml(const openstudio::path& path) { boost::optional<Attribute> result; if (boost::filesystem::exists(path)){ try{ QFile file(toQString(path)); file.open(QFile::ReadOnly); QDomDocument qDomDocument; qDomDocument.setContent(&file); file.close(); result = Attribute(qDomDocument.documentElement()); }catch(...){ } } return result; } openstudio::UUID Attribute::uuid() const { return m_impl->uuid(); } openstudio::UUID Attribute::versionUUID() const { return m_impl->versionUUID(); } std::string Attribute::name() const { return m_impl->name(); } boost::optional<std::string> Attribute::displayName() const { return m_impl->displayName(); } bool Attribute::setDisplayName(const std::string& displayName) { return m_impl->setDisplayName(displayName); } AttributeValueType Attribute::valueType() const { return m_impl->valueType(); } bool Attribute::valueAsBoolean() const { return m_impl->valueAsBoolean(); } void Attribute::setValue(bool value) { m_impl->setValue(value); } int Attribute::valueAsInteger() const { return m_impl->valueAsInteger(); } void Attribute::setValue(int value) { m_impl->setValue(value); } unsigned Attribute::valueAsUnsigned() const { return m_impl->valueAsUnsigned(); } void Attribute::setValue(unsigned value) { m_impl->setValue(value); } double Attribute::valueAsDouble() const { return m_impl->valueAsDouble(); } void Attribute::setValue(double value) { m_impl->setValue(value); } Quantity Attribute::valueAsQuantity() const { return m_impl->valueAsQuantity(); } void Attribute::setValue(const Quantity& value) { m_impl->setValue(value); } Unit Attribute::valueAsUnit() const { return m_impl->valueAsUnit(); } void Attribute::setValue(const Unit& value) { m_impl->setValue(value); } std::string Attribute::valueAsString() const { return m_impl->valueAsString(); } void Attribute::setValue(const char* value) { m_impl->setValue(value); } void Attribute::setValue(const std::string& value) { m_impl->setValue(value); } std::vector<Attribute> Attribute::valueAsAttributeVector() const { return m_impl->valueAsAttributeVector(); } void Attribute::setValue(const std::vector<Attribute>& value) { m_impl->setValue(value); } QVariant Attribute::valueAsQVariant() const { return m_impl->valueAsQVariant(); } boost::optional<Attribute> Attribute::findChildByName(const std::string& name) const { return m_impl->findChildByName(name); } boost::optional<std::string> Attribute::units() const { return m_impl->units(); } bool Attribute::setUnits(const std::string& units) { return m_impl->setUnits(units); } std::string Attribute::toString() const { return m_impl->toString(); } QDomDocument Attribute::toXml() const { return m_impl->toXml(); } bool Attribute::saveToXml(const openstudio::path& path) const { bool result = false; try { QFile file(toQString(path)); file.open(QFile::WriteOnly); QTextStream out(&file); this->toXml().save(out, 2); file.close(); result = true; } catch(...) {} return result; } bool Attribute::operator==(const Attribute& other) const { return m_impl->operator==(other); } void Attribute::setValue(const QVariant& value) { m_impl->setValue(value,true); } std::ostream& operator<<(std::ostream& os, const Attribute& attribute) { QString str; QTextStream qts(&str); attribute.toXml().save(qts, 2); os << str.toStdString(); return os; } Attribute createAttributeFromVector(const std::string& name, std::vector<int> value) { AttributeVector valueAsAttributes; BOOST_FOREACH(int v,value) { Attribute attribute(std::string(),v); valueAsAttributes.push_back(attribute); } return Attribute(name,valueAsAttributes); } Attribute createAttributeFromVector(const std::string& name, std::vector<double> value) { AttributeVector valueAsAttributes; BOOST_FOREACH(double v,value) { Attribute attribute(std::string(),v); valueAsAttributes.push_back(attribute); } return Attribute(name,valueAsAttributes); } std::vector<int> getIntVectorFromAttribute(const Attribute& attribute) { IntVector result; if (attribute.valueType() != AttributeValueType::AttributeVector) { LOG_FREE_AND_THROW("openstudio.Attribute","Attribute must be of type AttributeVector for this function to be applicable."); } AttributeVector attributes = attribute.valueAsAttributeVector(); BOOST_FOREACH(const Attribute& a, attributes) { result.push_back(a.valueAsInteger()); } return result; } std::vector<double> getDoubleVectorFromAttribute(const Attribute& attribute) { DoubleVector result; if (attribute.valueType() != AttributeValueType::AttributeVector) { LOG_FREE_AND_THROW("openstudio.Attribute","Attribute must be of type AttributeVector for this function to be applicable."); } AttributeVector attributes = attribute.valueAsAttributeVector(); BOOST_FOREACH(const Attribute& a, attributes) { result.push_back(a.valueAsDouble()); } return result; } bool isConsistent(const Attribute& candidate,const AttributeDescription& description) { return ((candidate.name() == description.name) && (std::find(description.validValueTypes.begin(), description.validValueTypes.end(), candidate.valueType()) != description.validValueTypes.end())); } bool prepareForDisplay(Attribute& attribute, const AttributeDescription& description) { if (isConsistent(attribute,description)) { attribute.setDisplayName(description.displayName); return true; } return false; } bool saveJSON(const std::vector<Attribute>& attributes, const openstudio::path& p, bool overwrite) { QVariantMap result = jsonMetadata().toMap(); result["attributes"] = detail::toVariant(attributes); return openstudio::saveJSON(QVariant(result),p,overwrite); } std::ostream& toJSON(const std::vector<Attribute>& attributes, std::ostream& os) { os << toJSON(attributes); return os; } std::string toJSON(const std::vector<Attribute>& attributes) { QVariantMap result = jsonMetadata().toMap(); result["attributes"] = detail::toVariant(attributes); return openstudio::toJSON(QVariant(result)); } std::vector<Attribute> toVectorOfAttribute(const openstudio::path& pathToJson) { QVariant variant = loadJSON(pathToJson); VersionString version = extractOpenStudioVersion(variant); QVariant attributesData = variant.toMap()["attributes"]; return detail::toVectorOfAttribute(attributesData,version); } std::vector<Attribute> toVectorOfAttribute(std::istream& json) { return toVectorOfAttribute(toString(json)); } std::vector<Attribute> toVectorOfAttribute(const std::string& json) { QVariant variant = loadJSON(json); VersionString version = extractOpenStudioVersion(variant); QVariant attributesData = variant.toMap()["attributes"]; return detail::toVectorOfAttribute(attributesData,version); } namespace detail { QVariant toVariant(const Attribute& attribute) { QVariantMap attributeData; attributeData["uuid"] = toQString(removeBraces(attribute.uuid())); attributeData["version_uuid"] = toQString(removeBraces(attribute.versionUUID())); attributeData["name"] = toQString(attribute.name()); if (attribute.displayName()) { attributeData["display_name"] = toQString(attribute.displayName().get()); } AttributeValueType valueType = attribute.valueType(); attributeData["value_type"] = toQString(valueType.valueName()); if (valueType == AttributeValueType::Quantity) { Quantity value = attribute.valueAsQuantity(); attributeData["value"] = QVariant(value.value()); attributeData["units"] = toQString(value.units().standardString()); } else if (valueType == AttributeValueType::Unit) { attributeData["units"] = toQString(attribute.valueAsUnit().standardString()); } else if (valueType == AttributeValueType::AttributeVector) { QVariantList childAttributesList; Q_FOREACH(const Attribute& child,attribute.valueAsAttributeVector()) { childAttributesList.push_back(toVariant(child)); } attributeData["value"] = QVariant(childAttributesList); if (attribute.units()) { attributeData["units"] = toQString(attribute.units().get()); } } else { // use QVariant directly QVariant val = attribute.valueAsQVariant(); if (std::string(val.typeName()) == std::string("std::string")) { // in some cases a std::string gets shoved in // convert it to QString val = toQString(val.value<std::string>()); } attributeData["value"] = val; if (attribute.units()) { attributeData["units"] = toQString(attribute.units().get()); } } return QVariant(attributeData); } Attribute toAttribute(const QVariant& variant, const VersionString& version) { QVariantMap map = variant.toMap(); openstudio::UUID uuid = toUUID(map["uuid"].toString().toStdString()); openstudio::UUID versionUUID = toUUID(map["version_uuid"].toString().toStdString()); std::string name = map["name"].toString().toStdString(); OptionalString displayName; if (map.contains("display_name")) { displayName = map["display_name"].toString().toStdString(); } OptionalUnit ou; OptionalQuantity oq; AttributeVector children; AttributeValueType valueType(map["value_type"].toString().toStdString()); switch (valueType.value()) { case AttributeValueType::Boolean : return Attribute(uuid, versionUUID, name, displayName, map["value"].toBool(), map.contains("units") ? map["units"].toString().toStdString() : OptionalString()); case AttributeValueType::Double : return Attribute(uuid, versionUUID, name, displayName, map["value"].toDouble(), map.contains("units") ? map["units"].toString().toStdString() : OptionalString()); case AttributeValueType::Quantity : oq = createQuantity(map["value"].toDouble(),map["units"].toString().toStdString()); OS_ASSERT(oq); return Attribute(uuid, versionUUID, name, displayName, oq.get()); case AttributeValueType::Unit : ou = createUnit(map["units"].toString().toStdString()); OS_ASSERT(ou); return Attribute(uuid, versionUUID, name, displayName, ou.get()); case AttributeValueType::Integer : return Attribute(uuid, versionUUID, name, displayName, map["value"].toInt(), map.contains("units") ? map["units"].toString().toStdString() : OptionalString()); case AttributeValueType::Unsigned : return Attribute(uuid, versionUUID, name, displayName, map["value"].toUInt(), map.contains("units") ? map["units"].toString().toStdString() : OptionalString()); case AttributeValueType::String : return Attribute(uuid, versionUUID, name, displayName, map["value"].toString().toStdString(), map.contains("units") ? map["units"].toString().toStdString() : OptionalString()); case AttributeValueType::AttributeVector : children = deserializeUnorderedVector<Attribute>( map["value"].toList(), boost::function<Attribute (const QVariant&)>(boost::bind(openstudio::detail::toAttribute,_1,version))); return Attribute(uuid, versionUUID, name, displayName, children, map.contains("units") ? map["units"].toString().toStdString() : OptionalString()); default : LOG_FREE_AND_THROW("openstudio.Attribute","Unknown AttributeValueType " << valueType.valueName() << "."); } } QVariant toVariant(const std::vector<Attribute>& attributes) { QVariantMap map; std::set<std::string> attributeNames; BOOST_FOREACH(const Attribute& attribute,attributes) { std::pair<std::set<std::string>::iterator,bool> insertResult = attributeNames.insert(attribute.name()); if (!insertResult.second) { LOG_FREE_AND_THROW("openstudio.Attribute","Asked to create a flat json serialization " << "of a vector of attributes with non-unique names."); } QString qName = toQString(attribute.name()); AttributeValueType valueType = attribute.valueType(); switch (valueType.value()) { case AttributeValueType::Boolean : map[qName] = attribute.valueAsBoolean(); break; case AttributeValueType::Integer : map[qName] = attribute.valueAsInteger(); break; case AttributeValueType::Unsigned : // designation as unsigned will be lost on deserialization map[qName] = attribute.valueAsUnsigned(); break; case AttributeValueType::Double : map[qName] = attribute.valueAsDouble(); break; case AttributeValueType::Quantity : // designation as Quantity will be lost on deserialization // (will be Double + units) map[qName] = attribute.valueAsQuantity().value(); map[toQString(attribute.name() + std::string("_units"))] = toQString(attribute.valueAsQuantity().units().print()); break; case AttributeValueType::Unit : // designation as Unit will be lost on deserialization // (will be of type String) map[qName] = toQString(attribute.valueAsUnit().print()); break; case AttributeValueType::String : map[qName] = toQString(attribute.valueAsString()); break; case AttributeValueType::AttributeVector : map[qName] = toVariant(attribute.valueAsAttributeVector()); break; default: LOG_FREE_AND_THROW("openstudio.Attribute","Unknown AttributeValueType " << valueType.valueName() << "."); } if (attribute.displayName()) { map[toQString(attribute.name() + std::string("_display_name"))] = toQString(attribute.displayName().get()); } if (attribute.units()) { map[toQString(attribute.name() + std::string("_units"))] = toQString(attribute.units().get()); } } return QVariant(map); } std::vector<Attribute> toVectorOfAttribute(const QVariant& variant, const VersionString& version) { AttributeVector result; QVariantMap map = variant.toMap(); boost::regex displayNameRegex("(.*)_display_name"); boost::regex unitsRegex("(.*)_units"); boost::smatch matches; std::set<std::string> processedAttributeNames; // serialization ensures uniqueness of names int itemCount(0); Q_FOREACH(const QString& key,map.keys()) { // determine attribute name std::string attributeName; std::string keyString = toString(key); if (boost::regex_match(keyString,matches,displayNameRegex)) { // ends in '_display_name'. // pull attribute name off and make sure is in map. attributeName = std::string(matches[1].first,matches[1].second); if (!map.contains(toQString(attributeName))) { // if it is not, attribute name actually ends in '_display_name'. attributeName = toString(key); } } else if (boost::regex_match(keyString,matches,unitsRegex)) { // ends in '_units'. // pull attribute name off and make sure is in map. attributeName = std::string(matches[1].first,matches[1].second); if (!map.contains(toQString(attributeName))) { // if it is not, attribute name actually ends in '_units'. attributeName = keyString; } } else { attributeName = keyString; } // see if already processed std::pair<std::set<std::string>::iterator, bool> insertResult = processedAttributeNames.insert(attributeName); if (insertResult.second) { // not processed yet QVariant value = map[toQString(attributeName)]; ++itemCount; // determine type switch (value.type()) { case QVariant::Bool: result.push_back(Attribute(attributeName,value.toBool())); break; case QVariant::Int: case QVariant::LongLong: case QVariant::UInt: case QVariant::ULongLong: result.push_back(Attribute(attributeName,value.toInt())); break; case QVariant::Double: result.push_back(Attribute(attributeName,value.toDouble())); break; case QVariant::String: result.push_back(Attribute(attributeName,value.toString().toStdString())); break; case QVariant::Map: result.push_back(Attribute(attributeName,toVectorOfAttribute(value,version))); break; default: LOG_FREE_AND_THROW("openstudio.Attribute","Unexpected QVariant::Type " << value.typeName() << "."); } // set displayName QString key = toQString(attributeName + std::string("_display_name")); if (map.contains(key)) { result.back().setDisplayName(map[key].toString().toStdString()); ++itemCount; } // set units key = toQString(attributeName + std::string("_units")); if (map.contains(key)) { result.back().setUnits(map[key].toString().toStdString()); ++itemCount; } } } OS_ASSERT(result.size() == processedAttributeNames.size()); OS_ASSERT(map.keys().size() == itemCount); return result; } } // detail } // openstudio
// // main.cpp // Assignment 5 demo // // Created by z on 3/30/18. // Copyright © 2018 210. All rights reserved. #include <string> #include <iostream> using namespace std; //DynamicStack.h // Stack template template <class T> class DynamicStack { private: int num_elements=0; // Structure for the stack nodes struct StackNode { T value; // Value in the node StackNode *next; // Pointer to the next node }; StackNode *top; // Pointer to the stack top public: //Constructor DynamicStack() { top = nullptr; } // Destructor ~DynamicStack(); // Stack operations void push(T); void pop(T &); bool isEmpty(); T& peek( ); // int size( ) const; void clear( ); void size() ; }; //*************************************************** // Destructor * //*************************************************** template <class T> DynamicStack<T>::~DynamicStack() { StackNode *nodePtr, *nextNode; // Position nodePtr at the top of the stack. nodePtr = top; // Traverse the list deleting each node. while (nodePtr != nullptr) { nextNode = nodePtr->next; delete nodePtr; nodePtr = nextNode; } } //************************************************************* // Member function push pushes the argument onto * // the stack. * //************************************************************* template <class T> void DynamicStack<T>::push(T item) { StackNode *newNode = nullptr; // Pointer to a new node // Allocate a new node and store num there. newNode = new StackNode; newNode->value = item; // If there are no nodes in the list // make newNode the first node. if (isEmpty()) { top = newNode; newNode->next = nullptr; } else // Otherwise, insert NewNode before top. { newNode->next = top; top = newNode; } this->num_elements++; } //************************************************************* // Member function pop pops the value at the top * // of the stack off, and copies it into the variable * // passed as an argument. * //************************************************************* template <class T> void DynamicStack<T>::pop(T &item) { StackNode *temp = nullptr; // Temporary pointer // First make sure the stack isn't empty. if (isEmpty()) { cout << "The stack is empty.\n"; } else // pop value off top of stack { item = top->value; temp = top->next; delete top; top = temp; this->num_elements--; } } //************************************************************* // Member function isEmpty returns true if the stack * // is empty, or false otherwise. * //************************************************************* template <class T> bool DynamicStack<T>::isEmpty() { bool status; if (!top) status = true; else status = false; return status; } template <class T> T& DynamicStack<T>::peek() { StackNode *top; return top; } template <class T> void DynamicStack<T>::clear() { StackNode *temp; if(!isEmpty()){ temp = top; /// Scan stack and free all nodes while(top != NULL){ temp = top; top = top->next; delete temp; } } top = NULL; } template <class T> void DynamicStack<T>::size() { cout << this->num_elements; } #include <string> #include <iostream> int main() { // Create the stack. DynamicStack<string> stack; string item; string item2; string x="bunch of items"; string y=" need another items"; string z= "need to work faster"; cout << "enter an item" << endl; getline(cin, item); cout << "enter an item" << endl; getline(cin, item2); stack.push(item); stack.push(item2); stack.pop(item); stack.push(x); stack.push(y); stack.push(z); stack.push(x); // Display the item. if (item != "") cout << item << " was popped.\n"; cout <<"size "; stack.size(); // stack.num_elements; cout <<"is empty "; stack.isEmpty(); cout <<"peek "; stack.peek(); cout <<"clear "; stack.clear(); stack.clear(); cout <<"size "; stack.size(); stack.pop(x); stack.pop(y); stack.pop(z); stack.pop(x); cout <<"is empty "; stack.isEmpty(); // cout <<"is empty "; //stack.peek(); return 0; }
/****************************************************************************** * * Project: GDAL * Purpose: Generic Binary format driver (.hdr but not ESRI .hdr!) * Author: Frank Warmerdam, warmerdam@pobox.com * ****************************************************************************** * Copyright (c) 2007, Frank Warmerdam <warmerdam@pobox.com> * Copyright (c) 2008-2011, Even Rouault <even dot rouault at spatialys.com> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include "cpl_string.h" #include "gdal_frmts.h" #include "ogr_spatialref.h" #include "rawdataset.h" #include <cstdlib> CPL_CVSID("$Id$") /* ==================================================================== */ /* Table relating USGS and ESRI state plane zones. */ /* ==================================================================== */ constexpr int anUsgsEsriZones[] = { 101, 3101, 102, 3126, 201, 3151, 202, 3176, 203, 3201, 301, 3226, 302, 3251, 401, 3276, 402, 3301, 403, 3326, 404, 3351, 405, 3376, 406, 3401, 407, 3426, 501, 3451, 502, 3476, 503, 3501, 600, 3526, 700, 3551, 901, 3601, 902, 3626, 903, 3576, 1001, 3651, 1002, 3676, 1101, 3701, 1102, 3726, 1103, 3751, 1201, 3776, 1202, 3801, 1301, 3826, 1302, 3851, 1401, 3876, 1402, 3901, 1501, 3926, 1502, 3951, 1601, 3976, 1602, 4001, 1701, 4026, 1702, 4051, 1703, 6426, 1801, 4076, 1802, 4101, 1900, 4126, 2001, 4151, 2002, 4176, 2101, 4201, 2102, 4226, 2103, 4251, 2111, 6351, 2112, 6376, 2113, 6401, 2201, 4276, 2202, 4301, 2203, 4326, 2301, 4351, 2302, 4376, 2401, 4401, 2402, 4426, 2403, 4451, 2500, 0, 2501, 4476, 2502, 4501, 2503, 4526, 2600, 0, 2601, 4551, 2602, 4576, 2701, 4601, 2702, 4626, 2703, 4651, 2800, 4676, 2900, 4701, 3001, 4726, 3002, 4751, 3003, 4776, 3101, 4801, 3102, 4826, 3103, 4851, 3104, 4876, 3200, 4901, 3301, 4926, 3302, 4951, 3401, 4976, 3402, 5001, 3501, 5026, 3502, 5051, 3601, 5076, 3602, 5101, 3701, 5126, 3702, 5151, 3800, 5176, 3900, 0, 3901, 5201, 3902, 5226, 4001, 5251, 4002, 5276, 4100, 5301, 4201, 5326, 4202, 5351, 4203, 5376, 4204, 5401, 4205, 5426, 4301, 5451, 4302, 5476, 4303, 5501, 4400, 5526, 4501, 5551, 4502, 5576, 4601, 5601, 4602, 5626, 4701, 5651, 4702, 5676, 4801, 5701, 4802, 5726, 4803, 5751, 4901, 5776, 4902, 5801, 4903, 5826, 4904, 5851, 5001, 6101, 5002, 6126, 5003, 6151, 5004, 6176, 5005, 6201, 5006, 6226, 5007, 6251, 5008, 6276, 5009, 6301, 5010, 6326, 5101, 5876, 5102, 5901, 5103, 5926, 5104, 5951, 5105, 5976, 5201, 6001, 5200, 6026, 5200, 6076, 5201, 6051, 5202, 6051, 5300, 0, 5400, 0 }; /************************************************************************/ /* ==================================================================== */ /* GenBinDataset */ /* ==================================================================== */ /************************************************************************/ class GenBinDataset final: public RawDataset { friend class GenBinBitRasterBand; VSILFILE *fpImage; // image data file. bool bGotTransform; double adfGeoTransform[6]; char *pszProjection; char **papszHDR; void ParseCoordinateSystem( char ** ); CPL_DISALLOW_COPY_ASSIGN(GenBinDataset) public: GenBinDataset(); ~GenBinDataset() override; CPLErr GetGeoTransform( double * padfTransform ) override; const char *_GetProjectionRef(void) override; const OGRSpatialReference* GetSpatialRef() const override { return GetSpatialRefFromOldGetProjectionRef(); } char **GetFileList() override; static GDALDataset *Open( GDALOpenInfo * ); }; /************************************************************************/ /* ==================================================================== */ /* GenBinBitRasterBand */ /* ==================================================================== */ /************************************************************************/ class GenBinBitRasterBand final: public GDALPamRasterBand { int nBits; CPL_DISALLOW_COPY_ASSIGN(GenBinBitRasterBand) public: GenBinBitRasterBand( GenBinDataset *poDS, int nBits ); ~GenBinBitRasterBand() override {} CPLErr IReadBlock( int, int, void * ) override; }; /************************************************************************/ /* GenBinBitRasterBand() */ /************************************************************************/ GenBinBitRasterBand::GenBinBitRasterBand( GenBinDataset *poDSIn, int nBitsIn ) : nBits(nBitsIn) { SetMetadataItem( "NBITS", CPLString().Printf("%d",nBitsIn), "IMAGE_STRUCTURE" ); poDS = poDSIn; nBand = 1; eDataType = GDT_Byte; nBlockXSize = poDSIn->nRasterXSize; nBlockYSize = 1; } /************************************************************************/ /* IReadBlock() */ /************************************************************************/ CPLErr GenBinBitRasterBand::IReadBlock( int /* nBlockXOff */, int nBlockYOff, void * pImage ) { GenBinDataset *poGDS = reinterpret_cast<GenBinDataset *>( poDS ); /* -------------------------------------------------------------------- */ /* Establish desired position. */ /* -------------------------------------------------------------------- */ const vsi_l_offset nLineStart = (static_cast<vsi_l_offset>( nBlockXSize ) * nBlockYOff * nBits) / 8; int iBitOffset = static_cast<int>( ( static_cast<vsi_l_offset>( nBlockXSize ) * nBlockYOff * nBits) % 8 ); const unsigned int nLineBytes = static_cast<unsigned int>( ( static_cast<vsi_l_offset>( nBlockXSize ) * (nBlockYOff+1) * nBits + 7) / 8 - nLineStart); /* -------------------------------------------------------------------- */ /* Read data into buffer. */ /* -------------------------------------------------------------------- */ GByte *pabyBuffer = static_cast<GByte *>( CPLCalloc( nLineBytes, 1 ) ); if( VSIFSeekL( poGDS->fpImage, nLineStart, SEEK_SET ) != 0 || VSIFReadL( pabyBuffer, 1, nLineBytes, poGDS->fpImage) != nLineBytes ) { CPLError( CE_Failure, CPLE_FileIO, "Failed to read %u bytes at offset %lu.\n%s", nLineBytes, static_cast<unsigned long>(nLineStart), VSIStrerror( errno ) ); CPLFree( pabyBuffer ); return CE_Failure; } /* -------------------------------------------------------------------- */ /* Copy data, promoting to 8bit. */ /* -------------------------------------------------------------------- */ GByte *pafImage = reinterpret_cast<GByte *>( pImage ); if( nBits == 1 ) { for( int iX = 0; iX < nBlockXSize; iX++, iBitOffset += nBits ) { if( pabyBuffer[iBitOffset>>3] & (0x80 >>(iBitOffset & 7)) ) pafImage[iX] = 1; else pafImage[iX] = 0; } } else if( nBits == 2 ) { for( int iX = 0; iX < nBlockXSize; iX++, iBitOffset += nBits ) { pafImage[iX] = (pabyBuffer[iBitOffset>>3]) >> (6-(iBitOffset&0x7)) & 0x3; } } else if( nBits == 4 ) { for( int iX = 0; iX < nBlockXSize; iX++, iBitOffset += nBits ) { if( iBitOffset == 0 ) pafImage[iX] = (pabyBuffer[iBitOffset>>3]) >> 4; else pafImage[iX] = (pabyBuffer[iBitOffset>>3]) & 0xf; } } else { CPLAssert( false ); } CPLFree( pabyBuffer ); return CE_None; } /************************************************************************/ /* ==================================================================== */ /* GenBinDataset */ /* ==================================================================== */ /************************************************************************/ /************************************************************************/ /* GenBinDataset() */ /************************************************************************/ GenBinDataset::GenBinDataset() : fpImage(nullptr), bGotTransform(false), pszProjection(CPLStrdup("")), papszHDR(nullptr) { adfGeoTransform[0] = 0.0; adfGeoTransform[1] = 1.0; adfGeoTransform[2] = 0.0; adfGeoTransform[3] = 0.0; adfGeoTransform[4] = 0.0; adfGeoTransform[5] = 1.0; } /************************************************************************/ /* ~GenBinDataset() */ /************************************************************************/ GenBinDataset::~GenBinDataset() { FlushCache(); if( fpImage != nullptr ) CPL_IGNORE_RET_VAL(VSIFCloseL( fpImage )); CPLFree( pszProjection ); CSLDestroy( papszHDR ); } /************************************************************************/ /* GetProjectionRef() */ /************************************************************************/ const char *GenBinDataset::_GetProjectionRef() { if (pszProjection && strlen(pszProjection) > 0) return pszProjection; return GDALPamDataset::_GetProjectionRef(); } /************************************************************************/ /* GetGeoTransform() */ /************************************************************************/ CPLErr GenBinDataset::GetGeoTransform( double * padfTransform ) { if( bGotTransform ) { memcpy( padfTransform, adfGeoTransform, sizeof(double) * 6 ); return CE_None; } return GDALPamDataset::GetGeoTransform( padfTransform ); } /************************************************************************/ /* GetFileList() */ /************************************************************************/ char **GenBinDataset::GetFileList() { const CPLString osPath = CPLGetPath( GetDescription() ); const CPLString osName = CPLGetBasename( GetDescription() ); // Main data file, etc. char **papszFileList = GDALPamDataset::GetFileList(); // Header file. const CPLString osFilename = CPLFormCIFilename( osPath, osName, "hdr" ); papszFileList = CSLAddString( papszFileList, osFilename ); return papszFileList; } /************************************************************************/ /* ParseCoordinateSystem() */ /************************************************************************/ void GenBinDataset::ParseCoordinateSystem( char **papszHdr ) { const char *pszProjName = CSLFetchNameValue( papszHdr, "PROJECTION_NAME" ); if( pszProjName == nullptr ) return; /* -------------------------------------------------------------------- */ /* Translate zone and parameters into numeric form. */ /* -------------------------------------------------------------------- */ int nZone = 0; if( CSLFetchNameValue( papszHdr, "PROJECTION_ZONE" ) ) nZone = atoi(CSLFetchNameValue( papszHdr, "PROJECTION_ZONE" )); #if 0 // TODO(schwehr): Why was this being done but not used? double adfProjParams[15] = { 0.0 }; if( CSLFetchNameValue( papszHdr, "PROJECTION_PARAMETERS" ) ) { char **papszTokens = CSLTokenizeString( CSLFetchNameValue( papszHdr, "PROJECTION_PARAMETERS" ) ); for( int i = 0; i < 15 && papszTokens[i] != NULL; i++ ) adfProjParams[i] = CPLAtofM( papszTokens[i] ); CSLDestroy( papszTokens ); } #endif /* -------------------------------------------------------------------- */ /* Handle projections. */ /* -------------------------------------------------------------------- */ const char *pszDatumName = CSLFetchNameValue( papszHdr, "DATUM_NAME" ); OGRSpatialReference oSRS; if( EQUAL(pszProjName,"UTM") && nZone != 0 ) { // Just getting that the negative zone for southern hemisphere is used. oSRS.SetUTM( std::abs(nZone), nZone > 0 ); } else if( EQUAL(pszProjName,"State Plane") && nZone != 0 ) { const int nPairs = sizeof(anUsgsEsriZones) / (2 * sizeof(int)); for( int i = 0; i < nPairs; i++ ) { if( anUsgsEsriZones[i*2+1] == nZone ) { nZone = anUsgsEsriZones[i*2]; break; } } const char *pszUnits = CSLFetchNameValueDef( papszHdr, "MAP_UNITS", "" ); double dfUnits = 0.0; if( EQUAL(pszUnits,"feet") ) dfUnits = CPLAtofM(SRS_UL_US_FOOT_CONV); else if( STARTS_WITH_CI(pszUnits, "MET") ) dfUnits = 1.0; else pszUnits = nullptr; oSRS.SetStatePlane( std::abs(nZone), pszDatumName==nullptr || !EQUAL(pszDatumName,"NAD27"), pszUnits, dfUnits ); } /* -------------------------------------------------------------------- */ /* Setup the geographic coordinate system. */ /* -------------------------------------------------------------------- */ if( oSRS.GetAttrNode( "GEOGCS" ) == nullptr ) { const char* pszSpheroidName = CSLFetchNameValue( papszHdr, "SPHEROID_NAME" ); const char* pszSemiMajor = CSLFetchNameValue( papszHdr, "SEMI_MAJOR_AXIS"); const char* pszSemiMinor = CSLFetchNameValue( papszHdr, "SEMI_MINOR_AXIS"); if( pszDatumName != nullptr && oSRS.SetWellKnownGeogCS( pszDatumName ) == OGRERR_NONE ) { // good } else if( pszSpheroidName && pszSemiMajor && pszSemiMinor ) { const double dfSemiMajor = CPLAtofM(pszSemiMajor); const double dfSemiMinor = CPLAtofM(pszSemiMinor); oSRS.SetGeogCS( pszSpheroidName, pszSpheroidName, pszSpheroidName, dfSemiMajor, (dfSemiMajor == 0.0 || dfSemiMajor == dfSemiMinor) ? 0.0 : 1.0 / (1.0 - dfSemiMinor/dfSemiMajor) ); } else // fallback default. oSRS.SetWellKnownGeogCS( "WGS84" ); } /* -------------------------------------------------------------------- */ /* Convert to WKT. */ /* -------------------------------------------------------------------- */ CPLFree( pszProjection ); pszProjection = nullptr; oSRS.exportToWkt( &pszProjection ); } /************************************************************************/ /* Open() */ /************************************************************************/ GDALDataset *GenBinDataset::Open( GDALOpenInfo * poOpenInfo ) { /* -------------------------------------------------------------------- */ /* We assume the user is pointing to the binary (i.e. .bil) file. */ /* -------------------------------------------------------------------- */ if( poOpenInfo->nHeaderBytes < 2 || poOpenInfo->fpL == nullptr ) return nullptr; /* -------------------------------------------------------------------- */ /* Now we need to tear apart the filename to form a .HDR */ /* filename. */ /* -------------------------------------------------------------------- */ const CPLString osPath = CPLGetPath( poOpenInfo->pszFilename ); const CPLString osName = CPLGetBasename( poOpenInfo->pszFilename ); CPLString osHDRFilename; char** papszSiblingFiles = poOpenInfo->GetSiblingFiles(); if( papszSiblingFiles ) { const int iFile = CSLFindString( papszSiblingFiles, CPLFormFilename( nullptr, osName, "hdr" ) ); if( iFile < 0 ) // return if there is no corresponding .hdr file return nullptr; osHDRFilename = CPLFormFilename( osPath, papszSiblingFiles[iFile], nullptr ); } else { osHDRFilename = CPLFormCIFilename( osPath, osName, "hdr" ); } const bool bSelectedHDR = EQUAL( osHDRFilename, poOpenInfo->pszFilename ); /* -------------------------------------------------------------------- */ /* Do we have a .hdr file? */ /* -------------------------------------------------------------------- */ VSILFILE *fp = VSIFOpenL( osHDRFilename, "r" ); if( fp == nullptr ) { return nullptr; } /* -------------------------------------------------------------------- */ /* Read a chunk to skim for expected keywords. */ /* -------------------------------------------------------------------- */ char achHeader[1000] = { '\0' }; const int nRead = static_cast<int>(VSIFReadL( achHeader, 1, sizeof(achHeader) - 1, fp )); achHeader[nRead] = '\0'; CPL_IGNORE_RET_VAL(VSIFSeekL( fp, 0, SEEK_SET )); if( strstr( achHeader, "BANDS:" ) == nullptr || strstr( achHeader, "ROWS:" ) == nullptr || strstr( achHeader, "COLS:" ) == nullptr ) { CPL_IGNORE_RET_VAL(VSIFCloseL( fp )); return nullptr; } /* -------------------------------------------------------------------- */ /* Has the user selected the .hdr file to open? */ /* -------------------------------------------------------------------- */ if( bSelectedHDR ) { CPLError( CE_Failure, CPLE_AppDefined, "The selected file is an Generic Binary header file, but to " "open Generic Binary datasets, the data file should be selected " "instead of the .hdr file. Please try again selecting" "the raw data file corresponding to the header file: %s", poOpenInfo->pszFilename ); CPL_IGNORE_RET_VAL(VSIFCloseL( fp )); return nullptr; } /* -------------------------------------------------------------------- */ /* Read the .hdr file. */ /* -------------------------------------------------------------------- */ char **papszHdr = nullptr; const char *pszLine = CPLReadLineL( fp ); while( pszLine != nullptr ) { if( EQUAL(pszLine,"PROJECTION_PARAMETERS:") ) { CPLString osPP = pszLine; pszLine = CPLReadLineL(fp); while( pszLine != nullptr && (*pszLine == '\t' || *pszLine == ' ') ) { osPP += pszLine; pszLine = CPLReadLineL(fp); } papszHdr = CSLAddString( papszHdr, osPP ); } else { char *pszName = nullptr; const char* pszKey = CPLParseNameValue( pszLine, &pszName ); if( pszKey && pszName ) { CPLString osValue = pszKey; osValue.Trim(); papszHdr = CSLSetNameValue( papszHdr, pszName, osValue ); } CPLFree( pszName ); pszLine = CPLReadLineL( fp ); } } CPL_IGNORE_RET_VAL(VSIFCloseL( fp )); if( CSLFetchNameValue( papszHdr, "COLS" ) == nullptr || CSLFetchNameValue( papszHdr, "ROWS" ) == nullptr || CSLFetchNameValue( papszHdr, "BANDS" ) == nullptr ) { CSLDestroy( papszHdr ); return nullptr; } /* -------------------------------------------------------------------- */ /* Create a corresponding GDALDataset. */ /* -------------------------------------------------------------------- */ GenBinDataset *poDS = new GenBinDataset(); /* -------------------------------------------------------------------- */ /* Capture some information from the file that is of interest. */ /* -------------------------------------------------------------------- */ const int nBands = atoi(CSLFetchNameValue( papszHdr, "BANDS" )); poDS->nRasterXSize = atoi(CSLFetchNameValue( papszHdr, "COLS" )); poDS->nRasterYSize = atoi(CSLFetchNameValue( papszHdr, "ROWS" )); poDS->papszHDR = papszHdr; if (!GDALCheckDatasetDimensions(poDS->nRasterXSize, poDS->nRasterYSize) || !GDALCheckBandCount(nBands, FALSE)) { delete poDS; return nullptr; } poDS->fpImage = poOpenInfo->fpL; poOpenInfo->fpL = nullptr; poDS->eAccess = poOpenInfo->eAccess; /* -------------------------------------------------------------------- */ /* Figure out the data type. */ /* -------------------------------------------------------------------- */ const char *pszDataType = CSLFetchNameValue( papszHdr, "DATATYPE" ); GDALDataType eDataType = GDT_Unknown; int nBits = -1; // Only needed for partial byte types if( pszDataType == nullptr ) eDataType = GDT_Byte; else if( EQUAL(pszDataType,"U16") ) eDataType = GDT_UInt16; else if( EQUAL(pszDataType,"S16") ) eDataType = GDT_Int16; else if( EQUAL(pszDataType,"F32") ) eDataType = GDT_Float32; else if( EQUAL(pszDataType,"F64") ) eDataType = GDT_Float64; else if( EQUAL(pszDataType,"U8") ) eDataType = GDT_Byte; else if( EQUAL(pszDataType,"U1") || EQUAL(pszDataType,"U2") || EQUAL(pszDataType,"U4") ) { nBits = atoi(pszDataType+1); eDataType = GDT_Byte; if( nBands != 1 ) { CPLError( CE_Failure, CPLE_OpenFailed, "Only one band is supported for U1/U2/U4 data type" ); delete poDS; return nullptr; } } else { eDataType = GDT_Byte; CPLError( CE_Warning, CPLE_AppDefined, "DATATYPE=%s not recognised, assuming Byte.", pszDataType ); } /* -------------------------------------------------------------------- */ /* Do we need byte swapping? */ /* -------------------------------------------------------------------- */ const char *pszBYTE_ORDER = CSLFetchNameValue(papszHdr,"BYTE_ORDER"); bool bNative = true; if( pszBYTE_ORDER != nullptr ) { #ifdef CPL_LSB bNative = STARTS_WITH_CI(pszBYTE_ORDER, "LSB"); #else bNative = !STARTS_WITH_CI(pszBYTE_ORDER, "LSB"); #endif } /* -------------------------------------------------------------------- */ /* Work out interleaving info. */ /* -------------------------------------------------------------------- */ const int nItemSize = GDALGetDataTypeSizeBytes(eDataType); int nPixelOffset = 0; int nLineOffset = 0; vsi_l_offset nBandOffset = 0; bool bIntOverflow = false; const char *pszInterleaving = CSLFetchNameValue(papszHdr, "INTERLEAVING"); if( pszInterleaving == nullptr ) pszInterleaving = "BIL"; if( EQUAL(pszInterleaving,"BSQ") || EQUAL(pszInterleaving,"NA") ) { nPixelOffset = nItemSize; if( poDS->nRasterXSize > INT_MAX / nItemSize ) bIntOverflow = true; else { nLineOffset = nItemSize * poDS->nRasterXSize; nBandOffset = nLineOffset * static_cast<vsi_l_offset>(poDS->nRasterYSize); } } else if( EQUAL(pszInterleaving,"BIP") ) { nPixelOffset = nItemSize * nBands; if( nPixelOffset == 0 || poDS->nRasterXSize > INT_MAX / nPixelOffset ) bIntOverflow = true; else { nLineOffset = nPixelOffset * poDS->nRasterXSize; nBandOffset = nItemSize; } } else { if( !EQUAL(pszInterleaving,"BIL") ) CPLError( CE_Warning, CPLE_AppDefined, "INTERLEAVING:%s not recognised, assume BIL.", pszInterleaving ); nPixelOffset = nItemSize; if( nPixelOffset == 0 || nBands == 0 || poDS->nRasterXSize > INT_MAX / (nPixelOffset * nBands) ) bIntOverflow = true; else { nLineOffset = nPixelOffset * nBands * poDS->nRasterXSize; nBandOffset = nItemSize * static_cast<vsi_l_offset>(poDS->nRasterXSize); } } if (bIntOverflow) { delete poDS; CPLError( CE_Failure, CPLE_AppDefined, "Int overflow occurred." ); return nullptr; } if( nBits < 0 && !RAWDatasetCheckMemoryUsage( poDS->nRasterXSize, poDS->nRasterYSize, nBands, nItemSize, nPixelOffset, nLineOffset, 0, nBandOffset, poDS->fpImage) ) { delete poDS; return nullptr; } poDS->SetDescription( poOpenInfo->pszFilename ); poDS->PamInitialize(); /* -------------------------------------------------------------------- */ /* Create band information objects. */ /* -------------------------------------------------------------------- */ poDS->nBands = nBands; for( int i = 0; i < poDS->nBands; i++ ) { if( nBits != -1 ) { poDS->SetBand( i+1, new GenBinBitRasterBand( poDS, nBits ) ); } else { poDS->SetBand( i+1, new RawRasterBand( poDS, i+1, poDS->fpImage, nBandOffset * i, nPixelOffset, nLineOffset, eDataType, bNative, RawRasterBand::OwnFP::NO ) ); } } /* -------------------------------------------------------------------- */ /* Get geotransform. */ /* -------------------------------------------------------------------- */ if( poDS->nRasterXSize > 1 && poDS->nRasterYSize > 1 && CSLFetchNameValue(papszHdr,"UL_X_COORDINATE") != nullptr && CSLFetchNameValue(papszHdr,"UL_Y_COORDINATE") != nullptr && CSLFetchNameValue(papszHdr,"LR_X_COORDINATE") != nullptr && CSLFetchNameValue(papszHdr,"LR_Y_COORDINATE") != nullptr ) { const double dfULX = CPLAtofM(CSLFetchNameValue(papszHdr,"UL_X_COORDINATE")); const double dfULY = CPLAtofM(CSLFetchNameValue(papszHdr,"UL_Y_COORDINATE")); const double dfLRX = CPLAtofM(CSLFetchNameValue(papszHdr,"LR_X_COORDINATE")); const double dfLRY = CPLAtofM(CSLFetchNameValue(papszHdr,"LR_Y_COORDINATE")); poDS->adfGeoTransform[1] = (dfLRX - dfULX) / (poDS->nRasterXSize-1); poDS->adfGeoTransform[2] = 0.0; poDS->adfGeoTransform[4] = 0.0; poDS->adfGeoTransform[5] = (dfLRY - dfULY) / (poDS->nRasterYSize-1); poDS->adfGeoTransform[0] = dfULX - poDS->adfGeoTransform[1] * 0.5; poDS->adfGeoTransform[3] = dfULY - poDS->adfGeoTransform[5] * 0.5; poDS->bGotTransform = true; } /* -------------------------------------------------------------------- */ /* Try and parse the coordinate system. */ /* -------------------------------------------------------------------- */ poDS->ParseCoordinateSystem( papszHdr ); /* -------------------------------------------------------------------- */ /* Initialize any PAM information. */ /* -------------------------------------------------------------------- */ poDS->TryLoadXML(); /* -------------------------------------------------------------------- */ /* Check for overviews. */ /* -------------------------------------------------------------------- */ poDS->oOvManager.Initialize( poDS, poOpenInfo->pszFilename ); return poDS; } /************************************************************************/ /* GDALRegister_GenBin() */ /************************************************************************/ void GDALRegister_GenBin() { if( GDALGetDriverByName( "GenBin" ) != nullptr ) return; GDALDriver *poDriver = new GDALDriver(); poDriver->SetDescription( "GenBin" ); poDriver->SetMetadataItem( GDAL_DCAP_RASTER, "YES" ); poDriver->SetMetadataItem( GDAL_DMD_LONGNAME, "Generic Binary (.hdr Labelled)" ); poDriver->SetMetadataItem( GDAL_DMD_HELPTOPIC, "drivers/raster/genbin.html" ); poDriver->SetMetadataItem( GDAL_DCAP_VIRTUALIO, "YES" ); poDriver->pfnOpen = GenBinDataset::Open; GetGDALDriverManager()->RegisterDriver( poDriver ); }
#include "semantic_analyser.h" #include <algorithm> #include <cstring> #include <regex> #include <string> #include <sys/stat.h> #include <bcc/libbpf.h> #include "arch/arch.h" #include "ast/ast.h" #include "ast/signal_bt.h" #include "fake_map.h" #include "log.h" #include "printf.h" #include "probe_matcher.h" #include "tracepoint_format_parser.h" #include "usdt.h" namespace bpftrace { namespace ast { static const std::map<std::string, std::tuple<size_t, bool>>& getIntcasts() { static const std::map<std::string, std::tuple<size_t, bool>> intcasts = { { "uint8", std::tuple<size_t, bool>{ 8, false } }, { "int8", std::tuple<size_t, bool>{ 8, true } }, { "uint16", std::tuple<size_t, bool>{ 16, false } }, { "int16", std::tuple<size_t, bool>{ 16, true } }, { "uint32", std::tuple<size_t, bool>{ 32, false } }, { "int32", std::tuple<size_t, bool>{ 32, true } }, { "uint64", std::tuple<size_t, bool>{ 64, false } }, { "int64", std::tuple<size_t, bool>{ 64, true } }, }; return intcasts; } void SemanticAnalyser::visit(Integer &integer) { integer.type = CreateInt64(); } void SemanticAnalyser::visit(PositionalParameter &param) { param.type = CreateInt64(); if (func_ == "str") { param.is_in_str = true; has_pos_param_ = true; } switch (param.ptype) { case PositionalParameterType::positional: if (param.n <= 0) LOG(ERROR, param.loc, err_) << "$" << std::to_string(param.n) + " is not a valid parameter"; if (is_final_pass()) { std::string pstr = bpftrace_.get_param(param.n, param.is_in_str); if (!is_numeric(pstr) && !param.is_in_str) { LOG(ERROR, param.loc, err_) << "$" << param.n << " used numerically but given \"" << pstr << "\". Try using str($" << param.n << ")."; } // string allocated in bpf stack. See codegen. if (param.is_in_str) param.type.SetAS(AddrSpace::kernel); } break; case PositionalParameterType::count: if (param.is_in_str) { LOG(ERROR, param.loc, err_) << "use $#, not str($#)"; } break; default: LOG(ERROR, param.loc, err_) << "unknown parameter type"; param.type = CreateNone(); break; } } void SemanticAnalyser::visit(String &string) { string.type = CreateString(string.str.size() + 1); // Skip check for printf()'s format string (1st argument) and create the // string with the original size. This is because format string is not part of // bpf byte code. if (func_ == "printf" && func_arg_idx_ == 0) return; if (!is_compile_time_func(func_) && string.str.size() > STRING_SIZE - 1) { LOG(ERROR, string.loc, err_) << "String is too long (over " << STRING_SIZE << " bytes): " << string.str; } // @a = buf("hi", 2). String allocated on bpf stack. See codegen string.type.SetAS(AddrSpace::kernel); } void SemanticAnalyser::visit(StackMode &mode) { mode.type = CreateStackMode(); if (mode.mode == "bpftrace") { mode.type.stack_type.mode = bpftrace::StackMode::bpftrace; } else if (mode.mode == "perf") { mode.type.stack_type.mode = bpftrace::StackMode::perf; } else { mode.type = CreateNone(); LOG(ERROR, mode.loc, err_) << "Unknown stack mode: '" + mode.mode + "'"; } } void SemanticAnalyser::visit(Identifier &identifier) { if (bpftrace_.enums_.count(identifier.ident) != 0) { identifier.type = CreateUInt64(); } else if (bpftrace_.structs.Has(identifier.ident)) { identifier.type = CreateRecord(identifier.ident, bpftrace_.structs.Lookup(identifier.ident)); } else if (func_ == "sizeof" && getIntcasts().count(identifier.ident) != 0) { identifier.type = CreateInt( std::get<0>(getIntcasts().at(identifier.ident))); } else { identifier.type = CreateNone(); LOG(ERROR, identifier.loc, err_) << "Unknown identifier: '" + identifier.ident + "'"; } } void SemanticAnalyser::builtin_args_tracepoint(AttachPoint *attach_point, Builtin &builtin) { /* * tracepoint wildcard expansion, part 2 of 3. This: * 1. expands the wildcard, then sets args to be the first matched probe. * This is so that enough of the type information is available to * survive the later semantic analyser checks. * 2. sets is_tparg so that codegen does the real type setting after * expansion. */ auto matches = bpftrace_.probe_matcher_->get_matches_for_ap(*attach_point); if (!matches.empty()) { auto &match = *matches.begin(); std::string tracepoint_struct = TracepointFormatParser::get_struct_name( match); AddrSpace as = (attach_point->target == "syscalls") ? AddrSpace::user : AddrSpace::kernel; builtin.type = CreatePointer(CreateRecord(tracepoint_struct, bpftrace_.structs.Lookup( tracepoint_struct)), as); builtin.type.MarkCtxAccess(); builtin.type.is_tparg = true; } } ProbeType SemanticAnalyser::single_provider_type(void) { ProbeType type = ProbeType::invalid; for (auto &attach_point : *probe_->attach_points) { ProbeType ap = probetype(attach_point->provider); if (type == ProbeType::invalid) type = ap; if (type != ap) return ProbeType::invalid; } return type; } AddrSpace SemanticAnalyser::find_addrspace(ProbeType pt) { switch (pt) { case ProbeType::kprobe: case ProbeType::kretprobe: case ProbeType::kfunc: case ProbeType::kretfunc: case ProbeType::tracepoint: case ProbeType::iter: return AddrSpace::kernel; case ProbeType::uprobe: case ProbeType::uretprobe: case ProbeType::usdt: return AddrSpace::user; // case : i:ms:1 (struct x*)ctx)->x // Cannot decide the addrspace. Provide backward compatibility, // if addrspace cannot be detected. case ProbeType::invalid: case ProbeType::profile: case ProbeType::interval: case ProbeType::software: case ProbeType::hardware: case ProbeType::watchpoint: case ProbeType::asyncwatchpoint: // Will trigger a warning in selectProbeReadHelper. return AddrSpace::none; } return {}; // unreached } void SemanticAnalyser::visit(Builtin &builtin) { if (builtin.ident == "ctx") { ProbeType pt = probetype((*probe_->attach_points)[0]->provider); bpf_prog_type bt = progtype(pt); std::string func = (*probe_->attach_points)[0]->func; for (auto &attach_point : *probe_->attach_points) { ProbeType pt = probetype(attach_point->provider); bpf_prog_type bt2 = progtype(pt); if (bt != bt2) LOG(ERROR, builtin.loc, err_) << "ctx cannot be used in different BPF program types: " << progtypeName(bt) << " and " << progtypeName(bt2); } switch (static_cast<libbpf::bpf_prog_type>(bt)) { case libbpf::BPF_PROG_TYPE_KPROBE: builtin.type = CreatePointer(CreateRecord("struct pt_regs", bpftrace_.structs.Lookup( "structs pt_regs")), AddrSpace::kernel); builtin.type.MarkCtxAccess(); break; case libbpf::BPF_PROG_TYPE_TRACEPOINT: LOG(ERROR, builtin.loc, err_) << "Use args instead of ctx in tracepoint"; break; case libbpf::BPF_PROG_TYPE_PERF_EVENT: builtin.type = CreatePointer( CreateRecord("struct bpf_perf_event_data", bpftrace_.structs.Lookup( "struct bpf_perf_event_data")), AddrSpace::kernel); builtin.type.MarkCtxAccess(); break; case libbpf::BPF_PROG_TYPE_TRACING: if (pt == ProbeType::iter) { std::string type; if (func == "task") { type = "struct bpf_iter__task"; } else if (func == "task_file") { type = "struct bpf_iter__task_file"; } else { LOG(ERROR, builtin.loc, err_) << "unsupported iter type: " << func; } builtin.type = CreatePointer( CreateRecord(type, bpftrace_.structs.Lookup(type)), AddrSpace::kernel); builtin.type.MarkCtxAccess(); } else { LOG(ERROR, builtin.loc, err_) << "invalid program type"; } break; default: LOG(ERROR, builtin.loc, err_) << "invalid program type"; break; } } else if (builtin.ident == "nsecs" || builtin.ident == "elapsed" || builtin.ident == "pid" || builtin.ident == "tid" || builtin.ident == "cgroup" || builtin.ident == "uid" || builtin.ident == "gid" || builtin.ident == "cpu" || builtin.ident == "rand" || builtin.ident == "numaid") { builtin.type = CreateUInt64(); if (builtin.ident == "cgroup" && !bpftrace_.feature_->has_helper_get_current_cgroup_id()) { LOG(ERROR, builtin.loc, err_) << "BPF_FUNC_get_current_cgroup_id is not available for your kernel " "version"; } } else if (builtin.ident == "curtask") { /* * Retype curtask to its original type: struct task_struct. */ builtin.type = CreatePointer(CreateRecord("struct task_struct", bpftrace_.structs.Lookup( "struct task_struct")), AddrSpace::kernel); } else if (builtin.ident == "retval") { ProbeType type = single_provider_type(); if (type == ProbeType::kretprobe || type == ProbeType::uretprobe) { builtin.type = CreateUInt64(); } else if (type == ProbeType::kfunc || type == ProbeType::kretfunc) { auto it = ap_args_.find("$retval"); if (it != ap_args_.end()) builtin.type = it->second; else LOG(ERROR, builtin.loc, err_) << "Can't find a field $retval"; } else { LOG(ERROR, builtin.loc, err_) << "The retval builtin can only be used with 'kretprobe' and " << "'uretprobe' and 'kfunc' probes" << (type == ProbeType::tracepoint ? " (try to use args->ret instead)" : ""); } // For kretprobe, kfunc, kretfunc -> AddrSpace::kernel // For uretprobe -> AddrSpace::user builtin.type.SetAS(find_addrspace(type)); } else if (builtin.ident == "kstack") { builtin.type = CreateStack(true, StackType()); } else if (builtin.ident == "ustack") { builtin.type = CreateStack(false, StackType()); } else if (builtin.ident == "comm") { builtin.type = CreateString(COMM_SIZE); // comm allocated in the bpf stack. See codegen // Case: @=comm and strncmp(@, "name") builtin.type.SetAS(AddrSpace::kernel); } else if (builtin.ident == "func") { for (auto &attach_point : *probe_->attach_points) { ProbeType type = probetype(attach_point->provider); if (type == ProbeType::kprobe || type == ProbeType::kretprobe) builtin.type = CreateKSym(); else if (type == ProbeType::uprobe || type == ProbeType::uretprobe) builtin.type = CreateUSym(); else LOG(ERROR, builtin.loc, err_) << "The func builtin can not be used with '" << attach_point->provider << "' probes"; } } else if (!builtin.ident.compare(0, 3, "arg") && builtin.ident.size() == 4 && builtin.ident.at(3) >= '0' && builtin.ident.at(3) <= '9') { ProbeType pt = probetype((*probe_->attach_points)[0]->provider); AddrSpace addrspace = find_addrspace(pt); for (auto &attach_point : *probe_->attach_points) { ProbeType type = probetype(attach_point->provider); if (type != ProbeType::kprobe && type != ProbeType::uprobe && type != ProbeType::usdt) LOG(ERROR, builtin.loc, err_) << "The " << builtin.ident << " builtin can only be used with " << "'kprobes', 'uprobes' and 'usdt' probes"; } int arg_num = atoi(builtin.ident.substr(3).c_str()); if (arg_num > arch::max_arg()) LOG(ERROR, builtin.loc, err_) << arch::name() << " doesn't support " << builtin.ident; builtin.type = CreateUInt64(); builtin.type.SetAS(addrspace); } else if (!builtin.ident.compare(0, 4, "sarg") && builtin.ident.size() == 5 && builtin.ident.at(4) >= '0' && builtin.ident.at(4) <= '9') { ProbeType pt = probetype((*probe_->attach_points)[0]->provider); AddrSpace addrspace = find_addrspace(pt); for (auto &attach_point : *probe_->attach_points) { ProbeType type = probetype(attach_point->provider); if (type != ProbeType::kprobe && type != ProbeType::uprobe) LOG(ERROR, builtin.loc, err_) << "The " + builtin.ident << " builtin can only be used with 'kprobes' and 'uprobes' probes"; if (is_final_pass() && (attach_point->address != 0 || attach_point->func_offset != 0)) { // If sargX values are needed when using an offset, they can be stored in a map // when entering the function and then referenced from an offset-based probe LOG(WARNING, builtin.loc, out_) << "Using an address offset with the sargX built-in can" "lead to unexpected behavior "; } } builtin.type = CreateUInt64(); builtin.type.SetAS(addrspace); } else if (builtin.ident == "probe") { builtin.type = CreateProbe(); probe_->need_expansion = true; } else if (builtin.ident == "username") { builtin.type = CreateUsername(); } else if (builtin.ident == "cpid") { if (!has_child_) { LOG(ERROR, builtin.loc, err_) << "cpid cannot be used without child command"; } builtin.type = CreateUInt32(); } else if (builtin.ident == "args") { for (auto &attach_point : *probe_->attach_points) { ProbeType type = probetype(attach_point->provider); if (type == ProbeType::tracepoint) { probe_->need_expansion = true; builtin_args_tracepoint(attach_point, builtin); } } ProbeType type = single_provider_type(); if (type == ProbeType::tracepoint) { // no special action in here } else if (type == ProbeType::kfunc || type == ProbeType::kretfunc) { builtin.type = CreatePointer(CreateRecord("struct kfunc", bpftrace_.structs.Lookup( "struct kfunc")), AddrSpace::kernel); builtin.type.MarkCtxAccess(); builtin.type.is_funcarg = true; } else if (type == ProbeType::uprobe) { // Add a dummy "placeholder" type here to satisfy semantic analyser. // An eventual FieldAccess is then resolved as an argument lookup. builtin.type = CreatePointer(CreateRecord("struct uprobe_args", bpftrace_.structs.Lookup( "struct uprobe_args")), AddrSpace::user); builtin.type.MarkCtxAccess(); builtin.type.is_funcarg = true; } else { LOG(ERROR, builtin.loc, err_) << "The args builtin can only be used with tracepoint/kfunc/uprobe" << "probes (" << probetypeName(type) << " used here)"; } } else { builtin.type = CreateNone(); LOG(ERROR, builtin.loc, err_) << "Unknown builtin variable: '" << builtin.ident << "'"; } } void SemanticAnalyser::visit(Call &call) { // Check for unsafe-ness first. It is likely the most pertinent issue // (and should be at the top) for any function call. if (bpftrace_.safe_mode_ && is_unsafe_func(call.func)) { LOG(ERROR, call.loc, err_) << call.func << "() is an unsafe function being used in safe mode"; } struct func_setter { func_setter(SemanticAnalyser &analyser, const std::string &s) : analyser_(analyser), old_func_(analyser_.func_) { analyser_.func_ = s; } ~func_setter() { analyser_.func_ = old_func_; analyser_.func_arg_idx_ = -1; } private: SemanticAnalyser &analyser_; std::string old_func_; }; func_setter scope_bound_func_setter{ *this, call.func }; if (call.vargs) { for (size_t i = 0; i < call.vargs->size(); ++i) { auto &expr = (*call.vargs)[i]; func_arg_idx_ = i; expr->accept(*this); } } for (auto &ap : *probe_->attach_points) { if (!check_available(call, *ap)) { LOG(ERROR, call.loc, err_) << call.func << " can not be used with \"" << ap->provider << "\" probes"; } } if (call.func == "hist") { check_assignment(call, true, false, false); check_nargs(call, 1); check_arg(call, Type::integer, 0); call.type = CreateHist(); } else if (call.func == "lhist") { check_assignment(call, true, false, false); if (check_nargs(call, 4)) { check_arg(call, Type::integer, 0, false); check_arg(call, Type::integer, 1, true); check_arg(call, Type::integer, 2, true); check_arg(call, Type::integer, 3, true); } if (is_final_pass()) { Expression *min_arg = call.vargs->at(1); Expression *max_arg = call.vargs->at(2); Expression *step_arg = call.vargs->at(3); auto min = bpftrace_.get_int_literal(min_arg); auto max = bpftrace_.get_int_literal(max_arg); auto step = bpftrace_.get_int_literal(step_arg); if (!min.has_value()) { LOG(ERROR, call.loc, err_) << call.func << ": invalid min value"; return; } if (!max.has_value()) { LOG(ERROR, call.loc, err_) << call.func << ": invalid max value"; return; } if (!step.has_value()) { LOG(ERROR, call.loc, err_) << call.func << ": invalid step value"; return; } if (*step <= 0) { LOG(ERROR, call.loc, err_) << "lhist() step must be >= 1 (" << *step << " provided)"; } else { int buckets = (*max - *min) / *step; if (buckets > 1000) { LOG(ERROR, call.loc, err_) << "lhist() too many buckets, must be <= 1000 (would need " << buckets << ")"; } } if (*min < 0) { LOG(ERROR, call.loc, err_) << "lhist() min must be non-negative (provided min " << *min << ")"; } if (*min > *max) { LOG(ERROR, call.loc, err_) << "lhist() min must be less than max (provided min " << *min << " and max " << *max << ")"; } if ((*max - *min) < *step) { LOG(ERROR, call.loc, err_) << "lhist() step is too large for the given range (provided step " << *step << " for range " << (*max - *min) << ")"; } } call.type = CreateLhist(); } else if (call.func == "count") { check_assignment(call, true, false, false); check_nargs(call, 0); call.type = CreateCount(true); } else if (call.func == "sum") { bool sign = false; check_assignment(call, true, false, false); if (check_nargs(call, 1)) { check_arg(call, Type::integer, 0); sign = call.vargs->at(0)->type.IsSigned(); } call.type = CreateSum(sign); } else if (call.func == "min") { bool sign = false; check_assignment(call, true, false, false); if (check_nargs(call, 1)) { check_arg(call, Type::integer, 0); sign = call.vargs->at(0)->type.IsSigned(); } call.type = CreateMin(sign); } else if (call.func == "max") { bool sign = false; check_assignment(call, true, false, false); if (check_nargs(call, 1)) { check_arg(call, Type::integer, 0); sign = call.vargs->at(0)->type.IsSigned(); } call.type = CreateMax(sign); } else if (call.func == "avg") { check_assignment(call, true, false, false); check_nargs(call, 1); check_arg(call, Type::integer, 0); call.type = CreateAvg(true); } else if (call.func == "stats") { check_assignment(call, true, false, false); check_nargs(call, 1); check_arg(call, Type::integer, 0); call.type = CreateStats(true); } else if (call.func == "delete") { check_assignment(call, false, false, false); if (check_nargs(call, 1)) { auto &arg = *call.vargs->at(0); if (!arg.is_map) LOG(ERROR, call.loc, err_) << "delete() expects a map to be provided"; } call.type = CreateNone(); } else if (call.func == "str") { if (check_varargs(call, 1, 2)) { auto *arg = call.vargs->at(0); auto &t = arg->type; if (!t.IsIntegerTy() && !t.IsPtrTy()) { LOG(ERROR, call.loc, err_) << call.func << "() expects an integer or a pointer type as first " << "argument (" << t << " provided)"; } call.type = CreateString(bpftrace_.strlen_); if (has_pos_param_) { if (dynamic_cast<PositionalParameter *>(arg)) call.is_literal = true; else { auto binop = dynamic_cast<Binop *>(arg); if (!(binop && (dynamic_cast<PositionalParameter *>(binop->left) || dynamic_cast<PositionalParameter *>(binop->right)))) { // Only str($1), str($1 + CONST), or str(CONST + $1) are allowed LOG(ERROR, call.loc, err_) << call.func << "() only accepts positional parameters" << " directly or with a single constant offset added"; } } } if (is_final_pass() && call.vargs->size() == 2 && check_arg(call, Type::integer, 1, false)) { auto &size_arg = *call.vargs->at(1); if (size_arg.is_literal) { auto &integer = static_cast<Integer &>(size_arg); long value = integer.n; if (value < 0) LOG(ERROR, call.loc, err_) << call.func << "cannot use negative length (" << value << ")"; } } // Required for cases like strncmp(str($1), str(2), 4)) call.type.SetAS(t.GetAS()); } has_pos_param_ = false; } else if (call.func == "buf") { if (!check_varargs(call, 1, 2)) return; auto &arg = *call.vargs->at(0); if (is_final_pass() && !(arg.type.IsIntTy() || arg.type.IsStringTy() || arg.type.IsPtrTy() || arg.type.IsArrayTy())) { LOG(ERROR, call.loc, err_) << call.func << "() expects an integer, string, or array argument but saw " << typestr(arg.type.type); } size_t max_buffer_size = bpftrace_.strlen_; size_t buffer_size = max_buffer_size; if (call.vargs->size() == 1) { if (arg.type.IsArrayTy()) buffer_size = arg.type.GetNumElements() * arg.type.GetElementTy()->GetSize(); else if (is_final_pass()) LOG(ERROR, call.loc, err_) << call.func << "() expects a length argument for non-array type " << typestr(arg.type.type); } else { if (is_final_pass()) check_arg(call, Type::integer, 1, false); auto &size_arg = *call.vargs->at(1); if (size_arg.type.IsIntTy() && size_arg.is_literal) { auto value = bpftrace_.get_int_literal(&size_arg); if (value.has_value()) { if (*value < 0) { LOG(ERROR, call.loc, err_) << call.func << " cannot use negative length (" << *value << ")"; } buffer_size = *value; } else LOG(ERROR, call.loc, err_) << call.func << ": invalid length value"; } } if (buffer_size > max_buffer_size) { if (is_final_pass()) LOG(WARNING, call.loc, out_) << call.func << "() length is too long and will be shortened to " << std::to_string(bpftrace_.strlen_) << " bytes (see BPFTRACE_STRLEN)"; buffer_size = max_buffer_size; } buffer_size++; // extra byte is used to embed the length of the buffer call.type = CreateBuffer(buffer_size); // Consider case : $a = buf("hi", 2); $b = buf("bye", 3); $a == $b // The result of buf is copied to bpf stack. Hence kernel probe read call.type.SetAS(AddrSpace::kernel); } else if (call.func == "ksym" || call.func == "usym") { if (check_nargs(call, 1)) { // allow symbol lookups on casts (eg, function pointers) auto &arg = *call.vargs->at(0); auto &type = arg.type; if (!type.IsIntegerTy() && !type.IsPtrTy()) LOG(ERROR, call.loc, err_) << call.func << "() expects an integer or pointer argument"; } if (call.func == "ksym") call.type = CreateKSym(); else if (call.func == "usym") call.type = CreateUSym(); } else if (call.func == "ntop") { if (!check_varargs(call, 1, 2)) return; auto arg = call.vargs->at(0); if (call.vargs->size() == 2) { arg = call.vargs->at(1); check_arg(call, Type::integer, 0); } if (!arg->type.IsIntTy() && !arg->type.IsStringTy() && !arg->type.IsArrayTy()) LOG(ERROR, call.loc, err_) << call.func << "() expects an integer or array argument, got " << arg->type.type; // Kind of: // // struct { // int af_type; // union { // char[4] inet4; // char[16] inet6; // } // } int buffer_size = 24; auto type = arg->type; if ((arg->type.IsArrayTy() || arg->type.IsStringTy()) && type.GetSize() != 4 && type.GetSize() != 16) LOG(ERROR, call.loc, err_) << call.func << "() argument must be 4 or 16 bytes in size"; call.type = CreateInet(buffer_size); } else if (call.func == "join") { check_assignment(call, false, false, false); call.type = CreateNone(); if (!check_varargs(call, 1, 2)) return; if (!is_final_pass()) return; auto &arg = *call.vargs->at(0); if (!(arg.type.IsIntTy() || arg.type.IsPtrTy())) { LOG(ERROR, call.loc, err_) << "() only supports int or pointer arguments" << " (" << arg.type.type << " provided)"; } if (call.vargs && call.vargs->size() > 1) check_arg(call, Type::string, 1, true); } else if (call.func == "reg") { if (check_nargs(call, 1)) { if (check_arg(call, Type::string, 0, true)) { auto reg_name = bpftrace_.get_string_literal(call.vargs->at(0)); int offset = arch::offset(reg_name);; if (offset == -1) { LOG(ERROR, call.loc, err_) << "'" << reg_name << "' is not a valid register on this architecture" << " (" << arch::name() << ")"; } } } call.type = CreateUInt64(); ProbeType pt = single_provider_type(); // In case of different attach_points, Set the addrspace to none. call.type.SetAS(find_addrspace(pt)); } else if (call.func == "kaddr") { if (check_nargs(call, 1)) { check_arg(call, Type::string, 0, true); } call.type = CreateUInt64(); call.type.SetAS(AddrSpace::kernel); } else if (call.func == "uaddr") { if (!check_nargs(call, 1)) return; if (!(check_arg(call, Type::string, 0, true) && check_symbol(call, 0))) return; std::vector<int> sizes; auto name = bpftrace_.get_string_literal(call.vargs->at(0)); for (auto &ap : *probe_->attach_points) { struct symbol sym = {}; int err = bpftrace_.resolve_uname(name, &sym, ap->target); if (err < 0 || sym.address == 0) { LOG(ERROR, call.loc, err_) << "Could not resolve symbol: " << ap->target << ":" << name; } sizes.push_back(sym.size); } for (size_t i = 1; i < sizes.size(); i++) { if (sizes.at(0) != sizes.at(i)) { LOG(ERROR, call.loc, err_) << "Symbol size mismatch between probes. Symbol \"" << name << "\" has size " << sizes.at(0) << " for probe \"" << probe_->attach_points->at(0)->name("") << "\" but size " << sizes.at(i) << " for probe \"" << probe_->attach_points->at(i)->name("") << "\""; } } size_t pointee_size = 0; switch (sizes.at(0)) { case 1: case 2: case 4: pointee_size = sizes.at(0) * 8; break; default: pointee_size = 64; } call.type = CreatePointer(CreateInt(pointee_size), AddrSpace::user); } else if (call.func == "cgroupid") { if (check_nargs(call, 1)) { check_arg(call, Type::string, 0, true); } call.type = CreateUInt64(); } else if (call.func == "printf" || call.func == "system" || call.func == "cat") { check_assignment(call, false, false, false); if (check_varargs(call, 1, 128)) { check_arg(call, Type::string, 0, true); if (is_final_pass()) { // NOTE: the same logic can be found in the resource_analyser pass auto &fmt_arg = *call.vargs->at(0); String &fmt = static_cast<String&>(fmt_arg); std::vector<Field> args; for (auto iter = call.vargs->begin() + 1; iter != call.vargs->end(); iter++) { // NOTE: modifying the type will break the resizing that happens // in the codegen. We have to copy the type here to avoid modification SizedType ty = (*iter)->type; // Promote to 64-bit if it's not an aggregate type if (!ty.IsAggregate() && !ty.IsTimestampTy()) ty.SetSize(8); args.push_back(Field{ .name = "", .type = ty, .offset = 0, .is_bitfield = false, .bitfield = Bitfield{ .read_bytes = 0, .access_rshift = 0, .mask = 0, }, }); } std::string msg = validate_format_string(fmt.str, args); if (msg != "") { LOG(ERROR, call.loc, err_) << msg; } } } call.type = CreateNone(); } else if (call.func == "exit") { check_assignment(call, false, false, false); check_nargs(call, 0); } else if (call.func == "print") { check_assignment(call, false, false, false); if (in_loop() && is_final_pass()) { LOG(WARNING, call.loc, out_) << "Due to it's asynchronous nature using 'print()' in a loop can " "lead to unexpected behavior. The map will likely be updated " "before the runtime can 'print' it."; } if (check_varargs(call, 1, 3)) { auto &arg = *call.vargs->at(0); if (arg.is_map) { Map &map = static_cast<Map&>(arg); map.skip_key_validation = true; if (map.vargs != nullptr) { LOG(ERROR, call.loc, err_) << "The map passed to " << call.func << "() should not be " << "indexed by a key"; } if (is_final_pass()) { if (call.vargs->size() > 1) check_arg(call, Type::integer, 1, true); if (call.vargs->size() > 2) check_arg(call, Type::integer, 2, true); if (map.type.IsStatsTy() && call.vargs->size() > 1) { LOG(WARNING, call.loc, out_) << "print()'s top and div arguments are ignored when used on " "stats() maps."; } } } // Note that IsPrintableTy() is somewhat disingenuous here. Printing a // non-map value requires being able to serialize the entire value, so // map-backed types like count(), min(), max(), etc. cannot be printed // through the non-map printing mechanism. // // We rely on the fact that semantic analysis enforces types like count(), // min(), max(), etc. to be assigned directly to a map. This ensures that // the previous `arg.is_map` arm is hit first. else if (arg.type.IsPrintableTy()) { if (call.vargs->size() != 1) LOG(ERROR, call.loc, err_) << "Non-map print() only takes 1 argument, " << call.vargs->size() << " found"; } else { if (is_final_pass()) LOG(ERROR, call.loc, err_) << arg.type << " type passed to " << call.func << "() is not printable"; } } } else if (call.func == "cgroup_path") { call.type = CreateCgroupPath(); if (check_varargs(call, 1, 2)) { check_arg(call, Type::integer, 0, false); call.vargs->size() > 1 && check_arg(call, Type::string, 1, false); } } else if (call.func == "clear") { check_assignment(call, false, false, false); if (check_nargs(call, 1)) { auto &arg = *call.vargs->at(0); if (!arg.is_map) LOG(ERROR, call.loc, err_) << "clear() expects a map to be provided"; else { Map &map = static_cast<Map&>(arg); map.skip_key_validation = true; if (map.vargs != nullptr) { LOG(ERROR, call.loc, err_) << "The map passed to " << call.func << "() should not be " << "indexed by a key"; } } } } else if (call.func == "zero") { check_assignment(call, false, false, false); if (check_nargs(call, 1)) { auto &arg = *call.vargs->at(0); if (!arg.is_map) LOG(ERROR, call.loc, err_) << "zero() expects a map to be provided"; else { Map &map = static_cast<Map&>(arg); map.skip_key_validation = true; if (map.vargs != nullptr) { LOG(ERROR, call.loc, err_) << "The map passed to " << call.func << "() should not be " << "indexed by a key"; } } } } else if (call.func == "time") { check_assignment(call, false, false, false); if (check_varargs(call, 0, 1)) { if (is_final_pass()) { if (call.vargs && call.vargs->size() > 0) check_arg(call, Type::string, 0, true); } } } else if (call.func == "strftime") { call.type = CreateTimestamp(); check_varargs(call, 2, 2) && is_final_pass() && check_arg(call, Type::string, 0, true) && check_arg(call, Type::integer, 1, false); } else if (call.func == "kstack") { check_stack_call(call, true); } else if (call.func == "ustack") { check_stack_call(call, false); } else if (call.func == "signal") { if (!bpftrace_.feature_->has_helper_send_signal()) { LOG(ERROR, call.loc, err_) << "BPF_FUNC_send_signal not available for your kernel version"; } check_assignment(call, false, false, false); if (!check_varargs(call, 1, 1)) { return; } auto &arg = *call.vargs->at(0); if (arg.type.IsStringTy() && arg.is_literal) { auto sig = bpftrace_.get_string_literal(&arg); if (signal_name_to_num(sig) < 1) { LOG(ERROR, call.loc, err_) << sig << " is not a valid signal"; } } else if (arg.type.IsIntTy() && arg.is_literal) { auto sig = bpftrace_.get_int_literal(&arg); if (!sig.has_value() || *sig < 1 || *sig > 64) { LOG(ERROR, call.loc, err_) << std::to_string(*sig) << " is not a valid signal, allowed range: [1,64]"; } } else if(arg.type.type != Type::integer) { LOG(ERROR, call.loc, err_) << "signal only accepts string literals or integers"; } } else if (call.func == "sizeof") { // sizeof() is a interesting builtin because the arguments can be either // an expression or a type. As a result, the only thing we'll check here // is that we have a single argument. check_nargs(call, 1); call.type = CreateUInt64(); } else if (call.func == "path") { if (!bpftrace_.feature_->has_d_path()) { LOG(ERROR, call.loc, err_) << "BPF_FUNC_d_path not available for your kernel version"; } if (check_varargs(call, 1, 1)) { // Argument for path can be both record and pointer. // It's pointer when it's passed directly from the probe // argument, like: path(args->path)) // It's record when it's referenced as object pointer // member, like: path(args->filp->f_path)) if (!check_arg(call, Type::record, 0, false, false) && !check_arg(call, Type::pointer, 0, false, false)) { auto &arg = *call.vargs->at(0); LOG(ERROR, call.loc, err_) << "path() only supports pointer or record argument (" << arg.type.type << " provided)"; } call.type = SizedType(Type::string, bpftrace_.strlen_); } for (auto &attach_point : *probe_->attach_points) { ProbeType type = probetype(attach_point->provider); if (type != ProbeType::kfunc && type != ProbeType::kretfunc && type != ProbeType::iter) LOG(ERROR, call.loc, err_) << "The path function can only be used with " << "'kfunc', 'kretfunc', 'iter' probes"; } } else if (call.func == "strncmp") { if (check_nargs(call, 3)) { check_arg(call, Type::string, 0); check_arg(call, Type::string, 1); if (check_arg(call, Type::integer, 2, true)){ auto size = bpftrace_.get_int_literal(call.vargs->at(2)); if (size.has_value()) { if (size < 0) LOG(ERROR, call.loc, err_) << "Builtin strncmp requires a non-negative size"; } else LOG(ERROR, call.loc, err_) << call.func << ": invalid size value"; } } call.type = CreateUInt64(); } else if (call.func == "override") { if (!bpftrace_.feature_->has_helper_override_return()) { LOG(ERROR, call.loc, err_) << "BPF_FUNC_override_return not available for your kernel version"; } check_assignment(call, false, false, false); if (check_varargs(call, 1, 1)) { check_arg(call, Type::integer, 0, false); } for (auto &attach_point : *probe_->attach_points) { ProbeType type = probetype(attach_point->provider); if (type != ProbeType::kprobe) { LOG(ERROR, call.loc, err_) << call.func << " can only be used with kprobes."; } } } else if (call.func == "kptr" || call.func == "uptr") { if (!check_nargs(call, 1)) return; // kptr should accept both integer or pointer. Consider case: kptr($1) auto &arg = *call.vargs->at(0); if (arg.type.type != Type::integer && arg.type.type != Type::pointer) { LOG(ERROR, call.loc, err_) << call.func << "() only supports " << "integer or pointer arguments (" << arg.type.type << " provided)"; return; } auto as = (call.func == "kptr" ? AddrSpace::kernel : AddrSpace::user); call.type = call.vargs->front()->type; call.type.SetAS(as); } else if (call.func == "macaddr") { if (!check_nargs(call, 1)) return; auto &arg = call.vargs->at(0); if (!arg->type.IsIntTy() && !arg->type.IsArrayTy() && !arg->type.IsByteArray() && !arg->type.IsPtrTy()) LOG(ERROR, call.loc, err_) << call.func << "() only supports array or pointer arguments" << " (" << arg->type.type << " provided)"; auto type = arg->type; if ((type.IsArrayTy() || type.IsByteArray()) && type.GetSize() != 6) LOG(ERROR, call.loc, err_) << call.func << "() argument must be 6 bytes in size"; if (type.IsStringTy() && arg->is_literal) LOG(ERROR, call.loc, err_) << call.func << "() does not support literal string arguments"; call.type = CreateMacAddress(); } else if (call.func == "unwatch") { if (check_nargs(call, 1)) check_arg(call, Type::integer, 0); // Return type cannot be used call.type = SizedType(Type::none, 0); } else if (call.func == "bswap") { if (!check_nargs(call, 1)) return; Expression *arg = call.vargs->at(0); if (arg->type.type != Type::integer) { LOG(ERROR, call.loc, err_) << call.func << "() only supports integer arguments (" << arg->type.type << " provided)"; return; } call.type = CreateUInt(arg->type.GetIntBitWidth()); } else { LOG(ERROR, call.loc, err_) << "Unknown function: '" << call.func << "'"; call.type = CreateNone(); } } void SemanticAnalyser::check_stack_call(Call &call, bool kernel) { call.type = CreateStack(kernel); if (!check_varargs(call, 0, 2)) { return; } StackType stack_type; if (call.vargs) { switch (call.vargs->size()) { case 0: break; case 1: { auto &arg = *call.vargs->at(0); // If we have a single argument it can be either // stack-mode or stack-size if (arg.type.IsStackModeTy()) { if (check_arg(call, Type::stack_mode, 0, true)) stack_type.mode = static_cast<StackMode &>(arg).type.stack_type.mode; } else { if (check_arg(call, Type::integer, 0, true)) { auto limit = bpftrace_.get_int_literal(&arg); if (limit.has_value()) stack_type.limit = *limit; else LOG(ERROR, call.loc, err_) << call.func << ": invalid limit value"; } } break; } case 2: { if (check_arg(call, Type::stack_mode, 0, true)) { auto &mode_arg = *call.vargs->at(0); stack_type.mode = static_cast<StackMode &>(mode_arg).type.stack_type.mode; } if (check_arg(call, Type::integer, 1, true)) { auto &limit_arg = call.vargs->at(1); auto limit = bpftrace_.get_int_literal(limit_arg); if (limit.has_value()) stack_type.limit = *limit; else LOG(ERROR, call.loc, err_) << call.func << ": invalid limit value"; } break; } default: LOG(ERROR, call.loc, err_) << "Invalid number of arguments"; break; } } if (stack_type.limit > MAX_STACK_SIZE) { LOG(ERROR, call.loc, err_) << call.func << "([int limit]): limit shouldn't exceed " << MAX_STACK_SIZE << ", " << stack_type.limit << " given"; } call.type = CreateStack(kernel, stack_type); } void SemanticAnalyser::visit(Map &map) { MapKey key; if (map.vargs) { for (unsigned int i = 0; i < map.vargs->size(); i++){ Expression * expr = map.vargs->at(i); expr->accept(*this); // Insert a cast to 64 bits if needed by injecting // a cast into the ast. if (expr->type.IsIntTy() && expr->type.GetSize() < 8) { std::string type = expr->type.IsSigned() ? "int64" : "uint64"; Expression *cast = new ast::Cast(type, false, false, expr, map.loc); cast->accept(*this); map.vargs->at(i) = cast; expr = cast; } else if (expr->type.IsCtxAccess()) { // map functions only accepts a pointer to a element in the stack LOG(ERROR, map.loc, err_) << "context cannot be used as a map key"; } else if (expr->type.type == Type::tuple) { LOG(ERROR, map.loc, err_) << "tuple cannot be used as a map key. Try a multi-key associative" " array instead (eg `@map[$1, $2] = ...)`."; } if (is_final_pass() && expr->type.IsNoneTy()) LOG(ERROR, expr->loc, err_) << "Invalid expression for assignment: "; SizedType keytype = expr->type; // Skip.IsSigned() when comparing keys to not break existing scripts // which use maps as a lookup table // TODO (fbs): This needs a better solution if (expr->type.IsIntTy()) keytype = CreateUInt(keytype.GetSize() * 8); key.args_.push_back(keytype); } } if (pass_ > 1 && !map.skip_key_validation) update_key_type(map, key); auto search_val = map_val_.find(map.ident); if (search_val != map_val_.end()) { map.type = search_val->second; } else { if (is_final_pass()) { LOG(ERROR, map.loc, err_) << "Undefined map: " << map.ident; } map.type = CreateNone(); } // MapKey default initializes to no args so we don't need to do anything // if we don't find a key here auto map_key_search_val = map_key_.find(map.ident); if (map_key_search_val != map_key_.end()) map.key_type = map_key_search_val->second; } void SemanticAnalyser::visit(Variable &var) { auto search_val = variable_val_[probe_].find(var.ident); if (search_val != variable_val_[probe_].end()) { var.type = search_val->second; } else { LOG(ERROR, var.loc, err_) << "Undefined or undeclared variable: " << var.ident; var.type = CreateNone(); } } void SemanticAnalyser::visit(ArrayAccess &arr) { arr.expr->accept(*this); arr.indexpr->accept(*this); SizedType &type = arr.expr->type; SizedType &indextype = arr.indexpr->type; if (is_final_pass()) { if (!type.IsArrayTy() && !type.IsPtrTy()) { LOG(ERROR, arr.loc, err_) << "The array index operator [] can only be " "used on arrays and pointers, found " << type.type << "."; return; } if (type.IsPtrTy() && type.GetPointeeTy()->GetSize() == 0) { LOG(ERROR, arr.loc, err_) << "The array index operator [] cannot be used " "on a pointer to an unsized type (void *)."; } if (indextype.IsIntTy() && arr.indexpr->is_literal) { if (type.IsArrayTy()) { auto index = bpftrace_.get_int_literal(arr.indexpr); if (index.has_value()) { if ((size_t)*index >= type.GetNumElements()) LOG(ERROR, arr.loc, err_) << "the index " << *index << " is out of bounds for array of size " << type.GetNumElements(); } else LOG(ERROR, arr.loc, err_) << "invalid index expression"; } } else { LOG(ERROR, arr.loc, err_) << "The array index operator [] only " "accepts literal integer indices."; } } if (type.IsArrayTy()) arr.type = *type.GetElementTy(); else if (type.IsPtrTy()) arr.type = *type.GetPointeeTy(); else arr.type = CreateNone(); arr.type.is_internal = type.is_internal; arr.type.SetAS(type.GetAS()); } void SemanticAnalyser::binop_int(Binop &binop) { bool lsign = binop.left->type.IsSigned(); bool rsign = binop.right->type.IsSigned(); auto left = binop.left; auto right = binop.right; // First check if operand signedness is the same if (lsign != rsign) { // Convert operands to unsigned if it helps make (lsign == rsign) // // For example: // // unsigned int a; // if (a > 10) ...; // // No warning should be emitted as we know that 10 can be // represented as unsigned int if (lsign && !rsign && left->is_literal && *bpftrace_.get_int_literal(left) >= 0) { lsign = false; } // The reverse (10 < a) should also hold else if (!lsign && rsign && right->is_literal && *bpftrace_.get_int_literal(right) >= 0) { rsign = false; } else { switch (binop.op) { case Operator::EQ: case Operator::NE: case Operator::LE: case Operator::GE: case Operator::LT: case Operator::GT: LOG(WARNING, binop.loc, out_) << "comparison of integers of different signs: '" << left->type << "' and '" << right->type << "'" << " can lead to undefined behavior"; break; case Operator::PLUS: case Operator::MINUS: case Operator::MUL: case Operator::DIV: case Operator::MOD: LOG(WARNING, binop.loc, out_) << "arithmetic on integers of different signs: '" << left->type << "' and '" << right->type << "'" << " can lead to undefined behavior"; break; default: break; } } } // Next, warn on any operations that require signed division. // // SDIV is not implemented for bpf. See Documentation/bpf/bpf_design_QA // in kernel sources if (binop.op == Operator::DIV || binop.op == Operator::MOD) { // Convert operands to unsigned if possible if (lsign && left->is_literal && *bpftrace_.get_int_literal(left) >= 0) lsign = false; if (rsign && right->is_literal && *bpftrace_.get_int_literal(right) >= 0) rsign = false; // If they're still signed, we have to warn if (lsign || rsign) { LOG(WARNING, binop.loc, out_) << "signed operands for '" << opstr(binop) << "' can lead to undefined behavior " << "(cast to unsigned to silence warning)"; } } if (func_ == "str") { // Check if one of the operands is a positional parameter // The other one should be a constant offset auto pos_param = dynamic_cast<PositionalParameter *>(left); auto offset = dynamic_cast<Integer *>(right); if (!pos_param) { pos_param = dynamic_cast<PositionalParameter *>(right); offset = dynamic_cast<Integer *>(left); } if (pos_param) { auto len = bpftrace_.get_param(pos_param->n, true).length(); if (!offset || binop.op != Operator::PLUS || offset->n < 0 || (size_t)offset->n > len) { LOG(ERROR, binop.loc + binop.right->loc, err_) << "only addition of a single constant less or equal to the " << "length of $" << pos_param->n << " (which is " << len << ")" << " is allowed inside str()"; } } } } void SemanticAnalyser::binop_ptr(Binop &binop) { auto &lht = binop.left->type; auto &rht = binop.right->type; bool left_is_ptr = lht.IsPtrTy(); auto &ptr = left_is_ptr ? lht : rht; auto &other = left_is_ptr ? rht : lht; auto compare = false; // Do what C does switch (binop.op) { case Operator::EQ: case Operator::NE: case Operator::LE: case Operator::GE: case Operator::LT: case Operator::GT: compare = true; break; default:; } auto invalid_op = [&binop, this, &lht, &rht]() { LOG(ERROR, binop.loc, err_) << "The " << opstr(binop) << " operator can not be used on expressions of types " << lht << ", " << rht; }; // Binop on two pointers if (other.IsPtrTy()) { if (compare) { binop.type = CreateUInt(64); if (is_final_pass()) { auto le = lht.GetPointeeTy(); auto re = rht.GetPointeeTy(); if (*le != *re) { LOG(WARNING, binop.left->loc + binop.right->loc, out_) << "comparison of distinct pointer types ('" << *le << ", '" << *re << "')"; } } } else invalid_op(); } // Binop on a pointer and int else if (other.IsIntTy()) { // sum is associative but minus only works with pointer on the left hand // side if (binop.op == Operator::MINUS && !left_is_ptr) invalid_op(); else if (binop.op == Operator::PLUS || binop.op == Operator::MINUS) binop.type = CreatePointer(*ptr.GetPointeeTy(), ptr.GetAS()); else if (compare) binop.type = CreateInt(64); else invalid_op(); } // Binop on a pointer and something else else { invalid_op(); } } void SemanticAnalyser::visit(Binop &binop) { binop.left->accept(*this); binop.right->accept(*this); auto &lht = binop.left->type; auto &rht = binop.right->type; bool lsign = binop.left->type.IsSigned(); bool rsign = binop.right->type.IsSigned(); if (lht.IsPtrTy() || rht.IsPtrTy()) { binop_ptr(binop); return; } bool is_signed = lsign && rsign; switch (binop.op) { case Operator::LEFT: case Operator::RIGHT: is_signed = lsign; break; default: break; } binop.type = CreateInteger(64, is_signed); auto addr_lhs = binop.left->type.GetAS(); auto addr_rhs = binop.right->type.GetAS(); // if lhs or rhs has different addrspace (not none), then set the // addrspace to none. This preserves the behaviour for x86. if (addr_lhs != addr_rhs && addr_lhs != AddrSpace::none && addr_rhs != AddrSpace::none) { if (is_final_pass()) LOG(WARNING, binop.loc, out_) << "Addrspace mismatch"; binop.type.SetAS(AddrSpace::none); } // Associativity from left to right for binary operator else if (addr_lhs != AddrSpace::none) { binop.type.SetAS(addr_lhs); } else { // In case rhs is none, then this triggers warning in selectProbeReadHelper. binop.type.SetAS(addr_rhs); } if (!is_final_pass()) { return; } if (lht.IsIntTy() && rht.IsIntTy()) { binop_int(binop); } else if (lht.IsPtrTy() || rht.IsPtrTy()) { // This case is caught earlier, just here for readability of the if/else // flow } // Compare type here, not the sized type as we it needs to work on strings of // different lengths else if (lht.type != rht.type) { LOG(ERROR, binop.left->loc + binop.right->loc, err_) << "Type mismatch for '" << opstr(binop) << "': comparing '" << lht << "' with '" << rht << "'"; } // Also allow combination like reg("sp") + 8 else if (binop.op != Operator::EQ && binop.op != Operator::NE) { LOG(ERROR, binop.loc, err_) << "The " << opstr(binop) << " operator can not be used on expressions of types " << lht << ", " << rht; } else if (binop.op == Operator::EQ && ((!binop.left->is_literal && binop.right->is_literal) || (binop.left->is_literal && !binop.right->is_literal))) { auto *lit = binop.left->is_literal ? binop.left : binop.right; auto *str = lit == binop.left ? binop.right : binop.left; auto lit_len = bpftrace_.get_string_literal(lit).size(); auto str_len = str->type.GetNumElements(); if (lit_len > str_len) { LOG(WARNING, binop.left->loc + binop.loc + binop.right->loc, out_) << "The literal is longer than the variable string (size=" << str_len << "), condition will always be false"; } } } void SemanticAnalyser::visit(Unop &unop) { if (unop.op == Operator::INCREMENT || unop.op == Operator::DECREMENT) { // Handle ++ and -- before visiting unop.expr, because these // operators should be able to work with undefined maps. if (!unop.expr->is_map && !unop.expr->is_variable) { LOG(ERROR, unop.loc, err_) << "The " << opstr(unop) << " operator must be applied to a map or variable"; } if (unop.expr->is_map) { Map &map = static_cast<Map&>(*unop.expr); auto *maptype = get_map_type(map); if (!maptype) assign_map_type(map, CreateInt64()); } } unop.expr->accept(*this); auto valid_ptr_op = false; switch (unop.op) { case Operator::INCREMENT: case Operator::DECREMENT: case Operator::MUL: valid_ptr_op = true; break; default:; } SizedType &type = unop.expr->type; if (is_final_pass()) { // Unops are only allowed on ints (e.g. ~$x), dereference only on pointers if (!type.IsIntegerTy() && !(type.IsPtrTy() && valid_ptr_op)) { LOG(ERROR, unop.loc, err_) << "The " << opstr(unop) << " operator can not be used on expressions of type '" << type << "'"; } } if (unop.op == Operator::MUL) { if (type.IsPtrTy()) { unop.type = SizedType(*type.GetPointeeTy()); if (type.IsCtxAccess()) { unop.type.MarkCtxAccess(); unop.type.is_funcarg = type.is_funcarg; unop.type.is_tparg = type.is_tparg; } unop.type.SetAS(type.GetAS()); } else if (type.IsRecordTy()) { LOG(ERROR, unop.loc, err_) << "Can not dereference struct/union of type '" << type.GetName() << "'. It is not a pointer."; } else if (type.IsIntTy()) { unop.type = CreateUInt64(); } } else if (unop.op == Operator::LNOT) { // CreateUInt() abort if a size is invalid, so check the size here if (!(type.GetSize() == 0 || type.GetSize() == 1 || type.GetSize() == 2 || type.GetSize() == 4 || type.GetSize() == 8)) { LOG(ERROR, unop.loc, err_) << "The " << opstr(unop) << " operator can not be used on expressions of type '" << type << "'"; } else { unop.type = CreateUInt(8 * type.GetSize()); } } else if (type.IsPtrTy() && valid_ptr_op) { unop.type = unop.expr->type; } else { unop.type = CreateInteger(64, type.IsSigned()); } } void SemanticAnalyser::visit(Ternary &ternary) { ternary.cond->accept(*this); ternary.left->accept(*this); ternary.right->accept(*this); Type &cond = ternary.cond->type.type; Type &lhs = ternary.left->type.type; Type &rhs = ternary.right->type.type; if (is_final_pass()) { if (lhs != rhs) { LOG(ERROR, ternary.loc, err_) << "Ternary operator must return the same type: " << "have '" << lhs << "' and '" << rhs << "'"; } if (cond != Type::integer) LOG(ERROR, ternary.loc, err_) << "Invalid condition in ternary: " << cond; } if (lhs == Type::string) ternary.type = CreateString(STRING_SIZE); else if (lhs == Type::integer) ternary.type = CreateInteger(64, ternary.left->type.IsSigned()); else if (lhs == Type::none) ternary.type = CreateNone(); else { LOG(ERROR, ternary.loc, err_) << "Ternary return type unsupported " << lhs; } } void SemanticAnalyser::visit(If &if_block) { if_block.cond->accept(*this); if (is_final_pass()) { Type &cond = if_block.cond->type.type; if (cond != Type::integer) LOG(ERROR, if_block.loc, err_) << "Invalid condition in if(): " << cond; } accept_statements(if_block.stmts); if (if_block.else_stmts) accept_statements(if_block.else_stmts); } void SemanticAnalyser::visit(Unroll &unroll) { unroll.expr->accept(*this); auto unroll_value = bpftrace_.get_int_literal(unroll.expr); if (!unroll_value.has_value()) { LOG(ERROR, unroll.loc, err_) << "invalid unroll value"; return; } unroll.var = *unroll_value; if (unroll.var > 100) { LOG(ERROR, unroll.loc, err_) << "unroll maximum value is 100"; } else if (unroll.var < 1) { LOG(ERROR, unroll.loc, err_) << "unroll minimum value is 1"; } accept_statements(unroll.stmts); } void SemanticAnalyser::visit(Jump &jump) { switch (jump.ident) { case JumpType::RETURN: // return can be used outside of loops break; case JumpType::BREAK: case JumpType::CONTINUE: if (!in_loop()) LOG(ERROR, jump.loc, err_) << opstr(jump) << " used outside of a loop"; break; default: LOG(ERROR, jump.loc, err_) << "Unknown jump: '" << opstr(jump) << "'"; } } void SemanticAnalyser::visit(While &while_block) { if (is_final_pass() && !bpftrace_.feature_->has_loop()) { LOG(WARNING, while_block.loc, out_) << "Kernel does not support bounded loops. Depending" " on LLVMs loop unroll to generate loadable code."; } while_block.cond->accept(*this); loop_depth_++; accept_statements(while_block.stmts); loop_depth_--; } void SemanticAnalyser::visit(FieldAccess &acc) { // A field access must have a field XOR index assert((acc.field.size() > 0) != (acc.index >= 0)); acc.expr->accept(*this); SizedType &type = acc.expr->type; if (type.IsPtrTy()) { LOG(ERROR, acc.loc, err_) << "Can not access field '" << acc.field << "' on type '" << type << "'. Try dereferencing it first, or using '->'"; return; } if (!type.IsRecordTy() && !type.IsTupleTy()) { if (is_final_pass()) { std::string field; if (acc.field.size()) field += "field '" + acc.field + "'"; else field += "index " + std::to_string(acc.index); LOG(ERROR, acc.loc, err_) << "Can not access " << field << " on expression of type '" << type << "'"; } return; } if (type.is_funcarg) { auto it = ap_args_.find(acc.field); if (it != ap_args_.end()) { acc.type = it->second; acc.type.SetAS(acc.expr->type.GetAS()); if (is_final_pass()) { if (acc.type.IsNoneTy()) LOG(ERROR, acc.loc, err_) << acc.field << " has unsupported type"; } } else { LOG(ERROR, acc.loc, err_) << "Can't find function parameter " << acc.field; } return; } if (type.IsTupleTy()) { if (acc.index < 0) { LOG(ERROR, acc.loc, err_) << "Tuples must be indexed with a constant and non-negative integer"; return; } bool valid_idx = static_cast<size_t>(acc.index) < type.GetFields().size(); // We may not have inferred the full type of the tuple yet in early passes // so wait until the final pass. if (!valid_idx && is_final_pass()) LOG(ERROR, acc.loc, err_) << "Invalid tuple index: " << acc.index << ". Found " << type.GetFields().size() << " elements in tuple."; if (valid_idx) acc.type = type.GetField(acc.index).type; return; } if (!bpftrace_.structs.Has(type.GetName())) { LOG(ERROR, acc.loc, err_) << "Unknown struct/union: '" << type.GetName() << "'"; return; } std::map<std::string, std::weak_ptr<const Struct>> structs; if (type.is_tparg) { for (AttachPoint *attach_point : *probe_->attach_points) { if (probetype(attach_point->provider) != ProbeType::tracepoint) { // The args builtin can only be used with tracepoint // an error message is already generated in visit(Builtin) // just continue semantic analysis continue; } auto matches = bpftrace_.probe_matcher_->get_matches_for_ap( *attach_point); for (auto &match : matches) { std::string tracepoint_struct = TracepointFormatParser::get_struct_name( match); structs[tracepoint_struct] = bpftrace_.structs.Lookup( tracepoint_struct); } } } else { structs[type.GetName()] = type.GetStruct(); } for (auto it : structs) { std::string cast_type = it.first; const auto record = it.second.lock(); if (!record->HasField(acc.field)) { LOG(ERROR, acc.loc, err_) << "Struct/union of type '" << cast_type << "' does not contain " << "a field named '" << acc.field << "'"; } else { const auto &field = record->GetField(acc.field); acc.type = field.type; if (acc.expr->type.IsCtxAccess() && (acc.type.IsArrayTy() || acc.type.IsRecordTy())) { // e.g., ((struct bpf_perf_event_data*)ctx)->regs.ax acc.type.MarkCtxAccess(); } acc.type.is_internal = type.is_internal; acc.type.SetAS(acc.expr->type.GetAS()); // The kernel uses the first 8 bytes to store `struct pt_regs`. Any // access to the first 8 bytes results in verifier error. if (type.is_tparg && field.offset < 8) LOG(ERROR, acc.loc, err_) << "BPF does not support accessing common tracepoint fields"; } } } void SemanticAnalyser::visit(Cast &cast) { cast.expr->accept(*this); if (cast.expr->type.IsRecordTy()) { LOG(ERROR, cast.loc, err_) << "Cannot cast from struct type \"" << cast.expr->type << "\""; } bool is_ctx = cast.expr->type.IsCtxAccess(); auto &intcasts = getIntcasts(); auto k_v = intcasts.find(cast.cast_type); // Built-in int types if (k_v != intcasts.end()) { auto &v = k_v->second; if (cast.is_pointer) { cast.type = CreatePointer(CreateInteger(std::get<0>(v), std::get<1>(v))); if (is_ctx) { LOG(ERROR, cast.loc, err_) << "Integer pointer casts are not supported for type: ctx"; } if (cast.is_double_pointer) cast.type = CreatePointer(cast.type); } else { cast.type = CreateInteger(std::get<0>(v), std::get<1>(v)); auto rhs = cast.expr->type; // Casting Type::ctx to Type::integer is supported to access a // tracepoint's __data_loc field. See #990 and #770 // In this case, the context information will be lost if (!rhs.IsIntTy() && !rhs.IsRecordTy() && !rhs.IsPtrTy() && !rhs.IsCtxAccess()) { LOG(ERROR, cast.loc, err_) << "Casts are not supported for type: \"" << rhs << "\""; } } // Consider both case *(int8)(retval) and *(int8*)retval cast.type.SetAS(cast.expr->type.GetAS()); return; } if (!bpftrace_.structs.Has(cast.cast_type)) { LOG(ERROR, cast.loc, err_) << "Unknown struct/union: '" << cast.cast_type << "'"; return; } SizedType struct_type = CreateRecord( cast.cast_type, bpftrace_.structs.Lookup(cast.cast_type)); if (cast.is_pointer) { cast.type = CreatePointer(struct_type); if (cast.is_double_pointer) cast.type = CreatePointer(cast.type); } else { LOG(ERROR, cast.loc, err_) << "Cannot cast to struct type \"" << cast.cast_type << "\""; } if (is_ctx) cast.type.MarkCtxAccess(); cast.type.SetAS(cast.expr->type.GetAS()); // case : BEGIN { @foo = (struct Foo)0; } // case : profile:hz:99 $task = (struct task_struct *)curtask. if (cast.type.GetAS() == AddrSpace::none) { ProbeType type = single_provider_type(); cast.type.SetAS(find_addrspace(type)); } } void SemanticAnalyser::visit(Tuple &tuple) { std::vector<SizedType> elements; for (size_t i = 0; i < tuple.elems->size(); ++i) { Expression *elem = tuple.elems->at(i); elem->accept(*this); // If elem type is none that means that the tuple contains some // invalid cast (e.g., (0, (aaa)0)). In this case, skip the tuple // creation. Cast already emits the error. if (elem->type.IsNoneTy() || elem->type.GetSize() == 0) return; elements.emplace_back(elem->type); } tuple.type = CreateTuple(bpftrace_.structs.AddTuple(elements)); } void SemanticAnalyser::visit(ExprStatement &expr) { expr.expr->accept(*this); } void SemanticAnalyser::visit(AssignMapStatement &assignment) { assignment.map->accept(*this); assignment.expr->accept(*this); assign_map_type(*assignment.map, assignment.expr->type); const std::string &map_ident = assignment.map->ident; auto type = assignment.expr->type; if (type.IsRecordTy()) { std::string ty = assignment.expr->type.GetName(); std::string stored_ty = map_val_[map_ident].GetName(); if (!stored_ty.empty() && stored_ty != ty) { LOG(ERROR, assignment.loc, err_) << "Type mismatch for " << map_ident << ": " << "trying to assign value of type '" << ty << "' when map already contains a value of type '" << stored_ty << "''"; } else { map_val_[map_ident] = assignment.expr->type; map_val_[map_ident].is_internal = true; } } else if (type.IsStringTy()) { auto map_size = map_val_[map_ident].GetSize(); auto expr_size = assignment.expr->type.GetSize(); if (map_size < expr_size) { LOG(WARNING, assignment.loc, out_) << "String size mismatch: " << map_size << " < " << expr_size << ". The value may be truncated."; } } else if (type.IsBufferTy()) { auto map_size = map_val_[map_ident].GetSize(); auto expr_size = assignment.expr->type.GetSize(); if (map_size != expr_size) { std::stringstream buf; buf << "Buffer size mismatch: " << map_size << " != " << expr_size << "."; if (map_size < expr_size) { buf << " The value may be truncated."; LOG(WARNING, assignment.loc, out_) << buf.str(); } else { // bpf_map_update_elem() expects map_size-length value LOG(ERROR, assignment.loc, err_) << buf.str(); } } } else if (type.IsCtxAccess()) { // bpf_map_update_elem() only accepts a pointer to a element in the stack LOG(ERROR, assignment.loc, err_) << "context cannot be assigned to a map"; } else if (type.IsTupleTy()) { // Early passes may not have been able to deduce the full types of tuple // elements yet. So wait until final pass. if (is_final_pass()) { const auto &map_type = map_val_[map_ident]; const auto &expr_type = assignment.expr->type; if (!expr_type.FitsInto(map_type)) { LOG(ERROR, assignment.loc, err_) << "Tuple type mismatch: " << map_type << " != " << expr_type << "."; } } } else if (type.IsArrayTy()) { const auto &map_type = map_val_[map_ident]; const auto &expr_type = assignment.expr->type; if (map_type == expr_type) { map_val_[map_ident].is_internal = true; } else { LOG(ERROR, assignment.loc, err_) << "Array type mismatch: " << map_type << " != " << expr_type << "."; } } if (is_final_pass()) { if (type.IsNoneTy()) LOG(ERROR, assignment.expr->loc, err_) << "Invalid expression for assignment: " << type; } } void SemanticAnalyser::visit(AssignVarStatement &assignment) { assignment.expr->accept(*this); std::string var_ident = assignment.var->ident; auto search = variable_val_[probe_].find(var_ident); auto &assignTy = assignment.expr->type; auto *builtin = dynamic_cast<Builtin *>(assignment.expr); if (builtin && builtin->ident == "args" && builtin->type.is_funcarg) { LOG(ERROR, assignment.loc, err_) << "args cannot be assigned to a variable"; } if (search != variable_val_[probe_].end()) { if (search->second.IsNoneTy()) { if (is_final_pass()) { LOG(ERROR, assignment.loc, err_) << "Undefined variable: " + var_ident; } else { search->second = assignTy; } } else if ((search->second.IsStringTy() && assignTy.IsStringTy()) || (search->second.IsTupleTy() && assignTy.IsTupleTy())) { update_string_size(search->second, assignTy); } else if (!search->second.IsSameType(assignTy)) { LOG(ERROR, assignment.loc, err_) << "Type mismatch for " << var_ident << ": " << "trying to assign value of type '" << assignTy << "' when variable already contains a value of type '" << search->second << "'"; } } else { // This variable hasn't been seen before variable_val_[probe_].insert({ var_ident, assignment.expr->type }); } auto &storedTy = variable_val_[probe_][var_ident]; assignment.var->type = storedTy; if (assignTy.IsRecordTy()) { if (assignTy.GetName() != storedTy.GetName()) { LOG(ERROR, assignment.loc, err_) << "Type mismatch for " << var_ident << ": " << "trying to assign value of type '" << assignTy.GetName() << "' when variable already contains a value of type '" << storedTy; } } else if (assignTy.IsStringTy()) { auto var_size = storedTy.GetSize(); auto expr_size = assignTy.GetSize(); if (var_size < expr_size) { LOG(WARNING, assignment.loc, out_) << "String size mismatch: " << var_size << " != " << expr_size << ". The value may be truncated."; } } else if (assignTy.IsBufferTy()) { auto var_size = storedTy.GetSize(); auto expr_size = assignTy.GetSize(); if (var_size != expr_size) { LOG(WARNING, assignment.loc, out_) << "Buffer size mismatch: " << var_size << " != " << expr_size << (var_size < expr_size ? ". The value may be truncated." : ". The value may contain garbage."); } } else if (assignTy.IsTupleTy()) { // Early passes may not have been able to deduce the full types of tuple // elements yet. So wait until final pass. if (is_final_pass()) { auto var_type = storedTy; auto expr_type = assignTy; if (!expr_type.FitsInto(var_type)) { LOG(ERROR, assignment.loc, err_) << "Tuple type mismatch: " << var_type << " != " << expr_type << "."; } } } if (is_final_pass()) { auto &ty = assignTy.type; if (ty == Type::none) LOG(ERROR, assignment.expr->loc, err_) << "Invalid expression for assignment: " << ty; } } void SemanticAnalyser::visit(Predicate &pred) { pred.expr->accept(*this); if (is_final_pass()) { SizedType &ty = pred.expr->type; if (!ty.IsIntTy() && !ty.IsPtrTy()) { LOG(ERROR, pred.loc, err_) << "Invalid type for predicate: " << pred.expr->type.type; } } } void SemanticAnalyser::visit(AttachPoint &ap) { ap.provider = probetypeName(ap.provider); if (ap.provider == "kprobe" || ap.provider == "kretprobe") { if (ap.target != "") LOG(ERROR, ap.loc, err_) << "kprobes should not have a target"; if (ap.func == "") LOG(ERROR, ap.loc, err_) << "kprobes should be attached to a function"; if (is_final_pass()) { // Warn if user tries to attach to a non-traceable function if (!has_wildcard(ap.func) && !bpftrace_.is_traceable_func(ap.func)) { LOG(WARNING, ap.loc, out_) << ap.func << " is not traceable (either non-existing, inlined, or marked as " "\"notrace\"); attaching to it will likely fail"; } } } else if (ap.provider == "uprobe" || ap.provider == "uretprobe") { if (ap.target == "") LOG(ERROR, ap.loc, err_) << ap.provider << " should have a target"; if (ap.func == "" && ap.address == 0) LOG(ERROR, ap.loc, err_) << ap.provider << " should be attached to a function and/or address"; if (ap.provider == "uretprobe" && ap.func_offset != 0) LOG(ERROR, ap.loc, err_) << "uretprobes can not be attached to a function offset"; auto paths = resolve_binary_path(ap.target, bpftrace_.pid()); switch (paths.size()) { case 0: LOG(ERROR, ap.loc, err_) << "uprobe target file '" << ap.target << "' does not exist or is not executable"; break; case 1: ap.target = paths.front(); break; default: // If we are doing a PATH lookup (ie not glob), we follow shell // behavior and take the first match. // Otherwise we keep the target with glob, it will be expanded later if (ap.target.find("*") == std::string::npos) { LOG(WARNING, ap.loc, out_) << "attaching to uprobe target file '" << paths.front() << "' but matched " << std::to_string(paths.size()) << " binaries"; ap.target = paths.front(); } } // Check if there were some arguments resolved for the probe auto args_it = bpftrace_.ap_args_.find(probe_->name()); if (args_it != bpftrace_.ap_args_.end()) { ap_args_.clear(); ap_args_.insert(args_it->second.begin(), args_it->second.end()); } } else if (ap.provider == "usdt") { bpftrace_.has_usdt_ = true; if (ap.func == "") LOG(ERROR, ap.loc, err_) << "usdt probe must have a target function or wildcard"; if (ap.target != "" && !(bpftrace_.pid() > 0 && has_wildcard(ap.target))) { auto paths = resolve_binary_path(ap.target, bpftrace_.pid()); switch (paths.size()) { case 0: LOG(ERROR, ap.loc, err_) << "usdt target file '" << ap.target << "' does not exist or is not executable"; break; case 1: ap.target = paths.front(); break; default: // If we are doing a PATH lookup (ie not glob), we follow shell // behavior and take the first match. // Otherwise we keep the target with glob, it will be expanded later if (ap.target.find("*") == std::string::npos) { LOG(WARNING, ap.loc, out_) << "attaching to usdt target file '" << paths.front() << "' but matched " << std::to_string(paths.size()) << " binaries"; ap.target = paths.front(); } } } if (bpftrace_.pid() > 0) { USDTHelper::probes_for_pid(bpftrace_.pid()); } else if (ap.target != "") { for (auto &path : resolve_binary_path(ap.target)) USDTHelper::probes_for_path(path); } else { LOG(ERROR, ap.loc, err_) << "usdt probe must specify at least path or pid to probe"; } } else if (ap.provider == "tracepoint") { if (ap.target == "" || ap.func == "") LOG(ERROR, ap.loc, err_) << "tracepoint probe must have a target"; } else if (ap.provider == "profile") { if (ap.target == "") LOG(ERROR, ap.loc, err_) << "profile probe must have unit of time"; else if (ap.target != "hz" && ap.target != "us" && ap.target != "ms" && ap.target != "s") LOG(ERROR, ap.loc, err_) << ap.target << " is not an accepted unit of time"; if (ap.func != "") LOG(ERROR, ap.loc, err_) << "profile probe must have an integer frequency"; else if (ap.freq <= 0) LOG(ERROR, ap.loc, err_) << "profile frequency should be a positive integer"; } else if (ap.provider == "interval") { if (ap.target == "") LOG(ERROR, ap.loc, err_) << "interval probe must have unit of time"; else if (ap.target != "ms" && ap.target != "s" && ap.target != "us" && ap.target != "hz") LOG(ERROR, ap.loc, err_) << ap.target << " is not an accepted unit of time"; if (ap.func != "") LOG(ERROR, ap.loc, err_) << "interval probe must have an integer frequency"; } else if (ap.provider == "software") { if (ap.target == "") LOG(ERROR, ap.loc, err_) << "software probe must have a software event name"; else { if (!has_wildcard(ap.target) && !ap.ignore_invalid) { bool found = false; for (auto &probeListItem : SW_PROBE_LIST) { if (ap.target == probeListItem.path || (!probeListItem.alias.empty() && ap.target == probeListItem.alias)) { found = true; break; } } if (!found) LOG(ERROR, ap.loc, err_) << ap.target << " is not a software probe"; } else if (!listing_) { LOG(ERROR, ap.loc, err_) << "wildcards are not allowed for hardware probe type"; } } if (ap.func != "") LOG(ERROR, ap.loc, err_) << "software probe can only have an integer count"; else if (ap.freq < 0) LOG(ERROR, ap.loc, err_) << "software count should be a positive integer"; } else if (ap.provider == "watchpoint" || ap.provider == "asyncwatchpoint") { if (ap.func.size()) { if (bpftrace_.pid() <= 0 && !has_child_) LOG(ERROR, ap.loc, err_) << "-p PID or -c CMD required for watchpoint"; if (ap.address > static_cast<uint64_t>(arch::max_arg())) LOG(ERROR, ap.loc, err_) << arch::name() << " doesn't support arg" << ap.address; } else if (ap.provider == "asyncwatchpoint") LOG(ERROR, ap.loc, err_) << ap.provider << " requires a function name"; else if (!ap.address) LOG(ERROR, ap.loc, err_) << "watchpoint must be attached to a non-zero address"; if (ap.len != 1 && ap.len != 2 && ap.len != 4 && ap.len != 8) LOG(ERROR, ap.loc, err_) << "watchpoint length must be one of (1,2,4,8)"; if (ap.mode.empty()) LOG(ERROR, ap.loc, err_) << "watchpoint mode must be combination of (r,w,x)"; std::sort(ap.mode.begin(), ap.mode.end()); for (const char c : ap.mode) { if (c != 'r' && c != 'w' && c != 'x') LOG(ERROR, ap.loc, err_) << "watchpoint mode must be combination of (r,w,x)"; } for (size_t i = 1; i < ap.mode.size(); ++i) { if (ap.mode[i - 1] == ap.mode[i]) LOG(ERROR, ap.loc, err_) << "watchpoint modes may not be duplicated"; } const auto invalid_modes = arch::invalid_watchpoint_modes(); if (std::any_of(invalid_modes.cbegin(), invalid_modes.cend(), [&](const auto &mode) { return mode == ap.mode; })) LOG(ERROR, ap.loc, err_) << "invalid watchpoint mode: " << ap.mode; } else if (ap.provider == "hardware") { if (ap.target == "") LOG(ERROR, ap.loc, err_) << "hardware probe must have a hardware event name"; else { if (!has_wildcard(ap.target) && !ap.ignore_invalid) { bool found = false; for (auto &probeListItem : HW_PROBE_LIST) { if (ap.target == probeListItem.path || (!probeListItem.alias.empty() && ap.target == probeListItem.alias)) { found = true; break; } } if (!found) LOG(ERROR, ap.loc, err_) << ap.target + " is not a hardware probe"; } else if (!listing_) { LOG(ERROR, ap.loc, err_) << "wildcards are not allowed for hardware probe type"; } } if (ap.func != "") LOG(ERROR, ap.loc, err_) << "hardware probe can only have an integer count"; else if (ap.freq < 0) LOG(ERROR, ap.loc, err_) << "hardware frequency should be a positive integer"; } else if (ap.provider == "BEGIN" || ap.provider == "END") { if (ap.target != "" || ap.func != "") LOG(ERROR, ap.loc, err_) << "BEGIN/END probes should not have a target"; if (is_final_pass()) { if (ap.provider == "BEGIN") { if (has_begin_probe_) LOG(ERROR, ap.loc, err_) << "More than one BEGIN probe defined"; has_begin_probe_ = true; } if (ap.provider == "END") { if (has_end_probe_) LOG(ERROR, ap.loc, err_) << "More than one END probe defined"; has_end_probe_ = true; } } } else if (ap.provider == "kfunc" || ap.provider == "kretfunc") { #ifndef HAVE_BCC_KFUNC LOG(ERROR, ap.loc, err_) << "kfunc/kretfunc not available for your linked against bcc version."; return; #endif bool supported = bpftrace_.feature_->has_prog_kfunc() && bpftrace_.btf_.has_data(); if (!supported) { LOG(ERROR, ap.loc, err_) << "kfunc/kretfunc not available for your kernel version."; return; } if (ap.func == "") LOG(ERROR, ap.loc, err_) << "kfunc should specify a function"; if (!listing_) { const auto &ap_map = bpftrace_.ap_args_; auto it = ap_map.find(probe_->name()); if (it != ap_map.end()) { auto args = it->second; ap_args_.clear(); ap_args_.insert(args.begin(), args.end()); } } } else if (ap.provider == "iter") { bool supported = false; if (ap.func == "task") { supported = bpftrace_.feature_->has_prog_iter_task() && bpftrace_.btf_.has_data(); } else if (ap.func == "task_file") { supported = bpftrace_.feature_->has_prog_iter_task_file() && bpftrace_.btf_.has_data(); } else if (listing_) { supported = true; } if (!supported) { LOG(ERROR, ap.loc, err_) << "iter " << ap.func << " not available for your kernel version."; } } else { LOG(ERROR, ap.loc, err_) << "Invalid provider: '" << ap.provider << "'"; } } void SemanticAnalyser::visit(Probe &probe) { auto aps = probe.attach_points->size(); probe_ = &probe; for (AttachPoint *ap : *probe.attach_points) { if (!listing_ && aps > 1 && ap->provider == "iter") { LOG(ERROR, ap->loc, err_) << "Only single iter attach point is allowed."; return; } ap->accept(*this); } if (probe.pred) { probe.pred->accept(*this); } if (probe.stmts) { for (Statement *stmt : *probe.stmts) { stmt->accept(*this); } } } void SemanticAnalyser::visit(Program &program) { for (Probe *probe : *program.probes) probe->accept(*this); } int SemanticAnalyser::analyse() { // Multiple passes to handle variables being used before they are defined std::string errors; int num_passes = listing_ ? 1 : num_passes_; for (pass_ = 1; pass_ <= num_passes; pass_++) { root_->accept(*this); errors = err_.str(); if (!errors.empty()) { out_ << errors; return pass_; } } return 0; } bool SemanticAnalyser::is_final_pass() const { return pass_ == num_passes_; } bool SemanticAnalyser::check_assignment(const Call &call, bool want_map, bool want_var, bool want_map_key) { if (want_map && want_var && want_map_key) { if (!call.map && !call.var && !call.key_for_map) { LOG(ERROR, call.loc, err_) << call.func << "() should be assigned to a map or a " "variable, or be used as a map key"; return false; } } else if (want_map && want_var) { if (!call.map && !call.var) { LOG(ERROR, call.loc, err_) << call.func << "() should be assigned to a map or a variable"; return false; } } else if (want_map && want_map_key) { if (!call.map && !call.key_for_map) { LOG(ERROR, call.loc, err_) << call.func << "() should be assigned to a map or be used as a map key"; return false; } } else if (want_var && want_map_key) { if (!call.var && !call.key_for_map) { LOG(ERROR, call.loc, err_) << call.func << "() should be assigned to a variable or be used as a map key"; return false; } } else if (want_map) { if (!call.map) { LOG(ERROR, call.loc, err_) << call.func << "() should be directly assigned to a map"; return false; } } else if (want_var) { if (!call.var) { LOG(ERROR, call.loc, err_) << call.func << "() should be assigned to a variable"; return false; } } else if (want_map_key) { if (!call.key_for_map) { LOG(ERROR, call.loc, err_) << call.func << "() should be used as a map key"; return false; } } else { if (call.map || call.var || call.key_for_map) { LOG(ERROR, call.loc, err_) << call.func << "() should not be used in an assignment or as a map key"; return false; } } return true; } bool SemanticAnalyser::check_nargs(const Call &call, size_t expected_nargs) { std::stringstream err; std::vector<Expression*>::size_type nargs = 0; if (call.vargs) nargs = call.vargs->size(); if (nargs != expected_nargs) { if (expected_nargs == 0) err << call.func << "() requires no arguments"; else if (expected_nargs == 1) err << call.func << "() requires one argument"; else err << call.func << "() requires " << expected_nargs << " arguments"; err << " (" << nargs << " provided)"; LOG(ERROR, call.loc, err_) << err.str(); return false; } return true; } bool SemanticAnalyser::check_varargs(const Call &call, size_t min_nargs, size_t max_nargs) { std::vector<Expression*>::size_type nargs = 0; std::stringstream err; if (call.vargs) nargs = call.vargs->size(); if (nargs < min_nargs) { if (min_nargs == 1) err << call.func << "() requires at least one argument"; else err << call.func << "() requires at least " << min_nargs << " arguments"; err << " (" << nargs << " provided)"; LOG(ERROR, call.loc, err_) << err.str(); return false; } else if (nargs > max_nargs) { if (max_nargs == 0) err << call.func << "() requires no arguments"; else if (max_nargs == 1) err << call.func << "() takes up to one argument"; else err << call.func << "() takes up to " << max_nargs << " arguments"; err << " (" << nargs << " provided)"; LOG(ERROR, call.loc, err_) << err.str(); return false; } return true; } bool SemanticAnalyser::check_arg(const Call &call, Type type, int arg_num, bool want_literal, bool fail) { if (!call.vargs) return false; auto &arg = *call.vargs->at(arg_num); if (want_literal && (!arg.is_literal || arg.type.type != type)) { if (fail) { LOG(ERROR, call.loc, err_) << call.func << "() expects a " << type << " literal (" << arg.type.type << " provided)"; if (type == Type::string) { // If the call requires a string literal and a positional parameter is // given, tell user to use str() auto *pos_param = dynamic_cast<PositionalParameter *>(&arg); if (pos_param) LOG(ERROR) << "Use str($" << pos_param->n << ") to treat $" << pos_param->n << " as a string"; } } return false; } else if (is_final_pass() && arg.type.type != type) { if (fail) { LOG(ERROR, call.loc, err_) << call.func << "() only supports " << type << " arguments (" << arg.type.type << " provided)"; } return false; } return true; } bool SemanticAnalyser::check_symbol(const Call &call, int arg_num __attribute__((unused))) { if (!call.vargs) return false; auto arg = bpftrace_.get_string_literal(call.vargs->at(0)); std::string re = "^[a-zA-Z0-9./_-]+$"; bool is_valid = std::regex_match(arg, std::regex(re)); if (!is_valid) { LOG(ERROR, call.loc, err_) << call.func << "() expects a string that is a valid symbol (" << re << ") as input (\"" << arg << "\" provided)"; return false; } return true; } bool SemanticAnalyser::check_available(const Call &call, const AttachPoint &ap) { auto &func = call.func; ProbeType type = probetype(ap.provider); if (func == "reg") { switch (type) { case ProbeType::kprobe: case ProbeType::kretprobe: case ProbeType::uprobe: case ProbeType::uretprobe: case ProbeType::usdt: case ProbeType::profile: case ProbeType::interval: case ProbeType::software: case ProbeType::hardware: case ProbeType::watchpoint: case ProbeType::asyncwatchpoint: return true; case ProbeType::invalid: case ProbeType::tracepoint: case ProbeType::kfunc: case ProbeType::kretfunc: case ProbeType::iter: return false; } } else if (func == "uaddr") { switch (type) { case ProbeType::usdt: case ProbeType::uretprobe: case ProbeType::uprobe: return true; case ProbeType::invalid: case ProbeType::kprobe: case ProbeType::kretprobe: case ProbeType::tracepoint: case ProbeType::profile: case ProbeType::interval: case ProbeType::software: case ProbeType::hardware: case ProbeType::watchpoint: case ProbeType::asyncwatchpoint: case ProbeType::kfunc: case ProbeType::kretfunc: case ProbeType::iter: return false; } } else if (func == "signal") { if (ap.provider == "BEGIN" || ap.provider == "END") return false; switch (type) { case ProbeType::kprobe: case ProbeType::kretprobe: case ProbeType::uprobe: case ProbeType::uretprobe: case ProbeType::usdt: case ProbeType::tracepoint: case ProbeType::profile: case ProbeType::kfunc: case ProbeType::kretfunc: return true; case ProbeType::invalid: case ProbeType::interval: case ProbeType::software: case ProbeType::hardware: case ProbeType::watchpoint: case ProbeType::asyncwatchpoint: case ProbeType::iter: return false; } } if (type == ProbeType::invalid) return false; return true; } SizedType *SemanticAnalyser::get_map_type(const Map &map) { const std::string &map_ident = map.ident; auto search = map_val_.find(map_ident); if (search == map_val_.end()) return nullptr; return &search->second; } /* * assign_map_type * * Semantic analysis for assigning a value of the provided type * to the given map. */ void SemanticAnalyser::assign_map_type(const Map &map, const SizedType &type) { const std::string &map_ident = map.ident; auto *maptype = get_map_type(map); if (maptype) { if (maptype->IsNoneTy()) { if (is_final_pass()) LOG(ERROR, map.loc, err_) << "Undefined map: " + map_ident; else *maptype = type; } else if (maptype->type != type.type) { LOG(ERROR, map.loc, err_) << "Type mismatch for " << map_ident << ": " << "trying to assign value of type '" << type << "' when map already contains a value of type '" << *maptype; } if (maptype->IsStringTy() || maptype->IsTupleTy()) update_string_size(*maptype, type); } else { // This map hasn't been seen before map_val_.insert({ map_ident, type }); if (map_val_[map_ident].IsIntTy()) { // Store all integer values as 64-bit in maps, so that there will // be space for any integer to be assigned to the map later map_val_[map_ident].SetSize(8); } } } void SemanticAnalyser::accept_statements(StatementList *stmts) { for (size_t i = 0; i < stmts->size(); i++) { auto stmt = stmts->at(i); stmt->accept(*this); if (is_final_pass()) { auto *jump = dynamic_cast<Jump *>(stmt); if (jump && i < (stmts->size() - 1)) { LOG(WARNING, jump->loc, out_) << "All code after a '" << opstr(*jump) << "' is unreachable."; } } } } void SemanticAnalyser::update_key_type(const Map &map, const MapKey &new_key) { auto key = map_key_.find(map.ident); if (key != map_key_.end()) { bool valid = true; if (key->second.args_.size() == new_key.args_.size()) { for (size_t i = 0; i < key->second.args_.size(); i++) { SizedType &key_type = key->second.args_[i]; const SizedType &new_key_type = new_key.args_[i]; if (key_type.IsStringTy() && new_key_type.IsStringTy()) { key_type.SetSize( std::max(key_type.GetSize(), new_key_type.GetSize())); } else if (key_type != new_key_type) { valid = false; break; } } } else valid = false; if (!valid) { LOG(ERROR, map.loc, err_) << "Argument mismatch for " << map.ident << ": " << "trying to access with arguments: " << new_key.argument_type_list() << " when map expects arguments: " << key->second.argument_type_list(); } } else map_key_.insert({ map.ident, new_key }); } bool SemanticAnalyser::update_string_size(SizedType &type, const SizedType &new_type) { if (type.IsStringTy() && new_type.IsStringTy() && type.GetSize() != new_type.GetSize()) { type.SetSize(std::max(type.GetSize(), new_type.GetSize())); return true; } if (type.IsTupleTy() && new_type.IsTupleTy() && type.GetFieldCount() == new_type.GetFieldCount()) { bool updated = false; std::vector<SizedType> new_elems; for (ssize_t i = 0; i < type.GetFieldCount(); i++) { if (update_string_size(type.GetField(i).type, new_type.GetField(i).type)) updated = true; new_elems.push_back(type.GetField(i).type); } if (updated) type = CreateTuple(bpftrace_.structs.AddTuple(new_elems)); return updated; } return false; } Pass CreateSemanticPass() { auto fn = [](Node &n, PassContext &ctx) { auto semantics = SemanticAnalyser(&n, ctx.b, !ctx.b.cmd_.empty()); int err = semantics.analyse(); if (err) return PassResult::Error("Semantic", err); return PassResult::Success(); }; return Pass("Semantic", fn); }; } // namespace ast } // namespace bpftrace
auto ARM7TDMI::fetch() -> void { pipeline.execute = pipeline.decode; pipeline.decode = pipeline.fetch; pipeline.decode.thumb = cpsr().t; u32 sequential = Sequential; if(pipeline.nonsequential) { pipeline.nonsequential = false; sequential = Nonsequential; } u32 mask = !cpsr().t ? 3 : 1; u32 size = !cpsr().t ? Word : Half; r(15).data += size >> 3; pipeline.fetch.address = r(15) & ~mask; pipeline.fetch.instruction = read(Prefetch | size | sequential, pipeline.fetch.address); } auto ARM7TDMI::instruction() -> void { u32 mask = !cpsr().t ? 3 : 1; u32 size = !cpsr().t ? Word : Half; if(pipeline.reload) { pipeline.reload = false; r(15).data &= ~mask; pipeline.fetch.address = r(15) & ~mask; pipeline.fetch.instruction = read(Prefetch | size | Nonsequential, pipeline.fetch.address); fetch(); } fetch(); if(irq && !cpsr().i) { exception(PSR::IRQ, 0x18); if(pipeline.execute.thumb) r(14).data += 2; return; } opcode = pipeline.execute.instruction; if(!pipeline.execute.thumb) { if(!TST(opcode.bit(28,31))) return; n12 index = (opcode & 0x0ff00000) >> 16 | (opcode & 0x000000f0) >> 4; armInstruction[index](opcode); } else { thumbInstruction[(n16)opcode](); } } auto ARM7TDMI::exception(u32 mode, n32 address) -> void { auto psr = cpsr(); cpsr().m = mode; spsr() = psr; cpsr().t = 0; if(cpsr().m == PSR::FIQ) cpsr().f = 1; cpsr().i = 1; r(14) = pipeline.decode.address; r(15) = address; } auto ARM7TDMI::armInitialize() -> void { #define bind(id, name, ...) { \ u32 index = (id & 0x0ff00000) >> 16 | (id & 0x000000f0) >> 4; \ assert(!armInstruction[index]); \ armInstruction[index] = [&](n32 opcode) { return armInstruction##name(arguments); }; \ armDisassemble[index] = [&](n32 opcode) { return armDisassemble##name(arguments); }; \ } #define pattern(s) \ std::integral_constant<u32, bit::test(s)>::value #define arguments \ opcode.bit( 0,23), /* displacement */ \ opcode.bit(24) /* link */ for(n4 displacementLo : range(16)) for(n4 displacementHi : range(16)) for(n1 link : range(2)) { auto opcode = pattern(".... 101? ???? ???? ???? ???? ???? ????") | displacementLo << 4 | displacementHi << 20 | link << 24; bind(opcode, Branch); } #undef arguments #define arguments \ opcode.bit( 0, 3) /* m */ { auto opcode = pattern(".... 0001 0010 ---- ---- ---- 0001 ????"); bind(opcode, BranchExchangeRegister); } #undef arguments #define arguments \ opcode.bit( 0, 7), /* immediate */ \ opcode.bit( 8,11), /* shift */ \ opcode.bit(12,15), /* d */ \ opcode.bit(16,19), /* n */ \ opcode.bit(20), /* save */ \ opcode.bit(21,24) /* mode */ for(n4 shiftHi : range(16)) for(n1 save : range(2)) for(n4 mode : range(16)) { if(mode >= 8 && mode <= 11 && !save) continue; //TST, TEQ, CMP, CMN auto opcode = pattern(".... 001? ???? ???? ???? ???? ???? ????") | shiftHi << 4 | save << 20 | mode << 21; bind(opcode, DataImmediate); } #undef arguments #define arguments \ opcode.bit( 0, 3), /* m */ \ opcode.bit( 5, 6), /* type */ \ opcode.bit( 7,11), /* shift */ \ opcode.bit(12,15), /* d */ \ opcode.bit(16,19), /* n */ \ opcode.bit(20), /* save */ \ opcode.bit(21,24) /* mode */ for(n2 type : range(4)) for(n1 shiftLo : range(2)) for(n1 save : range(2)) for(n4 mode : range(16)) { if(mode >= 8 && mode <= 11 && !save) continue; //TST, TEQ, CMP, CMN auto opcode = pattern(".... 000? ???? ???? ???? ???? ???0 ????") | type << 5 | shiftLo << 7 | save << 20 | mode << 21; bind(opcode, DataImmediateShift); } #undef arguments #define arguments \ opcode.bit( 0, 3), /* m */ \ opcode.bit( 5, 6), /* type */ \ opcode.bit( 8,11), /* s */ \ opcode.bit(12,15), /* d */ \ opcode.bit(16,19), /* n */ \ opcode.bit(20), /* save */ \ opcode.bit(21,24) /* mode */ for(n2 type : range(4)) for(n1 save : range(2)) for(n4 mode : range(16)) { if(mode >= 8 && mode <= 11 && !save) continue; //TST, TEQ, CMP, CMN auto opcode = pattern(".... 000? ???? ???? ???? ???? 0??1 ????") | type << 5 | save << 20 | mode << 21; bind(opcode, DataRegisterShift); } #undef arguments #define arguments \ opcode.bit( 0, 3) << 0 | opcode.bit( 8,11) << 4, /* immediate */ \ opcode.bit( 5), /* half */ \ opcode.bit(12,15), /* d */ \ opcode.bit(16,19), /* n */ \ opcode.bit(21), /* writeback */ \ opcode.bit(23), /* up */ \ opcode.bit(24) /* pre */ for(n1 half : range(2)) for(n1 writeback : range(2)) for(n1 up : range(2)) for(n1 pre : range(2)) { auto opcode = pattern(".... 000? ?1?1 ???? ???? ???? 11?1 ????") | half << 5 | writeback << 21 | up << 23 | pre << 24; bind(opcode, LoadImmediate); } #undef arguments #define arguments \ opcode.bit( 0, 3), /* m */ \ opcode.bit( 5), /* half */ \ opcode.bit(12,15), /* d */ \ opcode.bit(16,19), /* n */ \ opcode.bit(21), /* writeback */ \ opcode.bit(23), /* up */ \ opcode.bit(24) /* pre */ for(n1 half : range(2)) for(n1 writeback : range(2)) for(n1 up : range(2)) for(n1 pre : range(2)) { auto opcode = pattern(".... 000? ?0?1 ???? ???? ---- 11?1 ????") | half << 5 | writeback << 21 | up << 23 | pre << 24; bind(opcode, LoadRegister); } #undef arguments #define arguments \ opcode.bit( 0, 3), /* m */ \ opcode.bit(12,15), /* d */ \ opcode.bit(16,19), /* n */ \ opcode.bit(22) /* byte */ for(n1 byte : range(2)) { auto opcode = pattern(".... 0001 0?00 ???? ???? ---- 1001 ????") | byte << 22; bind(opcode, MemorySwap); } #undef arguments #define arguments \ opcode.bit( 0, 3) << 0 | opcode.bit( 8,11) << 4, /* immediate */ \ opcode.bit(12,15), /* d */ \ opcode.bit(16,19), /* n */ \ opcode.bit(20), /* mode */ \ opcode.bit(21), /* writeback */ \ opcode.bit(23), /* up */ \ opcode.bit(24) /* pre */ for(n1 mode : range(2)) for(n1 writeback : range(2)) for(n1 up : range(2)) for(n1 pre : range(2)) { auto opcode = pattern(".... 000? ?1?? ???? ???? ???? 1011 ????") | mode << 20 | writeback << 21 | up << 23 | pre << 24; bind(opcode, MoveHalfImmediate); } #undef arguments #define arguments \ opcode.bit( 0, 3), /* m */ \ opcode.bit(12,15), /* d */ \ opcode.bit(16,19), /* n */ \ opcode.bit(20), /* mode */ \ opcode.bit(21), /* writeback */ \ opcode.bit(23), /* up */ \ opcode.bit(24) /* pre */ for(n1 mode : range(2)) for(n1 writeback : range(2)) for(n1 up : range(2)) for(n1 pre : range(2)) { auto opcode = pattern(".... 000? ?0?? ???? ???? ---- 1011 ????") | mode << 20 | writeback << 21 | up << 23 | pre << 24; bind(opcode, MoveHalfRegister); } #undef arguments #define arguments \ opcode.bit( 0,11), /* immediate */ \ opcode.bit(12,15), /* d */ \ opcode.bit(16,19), /* n */ \ opcode.bit(20), /* mode */ \ opcode.bit(21), /* writeback */ \ opcode.bit(22), /* byte */ \ opcode.bit(23), /* up */ \ opcode.bit(24) /* pre */ for(n4 immediatePart : range(16)) for(n1 mode : range(2)) for(n1 writeback : range(2)) for(n1 byte : range(2)) for(n1 up : range(2)) for(n1 pre : range(2)) { auto opcode = pattern(".... 010? ???? ???? ???? ???? ???? ????") | immediatePart << 4 | mode << 20 | writeback << 21 | byte << 22 | up << 23 | pre << 24; bind(opcode, MoveImmediateOffset); } #undef arguments #define arguments \ opcode.bit( 0,15), /* list */ \ opcode.bit(16,19), /* n */ \ opcode.bit(20), /* mode */ \ opcode.bit(21), /* writeback */ \ opcode.bit(22), /* type */ \ opcode.bit(23), /* up */ \ opcode.bit(24) /* pre */ for(n4 listPart : range(16)) for(n1 mode : range(2)) for(n1 writeback : range(2)) for(n1 type : range(2)) for(n1 up : range(2)) for(n1 pre : range(2)) { auto opcode = pattern(".... 100? ???? ???? ???? ???? ???? ????") | listPart << 4 | mode << 20 | writeback << 21 | type << 22 | up << 23 | pre << 24; bind(opcode, MoveMultiple); } #undef arguments #define arguments \ opcode.bit( 0, 3), /* m */ \ opcode.bit( 5, 6), /* type */ \ opcode.bit( 7,11), /* shift */ \ opcode.bit(12,15), /* d */ \ opcode.bit(16,19), /* n */ \ opcode.bit(20), /* mode */ \ opcode.bit(21), /* writeback */ \ opcode.bit(22), /* byte */ \ opcode.bit(23), /* up */ \ opcode.bit(24) /* pre */ for(n2 type : range(4)) for(n1 shiftLo : range(2)) for(n1 mode : range(2)) for(n1 writeback : range(2)) for(n1 byte : range(2)) for(n1 up : range(2)) for(n1 pre : range(2)) { auto opcode = pattern(".... 011? ???? ???? ???? ???? ???0 ????") | type << 5 | shiftLo << 7 | mode << 20 | writeback << 21 | byte << 22 | up << 23 | pre << 24; bind(opcode, MoveRegisterOffset); } #undef arguments #define arguments \ opcode.bit(12,15), /* d */ \ opcode.bit(22) /* mode */ for(n1 mode : range(2)) { auto opcode = pattern(".... 0001 0?00 ---- ???? ---- 0000 ----") | mode << 22; bind(opcode, MoveToRegisterFromStatus); } #undef arguments #define arguments \ opcode.bit( 0, 7), /* immediate */ \ opcode.bit( 8,11), /* rotate */ \ opcode.bit(16,19), /* field */ \ opcode.bit(22) /* mode */ for(n4 immediateHi : range(16)) for(n1 mode : range(2)) { auto opcode = pattern(".... 0011 0?10 ???? ---- ???? ???? ????") | immediateHi << 4 | mode << 22; bind(opcode, MoveToStatusFromImmediate); } #undef arguments #define arguments \ opcode.bit( 0, 3), /* m */ \ opcode.bit(16,19), /* field */ \ opcode.bit(22) /* mode */ for(n1 mode : range(2)) { auto opcode = pattern(".... 0001 0?10 ???? ---- ---- 0000 ????") | mode << 22; bind(opcode, MoveToStatusFromRegister); } #undef arguments #define arguments \ opcode.bit( 0, 3), /* m */ \ opcode.bit( 8,11), /* s */ \ opcode.bit(12,15), /* n */ \ opcode.bit(16,19), /* d */ \ opcode.bit(20), /* save */ \ opcode.bit(21) /* accumulate */ for(n1 save : range(2)) for(n1 accumulate : range(2)) { auto opcode = pattern(".... 0000 00?? ???? ???? ???? 1001 ????") | save << 20 | accumulate << 21; bind(opcode, Multiply); } #undef arguments #define arguments \ opcode.bit( 0, 3), /* m */ \ opcode.bit( 8,11), /* s */ \ opcode.bit(12,15), /* l */ \ opcode.bit(16,19), /* h */ \ opcode.bit(20), /* save */ \ opcode.bit(21), /* accumulate */ \ opcode.bit(22) /* sign */ for(n1 save : range(2)) for(n1 accumulate : range(2)) for(n1 sign : range(2)) { auto opcode = pattern(".... 0000 1??? ???? ???? ???? 1001 ????") | save << 20 | accumulate << 21 | sign << 22; bind(opcode, MultiplyLong); } #undef arguments #define arguments \ opcode.bit( 0,23) /* immediate */ for(n4 immediateLo : range(16)) for(n4 immediateHi : range(16)) { auto opcode = pattern(".... 1111 ???? ???? ???? ???? ???? ????") | immediateLo << 4 | immediateHi << 20; bind(opcode, SoftwareInterrupt); } #undef arguments #define arguments for(n12 id : range(4096)) { if(armInstruction[id]) continue; auto opcode = pattern(".... ???? ???? ---- ---- ---- ???? ----") | id.bit(0,3) << 4 | id.bit(4,11) << 20; bind(opcode, Undefined); } #undef arguments #undef bind #undef pattern } auto ARM7TDMI::thumbInitialize() -> void { #define bind(id, name, ...) { \ assert(!thumbInstruction[id]); \ thumbInstruction[id] = [=] { return thumbInstruction##name(__VA_ARGS__); }; \ thumbDisassemble[id] = [=] { return thumbDisassemble##name(__VA_ARGS__); }; \ } #define pattern(s) \ std::integral_constant<u16, bit::test(s)>::value for(n3 d : range(8)) for(n3 m : range(8)) for(n4 mode : range(16)) { auto opcode = pattern("0100 00?? ???? ????") | d << 0 | m << 3 | mode << 6; bind(opcode, ALU, d, m, mode); } for(n4 d : range(16)) for(n4 m : range(16)) for(n2 mode : range(4)) { if(mode == 3) continue; auto opcode = pattern("0100 01?? ???? ????") | d.bit(0,2) << 0 | m << 3 | d.bit(3) << 7 | mode << 8; bind(opcode, ALUExtended, d, m, mode); } for(n8 immediate : range(256)) for(n3 d : range(8)) for(n1 mode : range(2)) { auto opcode = pattern("1010 ???? ???? ????") | immediate << 0 | d << 8 | mode << 11; bind(opcode, AddRegister, immediate, d, mode); } for(n3 d : range(8)) for(n3 n : range(8)) for(n3 immediate : range(8)) for(n1 mode : range(2)) { auto opcode = pattern("0001 11?? ???? ????") | d << 0 | n << 3 | immediate << 6 | mode << 9; bind(opcode, AdjustImmediate, d, n, immediate, mode); } for(n3 d : range(8)) for(n3 n : range(8)) for(n3 m : range(8)) for(n1 mode : range(2)) { auto opcode = pattern("0001 10?? ???? ????") | d << 0 | n << 3 | m << 6 | mode << 9; bind(opcode, AdjustRegister, d, n, m, mode); } for(n7 immediate : range(128)) for(n1 mode : range(2)) { auto opcode = pattern("1011 0000 ???? ????") | immediate << 0 | mode << 7; bind(opcode, AdjustStack, immediate, mode); } for(n3 _ : range(8)) for(n4 m : range(16)) { auto opcode = pattern("0100 0111 0??? ?---") | _ << 0 | m << 3; bind(opcode, BranchExchange, m); } for(n11 displacement : range(2048)) { auto opcode = pattern("1111 0??? ???? ????") | displacement << 0; bind(opcode, BranchFarPrefix, displacement); } for(n11 displacement : range(2048)) { auto opcode = pattern("1111 1??? ???? ????") | displacement << 0; bind(opcode, BranchFarSuffix, displacement); } for(n11 displacement : range(2048)) { auto opcode = pattern("1110 0??? ???? ????") | displacement << 0; bind(opcode, BranchNear, displacement); } for(n8 displacement : range(256)) for(n4 condition : range(16)) { if(condition == 15) continue; //BNV auto opcode = pattern("1101 ???? ???? ????") | displacement << 0 | condition << 8; bind(opcode, BranchTest, displacement, condition); } for(n8 immediate : range(256)) for(n3 d : range(8)) for(n2 mode : range(4)) { auto opcode = pattern("001? ???? ???? ????") | immediate << 0 | d << 8 | mode << 11; bind(opcode, Immediate, immediate, d, mode); } for(n8 displacement : range(256)) for(n3 d : range(8)) { auto opcode = pattern("0100 1??? ???? ????") | displacement << 0 | d << 8; bind(opcode, LoadLiteral, displacement, d); } for(n3 d : range(8)) for(n3 n : range(8)) for(n5 immediate : range(32)) for(n1 mode : range(2)) { auto opcode = pattern("0111 ???? ???? ????") | d << 0 | n << 3 | immediate << 6 | mode << 11; bind(opcode, MoveByteImmediate, d, n, immediate, mode); } for(n3 d : range(8)) for(n3 n : range(8)) for(n5 immediate : range(32)) for(n1 mode : range(2)) { auto opcode = pattern("1000 ???? ???? ????") | d << 0 | n << 3 | immediate << 6 | mode << 11; bind(opcode, MoveHalfImmediate, d, n, immediate, mode); } for(n8 list : range(256)) for(n3 n : range(8)) for(n1 mode : range(2)) { auto opcode = pattern("1100 ???? ???? ????") | list << 0 | n << 8 | mode << 11; bind(opcode, MoveMultiple, list, n, mode); } for(n3 d : range(8)) for(n3 n : range(8)) for(n3 m : range(8)) for(n3 mode : range(8)) { auto opcode = pattern("0101 ???? ???? ????") | d << 0 | n << 3 | m << 6 | mode << 9; bind(opcode, MoveRegisterOffset, d, n, m, mode); } for(n8 immediate : range(256)) for(n3 d : range(8)) for(n1 mode : range(2)) { auto opcode = pattern("1001 ???? ???? ????") | immediate << 0 | d << 8 | mode << 11; bind(opcode, MoveStack, immediate, d, mode); } for(n3 d : range(8)) for(n3 n : range(8)) for(n5 offset : range(32)) for(n1 mode : range(2)) { auto opcode = pattern("0110 ???? ???? ????") | d << 0 | n << 3 | offset << 6 | mode << 11; bind(opcode, MoveWordImmediate, d, n, offset, mode); } for(n3 d : range(8)) for(n3 m : range(8)) for(n5 immediate : range(32)) for(n2 mode : range(4)) { if(mode == 3) continue; auto opcode = pattern("000? ???? ???? ????") | d << 0 | m << 3 | immediate << 6 | mode << 11; bind(opcode, ShiftImmediate, d, m, immediate, mode); } for(n8 immediate : range(256)) { auto opcode = pattern("1101 1111 ???? ????") | immediate << 0; bind(opcode, SoftwareInterrupt, immediate); } for(n8 list : range(256)) for(n1 lrpc : range(2)) for(n1 mode : range(2)) { auto opcode = pattern("1011 ?10? ???? ????") | list << 0 | lrpc << 8 | mode << 11; bind(opcode, StackMultiple, list, lrpc, mode); } for(n16 id : range(65536)) { if(thumbInstruction[id]) continue; auto opcode = pattern("???? ???? ???? ????") | id << 0; bind(opcode, Undefined); } #undef bind #undef pattern }
/////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2004-2014, Industrial Light & Magic, a division of Lucas // Digital Ltd. LLC // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Industrial Light & Magic nor the names of // its contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // /////////////////////////////////////////////////////////////////////////// //----------------------------------------------------------------------------- // // exrstdattr -- a program that can set the values of most // standard attributes in an OpenEXR image file's header. // //----------------------------------------------------------------------------- #include <ImfStandardAttributes.h> #include <ImfVecAttribute.h> #include <ImfIntAttribute.h> #include <ImfInputFile.h> #include <ImfOutputFile.h> #include <ImfMultiPartInputFile.h> #include <ImfMultiPartOutputFile.h> #include <ImfTiledOutputFile.h> #include <ImfNamespace.h> #include <ImfPartType.h> #include <ImfInputPart.h> #include <ImfOutputPart.h> #include <ImfTiledInputPart.h> #include <ImfTiledOutputPart.h> #include <ImfDeepScanLineInputPart.h> #include <ImfDeepScanLineOutputPart.h> #include <ImfDeepTiledInputPart.h> #include <ImfDeepTiledOutputPart.h> #include <ImathNamespace.h> #include <map> #include <string> #include <iostream> #include <exception> #include <string.h> #include <stdlib.h> using namespace std; using namespace OPENEXR_IMF_NAMESPACE; using namespace IMATH_NAMESPACE; void usageMessage (const char argv0[], bool verbose = false) { cerr << "usage: " << argv0 << " [commands] infile outfile" << endl; if (verbose) { cerr << "\n" "Reads OpenEXR image file infile, sets the values of one\n" "or more attributes in the headers of the file, and saves\n" "the result in outfile. Infile and outfile must not refer\n" "to the same file (the program cannot edit an image file " "\"in place\").\n" "\n" "Command for selecting headers:\n" "\n" " -part i\n" " If i is greater than or equal to zero, and less\n" " than the number of parts in the input file, then\n" " the header for part i becomes \"current.\" If i\n" " is \"any\" or -1, then all headers become current.\n" " Subsequent attribute setting commands affect only\n" " the current header or headers. All headers are\n" " current before the first -part command.\n" "\n" " For example, the command sequence\n" "\n" " -focus 3 -part 2 -aperture 8 -expTime 0.01 " "-part any -owner luke\n" "\n" " sets the focus and owner attributes in all\n" " headers, as well as the aperture and expTime\n" " attributes in the header of part 2.\n" "\n" "Commands for setting attribute values:\n" "\n" " -chromaticities f f f f f f f f\n" " CIE xy chromaticities for the red, green\n" " and blue primaries, and for the white point\n" " (8 floats)\n" "\n" " -whiteLuminance f\n" " white luminance, in candelas per square meter\n" " (float, >= 0.0)\n" "\n" " -adoptedNeutral f f\n" " CIE xy coordinates that should be considered\n" " \"neutral\" during color rendering. Pixels in\n" " the image file whose xy coordinates match the\n" " adoptedNeutral value should be mapped to neutral\n" " values on the display. (2 floats)\n" "\n" " -renderingTransform s\n" " name of the CTL rendering transform for this\n" " image (string)\n" "\n" " -lookModTransform s\n" " name of the CTL look modification transform for\n" " this image (string)\n" "\n" " -xDensity f\n" " horizontal output density, in pixels per inch\n" " (float, >= 0.0)\n" "\n" " -owner s\n" " name of the owner of the image (string)\n" "\n" " -comments s\n" " additional information about the image (string)\n" "\n" " -capDate s\n" " date when the image was created or\n" " captured, in local time (string,\n" " formatted as YYYY:MM:DD hh:mm:ss)\n" "\n" " -utcOffset f\n" " offset of local time at capDate from UTC, in\n" " seconds (float, UTC == local time + x)\n" "\n" " -longitude f\n" " -latitude f\n" " -altitude f\n" " location where the image was recorded, in\n" " degrees east of Greenwich and north of the\n" " equator, and in meters above sea level\n" " (float)\n" "\n" " -focus f\n" " the camera's focus distance, in meters\n" " (float, > 0, or \"infinity\")\n" "\n" " -expTime f\n" " exposure time, in seconds (float, >= 0)\n" "\n" " -aperture f\n" " lens apterture, in f-stops (float, >= 0)\n" "\n" " -isoSpeed f\n" " effective speed of the film or image\n" " sensor that was used to record the image\n" " (float, >= 0)\n" "\n" " -envmap s\n" " indicates that the image is an environment map\n" " (string, LATLONG or CUBE)\n" "\n" " -framesPerSecond i i\n" " playback frame rate expressed as a ratio of two\n" " integers, n and d (the frame rate is n/d frames\n" " per second)\n" "\n" " -keyCode i i i i i i i\n" " key code that uniquely identifies a motion\n" " picture film frame using 7 integers:\n" " * film manufacturer code (0 - 99)\n" " * film type code (0 - 99)\n" " * prefix to identify film roll (0 - 999999)\n" " * count, increments once every perfsPerCount\n" " perforations (0 - 9999)\n" " * offset of frame, in perforations from\n" " zero-frame reference mark (0 - 119)\n" " * number of perforations per frame (1 - 15)\n" " * number of perforations per count (20 - 120)\n" "\n" " -timeCode i i\n" " SMPTE time and control code, specified as a pair\n" " of 8-digit base-16 integers. The first number\n" " contains the time address and flags (drop frame,\n" " color frame, field/phase, bgf0, bgf1, bgf2).\n" " The second number contains the user data and\n" " control codes.\n" "\n" " -wrapmodes s\n" " if the image is used as a texture map, specifies\n" " how the image should be extrapolated outside the\n" " zero-to-one texture coordinate range\n" " (string, e.g. \"clamp\" or \"periodic,clamp\")\n" "\n" " -pixelAspectRatio f\n" " width divided by height of a pixel\n" " (float, >= 0)\n" "\n" " -screenWindowWidth f\n" " width of the screen window (float, >= 0)\n" "\n" " -screenWindowCenter f f\n" " center of the screen window (2 floats)\n" "\n" " -string s s\n" " custom string attribute\n" " (2 strings, attribute name and value)\n" "\n" " -float s f\n" " custom float attribute (string + float,\n" " attribute name and value)\n" "\n" " -int s i\n" " custom integer attribute (string + integer,\n" " attribute name and value)\n" "\n" "Other Commands:\n" "\n" " -h prints this message\n"; cerr << endl; } exit (1); } struct SetAttr { string name; int part; Attribute * attr; SetAttr (const string &name, int part, Attribute *attr): name (name), part (part), attr (attr) {} }; typedef vector <SetAttr> SetAttrVector; void isNonNegative (const char attrName[], float f) { if (f < 0) { cerr << "The value for the " << attrName << " attribute " "must not be less than zero." << endl; exit (1); } } void isPositive (const char attrName[], float f) { if (f <= 0) { cerr << "The value for the " << attrName << " attribute " "must be greater than zero." << endl; exit (1); } } void notValidDate (const char attrName[]) { cerr << "The value for the " << attrName << " attribute " "is not a valid date of the form \"YYYY:MM:DD yy:mm:ss\"." << endl; exit (1); } int strToInt (const char str[], int length) { int x = 0; for (int i = 0; i < length; ++i) { if (str[i] < '0' || str[i] > '9') return -1; x = x * 10 + (str[i] - '0'); } return x; } void isDate (const char attrName[], const char str[]) { // // Check that str represents a valid // date of the form YYYY:MM:DD hh:mm:ss. // if (strlen (str) != 19 || str[4] != ':' || str[7] != ':' || str[10] != ' ' || str[13] != ':' || str[16] != ':') { notValidDate (attrName); } int Y = strToInt (str + 0, 4); // year int M = strToInt (str + 5, 2); // month int D = strToInt (str + 8, 2); // day int h = strToInt (str + 11, 2); // hour int m = strToInt (str + 14, 2); // minute int s = strToInt (str + 17, 2); // second if (Y < 0 || M < 1 || M > 12 || D < 1 || h < 0 || h > 23 || m < 0 || m > 59 || s < 0 || s > 59) { notValidDate (attrName); } if (M == 2) { bool leapYear = (Y % 4 == 0) && (Y % 100 != 0 || Y % 400 == 0); if (D > (leapYear? 29: 28)) notValidDate (attrName); } else if (M == 4 || M == 6 || M == 9 || M == 11) { if (D > 30) notValidDate (attrName); } else { if (D > 31) notValidDate (attrName); } } void getFloat (const char attrName[], int argc, char **argv, int &i, int part, SetAttrVector &attrs, void (*check) (const char attrName[], float f) = 0) { if (i > argc - 2) usageMessage (argv[0]); float f = static_cast<float>(strtod (argv[i + 1], 0)); if (check) check (attrName, f); attrs.push_back (SetAttr (attrName, part, new FloatAttribute (f))); i += 2; } void getPosFloatOrInf (const char attrName[], int argc, char **argv, int &i, int part, SetAttrVector &attrs) { if (i > argc - 2) usageMessage (argv[0]); float f; if (!strcmp (argv[i + 1], "inf") || !strcmp (argv[i + 1], "infinity")) { f = float (half::posInf()); } else { f = static_cast<float>(strtod (argv[i + 1], 0)); if (f <= 0) { cerr << "The value for the " << attrName << " attribute " "must be greater than zero, or \"infinity\"." << endl; exit (1); } } attrs.push_back (SetAttr (attrName, part, new FloatAttribute (f))); i += 2; } void getV2f (const char attrName[], int argc, char **argv, int &i, int part, SetAttrVector &attrs, void (*check) (const char attrName[], const V2f &v) = 0) { if (i > argc - 3) usageMessage (argv[0]); V2f v (static_cast<float>(strtod (argv[i + 1], 0)), static_cast<float>(strtod (argv[i + 2], 0))); if (check) check (attrName, v); attrs.push_back (SetAttr (attrName, part, new V2fAttribute (v))); i += 3; } void getRational (const char attrName[], int argc, char **argv, int &i, int part, SetAttrVector &attrs, void (*check) (const char attrName[], const Rational &r) = 0) { if (i > argc - 3) usageMessage (argv[0]); Rational r (strtol (argv[i + 1], 0, 0), strtol (argv[i + 2], 0, 0)); if (check) check (attrName, r); attrs.push_back (SetAttr (attrName, part, new RationalAttribute (r))); i += 3; } void getString (const char attrName[], int argc, char **argv, int &i, int part, SetAttrVector &attrs, void (*check) (const char attrName[], const char str[]) = 0) { if (i > argc - 2) usageMessage (argv[0]); const char *str = argv[i + 1]; if (check) check (attrName, str); attrs.push_back (SetAttr (attrName, part, new StringAttribute (str))); i += 2; } void getNameAndString (int argc, char **argv, int &i, int part, SetAttrVector &attrs) { if (i > argc - 3) usageMessage (argv[0]); const char *attrName = argv[i + 1]; const char *str = argv[i + 2]; attrs.push_back (SetAttr (attrName, part, new StringAttribute (str))); i += 3; } void getNameAndFloat (int argc, char **argv, int &i, int part, SetAttrVector &attrs) { if (i > argc - 3) usageMessage (argv[0]); const char *attrName = argv[i + 1]; float f = static_cast<float>(strtod (argv[i + 2], 0)); attrs.push_back (SetAttr (attrName, part, new FloatAttribute (f))); i += 3; } void getNameAndInt (int argc, char **argv, int &i, int part, SetAttrVector &attrs) { if (i > argc - 3) usageMessage (argv[0]); const char *attrName = argv[i + 1]; int j = strtol (argv[i + 2], 0, 0); attrs.push_back (SetAttr (attrName, part, new IntAttribute (j))); i += 3; } void getChromaticities (const char attrName[], int argc, char **argv, int &i, int part, SetAttrVector &attrs) { if (i > argc - 9) usageMessage (argv[0]); ChromaticitiesAttribute *a = new ChromaticitiesAttribute; attrs.push_back (SetAttr (attrName, part, a)); a->value().red.x = static_cast<float>(strtod (argv[i + 1], 0)); a->value().red.y = static_cast<float>(strtod (argv[i + 2], 0)); a->value().green.x = static_cast<float>(strtod (argv[i + 3], 0)); a->value().green.y = static_cast<float>(strtod (argv[i + 4], 0)); a->value().blue.x = static_cast<float>(strtod (argv[i + 5], 0)); a->value().blue.y = static_cast<float>(strtod (argv[i + 6], 0)); a->value().white.x = static_cast<float>(strtod (argv[i + 7], 0)); a->value().white.y = static_cast<float>(strtod (argv[i + 8], 0)); i += 9; } void getEnvmap (const char attrName[], int argc, char **argv, int &i, int part, SetAttrVector &attrs) { if (i > argc - 2) usageMessage (argv[0]); char *str = argv[i + 1]; Envmap type; if (!strcmp (str, "latlong") || !strcmp (str, "LATLONG")) { type = ENVMAP_LATLONG; } else if (!strcmp (str, "cube") || !strcmp (str, "CUBE")) { type = ENVMAP_CUBE; } else { cerr << "The value for the " << attrName << " attribute " "must be either LATLONG or CUBE." << endl; exit (1); } attrs.push_back (SetAttr (attrName, part, new EnvmapAttribute (type))); i += 2; } void getKeyCode (const char attrName[], int argc, char **argv, int &i, int part, SetAttrVector &attrs) { if (i > argc - 8) usageMessage (argv[0]); KeyCodeAttribute *a = new KeyCodeAttribute; attrs.push_back (SetAttr (attrName, part, a)); a->value().setFilmMfcCode (strtol (argv[i + 1], 0, 0)); a->value().setFilmType (strtol (argv[i + 2], 0, 0)); a->value().setPrefix (strtol (argv[i + 3], 0, 0)); a->value().setCount (strtol (argv[i + 4], 0, 0)); a->value().setPerfOffset (strtol (argv[i + 5], 0, 0)); a->value().setPerfsPerFrame (strtol (argv[i + 6], 0, 0)); a->value().setPerfsPerCount (strtol (argv[i + 7], 0, 0)); i += 8; } void getTimeCode (const char attrName[], int argc, char **argv, int &i, int part, SetAttrVector &attrs) { if (i > argc - 3) usageMessage (argv[0]); TimeCodeAttribute *a = new TimeCodeAttribute; attrs.push_back (SetAttr (attrName, part, a)); a->value().setTimeAndFlags (strtoul (argv[i + 1], 0, 16)); a->value().setUserData (strtoul (argv[i + 2], 0, 16)); i += 3; } void getPart (const char attrName[], int argc, char **argv, int &i, int &part) { if (i > argc - 2) usageMessage (argv[0]); if (!strcmp (argv[i + 1], "any")) part = -1; else part = strtol (argv[i + 1], 0, 0); i += 2; } int main(int argc, char **argv) { // // Parse the command line. // if (argc < 2) usageMessage (argv[0], true); int exitStatus = 0; try { const char *inFileName = 0; const char *outFileName = 0; SetAttrVector attrs; int part = -1; int i = 1; while (i < argc) { const char *attrName = argv[i] + 1; if (!strcmp (argv[i], "-part")) { getPart (attrName, argc, argv, i, part); } else if (!strcmp (argv[i], "-chromaticities")) { getChromaticities (attrName, argc, argv, i, part, attrs); } else if (!strcmp (argv[i], "-whiteLuminance")) { getFloat (attrName, argc, argv, i, part, attrs); } else if (!strcmp (argv[i], "-adoptedNeutral")) { getV2f (attrName, argc, argv, i, part, attrs); } else if (!strcmp (argv[i], "-renderingTransform")) { getString (attrName, argc, argv, i, part, attrs); } else if (!strcmp (argv[i], "-lookModTransform")) { getString (attrName, argc, argv, i, part, attrs); } else if (!strcmp (argv[i], "-xDensity")) { getFloat (attrName, argc, argv, i, part, attrs, isPositive); } else if (!strcmp (argv[i], "-owner")) { getString (attrName, argc, argv, i, part, attrs); } else if (!strcmp (argv[i], "-comments")) { getString (attrName, argc, argv, i, part, attrs); } else if (!strcmp (argv[i], "-capDate")) { getString (attrName, argc, argv, i, part, attrs, isDate); } else if (!strcmp (argv[i], "-utcOffset")) { getFloat (attrName, argc, argv, i, part, attrs); } else if (!strcmp (argv[i], "-longitude")) { getFloat (attrName, argc, argv, i, part, attrs); } else if (!strcmp (argv[i], "-latitude")) { getFloat (attrName, argc, argv, i, part, attrs); } else if (!strcmp (argv[i], "-altitude")) { getFloat (attrName, argc, argv, i, part, attrs); } else if (!strcmp (argv[i], "-focus")) { getPosFloatOrInf (attrName, argc, argv, i, part, attrs); } else if (!strcmp (argv[i], "-expTime")) { getFloat (attrName, argc, argv, i, part, attrs, isPositive); } else if (!strcmp (argv[i], "-aperture")) { getFloat (attrName, argc, argv, i, part, attrs, isPositive); } else if (!strcmp (argv[i], "-isoSpeed")) { getFloat (attrName, argc, argv, i, part, attrs, isPositive); } else if (!strcmp (argv[i], "-envmap")) { getEnvmap (attrName, argc, argv, i, part, attrs); } else if (!strcmp (argv[i], "-framesPerSecond")) { getRational (attrName, argc, argv, i, part, attrs); } else if (!strcmp (argv[i], "-keyCode")) { getKeyCode (attrName, argc, argv, i, part, attrs); } else if (!strcmp (argv[i], "-timeCode")) { getTimeCode (attrName, argc, argv, i, part, attrs); } else if (!strcmp (argv[i], "-wrapmodes")) { getString (attrName, argc, argv, i, part, attrs); } else if (!strcmp (argv[i], "-pixelAspectRatio")) { getFloat (attrName, argc, argv, i, part, attrs, isPositive); } else if (!strcmp (argv[i], "-screenWindowWidth")) { getFloat (attrName, argc, argv, i, part, attrs, isNonNegative); } else if (!strcmp (argv[i], "-screenWindowCenter")) { getV2f (attrName, argc, argv, i, part, attrs); } else if (!strcmp (argv[i], "-string")) { getNameAndString (argc, argv, i, part, attrs); } else if (!strcmp (argv[i], "-float")) { getNameAndFloat (argc, argv, i, part, attrs); } else if (!strcmp (argv[i], "-int")) { getNameAndInt (argc, argv, i, part, attrs); } else if (!strcmp (argv[i], "-h")) { usageMessage (argv[0], true); } else { if (inFileName == 0) inFileName = argv[i]; else outFileName = argv[i]; i += 1; } } if (inFileName == 0 || outFileName == 0) usageMessage (argv[0]); if (!strcmp (inFileName, outFileName)) { cerr << "Input and output cannot be the same file." << endl; return 1; } // // Load the headers from the input file // and add attributes to the headers. // MultiPartInputFile in (inFileName); int numParts = in.parts(); vector <Header> headers; for (int part = 0; part < numParts; ++part) { Header h = in.header (part); for (size_t i = 0; i < attrs.size(); ++i) { const SetAttr &attr = attrs[i]; if (attr.part == -1 || attr.part == part) { h.insert (attr.name, *attr.attr); } else if (attr.part < 0 || attr.part >= numParts) { cerr << "Invalid part number " << attr.part << ". " "Part numbers in file " << inFileName << " " "go from 0 to " << numParts - 1 << "." << endl; return 1; } } headers.push_back(h); } // // Crete an output file with the modified headers, // and copy the pixels from the input file to the // output file. // MultiPartOutputFile out (outFileName, &headers[0], numParts); for (int p = 0; p < numParts; ++p) { const Header &h = in.header (p); const string &type = h.type(); if (type == SCANLINEIMAGE) { InputPart inPart (in, p); OutputPart outPart (out, p); outPart.copyPixels (inPart); } else if (type == TILEDIMAGE) { TiledInputPart inPart (in, p); TiledOutputPart outPart (out, p); outPart.copyPixels (inPart); } else if (type == DEEPSCANLINE) { DeepScanLineInputPart inPart (in, p); DeepScanLineOutputPart outPart (out, p); outPart.copyPixels (inPart); } else if (type == DEEPTILE) { DeepTiledInputPart inPart (in, p); DeepTiledOutputPart outPart (out, p); outPart.copyPixels (inPart); } } } catch (const exception &e) { cerr << e.what() << endl; exitStatus = 1; } return exitStatus; }
/* * Copyright 2020 Northwestern Inclusive Technology Lab * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "core/system/platform/platform.h" #include "absl/strings/str_format.h" namespace sys { std::string Platform::GetVersionAsString() const { Version version = GetVersion(); return absl::StrFormat("%d.%d.%d", version.major_version, version.minor_version, version.patch_version); } // TODO(tommymchugh): Look into Android support for mobile devices. // Mobile devices are currently not supported so defaulting to false. bool Platform::IsMobile() const { return false; } } // namespace sys
// Copyright (C) 2020 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include "layer_transformation.hpp" #include <string> #include <sstream> #include <memory> #include <gtest/gtest.h> #include <transformations/utils/utils.hpp> #include <transformations/init_node_info.hpp> #include <low_precision/transformer.hpp> #include <low_precision/concat.hpp> #include <low_precision/concat_multi_channels.hpp> #include <low_precision/max_pool.hpp> #include <low_precision/clamp.hpp> #include "common_test_utils/ngraph_test_utils.hpp" #include "lpt_ngraph_functions/concat_function.hpp" #include "lpt_ngraph_functions/common/fake_quantize_on_data.hpp" #include "simple_low_precision_transformer.hpp" using namespace testing; using namespace ngraph; using namespace ngraph::pass; namespace { class ConcatTransformationActualValues { public: ngraph::builder::subgraph::FakeQuantizeOnData fakeQuantize1; ngraph::builder::subgraph::FakeQuantizeOnData fakeQuantize2; }; inline std::ostream& operator<<(std::ostream& out, const ConcatTransformationActualValues& values) { return out << "_" << values.fakeQuantize1 << "_" << values.fakeQuantize2; } class ConcatTransformationResultValues { public: ngraph::builder::subgraph::FakeQuantizeOnData fakeQuantize1; ngraph::builder::subgraph::FakeQuantizeOnData fakeQuantize2; ngraph::builder::subgraph::DequantizationOperations dequantizationOperations1; ngraph::builder::subgraph::DequantizationOperations dequantizationOperations2; }; inline std::ostream& operator<<(std::ostream& out, const ConcatTransformationResultValues& values) { return out << "_" << values.fakeQuantize1 << "_" << values.fakeQuantize2 << "_" << values.dequantizationOperations1 << "_" << values.dequantizationOperations2; } class ConcatTransformationTestValues { public: ngraph::Shape inputShape; ngraph::pass::low_precision::LayerTransformation::Params params; bool multiChannels; ConcatTransformationActualValues actual; ConcatTransformationResultValues result; }; inline std::ostream& operator<<(std::ostream& out, const ConcatTransformationTestValues& values) { return out << "_" << values.multiChannels << "_" << values.actual << "_" << values.result; } typedef std::tuple < ngraph::element::Type, bool, ConcatTransformationTestValues > ConcatTransformationParams; class ConcatWithDifferentChildsTransformation : public LayerTransformation, public testing::WithParamInterface<ConcatTransformationParams> { public: void SetUp() override { const ngraph::element::Type precision = std::get<0>(GetParam()); const bool updatePrecisions = std::get<1>(GetParam()); ConcatTransformationTestValues testValues = std::get<2>(GetParam()); testValues.params.updatePrecisions = updatePrecisions; if (!updatePrecisions) { testValues.result.fakeQuantize1.outputPrecision = testValues.actual.fakeQuantize1.outputPrecision; testValues.result.fakeQuantize2.outputPrecision = testValues.actual.fakeQuantize2.outputPrecision; } actualFunction = ngraph::builder::subgraph::ConcatFunction::getOriginalWithDifferentPrecisionOnChilds( precision, testValues.inputShape, testValues.actual.fakeQuantize1, testValues.actual.fakeQuantize2); SimpleLowPrecisionTransformer transform; if (testValues.multiChannels) { transform.add<ngraph::pass::low_precision::ConcatMultiChannelsTransformation, ngraph::opset1::Concat>(testValues.params); } else { transform.add<ngraph::pass::low_precision::ConcatTransformation, ngraph::opset1::Concat>(testValues.params); } transform.add<ngraph::pass::low_precision::MaxPoolTransformation, ngraph::opset1::MaxPool>(testValues.params); transform.add<ngraph::pass::low_precision::ClampTransformation, ngraph::opset1::Clamp>(testValues.params); transform.transform(actualFunction); if (!updatePrecisions) { // there is no Convert operation after MaxPool in FP32 testValues.result.dequantizationOperations2.convert = {}; } referenceFunction = ngraph::builder::subgraph::ConcatFunction::getReferenceWithDifferentPrecisionOnChilds( precision, testValues.inputShape, testValues.multiChannels, testValues.result.fakeQuantize1, testValues.result.fakeQuantize2, testValues.result.dequantizationOperations1, testValues.result.dequantizationOperations2); } static std::string getTestCaseName(testing::TestParamInfo<ConcatTransformationParams> obj) { const ngraph::element::Type precision = std::get<0>(obj.param); const bool updatePrecision = std::get<1>(obj.param); const ConcatTransformationTestValues testValues = std::get<2>(obj.param); std::ostringstream result; result << LayerTransformation::getTestCaseNameByParams(precision, testValues.inputShape, testValues.params) << "_" << (testValues.multiChannels ? "multiChannels_" : "notMultiChannels_") << (updatePrecision ? "updatePrecision_" : "notUpdatePrecision_") << testValues.actual << "_" << testValues.result << "_"; return result.str(); } }; TEST_P(ConcatWithDifferentChildsTransformation, CompareFunctions) { const ConcatTransformationTestValues testValues = std::get<2>(GetParam()); actualFunction->validate_nodes_and_infer_types(); auto res = compare_functions(referenceFunction, actualFunction, true, true, true); ASSERT_TRUE(res.first) << res.second; } const std::vector<ngraph::element::Type> precisions = { ngraph::element::f32, // ngraph::element::f16 }; const std::vector<bool> updatePrecisions = { true, false }; const std::vector<ConcatTransformationTestValues> testValues = { // U8 { { 1, 3, 10, 10 }, LayerTransformation::createParamsU8I8(), false, { { 256ul, ngraph::Shape({}), {0.f}, {2.55f}, {0.f}, {2.55f} }, { 256ul, ngraph::Shape({}), {0.f}, {2.55f / 2.f}, {0.f}, {2.55f / 2.f} } }, { { 256ul, ngraph::Shape({}), {0.f}, {2.55f}, {0.f}, {255.f}, ngraph::element::u8 }, { 256ul, ngraph::Shape({}), {0.f}, {2.55f / 2.f}, {0.f}, { 128.f}, ngraph::element::u8 }, { ngraph::element::f32, {}, { 0.01f } }, { ngraph::element::f32, {}, { 0.01f } } } }, // I8 { { 1, 3, 10, 10 }, LayerTransformation::createParamsI8I8(), false, { { 256ul, ngraph::Shape({}), {-1.28f}, {1.27f}, {-1.28f}, {1.27f} }, { 256ul, ngraph::Shape({}), {-1.28f / 2.f}, {1.27f / 2.f}, {-1.28f / 2.f}, {1.27f / 2.f} } }, { { 256ul, ngraph::Shape({}), {-1.28f}, {1.27f}, {-128.f}, {127.f}, ngraph::element::i8 }, { 256ul, ngraph::Shape({}), {-1.28f / 2.f}, {1.27f / 2.f}, {-64.f}, { 64.f}, ngraph::element::i8 }, { ngraph::element::f32, {}, { 0.01f } }, { ngraph::element::f32, {}, { 0.01f } } } }, // U8: concat multi channels { { 1, 3, 10, 10 }, LayerTransformation::createParamsU8I8(), true, { { 256ul, ngraph::Shape({}), {0.f}, {2.55f}, {0.f}, {2.55f} }, { 256ul, ngraph::Shape({}), {0.f}, {2.55f / 2.f}, {0.f}, {2.55f / 2.f} } }, { { 256ul, ngraph::Shape({}), {0.f}, {2.55f}, {0.f}, {255.f}, ngraph::element::u8 }, { 256ul, ngraph::Shape({}), {0.f}, {2.55f / 2.f}, {0.f}, { 255.f}, ngraph::element::u8 }, { ngraph::element::f32, {}, {{ 0.01f, 0.01f, 0.01f, 0.005f, 0.005f, 0.005f }} }, { ngraph::element::f32, {}, {{ 0.01f, 0.01f, 0.01f, 0.005f, 0.005f, 0.005f }} }, } }, // I8: concat multi channels { { 1, 3, 10, 10 }, LayerTransformation::createParamsI8I8(), true, { { 256ul, ngraph::Shape({}), {-1.28f}, {1.27f}, {-1.28f}, {1.27f} }, { 256ul, ngraph::Shape({}), {-1.28f / 2.f}, {1.27f / 2.f}, {-1.28f / 2.f}, {1.27f / 2.f} } }, { { 256ul, ngraph::Shape({}), {-1.28f}, {1.27f}, {-128.f}, {127.f}, ngraph::element::i8 }, { 256ul, ngraph::Shape({}), {-1.28f / 2.f}, {1.27f / 2.f}, {-128.f}, {127.f}, ngraph::element::i8 }, { ngraph::element::f32, {}, {{ 0.01f, 0.01f, 0.01f, 0.005f, 0.005f, 0.005f }} }, { ngraph::element::f32, {}, {{ 0.01f, 0.01f, 0.01f, 0.005f, 0.005f, 0.005f }} }, } }, }; INSTANTIATE_TEST_CASE_P( smoke_LPT, ConcatWithDifferentChildsTransformation, ::testing::Combine( ::testing::ValuesIn(precisions), ::testing::ValuesIn(updatePrecisions), ::testing::ValuesIn(testValues)), ConcatWithDifferentChildsTransformation::getTestCaseName); } // namespace
// Copyright 2019 Lawrence Livermore National Security, LLC and other // Devil Ray Developers. See the top-level COPYRIGHT file for details. // // SPDX-License-Identifier: (BSD-3-Clause) #include "gtest/gtest.h" #include <dray/vec.hpp> #include <type_traits> using namespace dray; TEST (dray_vec, dray_vec) { Vec3f vec = make_vec3f (1, 1, 1); Vec3f vec1 = make_vec3f (2, 2, 2); ASSERT_EQ (vec * 2, vec1); ASSERT_EQ (dot (vec, vec1), 6.f); }
// Copyright (c) 2014 The Lmcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "winshutdownmonitor.h" #if defined(Q_OS_WIN) && QT_VERSION >= 0x050000 #include "init.h" #include "util.h" #include <windows.h> #include <QDebug> #include <openssl/rand.h> // If we don't want a message to be processed by Qt, return true and set result to // the value that the window procedure should return. Otherwise return false. bool WinShutdownMonitor::nativeEventFilter(const QByteArray &eventType, void *pMessage, long *pnResult) { Q_UNUSED(eventType); MSG *pMsg = static_cast<MSG *>(pMessage); // Seed OpenSSL PRNG with Windows event data (e.g. mouse movements and other user interactions) if (RAND_event(pMsg->message, pMsg->wParam, pMsg->lParam) == 0) { // Warn only once as this is performance-critical static bool warned = false; if (!warned) { LogPrint("%s: OpenSSL RAND_event() failed to seed OpenSSL PRNG with enough data.\n", __func__); warned = true; } } switch(pMsg->message) { case WM_QUERYENDSESSION: { // Initiate a client shutdown after receiving a WM_QUERYENDSESSION and block // Windows session end until we have finished client shutdown. StartShutdown(); *pnResult = FALSE; return true; } case WM_ENDSESSION: { *pnResult = FALSE; return true; } } return false; } void WinShutdownMonitor::registerShutdownBlockReason(const QString& strReason, const HWND& mainWinId) { typedef BOOL (WINAPI *PSHUTDOWNBRCREATE)(HWND, LPCWSTR); PSHUTDOWNBRCREATE shutdownBRCreate = (PSHUTDOWNBRCREATE)GetProcAddress(GetModuleHandleA("User32.dll"), "ShutdownBlockReasonCreate"); if (shutdownBRCreate == NULL) { qWarning() << "registerShutdownBlockReason: GetProcAddress for ShutdownBlockReasonCreate failed"; return; } if (shutdownBRCreate(mainWinId, strReason.toStdWString().c_str())) qWarning() << "registerShutdownBlockReason: Successfully registered: " + strReason; else qWarning() << "registerShutdownBlockReason: Failed to register: " + strReason; } #endif
/*============================================================================= Phoenix V1.2.1 Copyright (c) 2001-2003 Joel de Guzman Copyright (c) 2003 Vaclav Vesely Use, modification and distribution is subject to the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) ==============================================================================*/ #include <iostream> #include <boost/detail/lightweight_test.hpp> #define PHOENIX_LIMIT 15 #include <boost/spirit/include/phoenix1_primitives.hpp> #include <boost/spirit/include/phoenix1_new.hpp> using namespace phoenix; using namespace std; class X { public: X(int i_ = 1) : i(i_) {} int i; }; /////////////////////////////////////////////////////////////////////////////// int main() { int i2 = 2; X x3(3); BOOST_TEST(new_<int>()() != NULL); BOOST_TEST(*new_<int>(arg1)(i2) == 2); BOOST_TEST(new_<X>()() != NULL); BOOST_TEST(new_<X>()()->i == 1); BOOST_TEST(new_<X>(arg1)(i2)->i == 2); BOOST_TEST(new_<X>(arg1)(x3)->i == 3); return boost::report_errors(); }
#include "if_else.h" //write include statement for if_else header file //write code for function named get_generation that accepts an int year and returns //a string, apply the following logic: //return "Centenial" when year greater than equal to 1996 to 2014 //return "Millenial" when year greater than equal to 1977 to 1995 //return "Generation X" when year greater than equal to 1965 to 1976 //return "Baby boomer" when year greater than equal to 1946 to 1964 //return "Silent Generation" when year greater than equal 1925 and less than equal 1945 //return "Invalid Year" otherwise string get_generation(int gen) { if (gen >= 1996 && gen <= 2014) { return "Centenial"; } else if(gen >= 1977 && gen <= 1995) { return "Millenial"; } else if (gen >= 1965 && gen <= 1976) { return "Generation X"; } else if (gen >= 1946 && gen <= 1964) { return "Baby Boomer"; } else if (gen >= 1925 && gen <= 1945) { return "Silent Generation"; } else { return "Invalid Year"; } }
//===-- SymbolFileDWARF.cpp -----------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "SymbolFileDWARF.h" #include "llvm/ADT/Optional.h" #include "llvm/Support/Casting.h" #include "llvm/Support/Threading.h" #include "lldb/Core/Module.h" #include "lldb/Core/ModuleList.h" #include "lldb/Core/ModuleSpec.h" #include "lldb/Core/PluginManager.h" #include "lldb/Core/Progress.h" #include "lldb/Core/Section.h" #include "lldb/Core/StreamFile.h" #include "lldb/Core/Value.h" #include "lldb/Utility/ArchSpec.h" #include "lldb/Utility/OptionParsing.h" #include "lldb/Utility/RegularExpression.h" #include "lldb/Utility/Scalar.h" #include "lldb/Utility/StreamString.h" #include "lldb/Utility/Timer.h" #include "Plugins/ExpressionParser/Clang/ClangModulesDeclVendor.h" #include "Plugins/Language/CPlusPlus/CPlusPlusLanguage.h" #include "lldb/Host/FileSystem.h" #include "lldb/Host/Host.h" #include "lldb/Interpreter/OptionValueFileSpecList.h" #include "lldb/Interpreter/OptionValueProperties.h" #include "Plugins/ExpressionParser/Clang/ClangUtil.h" #include "Plugins/SymbolFile/DWARF/DWARFDebugInfoEntry.h" #include "Plugins/TypeSystem/Clang/TypeSystemClang.h" #include "lldb/Symbol/Block.h" #include "lldb/Symbol/CompileUnit.h" #include "lldb/Symbol/CompilerDecl.h" #include "lldb/Symbol/CompilerDeclContext.h" #include "lldb/Symbol/DebugMacros.h" #include "lldb/Symbol/LineTable.h" #include "lldb/Symbol/LocateSymbolFile.h" #include "lldb/Symbol/ObjectFile.h" #include "lldb/Symbol/SymbolFile.h" #include "lldb/Symbol/TypeMap.h" #include "lldb/Symbol/TypeSystem.h" #include "lldb/Symbol/VariableList.h" #include "lldb/Target/Language.h" #include "lldb/Target/Target.h" #include "AppleDWARFIndex.h" #include "DWARFASTParser.h" #include "DWARFASTParserClang.h" #include "DWARFCompileUnit.h" #include "DWARFDebugAbbrev.h" #include "DWARFDebugAranges.h" #include "DWARFDebugInfo.h" #include "DWARFDebugMacro.h" #include "DWARFDebugRanges.h" #include "DWARFDeclContext.h" #include "DWARFFormValue.h" #include "DWARFTypeUnit.h" #include "DWARFUnit.h" #include "DebugNamesDWARFIndex.h" #include "LogChannelDWARF.h" #include "ManualDWARFIndex.h" #include "SymbolFileDWARFDebugMap.h" #include "SymbolFileDWARFDwo.h" #include "llvm/DebugInfo/DWARF/DWARFContext.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/FormatVariadic.h" #include <algorithm> #include <map> #include <memory> #include <cctype> #include <cstring> //#define ENABLE_DEBUG_PRINTF // COMMENT OUT THIS LINE PRIOR TO CHECKIN #ifdef ENABLE_DEBUG_PRINTF #include <cstdio> #define DEBUG_PRINTF(fmt, ...) printf(fmt, __VA_ARGS__) #else #define DEBUG_PRINTF(fmt, ...) #endif using namespace lldb; using namespace lldb_private; LLDB_PLUGIN_DEFINE(SymbolFileDWARF) char SymbolFileDWARF::ID; // static inline bool // child_requires_parent_class_union_or_struct_to_be_completed (dw_tag_t tag) //{ // switch (tag) // { // default: // break; // case DW_TAG_subprogram: // case DW_TAG_inlined_subroutine: // case DW_TAG_class_type: // case DW_TAG_structure_type: // case DW_TAG_union_type: // return true; // } // return false; //} // namespace { #define LLDB_PROPERTIES_symbolfiledwarf #include "SymbolFileDWARFProperties.inc" enum { #define LLDB_PROPERTIES_symbolfiledwarf #include "SymbolFileDWARFPropertiesEnum.inc" }; class PluginProperties : public Properties { public: static ConstString GetSettingName() { return SymbolFileDWARF::GetPluginNameStatic(); } PluginProperties() { m_collection_sp = std::make_shared<OptionValueProperties>(GetSettingName()); m_collection_sp->Initialize(g_symbolfiledwarf_properties); } bool IgnoreFileIndexes() const { return m_collection_sp->GetPropertyAtIndexAsBoolean( nullptr, ePropertyIgnoreIndexes, false); } }; typedef std::shared_ptr<PluginProperties> SymbolFileDWARFPropertiesSP; static const SymbolFileDWARFPropertiesSP &GetGlobalPluginProperties() { static const auto g_settings_sp(std::make_shared<PluginProperties>()); return g_settings_sp; } } // namespace static const llvm::DWARFDebugLine::LineTable * ParseLLVMLineTable(lldb_private::DWARFContext &context, llvm::DWARFDebugLine &line, dw_offset_t line_offset, dw_offset_t unit_offset) { Log *log = LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO); llvm::DWARFDataExtractor data = context.getOrLoadLineData().GetAsLLVM(); llvm::DWARFContext &ctx = context.GetAsLLVM(); llvm::Expected<const llvm::DWARFDebugLine::LineTable *> line_table = line.getOrParseLineTable( data, line_offset, ctx, nullptr, [&](llvm::Error e) { LLDB_LOG_ERROR( log, std::move(e), "SymbolFileDWARF::ParseLineTable failed to parse: {0}"); }); if (!line_table) { LLDB_LOG_ERROR(log, line_table.takeError(), "SymbolFileDWARF::ParseLineTable failed to parse: {0}"); return nullptr; } return *line_table; } static bool ParseLLVMLineTablePrologue(lldb_private::DWARFContext &context, llvm::DWARFDebugLine::Prologue &prologue, dw_offset_t line_offset, dw_offset_t unit_offset) { Log *log = LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO); bool success = true; llvm::DWARFDataExtractor data = context.getOrLoadLineData().GetAsLLVM(); llvm::DWARFContext &ctx = context.GetAsLLVM(); uint64_t offset = line_offset; llvm::Error error = prologue.parse( data, &offset, [&](llvm::Error e) { success = false; LLDB_LOG_ERROR(log, std::move(e), "SymbolFileDWARF::ParseSupportFiles failed to parse " "line table prologue: {0}"); }, ctx, nullptr); if (error) { LLDB_LOG_ERROR(log, std::move(error), "SymbolFileDWARF::ParseSupportFiles failed to parse line " "table prologue: {0}"); return false; } return success; } static llvm::Optional<std::string> GetFileByIndex(const llvm::DWARFDebugLine::Prologue &prologue, size_t idx, llvm::StringRef compile_dir, FileSpec::Style style) { // Try to get an absolute path first. std::string abs_path; auto absolute = llvm::DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath; if (prologue.getFileNameByIndex(idx, compile_dir, absolute, abs_path, style)) return std::move(abs_path); // Otherwise ask for a relative path. std::string rel_path; auto relative = llvm::DILineInfoSpecifier::FileLineInfoKind::RawValue; if (!prologue.getFileNameByIndex(idx, compile_dir, relative, rel_path, style)) return {}; return std::move(rel_path); } static FileSpecList ParseSupportFilesFromPrologue(const lldb::ModuleSP &module, const llvm::DWARFDebugLine::Prologue &prologue, FileSpec::Style style, llvm::StringRef compile_dir = {}) { FileSpecList support_files; size_t first_file = 0; if (prologue.getVersion() <= 4) { // File index 0 is not valid before DWARF v5. Add a dummy entry to ensure // support file list indices match those we get from the debug info and line // tables. support_files.Append(FileSpec()); first_file = 1; } const size_t number_of_files = prologue.FileNames.size(); for (size_t idx = first_file; idx <= number_of_files; ++idx) { std::string remapped_file; if (auto file_path = GetFileByIndex(prologue, idx, compile_dir, style)) { if (auto remapped = module->RemapSourceFile(llvm::StringRef(*file_path))) remapped_file = *remapped; else remapped_file = std::move(*file_path); } // Unconditionally add an entry, so the indices match up. support_files.EmplaceBack(remapped_file, style); } return support_files; } void SymbolFileDWARF::Initialize() { LogChannelDWARF::Initialize(); PluginManager::RegisterPlugin(GetPluginNameStatic(), GetPluginDescriptionStatic(), CreateInstance, DebuggerInitialize); SymbolFileDWARFDebugMap::Initialize(); } void SymbolFileDWARF::DebuggerInitialize(Debugger &debugger) { if (!PluginManager::GetSettingForSymbolFilePlugin( debugger, PluginProperties::GetSettingName())) { const bool is_global_setting = true; PluginManager::CreateSettingForSymbolFilePlugin( debugger, GetGlobalPluginProperties()->GetValueProperties(), ConstString("Properties for the dwarf symbol-file plug-in."), is_global_setting); } } void SymbolFileDWARF::Terminate() { SymbolFileDWARFDebugMap::Terminate(); PluginManager::UnregisterPlugin(CreateInstance); LogChannelDWARF::Terminate(); } lldb_private::ConstString SymbolFileDWARF::GetPluginNameStatic() { static ConstString g_name("dwarf"); return g_name; } const char *SymbolFileDWARF::GetPluginDescriptionStatic() { return "DWARF and DWARF3 debug symbol file reader."; } SymbolFile *SymbolFileDWARF::CreateInstance(ObjectFileSP objfile_sp) { return new SymbolFileDWARF(std::move(objfile_sp), /*dwo_section_list*/ nullptr); } TypeList &SymbolFileDWARF::GetTypeList() { std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); if (SymbolFileDWARFDebugMap *debug_map_symfile = GetDebugMapSymfile()) return debug_map_symfile->GetTypeList(); return SymbolFile::GetTypeList(); } void SymbolFileDWARF::GetTypes(const DWARFDIE &die, dw_offset_t min_die_offset, dw_offset_t max_die_offset, uint32_t type_mask, TypeSet &type_set) { if (die) { const dw_offset_t die_offset = die.GetOffset(); if (die_offset >= max_die_offset) return; if (die_offset >= min_die_offset) { const dw_tag_t tag = die.Tag(); bool add_type = false; switch (tag) { case DW_TAG_array_type: add_type = (type_mask & eTypeClassArray) != 0; break; case DW_TAG_unspecified_type: case DW_TAG_base_type: add_type = (type_mask & eTypeClassBuiltin) != 0; break; case DW_TAG_class_type: add_type = (type_mask & eTypeClassClass) != 0; break; case DW_TAG_structure_type: add_type = (type_mask & eTypeClassStruct) != 0; break; case DW_TAG_union_type: add_type = (type_mask & eTypeClassUnion) != 0; break; case DW_TAG_enumeration_type: add_type = (type_mask & eTypeClassEnumeration) != 0; break; case DW_TAG_subroutine_type: case DW_TAG_subprogram: case DW_TAG_inlined_subroutine: add_type = (type_mask & eTypeClassFunction) != 0; break; case DW_TAG_pointer_type: add_type = (type_mask & eTypeClassPointer) != 0; break; case DW_TAG_rvalue_reference_type: case DW_TAG_reference_type: add_type = (type_mask & eTypeClassReference) != 0; break; case DW_TAG_typedef: add_type = (type_mask & eTypeClassTypedef) != 0; break; case DW_TAG_ptr_to_member_type: add_type = (type_mask & eTypeClassMemberPointer) != 0; break; default: break; } if (add_type) { const bool assert_not_being_parsed = true; Type *type = ResolveTypeUID(die, assert_not_being_parsed); if (type) type_set.insert(type); } } for (DWARFDIE child_die : die.children()) { GetTypes(child_die, min_die_offset, max_die_offset, type_mask, type_set); } } } void SymbolFileDWARF::GetTypes(SymbolContextScope *sc_scope, TypeClass type_mask, TypeList &type_list) { std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); TypeSet type_set; CompileUnit *comp_unit = nullptr; if (sc_scope) comp_unit = sc_scope->CalculateSymbolContextCompileUnit(); const auto &get = [&](DWARFUnit *unit) { if (!unit) return; unit = &unit->GetNonSkeletonUnit(); GetTypes(unit->DIE(), unit->GetOffset(), unit->GetNextUnitOffset(), type_mask, type_set); }; if (comp_unit) { get(GetDWARFCompileUnit(comp_unit)); } else { DWARFDebugInfo &info = DebugInfo(); const size_t num_cus = info.GetNumUnits(); for (size_t cu_idx = 0; cu_idx < num_cus; ++cu_idx) get(info.GetUnitAtIndex(cu_idx)); } std::set<CompilerType> compiler_type_set; for (Type *type : type_set) { CompilerType compiler_type = type->GetForwardCompilerType(); if (compiler_type_set.find(compiler_type) == compiler_type_set.end()) { compiler_type_set.insert(compiler_type); type_list.Insert(type->shared_from_this()); } } } // Gets the first parent that is a lexical block, function or inlined // subroutine, or compile unit. DWARFDIE SymbolFileDWARF::GetParentSymbolContextDIE(const DWARFDIE &child_die) { DWARFDIE die; for (die = child_die.GetParent(); die; die = die.GetParent()) { dw_tag_t tag = die.Tag(); switch (tag) { case DW_TAG_compile_unit: case DW_TAG_partial_unit: case DW_TAG_subprogram: case DW_TAG_inlined_subroutine: case DW_TAG_lexical_block: return die; default: break; } } return DWARFDIE(); } SymbolFileDWARF::SymbolFileDWARF(ObjectFileSP objfile_sp, SectionList *dwo_section_list) : SymbolFile(std::move(objfile_sp)), UserID(0x7fffffff00000000), // Used by SymbolFileDWARFDebugMap to // when this class parses .o files to // contain the .o file index/ID m_debug_map_module_wp(), m_debug_map_symfile(nullptr), m_context(m_objfile_sp->GetModule()->GetSectionList(), dwo_section_list), m_fetched_external_modules(false), m_supports_DW_AT_APPLE_objc_complete_type(eLazyBoolCalculate) {} SymbolFileDWARF::~SymbolFileDWARF() = default; static ConstString GetDWARFMachOSegmentName() { static ConstString g_dwarf_section_name("__DWARF"); return g_dwarf_section_name; } UniqueDWARFASTTypeMap &SymbolFileDWARF::GetUniqueDWARFASTTypeMap() { SymbolFileDWARFDebugMap *debug_map_symfile = GetDebugMapSymfile(); if (debug_map_symfile) return debug_map_symfile->GetUniqueDWARFASTTypeMap(); else return m_unique_ast_type_map; } llvm::Expected<TypeSystem &> SymbolFileDWARF::GetTypeSystemForLanguage(LanguageType language) { if (SymbolFileDWARFDebugMap *debug_map_symfile = GetDebugMapSymfile()) return debug_map_symfile->GetTypeSystemForLanguage(language); auto type_system_or_err = m_objfile_sp->GetModule()->GetTypeSystemForLanguage(language); if (type_system_or_err) { type_system_or_err->SetSymbolFile(this); } return type_system_or_err; } void SymbolFileDWARF::InitializeObject() { Log *log = LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO); if (!GetGlobalPluginProperties()->IgnoreFileIndexes()) { StreamString module_desc; GetObjectFile()->GetModule()->GetDescription(module_desc.AsRawOstream(), lldb::eDescriptionLevelBrief); DWARFDataExtractor apple_names, apple_namespaces, apple_types, apple_objc; LoadSectionData(eSectionTypeDWARFAppleNames, apple_names); LoadSectionData(eSectionTypeDWARFAppleNamespaces, apple_namespaces); LoadSectionData(eSectionTypeDWARFAppleTypes, apple_types); LoadSectionData(eSectionTypeDWARFAppleObjC, apple_objc); if (apple_names.GetByteSize() > 0 || apple_namespaces.GetByteSize() > 0 || apple_types.GetByteSize() > 0 || apple_objc.GetByteSize() > 0) { Progress progress(llvm::formatv("Loading Apple DWARF index for {0}", module_desc.GetData())); m_index = AppleDWARFIndex::Create( *GetObjectFile()->GetModule(), apple_names, apple_namespaces, apple_types, apple_objc, m_context.getOrLoadStrData()); if (m_index) return; } DWARFDataExtractor debug_names; LoadSectionData(eSectionTypeDWARFDebugNames, debug_names); if (debug_names.GetByteSize() > 0) { Progress progress( llvm::formatv("Loading DWARF5 index for {0}", module_desc.GetData())); llvm::Expected<std::unique_ptr<DebugNamesDWARFIndex>> index_or = DebugNamesDWARFIndex::Create(*GetObjectFile()->GetModule(), debug_names, m_context.getOrLoadStrData(), *this); if (index_or) { m_index = std::move(*index_or); return; } LLDB_LOG_ERROR(log, index_or.takeError(), "Unable to read .debug_names data: {0}"); } } m_index = std::make_unique<ManualDWARFIndex>(*GetObjectFile()->GetModule(), *this); } bool SymbolFileDWARF::SupportedVersion(uint16_t version) { return version >= 2 && version <= 5; } uint32_t SymbolFileDWARF::CalculateAbilities() { uint32_t abilities = 0; if (m_objfile_sp != nullptr) { const Section *section = nullptr; const SectionList *section_list = m_objfile_sp->GetSectionList(); if (section_list == nullptr) return 0; uint64_t debug_abbrev_file_size = 0; uint64_t debug_info_file_size = 0; uint64_t debug_line_file_size = 0; section = section_list->FindSectionByName(GetDWARFMachOSegmentName()).get(); if (section) section_list = &section->GetChildren(); section = section_list->FindSectionByType(eSectionTypeDWARFDebugInfo, true).get(); if (section != nullptr) { debug_info_file_size = section->GetFileSize(); section = section_list->FindSectionByType(eSectionTypeDWARFDebugAbbrev, true) .get(); if (section) debug_abbrev_file_size = section->GetFileSize(); DWARFDebugAbbrev *abbrev = DebugAbbrev(); if (abbrev) { std::set<dw_form_t> invalid_forms; abbrev->GetUnsupportedForms(invalid_forms); if (!invalid_forms.empty()) { StreamString error; error.Printf("unsupported DW_FORM value%s:", invalid_forms.size() > 1 ? "s" : ""); for (auto form : invalid_forms) error.Printf(" %#x", form); m_objfile_sp->GetModule()->ReportWarning( "%s", error.GetString().str().c_str()); return 0; } } section = section_list->FindSectionByType(eSectionTypeDWARFDebugLine, true) .get(); if (section) debug_line_file_size = section->GetFileSize(); } else { const char *symfile_dir_cstr = m_objfile_sp->GetFileSpec().GetDirectory().GetCString(); if (symfile_dir_cstr) { if (strcasestr(symfile_dir_cstr, ".dsym")) { if (m_objfile_sp->GetType() == ObjectFile::eTypeDebugInfo) { // We have a dSYM file that didn't have a any debug info. If the // string table has a size of 1, then it was made from an // executable with no debug info, or from an executable that was // stripped. section = section_list->FindSectionByType(eSectionTypeDWARFDebugStr, true) .get(); if (section && section->GetFileSize() == 1) { m_objfile_sp->GetModule()->ReportWarning( "empty dSYM file detected, dSYM was created with an " "executable with no debug info."); } } } } } if (debug_abbrev_file_size > 0 && debug_info_file_size > 0) abilities |= CompileUnits | Functions | Blocks | GlobalVariables | LocalVariables | VariableTypes; if (debug_line_file_size > 0) abilities |= LineTables; } return abilities; } void SymbolFileDWARF::LoadSectionData(lldb::SectionType sect_type, DWARFDataExtractor &data) { ModuleSP module_sp(m_objfile_sp->GetModule()); const SectionList *section_list = module_sp->GetSectionList(); if (!section_list) return; SectionSP section_sp(section_list->FindSectionByType(sect_type, true)); if (!section_sp) return; data.Clear(); m_objfile_sp->ReadSectionData(section_sp.get(), data); } DWARFDebugAbbrev *SymbolFileDWARF::DebugAbbrev() { if (m_abbr) return m_abbr.get(); const DWARFDataExtractor &debug_abbrev_data = m_context.getOrLoadAbbrevData(); if (debug_abbrev_data.GetByteSize() == 0) return nullptr; auto abbr = std::make_unique<DWARFDebugAbbrev>(); llvm::Error error = abbr->parse(debug_abbrev_data); if (error) { Log *log = LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO); LLDB_LOG_ERROR(log, std::move(error), "Unable to read .debug_abbrev section: {0}"); return nullptr; } m_abbr = std::move(abbr); return m_abbr.get(); } DWARFDebugInfo &SymbolFileDWARF::DebugInfo() { llvm::call_once(m_info_once_flag, [&] { LLDB_SCOPED_TIMERF("%s this = %p", LLVM_PRETTY_FUNCTION, static_cast<void *>(this)); m_info = std::make_unique<DWARFDebugInfo>(*this, m_context); }); return *m_info; } DWARFCompileUnit *SymbolFileDWARF::GetDWARFCompileUnit(CompileUnit *comp_unit) { if (!comp_unit) return nullptr; // The compile unit ID is the index of the DWARF unit. DWARFUnit *dwarf_cu = DebugInfo().GetUnitAtIndex(comp_unit->GetID()); if (dwarf_cu && dwarf_cu->GetUserData() == nullptr) dwarf_cu->SetUserData(comp_unit); // It must be DWARFCompileUnit when it created a CompileUnit. return llvm::cast_or_null<DWARFCompileUnit>(dwarf_cu); } DWARFDebugRanges *SymbolFileDWARF::GetDebugRanges() { if (!m_ranges) { LLDB_SCOPED_TIMERF("%s this = %p", LLVM_PRETTY_FUNCTION, static_cast<void *>(this)); if (m_context.getOrLoadRangesData().GetByteSize() > 0) m_ranges = std::make_unique<DWARFDebugRanges>(); if (m_ranges) m_ranges->Extract(m_context); } return m_ranges.get(); } /// Make an absolute path out of \p file_spec and remap it using the /// module's source remapping dictionary. static void MakeAbsoluteAndRemap(FileSpec &file_spec, DWARFUnit &dwarf_cu, const ModuleSP &module_sp) { if (!file_spec) return; // If we have a full path to the compile unit, we don't need to // resolve the file. This can be expensive e.g. when the source // files are NFS mounted. file_spec.MakeAbsolute(dwarf_cu.GetCompilationDirectory()); if (auto remapped_file = module_sp->RemapSourceFile(file_spec.GetPath())) file_spec.SetFile(*remapped_file, FileSpec::Style::native); } /// Return the DW_AT_(GNU_)dwo_name. static const char *GetDWOName(DWARFCompileUnit &dwarf_cu, const DWARFDebugInfoEntry &cu_die) { const char *dwo_name = cu_die.GetAttributeValueAsString(&dwarf_cu, DW_AT_GNU_dwo_name, nullptr); if (!dwo_name) dwo_name = cu_die.GetAttributeValueAsString(&dwarf_cu, DW_AT_dwo_name, nullptr); return dwo_name; } lldb::CompUnitSP SymbolFileDWARF::ParseCompileUnit(DWARFCompileUnit &dwarf_cu) { CompUnitSP cu_sp; CompileUnit *comp_unit = (CompileUnit *)dwarf_cu.GetUserData(); if (comp_unit) { // We already parsed this compile unit, had out a shared pointer to it cu_sp = comp_unit->shared_from_this(); } else { if (dwarf_cu.GetOffset() == 0 && GetDebugMapSymfile()) { // Let the debug map create the compile unit cu_sp = m_debug_map_symfile->GetCompileUnit(this); dwarf_cu.SetUserData(cu_sp.get()); } else { ModuleSP module_sp(m_objfile_sp->GetModule()); if (module_sp) { auto initialize_cu = [&](const FileSpec &file_spec, LanguageType cu_language) { BuildCuTranslationTable(); cu_sp = std::make_shared<CompileUnit>( module_sp, &dwarf_cu, file_spec, *GetDWARFUnitIndex(dwarf_cu.GetID()), cu_language, eLazyBoolCalculate); dwarf_cu.SetUserData(cu_sp.get()); SetCompileUnitAtIndex(dwarf_cu.GetID(), cu_sp); }; auto lazy_initialize_cu = [&]() { // If the version is < 5, we can't do lazy initialization. if (dwarf_cu.GetVersion() < 5) return false; // If there is no DWO, there is no reason to initialize // lazily; we will do eager initialization in that case. if (GetDebugMapSymfile()) return false; const DWARFBaseDIE cu_die = dwarf_cu.GetUnitDIEOnly(); if (!cu_die) return false; if (!GetDWOName(dwarf_cu, *cu_die.GetDIE())) return false; // With DWARFv5 we can assume that the first support // file is also the name of the compile unit. This // allows us to avoid loading the non-skeleton unit, // which may be in a separate DWO file. FileSpecList support_files; if (!ParseSupportFiles(dwarf_cu, module_sp, support_files)) return false; if (support_files.GetSize() == 0) return false; initialize_cu(support_files.GetFileSpecAtIndex(0), eLanguageTypeUnknown); cu_sp->SetSupportFiles(std::move(support_files)); return true; }; if (!lazy_initialize_cu()) { // Eagerly initialize compile unit const DWARFBaseDIE cu_die = dwarf_cu.GetNonSkeletonUnit().GetUnitDIEOnly(); if (cu_die) { LanguageType cu_language = SymbolFileDWARF::LanguageTypeFromDWARF( dwarf_cu.GetDWARFLanguageType()); FileSpec cu_file_spec(cu_die.GetName(), dwarf_cu.GetPathStyle()); // Path needs to be remapped in this case. In the support files // case ParseSupportFiles takes care of the remapping. MakeAbsoluteAndRemap(cu_file_spec, dwarf_cu, module_sp); initialize_cu(cu_file_spec, cu_language); } } } } } return cu_sp; } void SymbolFileDWARF::BuildCuTranslationTable() { if (!m_lldb_cu_to_dwarf_unit.empty()) return; DWARFDebugInfo &info = DebugInfo(); if (!info.ContainsTypeUnits()) { // We can use a 1-to-1 mapping. No need to build a translation table. return; } for (uint32_t i = 0, num = info.GetNumUnits(); i < num; ++i) { if (auto *cu = llvm::dyn_cast<DWARFCompileUnit>(info.GetUnitAtIndex(i))) { cu->SetID(m_lldb_cu_to_dwarf_unit.size()); m_lldb_cu_to_dwarf_unit.push_back(i); } } } llvm::Optional<uint32_t> SymbolFileDWARF::GetDWARFUnitIndex(uint32_t cu_idx) { BuildCuTranslationTable(); if (m_lldb_cu_to_dwarf_unit.empty()) return cu_idx; if (cu_idx >= m_lldb_cu_to_dwarf_unit.size()) return llvm::None; return m_lldb_cu_to_dwarf_unit[cu_idx]; } uint32_t SymbolFileDWARF::CalculateNumCompileUnits() { BuildCuTranslationTable(); return m_lldb_cu_to_dwarf_unit.empty() ? DebugInfo().GetNumUnits() : m_lldb_cu_to_dwarf_unit.size(); } CompUnitSP SymbolFileDWARF::ParseCompileUnitAtIndex(uint32_t cu_idx) { ASSERT_MODULE_LOCK(this); if (llvm::Optional<uint32_t> dwarf_idx = GetDWARFUnitIndex(cu_idx)) { if (auto *dwarf_cu = llvm::cast_or_null<DWARFCompileUnit>( DebugInfo().GetUnitAtIndex(*dwarf_idx))) return ParseCompileUnit(*dwarf_cu); } return {}; } Function *SymbolFileDWARF::ParseFunction(CompileUnit &comp_unit, const DWARFDIE &die) { ASSERT_MODULE_LOCK(this); if (!die.IsValid()) return nullptr; auto type_system_or_err = GetTypeSystemForLanguage(GetLanguage(*die.GetCU())); if (auto err = type_system_or_err.takeError()) { LLDB_LOG_ERROR(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_SYMBOLS), std::move(err), "Unable to parse function"); return nullptr; } DWARFASTParser *dwarf_ast = type_system_or_err->GetDWARFParser(); if (!dwarf_ast) return nullptr; return dwarf_ast->ParseFunctionFromDWARF(comp_unit, die); } lldb::addr_t SymbolFileDWARF::FixupAddress(lldb::addr_t file_addr) { SymbolFileDWARFDebugMap *debug_map_symfile = GetDebugMapSymfile(); if (debug_map_symfile) return debug_map_symfile->LinkOSOFileAddress(this, file_addr); return file_addr; } bool SymbolFileDWARF::FixupAddress(Address &addr) { SymbolFileDWARFDebugMap *debug_map_symfile = GetDebugMapSymfile(); if (debug_map_symfile) { return debug_map_symfile->LinkOSOAddress(addr); } // This is a normal DWARF file, no address fixups need to happen return true; } lldb::LanguageType SymbolFileDWARF::ParseLanguage(CompileUnit &comp_unit) { std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); DWARFUnit *dwarf_cu = GetDWARFCompileUnit(&comp_unit); if (dwarf_cu) return GetLanguage(dwarf_cu->GetNonSkeletonUnit()); else return eLanguageTypeUnknown; } XcodeSDK SymbolFileDWARF::ParseXcodeSDK(CompileUnit &comp_unit) { std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); DWARFUnit *dwarf_cu = GetDWARFCompileUnit(&comp_unit); if (!dwarf_cu) return {}; const DWARFBaseDIE cu_die = dwarf_cu->GetNonSkeletonUnit().GetUnitDIEOnly(); if (!cu_die) return {}; const char *sdk = cu_die.GetAttributeValueAsString(DW_AT_APPLE_sdk, nullptr); if (!sdk) return {}; const char *sysroot = cu_die.GetAttributeValueAsString(DW_AT_LLVM_sysroot, ""); // Register the sysroot path remapping with the module belonging to // the CU as well as the one belonging to the symbol file. The two // would be different if this is an OSO object and module is the // corresponding debug map, in which case both should be updated. ModuleSP module_sp = comp_unit.GetModule(); if (module_sp) module_sp->RegisterXcodeSDK(sdk, sysroot); ModuleSP local_module_sp = m_objfile_sp->GetModule(); if (local_module_sp && local_module_sp != module_sp) local_module_sp->RegisterXcodeSDK(sdk, sysroot); return {sdk}; } size_t SymbolFileDWARF::ParseFunctions(CompileUnit &comp_unit) { LLDB_SCOPED_TIMER(); std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); DWARFUnit *dwarf_cu = GetDWARFCompileUnit(&comp_unit); if (!dwarf_cu) return 0; size_t functions_added = 0; dwarf_cu = &dwarf_cu->GetNonSkeletonUnit(); for (DWARFDebugInfoEntry &entry : dwarf_cu->dies()) { if (entry.Tag() != DW_TAG_subprogram) continue; DWARFDIE die(dwarf_cu, &entry); if (comp_unit.FindFunctionByUID(die.GetID())) continue; if (ParseFunction(comp_unit, die)) ++functions_added; } // FixupTypes(); return functions_added; } bool SymbolFileDWARF::ForEachExternalModule( CompileUnit &comp_unit, llvm::DenseSet<lldb_private::SymbolFile *> &visited_symbol_files, llvm::function_ref<bool(Module &)> lambda) { // Only visit each symbol file once. if (!visited_symbol_files.insert(this).second) return false; UpdateExternalModuleListIfNeeded(); for (auto &p : m_external_type_modules) { ModuleSP module = p.second; if (!module) continue; // Invoke the action and potentially early-exit. if (lambda(*module)) return true; for (std::size_t i = 0; i < module->GetNumCompileUnits(); ++i) { auto cu = module->GetCompileUnitAtIndex(i); bool early_exit = cu->ForEachExternalModule(visited_symbol_files, lambda); if (early_exit) return true; } } return false; } bool SymbolFileDWARF::ParseSupportFiles(CompileUnit &comp_unit, FileSpecList &support_files) { std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); DWARFUnit *dwarf_cu = GetDWARFCompileUnit(&comp_unit); if (!dwarf_cu) return false; if (!ParseSupportFiles(*dwarf_cu, comp_unit.GetModule(), support_files)) return false; comp_unit.SetSupportFiles(support_files); return true; } bool SymbolFileDWARF::ParseSupportFiles(DWARFUnit &dwarf_cu, const ModuleSP &module, FileSpecList &support_files) { dw_offset_t offset = dwarf_cu.GetLineTableOffset(); if (offset == DW_INVALID_OFFSET) return false; llvm::DWARFDebugLine::Prologue prologue; if (!ParseLLVMLineTablePrologue(m_context, prologue, offset, dwarf_cu.GetOffset())) return false; support_files = ParseSupportFilesFromPrologue( module, prologue, dwarf_cu.GetPathStyle(), dwarf_cu.GetCompilationDirectory().GetCString()); return true; } FileSpec SymbolFileDWARF::GetFile(DWARFUnit &unit, size_t file_idx) { if (auto *dwarf_cu = llvm::dyn_cast<DWARFCompileUnit>(&unit)) { if (CompileUnit *lldb_cu = GetCompUnitForDWARFCompUnit(*dwarf_cu)) return lldb_cu->GetSupportFiles().GetFileSpecAtIndex(file_idx); return FileSpec(); } auto &tu = llvm::cast<DWARFTypeUnit>(unit); return GetTypeUnitSupportFiles(tu).GetFileSpecAtIndex(file_idx); } const FileSpecList & SymbolFileDWARF::GetTypeUnitSupportFiles(DWARFTypeUnit &tu) { static FileSpecList empty_list; dw_offset_t offset = tu.GetLineTableOffset(); if (offset == DW_INVALID_OFFSET || offset == llvm::DenseMapInfo<dw_offset_t>::getEmptyKey() || offset == llvm::DenseMapInfo<dw_offset_t>::getTombstoneKey()) return empty_list; // Many type units can share a line table, so parse the support file list // once, and cache it based on the offset field. auto iter_bool = m_type_unit_support_files.try_emplace(offset); FileSpecList &list = iter_bool.first->second; if (iter_bool.second) { uint64_t line_table_offset = offset; llvm::DWARFDataExtractor data = m_context.getOrLoadLineData().GetAsLLVM(); llvm::DWARFContext &ctx = m_context.GetAsLLVM(); llvm::DWARFDebugLine::Prologue prologue; auto report = [](llvm::Error error) { Log *log = LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO); LLDB_LOG_ERROR(log, std::move(error), "SymbolFileDWARF::GetTypeUnitSupportFiles failed to parse " "the line table prologue"); }; llvm::Error error = prologue.parse(data, &line_table_offset, report, ctx); if (error) { report(std::move(error)); } else { list = ParseSupportFilesFromPrologue(GetObjectFile()->GetModule(), prologue, tu.GetPathStyle()); } } return list; } bool SymbolFileDWARF::ParseIsOptimized(CompileUnit &comp_unit) { std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); DWARFUnit *dwarf_cu = GetDWARFCompileUnit(&comp_unit); if (dwarf_cu) return dwarf_cu->GetNonSkeletonUnit().GetIsOptimized(); return false; } bool SymbolFileDWARF::ParseImportedModules( const lldb_private::SymbolContext &sc, std::vector<SourceModule> &imported_modules) { std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); assert(sc.comp_unit); DWARFUnit *dwarf_cu = GetDWARFCompileUnit(sc.comp_unit); if (!dwarf_cu) return false; auto lang = sc.comp_unit->GetLanguage(); if (!ClangModulesDeclVendor::LanguageSupportsClangModules(lang) && lang != eLanguageTypeSwift) return false; UpdateExternalModuleListIfNeeded(); const DWARFDIE die = dwarf_cu->DIE(); if (!die) return false; for (DWARFDIE child_die : die.children()) { if (child_die.Tag() != DW_TAG_imported_declaration && child_die.Tag() != DW_TAG_imported_module) continue; DWARFDIE module_die = child_die.GetReferencedDIE(DW_AT_import); if (module_die.Tag() != DW_TAG_module) continue; if (const char *name = module_die.GetAttributeValueAsString(DW_AT_name, nullptr)) { SourceModule module; module.path.push_back(ConstString(name)); DWARFDIE parent_die = module_die; while ((parent_die = parent_die.GetParent())) { if (parent_die.Tag() != DW_TAG_module) break; if (const char *name = parent_die.GetAttributeValueAsString(DW_AT_name, nullptr)) module.path.push_back(ConstString(name)); } std::reverse(module.path.begin(), module.path.end()); if (const char *include_path = module_die.GetAttributeValueAsString( DW_AT_LLVM_include_path, nullptr)) { FileSpec include_spec(include_path, dwarf_cu->GetPathStyle()); MakeAbsoluteAndRemap(include_spec, *dwarf_cu, m_objfile_sp->GetModule()); module.search_path = ConstString(include_spec.GetPath()); } if (const char *sysroot = dwarf_cu->DIE().GetAttributeValueAsString( DW_AT_LLVM_sysroot, nullptr)) module.sysroot = ConstString(sysroot); imported_modules.push_back(module); } } return true; } bool SymbolFileDWARF::ParseLineTable(CompileUnit &comp_unit) { std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); if (comp_unit.GetLineTable() != nullptr) return true; DWARFUnit *dwarf_cu = GetDWARFCompileUnit(&comp_unit); if (!dwarf_cu) return false; dw_offset_t offset = dwarf_cu->GetLineTableOffset(); if (offset == DW_INVALID_OFFSET) return false; llvm::DWARFDebugLine line; const llvm::DWARFDebugLine::LineTable *line_table = ParseLLVMLineTable(m_context, line, offset, dwarf_cu->GetOffset()); if (!line_table) return false; // FIXME: Rather than parsing the whole line table and then copying it over // into LLDB, we should explore using a callback to populate the line table // while we parse to reduce memory usage. std::vector<std::unique_ptr<LineSequence>> sequences; // The Sequences view contains only valid line sequences. Don't iterate over // the Rows directly. for (const llvm::DWARFDebugLine::Sequence &seq : line_table->Sequences) { std::unique_ptr<LineSequence> sequence = LineTable::CreateLineSequenceContainer(); for (unsigned idx = seq.FirstRowIndex; idx < seq.LastRowIndex; ++idx) { const llvm::DWARFDebugLine::Row &row = line_table->Rows[idx]; LineTable::AppendLineEntryToSequence( sequence.get(), row.Address.Address, row.Line, row.Column, row.File, row.IsStmt, row.BasicBlock, row.PrologueEnd, row.EpilogueBegin, row.EndSequence); } sequences.push_back(std::move(sequence)); } std::unique_ptr<LineTable> line_table_up = std::make_unique<LineTable>(&comp_unit, std::move(sequences)); if (SymbolFileDWARFDebugMap *debug_map_symfile = GetDebugMapSymfile()) { // We have an object file that has a line table with addresses that are not // linked. We need to link the line table and convert the addresses that // are relative to the .o file into addresses for the main executable. comp_unit.SetLineTable( debug_map_symfile->LinkOSOLineTable(this, line_table_up.get())); } else { comp_unit.SetLineTable(line_table_up.release()); } return true; } lldb_private::DebugMacrosSP SymbolFileDWARF::ParseDebugMacros(lldb::offset_t *offset) { auto iter = m_debug_macros_map.find(*offset); if (iter != m_debug_macros_map.end()) return iter->second; const DWARFDataExtractor &debug_macro_data = m_context.getOrLoadMacroData(); if (debug_macro_data.GetByteSize() == 0) return DebugMacrosSP(); lldb_private::DebugMacrosSP debug_macros_sp(new lldb_private::DebugMacros()); m_debug_macros_map[*offset] = debug_macros_sp; const DWARFDebugMacroHeader &header = DWARFDebugMacroHeader::ParseHeader(debug_macro_data, offset); DWARFDebugMacroEntry::ReadMacroEntries( debug_macro_data, m_context.getOrLoadStrData(), header.OffsetIs64Bit(), offset, this, debug_macros_sp); return debug_macros_sp; } bool SymbolFileDWARF::ParseDebugMacros(CompileUnit &comp_unit) { std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); DWARFUnit *dwarf_cu = GetDWARFCompileUnit(&comp_unit); if (dwarf_cu == nullptr) return false; const DWARFBaseDIE dwarf_cu_die = dwarf_cu->GetUnitDIEOnly(); if (!dwarf_cu_die) return false; lldb::offset_t sect_offset = dwarf_cu_die.GetAttributeValueAsUnsigned(DW_AT_macros, DW_INVALID_OFFSET); if (sect_offset == DW_INVALID_OFFSET) sect_offset = dwarf_cu_die.GetAttributeValueAsUnsigned(DW_AT_GNU_macros, DW_INVALID_OFFSET); if (sect_offset == DW_INVALID_OFFSET) return false; comp_unit.SetDebugMacros(ParseDebugMacros(&sect_offset)); return true; } size_t SymbolFileDWARF::ParseBlocksRecursive( lldb_private::CompileUnit &comp_unit, Block *parent_block, const DWARFDIE &orig_die, addr_t subprogram_low_pc, uint32_t depth) { size_t blocks_added = 0; DWARFDIE die = orig_die; while (die) { dw_tag_t tag = die.Tag(); switch (tag) { case DW_TAG_inlined_subroutine: case DW_TAG_subprogram: case DW_TAG_lexical_block: { Block *block = nullptr; if (tag == DW_TAG_subprogram) { // Skip any DW_TAG_subprogram DIEs that are inside of a normal or // inlined functions. These will be parsed on their own as separate // entities. if (depth > 0) break; block = parent_block; } else { BlockSP block_sp(new Block(die.GetID())); parent_block->AddChild(block_sp); block = block_sp.get(); } DWARFRangeList ranges; const char *name = nullptr; const char *mangled_name = nullptr; int decl_file = 0; int decl_line = 0; int decl_column = 0; int call_file = 0; int call_line = 0; int call_column = 0; if (die.GetDIENamesAndRanges(name, mangled_name, ranges, decl_file, decl_line, decl_column, call_file, call_line, call_column, nullptr)) { if (tag == DW_TAG_subprogram) { assert(subprogram_low_pc == LLDB_INVALID_ADDRESS); subprogram_low_pc = ranges.GetMinRangeBase(0); } else if (tag == DW_TAG_inlined_subroutine) { // We get called here for inlined subroutines in two ways. The first // time is when we are making the Function object for this inlined // concrete instance. Since we're creating a top level block at // here, the subprogram_low_pc will be LLDB_INVALID_ADDRESS. So we // need to adjust the containing address. The second time is when we // are parsing the blocks inside the function that contains the // inlined concrete instance. Since these will be blocks inside the // containing "real" function the offset will be for that function. if (subprogram_low_pc == LLDB_INVALID_ADDRESS) { subprogram_low_pc = ranges.GetMinRangeBase(0); } } const size_t num_ranges = ranges.GetSize(); for (size_t i = 0; i < num_ranges; ++i) { const DWARFRangeList::Entry &range = ranges.GetEntryRef(i); const addr_t range_base = range.GetRangeBase(); if (range_base >= subprogram_low_pc) block->AddRange(Block::Range(range_base - subprogram_low_pc, range.GetByteSize())); else { GetObjectFile()->GetModule()->ReportError( "0x%8.8" PRIx64 ": adding range [0x%" PRIx64 "-0x%" PRIx64 ") which has a base that is less than the function's low PC " "0x%" PRIx64 ". Please file a bug and attach the file at the " "start of this error message", block->GetID(), range_base, range.GetRangeEnd(), subprogram_low_pc); } } block->FinalizeRanges(); if (tag != DW_TAG_subprogram && (name != nullptr || mangled_name != nullptr)) { std::unique_ptr<Declaration> decl_up; if (decl_file != 0 || decl_line != 0 || decl_column != 0) decl_up = std::make_unique<Declaration>( comp_unit.GetSupportFiles().GetFileSpecAtIndex(decl_file), decl_line, decl_column); std::unique_ptr<Declaration> call_up; if (call_file != 0 || call_line != 0 || call_column != 0) call_up = std::make_unique<Declaration>( comp_unit.GetSupportFiles().GetFileSpecAtIndex(call_file), call_line, call_column); block->SetInlinedFunctionInfo(name, mangled_name, decl_up.get(), call_up.get()); } ++blocks_added; if (die.HasChildren()) { blocks_added += ParseBlocksRecursive(comp_unit, block, die.GetFirstChild(), subprogram_low_pc, depth + 1); } } } break; default: break; } // Only parse siblings of the block if we are not at depth zero. A depth of // zero indicates we are currently parsing the top level DW_TAG_subprogram // DIE if (depth == 0) die.Clear(); else die = die.GetSibling(); } return blocks_added; } bool SymbolFileDWARF::ClassOrStructIsVirtual(const DWARFDIE &parent_die) { if (parent_die) { for (DWARFDIE die : parent_die.children()) { dw_tag_t tag = die.Tag(); bool check_virtuality = false; switch (tag) { case DW_TAG_inheritance: case DW_TAG_subprogram: check_virtuality = true; break; default: break; } if (check_virtuality) { if (die.GetAttributeValueAsUnsigned(DW_AT_virtuality, 0) != 0) return true; } } } return false; } void SymbolFileDWARF::ParseDeclsForContext(CompilerDeclContext decl_ctx) { auto *type_system = decl_ctx.GetTypeSystem(); if (type_system != nullptr) type_system->GetDWARFParser()->EnsureAllDIEsInDeclContextHaveBeenParsed( decl_ctx); } user_id_t SymbolFileDWARF::GetUID(DIERef ref) { if (GetDebugMapSymfile()) return GetID() | ref.die_offset(); lldbassert(GetDwoNum().getValueOr(0) <= 0x3fffffff); return user_id_t(GetDwoNum().getValueOr(0)) << 32 | ref.die_offset() | lldb::user_id_t(GetDwoNum().hasValue()) << 62 | lldb::user_id_t(ref.section() == DIERef::Section::DebugTypes) << 63; } llvm::Optional<SymbolFileDWARF::DecodedUID> SymbolFileDWARF::DecodeUID(lldb::user_id_t uid) { // This method can be called without going through the symbol vendor so we // need to lock the module. std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); // Anytime we get a "lldb::user_id_t" from an lldb_private::SymbolFile API we // must make sure we use the correct DWARF file when resolving things. On // MacOSX, when using SymbolFileDWARFDebugMap, we will use multiple // SymbolFileDWARF classes, one for each .o file. We can often end up with // references to other DWARF objects and we must be ready to receive a // "lldb::user_id_t" that specifies a DIE from another SymbolFileDWARF // instance. if (SymbolFileDWARFDebugMap *debug_map = GetDebugMapSymfile()) { SymbolFileDWARF *dwarf = debug_map->GetSymbolFileByOSOIndex( debug_map->GetOSOIndexFromUserID(uid)); return DecodedUID{ *dwarf, {llvm::None, DIERef::Section::DebugInfo, dw_offset_t(uid)}}; } dw_offset_t die_offset = uid; if (die_offset == DW_INVALID_OFFSET) return llvm::None; DIERef::Section section = uid >> 63 ? DIERef::Section::DebugTypes : DIERef::Section::DebugInfo; llvm::Optional<uint32_t> dwo_num; bool dwo_valid = uid >> 62 & 1; if (dwo_valid) dwo_num = uid >> 32 & 0x3fffffff; return DecodedUID{*this, {dwo_num, section, die_offset}}; } DWARFDIE SymbolFileDWARF::GetDIE(lldb::user_id_t uid) { // This method can be called without going through the symbol vendor so we // need to lock the module. std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); llvm::Optional<DecodedUID> decoded = DecodeUID(uid); if (decoded) return decoded->dwarf.GetDIE(decoded->ref); return DWARFDIE(); } CompilerDecl SymbolFileDWARF::GetDeclForUID(lldb::user_id_t type_uid) { // This method can be called without going through the symbol vendor so we // need to lock the module. std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); // Anytime we have a lldb::user_id_t, we must get the DIE by calling // SymbolFileDWARF::GetDIE(). See comments inside the // SymbolFileDWARF::GetDIE() for details. if (DWARFDIE die = GetDIE(type_uid)) return GetDecl(die); return CompilerDecl(); } CompilerDeclContext SymbolFileDWARF::GetDeclContextForUID(lldb::user_id_t type_uid) { // This method can be called without going through the symbol vendor so we // need to lock the module. std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); // Anytime we have a lldb::user_id_t, we must get the DIE by calling // SymbolFileDWARF::GetDIE(). See comments inside the // SymbolFileDWARF::GetDIE() for details. if (DWARFDIE die = GetDIE(type_uid)) return GetDeclContext(die); return CompilerDeclContext(); } CompilerDeclContext SymbolFileDWARF::GetDeclContextContainingUID(lldb::user_id_t type_uid) { std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); // Anytime we have a lldb::user_id_t, we must get the DIE by calling // SymbolFileDWARF::GetDIE(). See comments inside the // SymbolFileDWARF::GetDIE() for details. if (DWARFDIE die = GetDIE(type_uid)) return GetContainingDeclContext(die); return CompilerDeclContext(); } void SymbolFileDWARF::GetDeclContextForUID( llvm::SmallVectorImpl<CompilerContext> &context, lldb::user_id_t type_uid) { if (DWARFDIE die = GetDIE(type_uid)) return die.GetDeclContext(context); } Type *SymbolFileDWARF::ResolveTypeUID(lldb::user_id_t type_uid) { std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); // Anytime we have a lldb::user_id_t, we must get the DIE by calling // SymbolFileDWARF::GetDIE(). See comments inside the // SymbolFileDWARF::GetDIE() for details. if (DWARFDIE type_die = GetDIE(type_uid)) return type_die.ResolveType(); else return nullptr; } llvm::Optional<SymbolFile::ArrayInfo> SymbolFileDWARF::GetDynamicArrayInfoForUID( lldb::user_id_t type_uid, const lldb_private::ExecutionContext *exe_ctx) { std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); if (DWARFDIE type_die = GetDIE(type_uid)) return DWARFASTParser::ParseChildArrayInfo(type_die, exe_ctx); else return llvm::None; } Type *SymbolFileDWARF::ResolveTypeUID(const DIERef &die_ref) { return ResolveType(GetDIE(die_ref), true); } Type *SymbolFileDWARF::ResolveTypeUID(const DWARFDIE &die, bool assert_not_being_parsed) { if (die) { Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO)); if (log) GetObjectFile()->GetModule()->LogMessage( log, "SymbolFileDWARF::ResolveTypeUID (die = 0x%8.8x) %s '%s'", die.GetOffset(), die.GetTagAsCString(), die.GetName()); // We might be coming in in the middle of a type tree (a class within a // class, an enum within a class), so parse any needed parent DIEs before // we get to this one... DWARFDIE decl_ctx_die = GetDeclContextDIEContainingDIE(die); if (decl_ctx_die) { if (log) { switch (decl_ctx_die.Tag()) { case DW_TAG_structure_type: case DW_TAG_union_type: case DW_TAG_class_type: { // Get the type, which could be a forward declaration if (log) GetObjectFile()->GetModule()->LogMessage( log, "SymbolFileDWARF::ResolveTypeUID (die = 0x%8.8x) %s '%s' " "resolve parent forward type for 0x%8.8x", die.GetOffset(), die.GetTagAsCString(), die.GetName(), decl_ctx_die.GetOffset()); } break; default: break; } } } return ResolveType(die); } return nullptr; } // This function is used when SymbolFileDWARFDebugMap owns a bunch of // SymbolFileDWARF objects to detect if this DWARF file is the one that can // resolve a compiler_type. bool SymbolFileDWARF::HasForwardDeclForClangType( const CompilerType &compiler_type) { CompilerType compiler_type_no_qualifiers = ClangUtil::RemoveFastQualifiers(compiler_type); if (GetForwardDeclClangTypeToDie().count( compiler_type_no_qualifiers.GetOpaqueQualType())) { return true; } TypeSystem *type_system = compiler_type.GetTypeSystem(); TypeSystemClang *clang_type_system = llvm::dyn_cast_or_null<TypeSystemClang>(type_system); if (!clang_type_system) return false; DWARFASTParserClang *ast_parser = static_cast<DWARFASTParserClang *>(clang_type_system->GetDWARFParser()); return ast_parser->GetClangASTImporter().CanImport(compiler_type); } bool SymbolFileDWARF::CompleteType(CompilerType &compiler_type) { std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); TypeSystemClang *clang_type_system = llvm::dyn_cast_or_null<TypeSystemClang>(compiler_type.GetTypeSystem()); if (clang_type_system) { DWARFASTParserClang *ast_parser = static_cast<DWARFASTParserClang *>(clang_type_system->GetDWARFParser()); if (ast_parser && ast_parser->GetClangASTImporter().CanImport(compiler_type)) return ast_parser->GetClangASTImporter().CompleteType(compiler_type); } // We have a struct/union/class/enum that needs to be fully resolved. CompilerType compiler_type_no_qualifiers = ClangUtil::RemoveFastQualifiers(compiler_type); auto die_it = GetForwardDeclClangTypeToDie().find( compiler_type_no_qualifiers.GetOpaqueQualType()); if (die_it == GetForwardDeclClangTypeToDie().end()) { // We have already resolved this type... return true; } DWARFDIE dwarf_die = GetDIE(die_it->getSecond()); if (dwarf_die) { // Once we start resolving this type, remove it from the forward // declaration map in case anyone child members or other types require this // type to get resolved. The type will get resolved when all of the calls // to SymbolFileDWARF::ResolveClangOpaqueTypeDefinition are done. GetForwardDeclClangTypeToDie().erase(die_it); Type *type = GetDIEToType().lookup(dwarf_die.GetDIE()); Log *log(LogChannelDWARF::GetLogIfAny(DWARF_LOG_DEBUG_INFO | DWARF_LOG_TYPE_COMPLETION)); if (log) GetObjectFile()->GetModule()->LogMessageVerboseBacktrace( log, "0x%8.8" PRIx64 ": %s '%s' resolving forward declaration...", dwarf_die.GetID(), dwarf_die.GetTagAsCString(), type->GetName().AsCString()); assert(compiler_type); if (DWARFASTParser *dwarf_ast = GetDWARFParser(*dwarf_die.GetCU())) return dwarf_ast->CompleteTypeFromDWARF(dwarf_die, type, compiler_type); } return false; } Type *SymbolFileDWARF::ResolveType(const DWARFDIE &die, bool assert_not_being_parsed, bool resolve_function_context) { if (die) { Type *type = GetTypeForDIE(die, resolve_function_context).get(); if (assert_not_being_parsed) { if (type != DIE_IS_BEING_PARSED) return type; GetObjectFile()->GetModule()->ReportError( "Parsing a die that is being parsed die: 0x%8.8x: %s %s", die.GetOffset(), die.GetTagAsCString(), die.GetName()); } else return type; } return nullptr; } CompileUnit * SymbolFileDWARF::GetCompUnitForDWARFCompUnit(DWARFCompileUnit &dwarf_cu) { if (dwarf_cu.IsDWOUnit()) { DWARFCompileUnit *non_dwo_cu = static_cast<DWARFCompileUnit *>(dwarf_cu.GetUserData()); assert(non_dwo_cu); return non_dwo_cu->GetSymbolFileDWARF().GetCompUnitForDWARFCompUnit( *non_dwo_cu); } // Check if the symbol vendor already knows about this compile unit? if (dwarf_cu.GetUserData() == nullptr) { // The symbol vendor doesn't know about this compile unit, we need to parse // and add it to the symbol vendor object. return ParseCompileUnit(dwarf_cu).get(); } return static_cast<CompileUnit *>(dwarf_cu.GetUserData()); } void SymbolFileDWARF::GetObjCMethods( ConstString class_name, llvm::function_ref<bool(DWARFDIE die)> callback) { m_index->GetObjCMethods(class_name, callback); } bool SymbolFileDWARF::GetFunction(const DWARFDIE &die, SymbolContext &sc) { sc.Clear(false); if (die && llvm::isa<DWARFCompileUnit>(die.GetCU())) { // Check if the symbol vendor already knows about this compile unit? sc.comp_unit = GetCompUnitForDWARFCompUnit(llvm::cast<DWARFCompileUnit>(*die.GetCU())); sc.function = sc.comp_unit->FindFunctionByUID(die.GetID()).get(); if (sc.function == nullptr) sc.function = ParseFunction(*sc.comp_unit, die); if (sc.function) { sc.module_sp = sc.function->CalculateSymbolContextModule(); return true; } } return false; } lldb::ModuleSP SymbolFileDWARF::GetExternalModule(ConstString name) { UpdateExternalModuleListIfNeeded(); const auto &pos = m_external_type_modules.find(name); if (pos != m_external_type_modules.end()) return pos->second; else return lldb::ModuleSP(); } DWARFDIE SymbolFileDWARF::GetDIE(const DIERef &die_ref) { if (die_ref.dwo_num()) { SymbolFileDWARF *dwarf = *die_ref.dwo_num() == 0x3fffffff ? m_dwp_symfile.get() : this->DebugInfo() .GetUnitAtIndex(*die_ref.dwo_num()) ->GetDwoSymbolFile(); return dwarf->DebugInfo().GetDIE(die_ref); } return DebugInfo().GetDIE(die_ref); } /// Return the DW_AT_(GNU_)dwo_id. /// FIXME: Technically 0 is a valid hash. static uint64_t GetDWOId(DWARFCompileUnit &dwarf_cu, const DWARFDebugInfoEntry &cu_die) { uint64_t dwo_id = cu_die.GetAttributeValueAsUnsigned(&dwarf_cu, DW_AT_GNU_dwo_id, 0); if (!dwo_id) dwo_id = cu_die.GetAttributeValueAsUnsigned(&dwarf_cu, DW_AT_dwo_id, 0); return dwo_id; } llvm::Optional<uint64_t> SymbolFileDWARF::GetDWOId() { if (GetNumCompileUnits() == 1) { if (auto comp_unit = GetCompileUnitAtIndex(0)) if (DWARFCompileUnit *cu = GetDWARFCompileUnit(comp_unit.get())) if (DWARFDebugInfoEntry *cu_die = cu->DIE().GetDIE()) if (uint64_t dwo_id = ::GetDWOId(*cu, *cu_die)) return dwo_id; } return {}; } std::shared_ptr<SymbolFileDWARFDwo> SymbolFileDWARF::GetDwoSymbolFileForCompileUnit( DWARFUnit &unit, const DWARFDebugInfoEntry &cu_die) { // If this is a Darwin-style debug map (non-.dSYM) symbol file, // never attempt to load ELF-style DWO files since the -gmodules // support uses the same DWO machanism to specify full debug info // files for modules. This is handled in // UpdateExternalModuleListIfNeeded(). if (GetDebugMapSymfile()) return nullptr; DWARFCompileUnit *dwarf_cu = llvm::dyn_cast<DWARFCompileUnit>(&unit); // Only compile units can be split into two parts. if (!dwarf_cu) return nullptr; const char *dwo_name = GetDWOName(*dwarf_cu, cu_die); if (!dwo_name) return nullptr; if (std::shared_ptr<SymbolFileDWARFDwo> dwp_sp = GetDwpSymbolFile()) return dwp_sp; FileSpec dwo_file(dwo_name); FileSystem::Instance().Resolve(dwo_file); if (dwo_file.IsRelative()) { const char *comp_dir = cu_die.GetAttributeValueAsString(dwarf_cu, DW_AT_comp_dir, nullptr); if (!comp_dir) return nullptr; dwo_file.SetFile(comp_dir, FileSpec::Style::native); if (dwo_file.IsRelative()) { // if DW_AT_comp_dir is relative, it should be relative to the location // of the executable, not to the location from which the debugger was // launched. dwo_file.PrependPathComponent( m_objfile_sp->GetFileSpec().GetDirectory().GetStringRef()); } FileSystem::Instance().Resolve(dwo_file); dwo_file.AppendPathComponent(dwo_name); } if (!FileSystem::Instance().Exists(dwo_file)) return nullptr; const lldb::offset_t file_offset = 0; DataBufferSP dwo_file_data_sp; lldb::offset_t dwo_file_data_offset = 0; ObjectFileSP dwo_obj_file = ObjectFile::FindPlugin( GetObjectFile()->GetModule(), &dwo_file, file_offset, FileSystem::Instance().GetByteSize(dwo_file), dwo_file_data_sp, dwo_file_data_offset); if (dwo_obj_file == nullptr) return nullptr; return std::make_shared<SymbolFileDWARFDwo>(*this, dwo_obj_file, dwarf_cu->GetID()); } void SymbolFileDWARF::UpdateExternalModuleListIfNeeded() { if (m_fetched_external_modules) return; m_fetched_external_modules = true; DWARFDebugInfo &debug_info = DebugInfo(); // Follow DWO skeleton unit breadcrumbs. const uint32_t num_compile_units = GetNumCompileUnits(); for (uint32_t cu_idx = 0; cu_idx < num_compile_units; ++cu_idx) { auto *dwarf_cu = llvm::dyn_cast<DWARFCompileUnit>(debug_info.GetUnitAtIndex(cu_idx)); if (!dwarf_cu) continue; const DWARFBaseDIE die = dwarf_cu->GetUnitDIEOnly(); if (!die || die.HasChildren() || !die.GetDIE()) continue; const char *name = die.GetAttributeValueAsString(DW_AT_name, nullptr); if (!name) continue; ConstString const_name(name); ModuleSP &module_sp = m_external_type_modules[const_name]; if (module_sp) continue; const char *dwo_path = GetDWOName(*dwarf_cu, *die.GetDIE()); if (!dwo_path) continue; ModuleSpec dwo_module_spec; dwo_module_spec.GetFileSpec().SetFile(dwo_path, FileSpec::Style::native); if (dwo_module_spec.GetFileSpec().IsRelative()) { const char *comp_dir = die.GetAttributeValueAsString(DW_AT_comp_dir, nullptr); if (comp_dir) { dwo_module_spec.GetFileSpec().SetFile(comp_dir, FileSpec::Style::native); FileSystem::Instance().Resolve(dwo_module_spec.GetFileSpec()); dwo_module_spec.GetFileSpec().AppendPathComponent(dwo_path); } } dwo_module_spec.GetArchitecture() = m_objfile_sp->GetModule()->GetArchitecture(); // When LLDB loads "external" modules it looks at the presence of // DW_AT_dwo_name. However, when the already created module // (corresponding to .dwo itself) is being processed, it will see // the presence of DW_AT_dwo_name (which contains the name of dwo // file) and will try to call ModuleList::GetSharedModule // again. In some cases (i.e., for empty files) Clang 4.0 // generates a *.dwo file which has DW_AT_dwo_name, but no // DW_AT_comp_dir. In this case the method // ModuleList::GetSharedModule will fail and the warning will be // printed. However, as one can notice in this case we don't // actually need to try to load the already loaded module // (corresponding to .dwo) so we simply skip it. if (m_objfile_sp->GetFileSpec().GetFileNameExtension() == ".dwo" && llvm::StringRef(m_objfile_sp->GetFileSpec().GetPath()) .endswith(dwo_module_spec.GetFileSpec().GetPath())) { continue; } Status error = ModuleList::GetSharedModule(dwo_module_spec, module_sp, nullptr, nullptr, nullptr); if (!module_sp) { GetObjectFile()->GetModule()->ReportWarning( "0x%8.8x: unable to locate module needed for external types: " "%s\nerror: %s\nDebugging will be degraded due to missing " "types. Rebuilding the project will regenerate the needed " "module files.", die.GetOffset(), dwo_module_spec.GetFileSpec().GetPath().c_str(), error.AsCString("unknown error")); continue; } // Verify the DWO hash. // FIXME: Technically "0" is a valid hash. uint64_t dwo_id = ::GetDWOId(*dwarf_cu, *die.GetDIE()); if (!dwo_id) continue; auto *dwo_symfile = llvm::dyn_cast_or_null<SymbolFileDWARF>(module_sp->GetSymbolFile()); if (!dwo_symfile) continue; llvm::Optional<uint64_t> dwo_dwo_id = dwo_symfile->GetDWOId(); if (!dwo_dwo_id) continue; if (dwo_id != dwo_dwo_id) { GetObjectFile()->GetModule()->ReportWarning( "0x%8.8x: Module %s is out-of-date (hash mismatch). Type information " "from this module may be incomplete or inconsistent with the rest of " "the program. Rebuilding the project will regenerate the needed " "module files.", die.GetOffset(), dwo_module_spec.GetFileSpec().GetPath().c_str()); } } } SymbolFileDWARF::GlobalVariableMap &SymbolFileDWARF::GetGlobalAranges() { if (!m_global_aranges_up) { m_global_aranges_up = std::make_unique<GlobalVariableMap>(); ModuleSP module_sp = GetObjectFile()->GetModule(); if (module_sp) { const size_t num_cus = module_sp->GetNumCompileUnits(); for (size_t i = 0; i < num_cus; ++i) { CompUnitSP cu_sp = module_sp->GetCompileUnitAtIndex(i); if (cu_sp) { VariableListSP globals_sp = cu_sp->GetVariableList(true); if (globals_sp) { const size_t num_globals = globals_sp->GetSize(); for (size_t g = 0; g < num_globals; ++g) { VariableSP var_sp = globals_sp->GetVariableAtIndex(g); if (var_sp && !var_sp->GetLocationIsConstantValueData()) { const DWARFExpression &location = var_sp->LocationExpression(); Value location_result; Status error; if (location.Evaluate(nullptr, LLDB_INVALID_ADDRESS, nullptr, nullptr, location_result, &error)) { if (location_result.GetValueType() == Value::ValueType::FileAddress) { lldb::addr_t file_addr = location_result.GetScalar().ULongLong(); lldb::addr_t byte_size = 1; if (var_sp->GetType()) byte_size = var_sp->GetType()->GetByteSize(nullptr).getValueOr(0); m_global_aranges_up->Append(GlobalVariableMap::Entry( file_addr, byte_size, var_sp.get())); } } } } } } } } m_global_aranges_up->Sort(); } return *m_global_aranges_up; } void SymbolFileDWARF::ResolveFunctionAndBlock(lldb::addr_t file_vm_addr, bool lookup_block, SymbolContext &sc) { assert(sc.comp_unit); DWARFCompileUnit &cu = GetDWARFCompileUnit(sc.comp_unit)->GetNonSkeletonUnit(); DWARFDIE function_die = cu.LookupAddress(file_vm_addr); DWARFDIE block_die; if (function_die) { sc.function = sc.comp_unit->FindFunctionByUID(function_die.GetID()).get(); if (sc.function == nullptr) sc.function = ParseFunction(*sc.comp_unit, function_die); if (sc.function && lookup_block) block_die = function_die.LookupDeepestBlock(file_vm_addr); } if (!sc.function || ! lookup_block) return; Block &block = sc.function->GetBlock(true); if (block_die) sc.block = block.FindBlockByID(block_die.GetID()); else sc.block = block.FindBlockByID(function_die.GetID()); } uint32_t SymbolFileDWARF::ResolveSymbolContext(const Address &so_addr, SymbolContextItem resolve_scope, SymbolContext &sc) { std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); LLDB_SCOPED_TIMERF("SymbolFileDWARF::" "ResolveSymbolContext (so_addr = { " "section = %p, offset = 0x%" PRIx64 " }, resolve_scope = 0x%8.8x)", static_cast<void *>(so_addr.GetSection().get()), so_addr.GetOffset(), resolve_scope); uint32_t resolved = 0; if (resolve_scope & (eSymbolContextCompUnit | eSymbolContextFunction | eSymbolContextBlock | eSymbolContextLineEntry | eSymbolContextVariable)) { lldb::addr_t file_vm_addr = so_addr.GetFileAddress(); DWARFDebugInfo &debug_info = DebugInfo(); const DWARFDebugAranges &aranges = debug_info.GetCompileUnitAranges(); const dw_offset_t cu_offset = aranges.FindAddress(file_vm_addr); if (cu_offset == DW_INVALID_OFFSET) { // Global variables are not in the compile unit address ranges. The only // way to currently find global variables is to iterate over the // .debug_pubnames or the __apple_names table and find all items in there // that point to DW_TAG_variable DIEs and then find the address that // matches. if (resolve_scope & eSymbolContextVariable) { GlobalVariableMap &map = GetGlobalAranges(); const GlobalVariableMap::Entry *entry = map.FindEntryThatContains(file_vm_addr); if (entry && entry->data) { Variable *variable = entry->data; SymbolContextScope *scc = variable->GetSymbolContextScope(); if (scc) { scc->CalculateSymbolContext(&sc); sc.variable = variable; } return sc.GetResolvedMask(); } } } else { uint32_t cu_idx = DW_INVALID_INDEX; if (auto *dwarf_cu = llvm::dyn_cast_or_null<DWARFCompileUnit>( debug_info.GetUnitAtOffset(DIERef::Section::DebugInfo, cu_offset, &cu_idx))) { sc.comp_unit = GetCompUnitForDWARFCompUnit(*dwarf_cu); if (sc.comp_unit) { resolved |= eSymbolContextCompUnit; bool force_check_line_table = false; if (resolve_scope & (eSymbolContextFunction | eSymbolContextBlock)) { ResolveFunctionAndBlock(file_vm_addr, resolve_scope & eSymbolContextBlock, sc); if (sc.function) resolved |= eSymbolContextFunction; else { // We might have had a compile unit that had discontiguous address // ranges where the gaps are symbols that don't have any debug // info. Discontiguous compile unit address ranges should only // happen when there aren't other functions from other compile // units in these gaps. This helps keep the size of the aranges // down. force_check_line_table = true; } if (sc.block) resolved |= eSymbolContextBlock; } if ((resolve_scope & eSymbolContextLineEntry) || force_check_line_table) { LineTable *line_table = sc.comp_unit->GetLineTable(); if (line_table != nullptr) { // And address that makes it into this function should be in terms // of this debug file if there is no debug map, or it will be an // address in the .o file which needs to be fixed up to be in // terms of the debug map executable. Either way, calling // FixupAddress() will work for us. Address exe_so_addr(so_addr); if (FixupAddress(exe_so_addr)) { if (line_table->FindLineEntryByAddress(exe_so_addr, sc.line_entry)) { resolved |= eSymbolContextLineEntry; } } } } if (force_check_line_table && !(resolved & eSymbolContextLineEntry)) { // We might have had a compile unit that had discontiguous address // ranges where the gaps are symbols that don't have any debug info. // Discontiguous compile unit address ranges should only happen when // there aren't other functions from other compile units in these // gaps. This helps keep the size of the aranges down. sc.comp_unit = nullptr; resolved &= ~eSymbolContextCompUnit; } } else { GetObjectFile()->GetModule()->ReportWarning( "0x%8.8x: compile unit %u failed to create a valid " "lldb_private::CompileUnit class.", cu_offset, cu_idx); } } } } return resolved; } uint32_t SymbolFileDWARF::ResolveSymbolContext( const SourceLocationSpec &src_location_spec, SymbolContextItem resolve_scope, SymbolContextList &sc_list) { std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); const FileSpec &file_spec = src_location_spec.GetFileSpec(); const uint32_t line = src_location_spec.GetLine().getValueOr(0); const bool check_inlines = src_location_spec.GetCheckInlines(); const uint32_t prev_size = sc_list.GetSize(); if (resolve_scope & eSymbolContextCompUnit) { for (uint32_t cu_idx = 0, num_cus = GetNumCompileUnits(); cu_idx < num_cus; ++cu_idx) { CompileUnit *dc_cu = ParseCompileUnitAtIndex(cu_idx).get(); if (!dc_cu) continue; bool file_spec_matches_cu_file_spec = FileSpec::Match( src_location_spec.GetFileSpec(), dc_cu->GetPrimaryFile()); if (check_inlines || file_spec_matches_cu_file_spec) { SymbolContext sc(m_objfile_sp->GetModule()); sc.comp_unit = dc_cu; uint32_t file_idx = UINT32_MAX; // If we are looking for inline functions only and we don't find it // in the support files, we are done. if (check_inlines) { file_idx = sc.comp_unit->GetSupportFiles().FindFileIndex(1, file_spec, true); if (file_idx == UINT32_MAX) continue; } if (line != 0) { LineTable *line_table = sc.comp_unit->GetLineTable(); if (line_table != nullptr && line != 0) { // We will have already looked up the file index if we are // searching for inline entries. if (!check_inlines) file_idx = sc.comp_unit->GetSupportFiles().FindFileIndex( 1, file_spec, true); if (file_idx != UINT32_MAX) { uint32_t found_line; uint16_t found_column; uint32_t line_idx = line_table->FindLineEntryIndexByFileIndex( 0, file_idx, src_location_spec, &sc.line_entry); found_line = sc.line_entry.line; found_column = sc.line_entry.column; while (line_idx != UINT32_MAX) { sc.function = nullptr; sc.block = nullptr; if (resolve_scope & (eSymbolContextFunction | eSymbolContextBlock)) { const lldb::addr_t file_vm_addr = sc.line_entry.range.GetBaseAddress().GetFileAddress(); if (file_vm_addr != LLDB_INVALID_ADDRESS) { ResolveFunctionAndBlock( file_vm_addr, resolve_scope & eSymbolContextBlock, sc); } } SourceLocationSpec found_location_spec( file_spec, found_line, found_column, /*check_inlines=*/false, /*exact=*/true); sc_list.Append(sc); line_idx = line_table->FindLineEntryIndexByFileIndex( line_idx + 1, file_idx, found_location_spec, &sc.line_entry); } } } else if (file_spec_matches_cu_file_spec && !check_inlines) { // only append the context if we aren't looking for inline call // sites by file and line and if the file spec matches that of // the compile unit sc_list.Append(sc); } } else if (file_spec_matches_cu_file_spec && !check_inlines) { // only append the context if we aren't looking for inline call // sites by file and line and if the file spec matches that of // the compile unit sc_list.Append(sc); } if (!check_inlines) break; } } } return sc_list.GetSize() - prev_size; } void SymbolFileDWARF::PreloadSymbols() { std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); m_index->Preload(); } std::recursive_mutex &SymbolFileDWARF::GetModuleMutex() const { lldb::ModuleSP module_sp(m_debug_map_module_wp.lock()); if (module_sp) return module_sp->GetMutex(); return GetObjectFile()->GetModule()->GetMutex(); } bool SymbolFileDWARF::DeclContextMatchesThisSymbolFile( const lldb_private::CompilerDeclContext &decl_ctx) { if (!decl_ctx.IsValid()) { // Invalid namespace decl which means we aren't matching only things in // this symbol file, so return true to indicate it matches this symbol // file. return true; } TypeSystem *decl_ctx_type_system = decl_ctx.GetTypeSystem(); auto type_system_or_err = GetTypeSystemForLanguage( decl_ctx_type_system->GetMinimumLanguage(nullptr)); if (auto err = type_system_or_err.takeError()) { LLDB_LOG_ERROR(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_SYMBOLS), std::move(err), "Unable to match namespace decl using TypeSystem"); return false; } if (decl_ctx_type_system == &type_system_or_err.get()) return true; // The type systems match, return true // The namespace AST was valid, and it does not match... Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS)); if (log) GetObjectFile()->GetModule()->LogMessage( log, "Valid namespace does not match symbol file"); return false; } void SymbolFileDWARF::FindGlobalVariables( ConstString name, const CompilerDeclContext &parent_decl_ctx, uint32_t max_matches, VariableList &variables) { std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS)); if (log) GetObjectFile()->GetModule()->LogMessage( log, "SymbolFileDWARF::FindGlobalVariables (name=\"%s\", " "parent_decl_ctx=%p, max_matches=%u, variables)", name.GetCString(), static_cast<const void *>(&parent_decl_ctx), max_matches); if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx)) return; // Remember how many variables are in the list before we search. const uint32_t original_size = variables.GetSize(); llvm::StringRef basename; llvm::StringRef context; bool name_is_mangled = (bool)Mangled(name); if (!CPlusPlusLanguage::ExtractContextAndIdentifier(name.GetCString(), context, basename)) basename = name.GetStringRef(); // Loop invariant: Variables up to this index have been checked for context // matches. uint32_t pruned_idx = original_size; SymbolContext sc; m_index->GetGlobalVariables(ConstString(basename), [&](DWARFDIE die) { if (!sc.module_sp) sc.module_sp = m_objfile_sp->GetModule(); assert(sc.module_sp); if (die.Tag() != DW_TAG_variable) return true; auto *dwarf_cu = llvm::dyn_cast<DWARFCompileUnit>(die.GetCU()); if (!dwarf_cu) return true; sc.comp_unit = GetCompUnitForDWARFCompUnit(*dwarf_cu); if (parent_decl_ctx) { if (DWARFASTParser *dwarf_ast = GetDWARFParser(*die.GetCU())) { CompilerDeclContext actual_parent_decl_ctx = dwarf_ast->GetDeclContextContainingUIDFromDWARF(die); if (!actual_parent_decl_ctx || actual_parent_decl_ctx != parent_decl_ctx) return true; } } ParseVariables(sc, die, LLDB_INVALID_ADDRESS, false, false, &variables); while (pruned_idx < variables.GetSize()) { VariableSP var_sp = variables.GetVariableAtIndex(pruned_idx); if (name_is_mangled || var_sp->GetName().GetStringRef().contains(name.GetStringRef())) ++pruned_idx; else variables.RemoveVariableAtIndex(pruned_idx); } return variables.GetSize() - original_size < max_matches; }); // Return the number of variable that were appended to the list const uint32_t num_matches = variables.GetSize() - original_size; if (log && num_matches > 0) { GetObjectFile()->GetModule()->LogMessage( log, "SymbolFileDWARF::FindGlobalVariables (name=\"%s\", " "parent_decl_ctx=%p, max_matches=%u, variables) => %u", name.GetCString(), static_cast<const void *>(&parent_decl_ctx), max_matches, num_matches); } } void SymbolFileDWARF::FindGlobalVariables(const RegularExpression &regex, uint32_t max_matches, VariableList &variables) { std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS)); if (log) { GetObjectFile()->GetModule()->LogMessage( log, "SymbolFileDWARF::FindGlobalVariables (regex=\"%s\", " "max_matches=%u, variables)", regex.GetText().str().c_str(), max_matches); } // Remember how many variables are in the list before we search. const uint32_t original_size = variables.GetSize(); SymbolContext sc; m_index->GetGlobalVariables(regex, [&](DWARFDIE die) { if (!sc.module_sp) sc.module_sp = m_objfile_sp->GetModule(); assert(sc.module_sp); DWARFCompileUnit *dwarf_cu = llvm::dyn_cast<DWARFCompileUnit>(die.GetCU()); if (!dwarf_cu) return true; sc.comp_unit = GetCompUnitForDWARFCompUnit(*dwarf_cu); ParseVariables(sc, die, LLDB_INVALID_ADDRESS, false, false, &variables); return variables.GetSize() - original_size < max_matches; }); } bool SymbolFileDWARF::ResolveFunction(const DWARFDIE &orig_die, bool include_inlines, SymbolContextList &sc_list) { SymbolContext sc; if (!orig_die) return false; // If we were passed a die that is not a function, just return false... if (!(orig_die.Tag() == DW_TAG_subprogram || (include_inlines && orig_die.Tag() == DW_TAG_inlined_subroutine))) return false; DWARFDIE die = orig_die; DWARFDIE inlined_die; if (die.Tag() == DW_TAG_inlined_subroutine) { inlined_die = die; while (true) { die = die.GetParent(); if (die) { if (die.Tag() == DW_TAG_subprogram) break; } else break; } } assert(die && die.Tag() == DW_TAG_subprogram); if (GetFunction(die, sc)) { Address addr; // Parse all blocks if needed if (inlined_die) { Block &function_block = sc.function->GetBlock(true); sc.block = function_block.FindBlockByID(inlined_die.GetID()); if (sc.block == nullptr) sc.block = function_block.FindBlockByID(inlined_die.GetOffset()); if (sc.block == nullptr || !sc.block->GetStartAddress(addr)) addr.Clear(); } else { sc.block = nullptr; addr = sc.function->GetAddressRange().GetBaseAddress(); } if (auto section_sp = addr.GetSection()) { if (section_sp->GetPermissions() & ePermissionsExecutable) { sc_list.Append(sc); return true; } } } return false; } bool SymbolFileDWARF::DIEInDeclContext(const CompilerDeclContext &decl_ctx, const DWARFDIE &die) { // If we have no parent decl context to match this DIE matches, and if the // parent decl context isn't valid, we aren't trying to look for any // particular decl context so any die matches. if (!decl_ctx.IsValid()) return true; if (die) { if (DWARFASTParser *dwarf_ast = GetDWARFParser(*die.GetCU())) { if (CompilerDeclContext actual_decl_ctx = dwarf_ast->GetDeclContextContainingUIDFromDWARF(die)) return decl_ctx.IsContainedInLookup(actual_decl_ctx); } } return false; } void SymbolFileDWARF::FindFunctions(ConstString name, const CompilerDeclContext &parent_decl_ctx, FunctionNameType name_type_mask, bool include_inlines, SymbolContextList &sc_list) { std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); LLDB_SCOPED_TIMERF("SymbolFileDWARF::FindFunctions (name = '%s')", name.AsCString()); // eFunctionNameTypeAuto should be pre-resolved by a call to // Module::LookupInfo::LookupInfo() assert((name_type_mask & eFunctionNameTypeAuto) == 0); Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS)); if (log) { GetObjectFile()->GetModule()->LogMessage( log, "SymbolFileDWARF::FindFunctions (name=\"%s\", name_type_mask=0x%x, sc_list)", name.GetCString(), name_type_mask); } if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx)) return; // If name is empty then we won't find anything. if (name.IsEmpty()) return; // Remember how many sc_list are in the list before we search in case we are // appending the results to a variable list. const uint32_t original_size = sc_list.GetSize(); llvm::DenseSet<const DWARFDebugInfoEntry *> resolved_dies; m_index->GetFunctions(name, *this, parent_decl_ctx, name_type_mask, [&](DWARFDIE die) { if (resolved_dies.insert(die.GetDIE()).second) ResolveFunction(die, include_inlines, sc_list); return true; }); // Return the number of variable that were appended to the list const uint32_t num_matches = sc_list.GetSize() - original_size; if (log && num_matches > 0) { GetObjectFile()->GetModule()->LogMessage( log, "SymbolFileDWARF::FindFunctions (name=\"%s\", " "name_type_mask=0x%x, include_inlines=%d, sc_list) => %u", name.GetCString(), name_type_mask, include_inlines, num_matches); } } void SymbolFileDWARF::FindFunctions(const RegularExpression &regex, bool include_inlines, SymbolContextList &sc_list) { std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); LLDB_SCOPED_TIMERF("SymbolFileDWARF::FindFunctions (regex = '%s')", regex.GetText().str().c_str()); Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS)); if (log) { GetObjectFile()->GetModule()->LogMessage( log, "SymbolFileDWARF::FindFunctions (regex=\"%s\", sc_list)", regex.GetText().str().c_str()); } llvm::DenseSet<const DWARFDebugInfoEntry *> resolved_dies; m_index->GetFunctions(regex, [&](DWARFDIE die) { if (resolved_dies.insert(die.GetDIE()).second) ResolveFunction(die, include_inlines, sc_list); return true; }); } void SymbolFileDWARF::GetMangledNamesForFunction( const std::string &scope_qualified_name, std::vector<ConstString> &mangled_names) { DWARFDebugInfo &info = DebugInfo(); uint32_t num_comp_units = info.GetNumUnits(); for (uint32_t i = 0; i < num_comp_units; i++) { DWARFUnit *cu = info.GetUnitAtIndex(i); if (cu == nullptr) continue; SymbolFileDWARFDwo *dwo = cu->GetDwoSymbolFile(); if (dwo) dwo->GetMangledNamesForFunction(scope_qualified_name, mangled_names); } for (DIERef die_ref : m_function_scope_qualified_name_map.lookup(scope_qualified_name)) { DWARFDIE die = GetDIE(die_ref); mangled_names.push_back(ConstString(die.GetMangledName())); } } void SymbolFileDWARF::FindTypes( ConstString name, const CompilerDeclContext &parent_decl_ctx, uint32_t max_matches, llvm::DenseSet<lldb_private::SymbolFile *> &searched_symbol_files, TypeMap &types) { std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); // Make sure we haven't already searched this SymbolFile before. if (!searched_symbol_files.insert(this).second) return; Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS)); if (log) { if (parent_decl_ctx) GetObjectFile()->GetModule()->LogMessage( log, "SymbolFileDWARF::FindTypes (sc, name=\"%s\", parent_decl_ctx = " "%p (\"%s\"), max_matches=%u, type_list)", name.GetCString(), static_cast<const void *>(&parent_decl_ctx), parent_decl_ctx.GetName().AsCString("<NULL>"), max_matches); else GetObjectFile()->GetModule()->LogMessage( log, "SymbolFileDWARF::FindTypes (sc, name=\"%s\", parent_decl_ctx = " "NULL, max_matches=%u, type_list)", name.GetCString(), max_matches); } if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx)) return; m_index->GetTypes(name, [&](DWARFDIE die) { if (!DIEInDeclContext(parent_decl_ctx, die)) return true; // The containing decl contexts don't match Type *matching_type = ResolveType(die, true, true); if (!matching_type) return true; // We found a type pointer, now find the shared pointer form our type // list types.InsertUnique(matching_type->shared_from_this()); return types.GetSize() < max_matches; }); // Next search through the reachable Clang modules. This only applies for // DWARF objects compiled with -gmodules that haven't been processed by // dsymutil. if (types.GetSize() < max_matches) { UpdateExternalModuleListIfNeeded(); for (const auto &pair : m_external_type_modules) if (ModuleSP external_module_sp = pair.second) if (SymbolFile *sym_file = external_module_sp->GetSymbolFile()) sym_file->FindTypes(name, parent_decl_ctx, max_matches, searched_symbol_files, types); } if (log && types.GetSize()) { if (parent_decl_ctx) { GetObjectFile()->GetModule()->LogMessage( log, "SymbolFileDWARF::FindTypes (sc, name=\"%s\", parent_decl_ctx " "= %p (\"%s\"), max_matches=%u, type_list) => %u", name.GetCString(), static_cast<const void *>(&parent_decl_ctx), parent_decl_ctx.GetName().AsCString("<NULL>"), max_matches, types.GetSize()); } else { GetObjectFile()->GetModule()->LogMessage( log, "SymbolFileDWARF::FindTypes (sc, name=\"%s\", parent_decl_ctx " "= NULL, max_matches=%u, type_list) => %u", name.GetCString(), max_matches, types.GetSize()); } } } void SymbolFileDWARF::FindTypes( llvm::ArrayRef<CompilerContext> pattern, LanguageSet languages, llvm::DenseSet<SymbolFile *> &searched_symbol_files, TypeMap &types) { // Make sure we haven't already searched this SymbolFile before. if (!searched_symbol_files.insert(this).second) return; std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); if (pattern.empty()) return; ConstString name = pattern.back().name; if (!name) return; m_index->GetTypes(name, [&](DWARFDIE die) { if (!languages[GetLanguageFamily(*die.GetCU())]) return true; llvm::SmallVector<CompilerContext, 4> die_context; die.GetDeclContext(die_context); if (!contextMatches(die_context, pattern)) return true; if (Type *matching_type = ResolveType(die, true, true)) { // We found a type pointer, now find the shared pointer form our type // list. types.InsertUnique(matching_type->shared_from_this()); } return true; }); // Next search through the reachable Clang modules. This only applies for // DWARF objects compiled with -gmodules that haven't been processed by // dsymutil. UpdateExternalModuleListIfNeeded(); for (const auto &pair : m_external_type_modules) if (ModuleSP external_module_sp = pair.second) external_module_sp->FindTypes(pattern, languages, searched_symbol_files, types); } CompilerDeclContext SymbolFileDWARF::FindNamespace(ConstString name, const CompilerDeclContext &parent_decl_ctx) { std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS)); if (log) { GetObjectFile()->GetModule()->LogMessage( log, "SymbolFileDWARF::FindNamespace (sc, name=\"%s\")", name.GetCString()); } CompilerDeclContext namespace_decl_ctx; if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx)) return namespace_decl_ctx; m_index->GetNamespaces(name, [&](DWARFDIE die) { if (!DIEInDeclContext(parent_decl_ctx, die)) return true; // The containing decl contexts don't match DWARFASTParser *dwarf_ast = GetDWARFParser(*die.GetCU()); if (!dwarf_ast) return true; namespace_decl_ctx = dwarf_ast->GetDeclContextForUIDFromDWARF(die); return !namespace_decl_ctx.IsValid(); }); if (log && namespace_decl_ctx) { GetObjectFile()->GetModule()->LogMessage( log, "SymbolFileDWARF::FindNamespace (sc, name=\"%s\") => " "CompilerDeclContext(%p/%p) \"%s\"", name.GetCString(), static_cast<const void *>(namespace_decl_ctx.GetTypeSystem()), static_cast<const void *>(namespace_decl_ctx.GetOpaqueDeclContext()), namespace_decl_ctx.GetName().AsCString("<NULL>")); } return namespace_decl_ctx; } TypeSP SymbolFileDWARF::GetTypeForDIE(const DWARFDIE &die, bool resolve_function_context) { TypeSP type_sp; if (die) { Type *type_ptr = GetDIEToType().lookup(die.GetDIE()); if (type_ptr == nullptr) { SymbolContextScope *scope; if (auto *dwarf_cu = llvm::dyn_cast<DWARFCompileUnit>(die.GetCU())) scope = GetCompUnitForDWARFCompUnit(*dwarf_cu); else scope = GetObjectFile()->GetModule().get(); assert(scope); SymbolContext sc(scope); const DWARFDebugInfoEntry *parent_die = die.GetParent().GetDIE(); while (parent_die != nullptr) { if (parent_die->Tag() == DW_TAG_subprogram) break; parent_die = parent_die->GetParent(); } SymbolContext sc_backup = sc; if (resolve_function_context && parent_die != nullptr && !GetFunction(DWARFDIE(die.GetCU(), parent_die), sc)) sc = sc_backup; type_sp = ParseType(sc, die, nullptr); } else if (type_ptr != DIE_IS_BEING_PARSED) { // Grab the existing type from the master types lists type_sp = type_ptr->shared_from_this(); } } return type_sp; } DWARFDIE SymbolFileDWARF::GetDeclContextDIEContainingDIE(const DWARFDIE &orig_die) { if (orig_die) { DWARFDIE die = orig_die; while (die) { // If this is the original DIE that we are searching for a declaration // for, then don't look in the cache as we don't want our own decl // context to be our decl context... if (orig_die != die) { switch (die.Tag()) { case DW_TAG_compile_unit: case DW_TAG_partial_unit: case DW_TAG_namespace: case DW_TAG_structure_type: case DW_TAG_union_type: case DW_TAG_class_type: case DW_TAG_lexical_block: case DW_TAG_subprogram: return die; case DW_TAG_inlined_subroutine: { DWARFDIE abs_die = die.GetReferencedDIE(DW_AT_abstract_origin); if (abs_die) { return abs_die; } break; } default: break; } } DWARFDIE spec_die = die.GetReferencedDIE(DW_AT_specification); if (spec_die) { DWARFDIE decl_ctx_die = GetDeclContextDIEContainingDIE(spec_die); if (decl_ctx_die) return decl_ctx_die; } DWARFDIE abs_die = die.GetReferencedDIE(DW_AT_abstract_origin); if (abs_die) { DWARFDIE decl_ctx_die = GetDeclContextDIEContainingDIE(abs_die); if (decl_ctx_die) return decl_ctx_die; } die = die.GetParent(); } } return DWARFDIE(); } Symbol *SymbolFileDWARF::GetObjCClassSymbol(ConstString objc_class_name) { Symbol *objc_class_symbol = nullptr; if (m_objfile_sp) { Symtab *symtab = m_objfile_sp->GetSymtab(); if (symtab) { objc_class_symbol = symtab->FindFirstSymbolWithNameAndType( objc_class_name, eSymbolTypeObjCClass, Symtab::eDebugNo, Symtab::eVisibilityAny); } } return objc_class_symbol; } // Some compilers don't emit the DW_AT_APPLE_objc_complete_type attribute. If // they don't then we can end up looking through all class types for a complete // type and never find the full definition. We need to know if this attribute // is supported, so we determine this here and cache th result. We also need to // worry about the debug map // DWARF file // if we are doing darwin DWARF in .o file debugging. bool SymbolFileDWARF::Supports_DW_AT_APPLE_objc_complete_type(DWARFUnit *cu) { if (m_supports_DW_AT_APPLE_objc_complete_type == eLazyBoolCalculate) { m_supports_DW_AT_APPLE_objc_complete_type = eLazyBoolNo; if (cu && cu->Supports_DW_AT_APPLE_objc_complete_type()) m_supports_DW_AT_APPLE_objc_complete_type = eLazyBoolYes; else { DWARFDebugInfo &debug_info = DebugInfo(); const uint32_t num_compile_units = GetNumCompileUnits(); for (uint32_t cu_idx = 0; cu_idx < num_compile_units; ++cu_idx) { DWARFUnit *dwarf_cu = debug_info.GetUnitAtIndex(cu_idx); if (dwarf_cu != cu && dwarf_cu->Supports_DW_AT_APPLE_objc_complete_type()) { m_supports_DW_AT_APPLE_objc_complete_type = eLazyBoolYes; break; } } } if (m_supports_DW_AT_APPLE_objc_complete_type == eLazyBoolNo && GetDebugMapSymfile()) return m_debug_map_symfile->Supports_DW_AT_APPLE_objc_complete_type(this); } return m_supports_DW_AT_APPLE_objc_complete_type == eLazyBoolYes; } // This function can be used when a DIE is found that is a forward declaration // DIE and we want to try and find a type that has the complete definition. TypeSP SymbolFileDWARF::FindCompleteObjCDefinitionTypeForDIE( const DWARFDIE &die, ConstString type_name, bool must_be_implementation) { TypeSP type_sp; if (!type_name || (must_be_implementation && !GetObjCClassSymbol(type_name))) return type_sp; m_index->GetCompleteObjCClass( type_name, must_be_implementation, [&](DWARFDIE type_die) { bool try_resolving_type = false; // Don't try and resolve the DIE we are looking for with the DIE // itself! if (type_die != die) { switch (type_die.Tag()) { case DW_TAG_class_type: case DW_TAG_structure_type: try_resolving_type = true; break; default: break; } } if (!try_resolving_type) return true; if (must_be_implementation && type_die.Supports_DW_AT_APPLE_objc_complete_type()) try_resolving_type = type_die.GetAttributeValueAsUnsigned( DW_AT_APPLE_objc_complete_type, 0); if (!try_resolving_type) return true; Type *resolved_type = ResolveType(type_die, false, true); if (!resolved_type || resolved_type == DIE_IS_BEING_PARSED) return true; DEBUG_PRINTF( "resolved 0x%8.8" PRIx64 " from %s to 0x%8.8" PRIx64 " (cu 0x%8.8" PRIx64 ")\n", die.GetID(), m_objfile_sp->GetFileSpec().GetFilename().AsCString("<Unknown>"), type_die.GetID(), type_cu->GetID()); if (die) GetDIEToType()[die.GetDIE()] = resolved_type; type_sp = resolved_type->shared_from_this(); return false; }); return type_sp; } // This function helps to ensure that the declaration contexts match for two // different DIEs. Often times debug information will refer to a forward // declaration of a type (the equivalent of "struct my_struct;". There will // often be a declaration of that type elsewhere that has the full definition. // When we go looking for the full type "my_struct", we will find one or more // matches in the accelerator tables and we will then need to make sure the // type was in the same declaration context as the original DIE. This function // can efficiently compare two DIEs and will return true when the declaration // context matches, and false when they don't. bool SymbolFileDWARF::DIEDeclContextsMatch(const DWARFDIE &die1, const DWARFDIE &die2) { if (die1 == die2) return true; std::vector<DWARFDIE> decl_ctx_1; std::vector<DWARFDIE> decl_ctx_2; // The declaration DIE stack is a stack of the declaration context DIEs all // the way back to the compile unit. If a type "T" is declared inside a class // "B", and class "B" is declared inside a class "A" and class "A" is in a // namespace "lldb", and the namespace is in a compile unit, there will be a // stack of DIEs: // // [0] DW_TAG_class_type for "B" // [1] DW_TAG_class_type for "A" // [2] DW_TAG_namespace for "lldb" // [3] DW_TAG_compile_unit or DW_TAG_partial_unit for the source file. // // We grab both contexts and make sure that everything matches all the way // back to the compiler unit. // First lets grab the decl contexts for both DIEs decl_ctx_1 = die1.GetDeclContextDIEs(); decl_ctx_2 = die2.GetDeclContextDIEs(); // Make sure the context arrays have the same size, otherwise we are done const size_t count1 = decl_ctx_1.size(); const size_t count2 = decl_ctx_2.size(); if (count1 != count2) return false; // Make sure the DW_TAG values match all the way back up the compile unit. If // they don't, then we are done. DWARFDIE decl_ctx_die1; DWARFDIE decl_ctx_die2; size_t i; for (i = 0; i < count1; i++) { decl_ctx_die1 = decl_ctx_1[i]; decl_ctx_die2 = decl_ctx_2[i]; if (decl_ctx_die1.Tag() != decl_ctx_die2.Tag()) return false; } #ifndef NDEBUG // Make sure the top item in the decl context die array is always // DW_TAG_compile_unit or DW_TAG_partial_unit. If it isn't then // something went wrong in the DWARFDIE::GetDeclContextDIEs() // function. dw_tag_t cu_tag = decl_ctx_1[count1 - 1].Tag(); UNUSED_IF_ASSERT_DISABLED(cu_tag); assert(cu_tag == DW_TAG_compile_unit || cu_tag == DW_TAG_partial_unit); #endif // Always skip the compile unit when comparing by only iterating up to "count // - 1". Here we compare the names as we go. for (i = 0; i < count1 - 1; i++) { decl_ctx_die1 = decl_ctx_1[i]; decl_ctx_die2 = decl_ctx_2[i]; const char *name1 = decl_ctx_die1.GetName(); const char *name2 = decl_ctx_die2.GetName(); // If the string was from a DW_FORM_strp, then the pointer will often be // the same! if (name1 == name2) continue; // Name pointers are not equal, so only compare the strings if both are not // NULL. if (name1 && name2) { // If the strings don't compare, we are done... if (strcmp(name1, name2) != 0) return false; } else { // One name was NULL while the other wasn't return false; } } // We made it through all of the checks and the declaration contexts are // equal. return true; } TypeSP SymbolFileDWARF::FindDefinitionTypeForDWARFDeclContext( const DWARFDeclContext &dwarf_decl_ctx) { TypeSP type_sp; const uint32_t dwarf_decl_ctx_count = dwarf_decl_ctx.GetSize(); if (dwarf_decl_ctx_count > 0) { const ConstString type_name(dwarf_decl_ctx[0].name); const dw_tag_t tag = dwarf_decl_ctx[0].tag; if (type_name) { Log *log(LogChannelDWARF::GetLogIfAny(DWARF_LOG_TYPE_COMPLETION | DWARF_LOG_LOOKUPS)); if (log) { GetObjectFile()->GetModule()->LogMessage( log, "SymbolFileDWARF::FindDefinitionTypeForDWARFDeclContext(tag=%" "s, qualified-name='%s')", DW_TAG_value_to_name(dwarf_decl_ctx[0].tag), dwarf_decl_ctx.GetQualifiedName()); } // Get the type system that we are looking to find a type for. We will // use this to ensure any matches we find are in a language that this // type system supports const LanguageType language = dwarf_decl_ctx.GetLanguage(); TypeSystem *type_system = nullptr; if (language != eLanguageTypeUnknown) { auto type_system_or_err = GetTypeSystemForLanguage(language); if (auto err = type_system_or_err.takeError()) { LLDB_LOG_ERROR( lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_SYMBOLS), std::move(err), "Cannot get TypeSystem for language {}", Language::GetNameForLanguageType(language)); } else { type_system = &type_system_or_err.get(); } } m_index->GetTypes(dwarf_decl_ctx, [&](DWARFDIE type_die) { // Make sure type_die's langauge matches the type system we are // looking for. We don't want to find a "Foo" type from Java if we // are looking for a "Foo" type for C, C++, ObjC, or ObjC++. if (type_system && !type_system->SupportsLanguage(GetLanguage(*type_die.GetCU()))) return true; bool try_resolving_type = false; // Don't try and resolve the DIE we are looking for with the DIE // itself! const dw_tag_t type_tag = type_die.Tag(); // Make sure the tags match if (type_tag == tag) { // The tags match, lets try resolving this type try_resolving_type = true; } else { // The tags don't match, but we need to watch our for a forward // declaration for a struct and ("struct foo") ends up being a // class ("class foo { ... };") or vice versa. switch (type_tag) { case DW_TAG_class_type: // We had a "class foo", see if we ended up with a "struct foo // { ... };" try_resolving_type = (tag == DW_TAG_structure_type); break; case DW_TAG_structure_type: // We had a "struct foo", see if we ended up with a "class foo // { ... };" try_resolving_type = (tag == DW_TAG_class_type); break; default: // Tags don't match, don't event try to resolve using this type // whose name matches.... break; } } if (!try_resolving_type) { if (log) { std::string qualified_name; type_die.GetQualifiedName(qualified_name); GetObjectFile()->GetModule()->LogMessage( log, "SymbolFileDWARF::" "FindDefinitionTypeForDWARFDeclContext(tag=%s, " "qualified-name='%s') ignoring die=0x%8.8x (%s)", DW_TAG_value_to_name(dwarf_decl_ctx[0].tag), dwarf_decl_ctx.GetQualifiedName(), type_die.GetOffset(), qualified_name.c_str()); } return true; } DWARFDeclContext type_dwarf_decl_ctx = GetDWARFDeclContext(type_die); if (log) { GetObjectFile()->GetModule()->LogMessage( log, "SymbolFileDWARF::" "FindDefinitionTypeForDWARFDeclContext(tag=%s, " "qualified-name='%s') trying die=0x%8.8x (%s)", DW_TAG_value_to_name(dwarf_decl_ctx[0].tag), dwarf_decl_ctx.GetQualifiedName(), type_die.GetOffset(), type_dwarf_decl_ctx.GetQualifiedName()); } // Make sure the decl contexts match all the way up if (dwarf_decl_ctx != type_dwarf_decl_ctx) return true; Type *resolved_type = ResolveType(type_die, false); if (!resolved_type || resolved_type == DIE_IS_BEING_PARSED) return true; type_sp = resolved_type->shared_from_this(); return false; }); } } return type_sp; } bool SymbolFileDWARF::GetCompileOption(const char *option, std::string &value, CompileUnit *cu) { value.clear(); DWARFDebugInfo &debug_info = DebugInfo(); const uint32_t num_compile_units = GetNumCompileUnits(); if (cu) { auto *dwarf_cu = llvm::dyn_cast_or_null<DWARFCompileUnit>(GetDWARFCompileUnit(cu)); if (dwarf_cu) { // GetDWARFCompileUnit() only looks up by CU#. Make sure that // this is actually the correct SymbolFile by converting it // back to a CompileUnit. if (GetCompUnitForDWARFCompUnit(*dwarf_cu) != cu) return false; const DWARFBaseDIE die = dwarf_cu->GetUnitDIEOnly(); if (die) { const char *flags = die.GetAttributeValueAsString(DW_AT_APPLE_flags, NULL); if (flags) { if (strstr(flags, option)) { Args compiler_args(flags); return OptionParsing::GetOptionValueAsString(compiler_args, option, value); } } } } } else { for (uint32_t cu_idx = 0; cu_idx < num_compile_units; ++cu_idx) { DWARFUnit *dwarf_cu = debug_info.GetUnitAtIndex(cu_idx); if (dwarf_cu) { const DWARFBaseDIE die = dwarf_cu->GetUnitDIEOnly(); if (die) { const char *flags = die.GetAttributeValueAsString(DW_AT_APPLE_flags, NULL); if (flags) { if (strstr(flags, option)) { Args compiler_args(flags); return OptionParsing::GetOptionValueAsString(compiler_args, option, value); } } } } } } return false; } TypeSP SymbolFileDWARF::ParseType(const SymbolContext &sc, const DWARFDIE &die, bool *type_is_new_ptr) { if (!die) return {}; auto type_system_or_err = GetTypeSystemForLanguage(GetLanguage(*die.GetCU())); if (auto err = type_system_or_err.takeError()) { LLDB_LOG_ERROR(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_SYMBOLS), std::move(err), "Unable to parse type"); return {}; } DWARFASTParser *dwarf_ast = type_system_or_err->GetDWARFParser(); if (!dwarf_ast) return {}; TypeSP type_sp = dwarf_ast->ParseTypeFromDWARF(sc, die, type_is_new_ptr); if (type_sp) { GetTypeList().Insert(type_sp); if (die.Tag() == DW_TAG_subprogram) { std::string scope_qualified_name(GetDeclContextForUID(die.GetID()) .GetScopeQualifiedName() .AsCString("")); if (scope_qualified_name.size()) { m_function_scope_qualified_name_map[scope_qualified_name].insert( *die.GetDIERef()); } } } return type_sp; } size_t SymbolFileDWARF::ParseTypes(const SymbolContext &sc, const DWARFDIE &orig_die, bool parse_siblings, bool parse_children) { size_t types_added = 0; DWARFDIE die = orig_die; while (die) { const dw_tag_t tag = die.Tag(); bool type_is_new = false; Tag dwarf_tag = static_cast<Tag>(tag); // TODO: Currently ParseTypeFromDWARF(...) which is called by ParseType(...) // does not handle DW_TAG_subrange_type. It is not clear if this is a bug or // not. if (isType(dwarf_tag) && tag != DW_TAG_subrange_type) ParseType(sc, die, &type_is_new); if (type_is_new) ++types_added; if (parse_children && die.HasChildren()) { if (die.Tag() == DW_TAG_subprogram) { SymbolContext child_sc(sc); child_sc.function = sc.comp_unit->FindFunctionByUID(die.GetID()).get(); types_added += ParseTypes(child_sc, die.GetFirstChild(), true, true); } else types_added += ParseTypes(sc, die.GetFirstChild(), true, true); } if (parse_siblings) die = die.GetSibling(); else die.Clear(); } return types_added; } size_t SymbolFileDWARF::ParseBlocksRecursive(Function &func) { std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); CompileUnit *comp_unit = func.GetCompileUnit(); lldbassert(comp_unit); DWARFUnit *dwarf_cu = GetDWARFCompileUnit(comp_unit); if (!dwarf_cu) return 0; size_t functions_added = 0; const dw_offset_t function_die_offset = func.GetID(); DWARFDIE function_die = dwarf_cu->GetNonSkeletonUnit().GetDIE(function_die_offset); if (function_die) { ParseBlocksRecursive(*comp_unit, &func.GetBlock(false), function_die, LLDB_INVALID_ADDRESS, 0); } return functions_added; } size_t SymbolFileDWARF::ParseTypes(CompileUnit &comp_unit) { std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); size_t types_added = 0; DWARFUnit *dwarf_cu = GetDWARFCompileUnit(&comp_unit); if (dwarf_cu) { DWARFDIE dwarf_cu_die = dwarf_cu->DIE(); if (dwarf_cu_die && dwarf_cu_die.HasChildren()) { SymbolContext sc; sc.comp_unit = &comp_unit; types_added = ParseTypes(sc, dwarf_cu_die.GetFirstChild(), true, true); } } return types_added; } size_t SymbolFileDWARF::ParseVariablesForContext(const SymbolContext &sc) { std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); if (sc.comp_unit != nullptr) { if (sc.function) { DWARFDIE function_die = GetDIE(sc.function->GetID()); dw_addr_t func_lo_pc = LLDB_INVALID_ADDRESS; DWARFRangeList ranges; if (function_die.GetDIE()->GetAttributeAddressRanges( function_die.GetCU(), ranges, /*check_hi_lo_pc=*/true)) func_lo_pc = ranges.GetMinRangeBase(0); if (func_lo_pc != LLDB_INVALID_ADDRESS) { const size_t num_variables = ParseVariables( sc, function_die.GetFirstChild(), func_lo_pc, true, true); // Let all blocks know they have parse all their variables sc.function->GetBlock(false).SetDidParseVariables(true, true); return num_variables; } } else if (sc.comp_unit) { DWARFUnit *dwarf_cu = DebugInfo().GetUnitAtIndex(sc.comp_unit->GetID()); if (dwarf_cu == nullptr) return 0; uint32_t vars_added = 0; VariableListSP variables(sc.comp_unit->GetVariableList(false)); if (variables.get() == nullptr) { variables = std::make_shared<VariableList>(); sc.comp_unit->SetVariableList(variables); m_index->GetGlobalVariables(*dwarf_cu, [&](DWARFDIE die) { VariableSP var_sp(ParseVariableDIE(sc, die, LLDB_INVALID_ADDRESS)); if (var_sp) { variables->AddVariableIfUnique(var_sp); ++vars_added; } return true; }); } return vars_added; } } return 0; } VariableSP SymbolFileDWARF::ParseVariableDIE(const SymbolContext &sc, const DWARFDIE &die, const lldb::addr_t func_low_pc) { if (die.GetDWARF() != this) return die.GetDWARF()->ParseVariableDIE(sc, die, func_low_pc); if (!die) return nullptr; if (VariableSP var_sp = GetDIEToVariable()[die.GetDIE()]) return var_sp; // Already been parsed! const dw_tag_t tag = die.Tag(); ModuleSP module = GetObjectFile()->GetModule(); if (tag != DW_TAG_variable && tag != DW_TAG_constant && (tag != DW_TAG_formal_parameter || !sc.function)) return nullptr; DWARFAttributes attributes; const size_t num_attributes = die.GetAttributes(attributes); DWARFDIE spec_die; VariableSP var_sp; const char *name = nullptr; const char *mangled = nullptr; Declaration decl; DWARFFormValue type_die_form; DWARFExpression location; bool is_external = false; bool is_artificial = false; DWARFFormValue const_value_form, location_form; Variable::RangeList scope_ranges; for (size_t i = 0; i < num_attributes; ++i) { dw_attr_t attr = attributes.AttributeAtIndex(i); DWARFFormValue form_value; if (!attributes.ExtractFormValueAtIndex(i, form_value)) continue; switch (attr) { case DW_AT_decl_file: decl.SetFile( attributes.CompileUnitAtIndex(i)->GetFile(form_value.Unsigned())); break; case DW_AT_decl_line: decl.SetLine(form_value.Unsigned()); break; case DW_AT_decl_column: decl.SetColumn(form_value.Unsigned()); break; case DW_AT_name: name = form_value.AsCString(); break; case DW_AT_linkage_name: case DW_AT_MIPS_linkage_name: mangled = form_value.AsCString(); break; case DW_AT_type: type_die_form = form_value; break; case DW_AT_external: is_external = form_value.Boolean(); break; case DW_AT_const_value: const_value_form = form_value; break; case DW_AT_location: location_form = form_value; break; case DW_AT_specification: spec_die = form_value.Reference(); break; case DW_AT_start_scope: // TODO: Implement this. break; case DW_AT_artificial: is_artificial = form_value.Boolean(); break; case DW_AT_declaration: case DW_AT_description: case DW_AT_endianity: case DW_AT_segment: case DW_AT_visibility: default: case DW_AT_abstract_origin: case DW_AT_sibling: break; } } if (tag == DW_TAG_variable && mangled && sc.comp_unit->GetLanguage() == eLanguageTypeSwift) mangled = nullptr; // Prefer DW_AT_location over DW_AT_const_value. Both can be emitted e.g. // for static constexpr member variables -- DW_AT_const_value will be // present in the class declaration and DW_AT_location in the DIE defining // the member. bool location_is_const_value_data = false; bool has_explicit_location = false; bool use_type_size_for_value = false; if (location_form.IsValid()) { has_explicit_location = true; if (DWARFFormValue::IsBlockForm(location_form.Form())) { const DWARFDataExtractor &data = die.GetData(); uint32_t block_offset = location_form.BlockData() - data.GetDataStart(); uint32_t block_length = location_form.Unsigned(); location = DWARFExpression( module, DataExtractor(data, block_offset, block_length), die.GetCU()); } else { DataExtractor data = die.GetCU()->GetLocationData(); dw_offset_t offset = location_form.Unsigned(); if (location_form.Form() == DW_FORM_loclistx) offset = die.GetCU()->GetLoclistOffset(offset).getValueOr(-1); if (data.ValidOffset(offset)) { data = DataExtractor(data, offset, data.GetByteSize() - offset); location = DWARFExpression(module, data, die.GetCU()); assert(func_low_pc != LLDB_INVALID_ADDRESS); location.SetLocationListAddresses( location_form.GetUnit()->GetBaseAddress(), func_low_pc); } } } else if (const_value_form.IsValid()) { location_is_const_value_data = true; // The constant value will be either a block, a data value or a // string. const DWARFDataExtractor &debug_info_data = die.GetData(); if (DWARFFormValue::IsBlockForm(const_value_form.Form())) { // Retrieve the value as a block expression. uint32_t block_offset = const_value_form.BlockData() - debug_info_data.GetDataStart(); uint32_t block_length = const_value_form.Unsigned(); location = DWARFExpression( module, DataExtractor(debug_info_data, block_offset, block_length), die.GetCU()); } else if (DWARFFormValue::IsDataForm(const_value_form.Form())) { // Constant value size does not have to match the size of the // variable. We will fetch the size of the type after we create // it. use_type_size_for_value = true; } else if (const char *str = const_value_form.AsCString()) { uint32_t string_length = strlen(str) + 1; location = DWARFExpression( module, DataExtractor(str, string_length, die.GetCU()->GetByteOrder(), die.GetCU()->GetAddressByteSize()), die.GetCU()); } } const DWARFDIE parent_context_die = GetDeclContextDIEContainingDIE(die); const dw_tag_t parent_tag = die.GetParent().Tag(); bool is_static_member = (parent_tag == DW_TAG_compile_unit || parent_tag == DW_TAG_partial_unit) && (parent_context_die.Tag() == DW_TAG_class_type || parent_context_die.Tag() == DW_TAG_structure_type); ValueType scope = eValueTypeInvalid; const DWARFDIE sc_parent_die = GetParentSymbolContextDIE(die); SymbolContextScope *symbol_context_scope = nullptr; bool has_explicit_mangled = mangled != nullptr; if (!mangled) { // LLDB relies on the mangled name (DW_TAG_linkage_name or // DW_AT_MIPS_linkage_name) to generate fully qualified names // of global variables with commands like "frame var j". For // example, if j were an int variable holding a value 4 and // declared in a namespace B which in turn is contained in a // namespace A, the command "frame var j" returns // "(int) A::B::j = 4". // If the compiler does not emit a linkage name, we should be // able to generate a fully qualified name from the // declaration context. if ((parent_tag == DW_TAG_compile_unit || parent_tag == DW_TAG_partial_unit) && Language::LanguageIsCPlusPlus(GetLanguage(*die.GetCU()))) mangled = GetDWARFDeclContext(die).GetQualifiedNameAsConstString().GetCString(); } if (tag == DW_TAG_formal_parameter) scope = eValueTypeVariableArgument; else { // DWARF doesn't specify if a DW_TAG_variable is a local, global // or static variable, so we have to do a little digging: // 1) DW_AT_linkage_name implies static lifetime (but may be missing) // 2) An empty DW_AT_location is an (optimized-out) static lifetime var. // 3) DW_AT_location containing a DW_OP_addr implies static lifetime. // Clang likes to combine small global variables into the same symbol // with locations like: DW_OP_addr(0x1000), DW_OP_constu(2), DW_OP_plus // so we need to look through the whole expression. bool is_static_lifetime = has_explicit_mangled || (has_explicit_location && !location.IsValid()); // Check if the location has a DW_OP_addr with any address value... lldb::addr_t location_DW_OP_addr = LLDB_INVALID_ADDRESS; if (!location_is_const_value_data) { bool op_error = false; location_DW_OP_addr = location.GetLocation_DW_OP_addr(0, op_error); if (op_error) { StreamString strm; location.DumpLocationForAddress(&strm, eDescriptionLevelFull, 0, 0, nullptr); GetObjectFile()->GetModule()->ReportError( "0x%8.8x: %s has an invalid location: %s", die.GetOffset(), die.GetTagAsCString(), strm.GetData()); } if (location_DW_OP_addr != LLDB_INVALID_ADDRESS) is_static_lifetime = true; } SymbolFileDWARFDebugMap *debug_map_symfile = GetDebugMapSymfile(); if (debug_map_symfile) // Set the module of the expression to the linked module // instead of the oject file so the relocated address can be // found there. location.SetModule(debug_map_symfile->GetObjectFile()->GetModule()); if (is_static_lifetime) { if (is_external) scope = eValueTypeVariableGlobal; else scope = eValueTypeVariableStatic; if (debug_map_symfile) { // When leaving the DWARF in the .o files on darwin, when we have a // global variable that wasn't initialized, the .o file might not // have allocated a virtual address for the global variable. In // this case it will have created a symbol for the global variable // that is undefined/data and external and the value will be the // byte size of the variable. When we do the address map in // SymbolFileDWARFDebugMap we rely on having an address, we need to // do some magic here so we can get the correct address for our // global variable. The address for all of these entries will be // zero, and there will be an undefined symbol in this object file, // and the executable will have a matching symbol with a good // address. So here we dig up the correct address and replace it in // the location for the variable, and set the variable's symbol // context scope to be that of the main executable so the file // address will resolve correctly. bool linked_oso_file_addr = false; if (is_external && location_DW_OP_addr == 0) { // we have a possible uninitialized extern global ConstString const_name(mangled ? mangled : name); ObjectFile *debug_map_objfile = debug_map_symfile->GetObjectFile(); if (debug_map_objfile) { Symtab *debug_map_symtab = debug_map_objfile->GetSymtab(); if (debug_map_symtab) { Symbol *exe_symbol = debug_map_symtab->FindFirstSymbolWithNameAndType( const_name, eSymbolTypeData, Symtab::eDebugYes, Symtab::eVisibilityExtern); if (exe_symbol) { if (exe_symbol->ValueIsAddress()) { const addr_t exe_file_addr = exe_symbol->GetAddressRef().GetFileAddress(); if (exe_file_addr != LLDB_INVALID_ADDRESS) { if (location.Update_DW_OP_addr(exe_file_addr)) { linked_oso_file_addr = true; symbol_context_scope = exe_symbol; } } } } } } } if (!linked_oso_file_addr) { // The DW_OP_addr is not zero, but it contains a .o file address // which needs to be linked up correctly. const lldb::addr_t exe_file_addr = debug_map_symfile->LinkOSOFileAddress(this, location_DW_OP_addr); if (exe_file_addr != LLDB_INVALID_ADDRESS) { // Update the file address for this variable location.Update_DW_OP_addr(exe_file_addr); } else { // Variable didn't make it into the final executable return var_sp; } } } } else { if (location_is_const_value_data && die.GetDIE()->IsGlobalOrStaticScopeVariable()) scope = eValueTypeVariableStatic; else { scope = eValueTypeVariableLocal; if (debug_map_symfile) { // We need to check for TLS addresses that we need to fixup if (location.ContainsThreadLocalStorage()) { location.LinkThreadLocalStorage( debug_map_symfile->GetObjectFile()->GetModule(), [this, debug_map_symfile]( lldb::addr_t unlinked_file_addr) -> lldb::addr_t { return debug_map_symfile->LinkOSOFileAddress( this, unlinked_file_addr); }); scope = eValueTypeVariableThreadLocal; } } } } } if (symbol_context_scope == nullptr) { switch (parent_tag) { case DW_TAG_subprogram: case DW_TAG_inlined_subroutine: case DW_TAG_lexical_block: if (sc.function) { symbol_context_scope = sc.function->GetBlock(true).FindBlockByID(sc_parent_die.GetID()); if (symbol_context_scope == nullptr) symbol_context_scope = sc.function; } break; default: symbol_context_scope = sc.comp_unit; break; } } if (symbol_context_scope) { auto type_sp = std::make_shared<SymbolFileType>( *this, GetUID(type_die_form.Reference())); if (use_type_size_for_value && type_sp->GetType()) location.UpdateValue( const_value_form.Unsigned(), type_sp->GetType()->GetByteSize(nullptr).getValueOr(0), die.GetCU()->GetAddressByteSize()); // Swift let-bindings are marked by a DW_TAG_const_type. bool is_constant = false; if (sc.comp_unit->GetLanguage() == eLanguageTypeSwift) { DWARFDIE type_die = die.GetReferencedDIE(llvm::dwarf::DW_AT_type); if (type_die && type_die.Tag() == llvm::dwarf::DW_TAG_const_type) is_constant = true; } var_sp = std::make_shared<Variable>( die.GetID(), name, mangled, type_sp, scope, symbol_context_scope, scope_ranges, &decl, location, is_external, is_artificial, location_is_const_value_data, is_static_member, is_constant); } else { // Not ready to parse this variable yet. It might be a global or static // variable that is in a function scope and the function in the symbol // context wasn't filled in yet return var_sp; } // Cache var_sp even if NULL (the variable was just a specification or was // missing vital information to be able to be displayed in the debugger // (missing location due to optimization, etc)) so we don't re-parse this // DIE over and over later... GetDIEToVariable()[die.GetDIE()] = var_sp; if (spec_die) GetDIEToVariable()[spec_die.GetDIE()] = var_sp; return var_sp; } DWARFDIE SymbolFileDWARF::FindBlockContainingSpecification( const DIERef &func_die_ref, dw_offset_t spec_block_die_offset) { // Give the concrete function die specified by "func_die_offset", find the // concrete block whose DW_AT_specification or DW_AT_abstract_origin points // to "spec_block_die_offset" return FindBlockContainingSpecification(DebugInfo().GetDIE(func_die_ref), spec_block_die_offset); } DWARFDIE SymbolFileDWARF::FindBlockContainingSpecification( const DWARFDIE &die, dw_offset_t spec_block_die_offset) { if (die) { switch (die.Tag()) { case DW_TAG_subprogram: case DW_TAG_inlined_subroutine: case DW_TAG_lexical_block: { if (die.GetReferencedDIE(DW_AT_specification).GetOffset() == spec_block_die_offset) return die; if (die.GetReferencedDIE(DW_AT_abstract_origin).GetOffset() == spec_block_die_offset) return die; } break; default: break; } // Give the concrete function die specified by "func_die_offset", find the // concrete block whose DW_AT_specification or DW_AT_abstract_origin points // to "spec_block_die_offset" for (DWARFDIE child_die : die.children()) { DWARFDIE result_die = FindBlockContainingSpecification(child_die, spec_block_die_offset); if (result_die) return result_die; } } return DWARFDIE(); } size_t SymbolFileDWARF::ParseVariables(const SymbolContext &sc, const DWARFDIE &orig_die, const lldb::addr_t func_low_pc, bool parse_siblings, bool parse_children, VariableList *cc_variable_list) { if (!orig_die) return 0; VariableListSP variable_list_sp; size_t vars_added = 0; DWARFDIE die = orig_die; while (die) { dw_tag_t tag = die.Tag(); // Check to see if we have already parsed this variable or constant? VariableSP var_sp = GetDIEToVariable()[die.GetDIE()]; if (var_sp) { if (cc_variable_list) cc_variable_list->AddVariableIfUnique(var_sp); } else { // We haven't already parsed it, lets do that now. if ((tag == DW_TAG_variable) || (tag == DW_TAG_constant) || (tag == DW_TAG_formal_parameter && sc.function)) { if (variable_list_sp.get() == nullptr) { DWARFDIE sc_parent_die = GetParentSymbolContextDIE(orig_die); dw_tag_t parent_tag = sc_parent_die.Tag(); switch (parent_tag) { case DW_TAG_compile_unit: case DW_TAG_partial_unit: if (sc.comp_unit != nullptr) { variable_list_sp = sc.comp_unit->GetVariableList(false); if (variable_list_sp.get() == nullptr) { variable_list_sp = std::make_shared<VariableList>(); } } else { GetObjectFile()->GetModule()->ReportError( "parent 0x%8.8" PRIx64 " %s with no valid compile unit in " "symbol context for 0x%8.8" PRIx64 " %s.\n", sc_parent_die.GetID(), sc_parent_die.GetTagAsCString(), orig_die.GetID(), orig_die.GetTagAsCString()); } break; case DW_TAG_subprogram: case DW_TAG_inlined_subroutine: case DW_TAG_lexical_block: if (sc.function != nullptr) { // Check to see if we already have parsed the variables for the // given scope Block *block = sc.function->GetBlock(true).FindBlockByID( sc_parent_die.GetID()); if (block == nullptr) { // This must be a specification or abstract origin with a // concrete block counterpart in the current function. We need // to find the concrete block so we can correctly add the // variable to it const DWARFDIE concrete_block_die = FindBlockContainingSpecification( GetDIE(sc.function->GetID()), sc_parent_die.GetOffset()); if (concrete_block_die) block = sc.function->GetBlock(true).FindBlockByID( concrete_block_die.GetID()); } if (block != nullptr) { const bool can_create = false; variable_list_sp = block->GetBlockVariableList(can_create); if (variable_list_sp.get() == nullptr) { variable_list_sp = std::make_shared<VariableList>(); block->SetVariableList(variable_list_sp); } } } break; default: GetObjectFile()->GetModule()->ReportError( "didn't find appropriate parent DIE for variable list for " "0x%8.8" PRIx64 " %s.\n", orig_die.GetID(), orig_die.GetTagAsCString()); break; } } if (variable_list_sp) { VariableSP var_sp(ParseVariableDIE(sc, die, func_low_pc)); if (var_sp) { variable_list_sp->AddVariableIfUnique(var_sp); if (cc_variable_list) cc_variable_list->AddVariableIfUnique(var_sp); ++vars_added; } } } } bool skip_children = (sc.function == nullptr && tag == DW_TAG_subprogram); if (!skip_children && parse_children && die.HasChildren()) { vars_added += ParseVariables(sc, die.GetFirstChild(), func_low_pc, true, true, cc_variable_list); } if (parse_siblings) die = die.GetSibling(); else die.Clear(); } return vars_added; } /// Collect call site parameters in a DW_TAG_call_site DIE. static CallSiteParameterArray CollectCallSiteParameters(ModuleSP module, DWARFDIE call_site_die) { CallSiteParameterArray parameters; for (DWARFDIE child : call_site_die.children()) { if (child.Tag() != DW_TAG_call_site_parameter && child.Tag() != DW_TAG_GNU_call_site_parameter) continue; llvm::Optional<DWARFExpression> LocationInCallee; llvm::Optional<DWARFExpression> LocationInCaller; DWARFAttributes attributes; const size_t num_attributes = child.GetAttributes(attributes); // Parse the location at index \p attr_index within this call site parameter // DIE, or return None on failure. auto parse_simple_location = [&](int attr_index) -> llvm::Optional<DWARFExpression> { DWARFFormValue form_value; if (!attributes.ExtractFormValueAtIndex(attr_index, form_value)) return {}; if (!DWARFFormValue::IsBlockForm(form_value.Form())) return {}; auto data = child.GetData(); uint32_t block_offset = form_value.BlockData() - data.GetDataStart(); uint32_t block_length = form_value.Unsigned(); return DWARFExpression(module, DataExtractor(data, block_offset, block_length), child.GetCU()); }; for (size_t i = 0; i < num_attributes; ++i) { dw_attr_t attr = attributes.AttributeAtIndex(i); if (attr == DW_AT_location) LocationInCallee = parse_simple_location(i); if (attr == DW_AT_call_value || attr == DW_AT_GNU_call_site_value) LocationInCaller = parse_simple_location(i); } if (LocationInCallee && LocationInCaller) { CallSiteParameter param = {*LocationInCallee, *LocationInCaller}; parameters.push_back(param); } } return parameters; } /// Collect call graph edges present in a function DIE. std::vector<std::unique_ptr<lldb_private::CallEdge>> SymbolFileDWARF::CollectCallEdges(ModuleSP module, DWARFDIE function_die) { // Check if the function has a supported call site-related attribute. // TODO: In the future it may be worthwhile to support call_all_source_calls. bool has_call_edges = function_die.GetAttributeValueAsUnsigned(DW_AT_call_all_calls, 0) || function_die.GetAttributeValueAsUnsigned(DW_AT_GNU_all_call_sites, 0); if (!has_call_edges) return {}; Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP)); LLDB_LOG(log, "CollectCallEdges: Found call site info in {0}", function_die.GetPubname()); // Scan the DIE for TAG_call_site entries. // TODO: A recursive scan of all blocks in the subprogram is needed in order // to be DWARF5-compliant. This may need to be done lazily to be performant. // For now, assume that all entries are nested directly under the subprogram // (this is the kind of DWARF LLVM produces) and parse them eagerly. std::vector<std::unique_ptr<CallEdge>> call_edges; for (DWARFDIE child : function_die.children()) { if (child.Tag() != DW_TAG_call_site && child.Tag() != DW_TAG_GNU_call_site) continue; llvm::Optional<DWARFDIE> call_origin; llvm::Optional<DWARFExpression> call_target; addr_t return_pc = LLDB_INVALID_ADDRESS; addr_t call_inst_pc = LLDB_INVALID_ADDRESS; addr_t low_pc = LLDB_INVALID_ADDRESS; bool tail_call = false; // Second DW_AT_low_pc may come from DW_TAG_subprogram referenced by // DW_TAG_GNU_call_site's DW_AT_abstract_origin overwriting our 'low_pc'. // So do not inherit attributes from DW_AT_abstract_origin. DWARFAttributes attributes; const size_t num_attributes = child.GetAttributes(attributes, DWARFDIE::Recurse::no); for (size_t i = 0; i < num_attributes; ++i) { DWARFFormValue form_value; if (!attributes.ExtractFormValueAtIndex(i, form_value)) { LLDB_LOG(log, "CollectCallEdges: Could not extract TAG_call_site form"); break; } dw_attr_t attr = attributes.AttributeAtIndex(i); if (attr == DW_AT_call_tail_call || attr == DW_AT_GNU_tail_call) tail_call = form_value.Boolean(); // Extract DW_AT_call_origin (the call target's DIE). if (attr == DW_AT_call_origin || attr == DW_AT_abstract_origin) { call_origin = form_value.Reference(); if (!call_origin->IsValid()) { LLDB_LOG(log, "CollectCallEdges: Invalid call origin in {0}", function_die.GetPubname()); break; } } if (attr == DW_AT_low_pc) low_pc = form_value.Address(); // Extract DW_AT_call_return_pc (the PC the call returns to) if it's // available. It should only ever be unavailable for tail call edges, in // which case use LLDB_INVALID_ADDRESS. if (attr == DW_AT_call_return_pc) return_pc = form_value.Address(); // Extract DW_AT_call_pc (the PC at the call/branch instruction). It // should only ever be unavailable for non-tail calls, in which case use // LLDB_INVALID_ADDRESS. if (attr == DW_AT_call_pc) call_inst_pc = form_value.Address(); // Extract DW_AT_call_target (the location of the address of the indirect // call). if (attr == DW_AT_call_target || attr == DW_AT_GNU_call_site_target) { if (!DWARFFormValue::IsBlockForm(form_value.Form())) { LLDB_LOG(log, "CollectCallEdges: AT_call_target does not have block form"); break; } auto data = child.GetData(); uint32_t block_offset = form_value.BlockData() - data.GetDataStart(); uint32_t block_length = form_value.Unsigned(); call_target = DWARFExpression( module, DataExtractor(data, block_offset, block_length), child.GetCU()); } } if (!call_origin && !call_target) { LLDB_LOG(log, "CollectCallEdges: call site without any call target"); continue; } addr_t caller_address; CallEdge::AddrType caller_address_type; if (return_pc != LLDB_INVALID_ADDRESS) { caller_address = return_pc; caller_address_type = CallEdge::AddrType::AfterCall; } else if (low_pc != LLDB_INVALID_ADDRESS) { caller_address = low_pc; caller_address_type = CallEdge::AddrType::AfterCall; } else if (call_inst_pc != LLDB_INVALID_ADDRESS) { caller_address = call_inst_pc; caller_address_type = CallEdge::AddrType::Call; } else { LLDB_LOG(log, "CollectCallEdges: No caller address"); continue; } // Adjust any PC forms. It needs to be fixed up if the main executable // contains a debug map (i.e. pointers to object files), because we need a // file address relative to the executable's text section. caller_address = FixupAddress(caller_address); // Extract call site parameters. CallSiteParameterArray parameters = CollectCallSiteParameters(module, child); std::unique_ptr<CallEdge> edge; if (call_origin) { LLDB_LOG(log, "CollectCallEdges: Found call origin: {0} (retn-PC: {1:x}) " "(call-PC: {2:x})", call_origin->GetPubname(), return_pc, call_inst_pc); edge = std::make_unique<DirectCallEdge>( call_origin->GetMangledName(), caller_address_type, caller_address, tail_call, std::move(parameters)); } else { if (log) { StreamString call_target_desc; call_target->GetDescription(&call_target_desc, eDescriptionLevelBrief, LLDB_INVALID_ADDRESS, nullptr); LLDB_LOG(log, "CollectCallEdges: Found indirect call target: {0}", call_target_desc.GetString()); } edge = std::make_unique<IndirectCallEdge>( *call_target, caller_address_type, caller_address, tail_call, std::move(parameters)); } if (log && parameters.size()) { for (const CallSiteParameter &param : parameters) { StreamString callee_loc_desc, caller_loc_desc; param.LocationInCallee.GetDescription(&callee_loc_desc, eDescriptionLevelBrief, LLDB_INVALID_ADDRESS, nullptr); param.LocationInCaller.GetDescription(&caller_loc_desc, eDescriptionLevelBrief, LLDB_INVALID_ADDRESS, nullptr); LLDB_LOG(log, "CollectCallEdges: \tparam: {0} => {1}", callee_loc_desc.GetString(), caller_loc_desc.GetString()); } } call_edges.push_back(std::move(edge)); } return call_edges; } std::vector<std::unique_ptr<lldb_private::CallEdge>> SymbolFileDWARF::ParseCallEdgesInFunction(UserID func_id) { // ParseCallEdgesInFunction must be called at the behest of an exclusively // locked lldb::Function instance. Storage for parsed call edges is owned by // the lldb::Function instance: locking at the SymbolFile level would be too // late, because the act of storing results from ParseCallEdgesInFunction // would be racy. DWARFDIE func_die = GetDIE(func_id.GetID()); if (func_die.IsValid()) return CollectCallEdges(GetObjectFile()->GetModule(), func_die); return {}; } // PluginInterface protocol ConstString SymbolFileDWARF::GetPluginName() { return GetPluginNameStatic(); } uint32_t SymbolFileDWARF::GetPluginVersion() { return 1; } void SymbolFileDWARF::Dump(lldb_private::Stream &s) { SymbolFile::Dump(s); m_index->Dump(s); } void SymbolFileDWARF::DumpClangAST(Stream &s) { auto ts_or_err = GetTypeSystemForLanguage(eLanguageTypeC_plus_plus); if (!ts_or_err) return; TypeSystemClang *clang = llvm::dyn_cast_or_null<TypeSystemClang>(&ts_or_err.get()); if (!clang) return; clang->Dump(s); } SymbolFileDWARFDebugMap *SymbolFileDWARF::GetDebugMapSymfile() { if (m_debug_map_symfile == nullptr) { lldb::ModuleSP module_sp(m_debug_map_module_wp.lock()); if (module_sp) { m_debug_map_symfile = static_cast<SymbolFileDWARFDebugMap *>(module_sp->GetSymbolFile()); } } return m_debug_map_symfile; } const std::shared_ptr<SymbolFileDWARFDwo> &SymbolFileDWARF::GetDwpSymbolFile() { llvm::call_once(m_dwp_symfile_once_flag, [this]() { ModuleSpec module_spec; module_spec.GetFileSpec() = m_objfile_sp->GetFileSpec(); module_spec.GetSymbolFileSpec() = FileSpec(m_objfile_sp->GetModule()->GetFileSpec().GetPath() + ".dwp"); FileSpecList search_paths = Target::GetDefaultDebugFileSearchPaths(); FileSpec dwp_filespec = Symbols::LocateExecutableSymbolFile(module_spec, search_paths); if (FileSystem::Instance().Exists(dwp_filespec)) { DataBufferSP dwp_file_data_sp; lldb::offset_t dwp_file_data_offset = 0; ObjectFileSP dwp_obj_file = ObjectFile::FindPlugin( GetObjectFile()->GetModule(), &dwp_filespec, 0, FileSystem::Instance().GetByteSize(dwp_filespec), dwp_file_data_sp, dwp_file_data_offset); if (!dwp_obj_file) return; m_dwp_symfile = std::make_shared<SymbolFileDWARFDwo>(*this, dwp_obj_file, 0x3fffffff); } }); return m_dwp_symfile; } llvm::Expected<TypeSystem &> SymbolFileDWARF::GetTypeSystem(DWARFUnit &unit) { return unit.GetSymbolFileDWARF().GetTypeSystemForLanguage(GetLanguage(unit)); } DWARFASTParser *SymbolFileDWARF::GetDWARFParser(DWARFUnit &unit) { auto type_system_or_err = GetTypeSystem(unit); if (auto err = type_system_or_err.takeError()) { LLDB_LOG_ERROR(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_SYMBOLS), std::move(err), "Unable to get DWARFASTParser"); return nullptr; } return type_system_or_err->GetDWARFParser(); } CompilerDecl SymbolFileDWARF::GetDecl(const DWARFDIE &die) { if (DWARFASTParser *dwarf_ast = GetDWARFParser(*die.GetCU())) return dwarf_ast->GetDeclForUIDFromDWARF(die); return CompilerDecl(); } CompilerDeclContext SymbolFileDWARF::GetDeclContext(const DWARFDIE &die) { if (DWARFASTParser *dwarf_ast = GetDWARFParser(*die.GetCU())) return dwarf_ast->GetDeclContextForUIDFromDWARF(die); return CompilerDeclContext(); } CompilerDeclContext SymbolFileDWARF::GetContainingDeclContext(const DWARFDIE &die) { if (DWARFASTParser *dwarf_ast = GetDWARFParser(*die.GetCU())) return dwarf_ast->GetDeclContextContainingUIDFromDWARF(die); return CompilerDeclContext(); } DWARFDeclContext SymbolFileDWARF::GetDWARFDeclContext(const DWARFDIE &die) { if (!die.IsValid()) return {}; DWARFDeclContext dwarf_decl_ctx = die.GetDIE()->GetDWARFDeclContext(die.GetCU()); dwarf_decl_ctx.SetLanguage(GetLanguage(*die.GetCU())); return dwarf_decl_ctx; } LanguageType SymbolFileDWARF::LanguageTypeFromDWARF(uint64_t val) { // Note: user languages between lo_user and hi_user must be handled // explicitly here. switch (val) { case DW_LANG_Mips_Assembler: return eLanguageTypeMipsAssembler; case DW_LANG_GOOGLE_RenderScript: return eLanguageTypeExtRenderScript; default: return static_cast<LanguageType>(val); } } LanguageType SymbolFileDWARF::GetLanguage(DWARFUnit &unit) { return LanguageTypeFromDWARF(unit.GetDWARFLanguageType()); } LanguageType SymbolFileDWARF::GetLanguageFamily(DWARFUnit &unit) { auto lang = (llvm::dwarf::SourceLanguage)unit.GetDWARFLanguageType(); if (llvm::dwarf::isCPlusPlus(lang)) lang = DW_LANG_C_plus_plus; return LanguageTypeFromDWARF(lang); }
/****************************************************************************** * Copyright (c) Intel Corporation - All rights reserved. * * This file is part of the LIBXSMM library. * * * * For information on the license, see the LICENSE file. * * Further information: https://github.com/hfp/libxsmm/ * * SPDX-License-Identifier: BSD-3-Clause * ******************************************************************************/ /* Dhiraj Kalamkar (Intel Corp.) ******************************************************************************/ #include <vector> #include <time.h> #include <sys/syscall.h> #include <algorithm> #include <iterator> #include <set> #include <parallel/algorithm> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <time.h> #include <math.h> #include <unistd.h> #include <assert.h> #include <immintrin.h> #include <libxsmm.h> #ifdef USE_PERF_COUNTERS #include "counters.h" #endif #include "radix_sort.h" #include "utils.h" const int alignment = 64; typedef long ITyp; typedef float FTyp; thread_local struct drand48_data rand_buf; void set_random_seed(int seed) { #pragma omp parallel { int tid = omp_get_thread_num(); srand48_r(seed+tid, &rand_buf); } } template<typename T> void init_zero(size_t sz, T *buf) { #pragma omp parallel for for(size_t i = 0; i < sz; i++) buf[i] = (T)0; } template<typename T> void init_random(size_t sz, T *buf, T low = -0.1, T high = 0.1) { T range = high - low; #pragma omp parallel for schedule(static) for(size_t i = 0; i < sz; i++) { double randval; drand48_r(&rand_buf, &randval); buf[i] = randval * range - low; } } double get_checksum(FTyp *buf, size_t sz) { double sum = 0.0; #pragma omp parallel for reduction(+:sum) for(size_t i = 0; i < sz; i++) { sum += buf[i]; } return sum; } inline void *my_malloc(size_t sz, size_t align) { return _mm_malloc(sz, align); } inline void my_free(void *p) { if(!p) return; _mm_free(p); } #define DECL_VLA_PTR(type, name, dims, ptr) type (*name)dims = (type (*)dims)ptr template <typename T> class EmbeddingBagImpl { public: EmbeddingBagImpl(long M, long E) : M(M), E(E) { weight_ = (T*)my_malloc((size_t)M * E * sizeof(T), alignment); h = (T*)my_malloc((size_t)M * sizeof(T), alignment); #ifdef USE_LIBXSMM_JIT _ld = E; kernel = libxsmm_dispatch_meltw_unary(E, 0, &_ld, &_ld, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32, (sizeof(long) == 8) ? LIBXSMM_MELTW_FLAG_UNARY_IDX_SIZE_8BYTES : LIBXSMM_MELTW_FLAG_UNARY_IDX_SIZE_4BYTES, LIBXSMM_MELTW_TYPE_UNARY_REDUCE_COLS_IDX); kernel1 = libxsmm_dispatch_meltw_unary(E, 1, &_ld, &_ld, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32, LIBXSMM_MELTW_FLAG_UNARY_REDUCE_ROWS, LIBXSMM_MELTW_TYPE_UNARY_REDUCE_X2_OP_ADD); kernel2 = libxsmm_dispatch_meltw_binary(E, 1, &_ld, &_ld, &_ld, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32, LIBXSMM_MELTW_FLAG_BINARY_BCAST_SCALAR_IN_0, LIBXSMM_MELTW_TYPE_BINARY_MULADD); #endif } ~EmbeddingBagImpl() { my_free(weight_); my_free(h); weight_ = 0; h = 0; } void init(T low = -0.01, T high = 0.01) { //init_random(M * E, weight_, low, high); init_zero(M * E, weight_); //init_random(M, h, low, high); init_zero(M, h); } void fused_backward_update_adagrad(long U, long NS, long N, long *mb_offsets, long *mb_indices, long *wt_indices, T *outGrad_, float lr, float eps) { DECL_VLA_PTR(T, outGrad, [E], outGrad_); DECL_VLA_PTR(T, wt, [E], weight_); #pragma omp parallel for for (int u = 0; u < U; u++) { int start = mb_offsets[u]; int end = mb_offsets[u+1]; float g_sum[E]; float sum = 0.0; #ifdef USE_LIBXSMM_JIT // lookup reduction kernel libxsmm_meltw_unary_param params; unsigned long long __n = end - start; params.in.primary = outGrad; params.in.secondary = mb_indices[start]; params.in.tertiary = &__n; params.out.primary = &g_sum[0]; kernel( &params ); // squared + reduction kernel libxsmm_meltw_unary_param params1; params1.in.primary = g_sum; params1.out.primary = &sum; kernel1( &params1 ); sum /= E; int idx = wt_indices[u]; float hi = h[idx]; hi += sum; h[idx] = hi; float scale = lr / (sqrt(hi) + eps); // scale and accumulate kernel libxsmm_meltw_binary_param binary_param; binary_param.in0.primary = (void*)&scale; binary_param.in1.primary = (void*)g_sum; binary_param.out.primary = (void*)&wt[idx][0]; kernel2(&binary_param); #else for (int l = start; l < end; l++) { int idx = mb_indices[l]; for (int e = 0; e < E; e++) { g_sum[e] += outGrad[idx][e]; } } for (int e = 0; e < E; e++) { sum += g_sum[e] * g_sum[e]; } sum /= E; int idx = wt_indices[u]; float hi = h[idx]; hi += sum; h[idx] = hi; float scale = lr / (sqrt(hi) + eps); for (int e = 0; e < E; e++) { wt[idx][e] += g_sum[e] * scale; } #endif } } T *weight_; T *h; long M; long E; #ifdef USE_LIBXSMM_JIT int _ld; libxsmm_meltwfunction_unary kernel; libxsmm_meltwfunction_unary kernel1; libxsmm_meltwfunction_binary kernel2; #endif }; typedef EmbeddingBagImpl<FTyp> EmbeddingBag; struct EmbeddingInOut { int M, N, NS, E, U; ITyp *offsets; ITyp *indices; FTyp *output; FTyp *gradout; //FTyp *grads; ITyp * mb_offsets; ITyp * mb_indices; ITyp * wt_indices; }; void sparse_transpose_radix(EmbeddingInOut *eio) { int M = eio->M; int N = eio->N; int NS = eio->NS; Key_Value_Pair<int>* tmpBuf = (Key_Value_Pair<int>*)my_malloc((NS) * sizeof(Key_Value_Pair<int>), alignment); Key_Value_Pair<int>* tmpBuf1 = (Key_Value_Pair<int>*)my_malloc((NS) * sizeof(Key_Value_Pair<int>), alignment); auto t0 = get_time(); #pragma omp parallel for for(int i = 0; i < N; i++) { int start = eio->offsets[i]; int end = eio->offsets[i+1]; for (int j = start; j < end; j++) { tmpBuf[j].first = eio->indices[j]; tmpBuf[j].second = i; } } auto t1 = get_time(); #ifdef DEBUG_TIME printf("Keypair buffer fill Time = %.3f ms\n", t1-t0); #endif t0 = get_time(); Key_Value_Pair<int>* tmpBuf2 = radix_sort_parallel<int>(&tmpBuf[0], &tmpBuf1[0], NS, M); t1 = get_time(); #ifdef DEBUG_TIME printf("Radix Sort Time = %.3f ms\n", t1-t0); #endif int max_thds = omp_get_max_threads(); int num_uniq[max_thds]; t0 = get_time(); #pragma omp parallel { int tid = omp_get_thread_num(); num_uniq[tid] = 0; #pragma omp for schedule(static) for (int i = 1; i < NS; i++) { if (tmpBuf2[i].first != tmpBuf2[i-1].first) num_uniq[tid]++; } } num_uniq[0] += 1; for(int i = 1; i < max_thds; i++) num_uniq[i] += num_uniq[i-1]; int U = num_uniq[max_thds-1]; t1 = get_time(); #ifdef DEBUG_TIME printf("Num Unique Index Time = %.3f ms\n", t1-t0); #endif t0 = get_time(); eio->mb_offsets[0] = 0; eio->mb_indices[0] = tmpBuf2[0].second; eio->wt_indices[0] = tmpBuf2[0].first; #pragma omp parallel { int tid = omp_get_thread_num(); ITyp *tstart = (tid == 0 ? eio->wt_indices + 1 : eio->wt_indices + num_uniq[tid-1]); ITyp *t_offs = (tid == 0 ? eio->mb_offsets + 1 : eio->mb_offsets + num_uniq[tid-1]); #pragma omp for schedule(static) for (int i = 1; i < NS; i++) { eio->mb_indices[i] = tmpBuf2[i].second; if (tmpBuf2[i].first != tmpBuf2[i-1].first) { *tstart = tmpBuf2[i].first; *t_offs = i; tstart++; t_offs++; } } } t1 = get_time(); #ifdef DEBUG_TIME printf("Offset/Index array construction Time = %.3f ms\n", t1-t0); #endif eio->mb_offsets[U] = NS; eio->U = U; my_free(tmpBuf); my_free(tmpBuf1); } // based on https://www.csee.usf.edu/~kchriste/tools/genzipf.c int zipf_dist(double alpha, int M) { static int init_done = 0; static double k = 0; static double *sum_probs; static int prev_M = 0; double z; int value = 0; int i; int low, high, mid; if (prev_M != M) { init_done = 0; prev_M = M; } if (!init_done) { for (i=1; i<=M; i++) k = k + (1.0 / pow((double) i, alpha)); k = 1.0 / k; sum_probs = (double *) my_malloc((M+1)*sizeof(double), alignment); sum_probs[0] = 0; for (i=1; i<=M; i++) { sum_probs[i] = sum_probs[i-1] + k / pow((double) i, alpha); } init_done = 1; } do { drand48_r(&rand_buf, &z); } while ((z == 0) || (z == 1)); low = 1, high = M, mid; do { mid = floor((low+high)/2); if (sum_probs[mid] >= z && sum_probs[mid-1] < z) { value = mid; break; } else if (sum_probs[mid] >= z) { high = mid-1; } else { low = mid+1; } } while (low <= high); assert((value >=1) && (value <= M)); return(value); } void allocate_buffers_and_generte_rnd_input(long N, long P, double alpha, EmbeddingBag *eb, EmbeddingInOut *eio) { long E = eb->E; long M = eb->M; long NS = 0; eio->M = M; eio->N = N; eio->E = E; eio->offsets = (ITyp*)my_malloc((N+1) * sizeof(ITyp), alignment); eio->output = (FTyp*)my_malloc(N * E * sizeof(FTyp), alignment); eio->gradout = (FTyp*)my_malloc(N * E * sizeof(FTyp), alignment); init_zero(N * E, eio->output); init_random(N * E, eio->gradout, -0.01f, 0.01f); eio->offsets[0] = 0; for(int i = 1; i <= N; i++) { double randval; drand48_r(&rand_buf, &randval); int cp = (int)(randval * P * 2); if (cp == 0) cp = 1; NS += cp; eio->offsets[i] = NS; } eio->NS = NS; eio->indices = (ITyp*)my_malloc(NS * sizeof(ITyp), alignment); //eio->grads = (FTyp*)my_malloc(NS * E * sizeof(FTyp), alignment); //init_zero(NS * E, eio->grads); #pragma omp parallel for for (int n = 0; n < N; n++) { int start = eio->offsets[n]; int end = eio->offsets[n+1]; std::set<ITyp> s_ind; ITyp ind; double randval; while(s_ind.size() < (end - start)) { if (alpha == 0.0) { drand48_r(&rand_buf, &randval); ind = (ITyp)(randval * M); } else { ind = (ITyp) zipf_dist(alpha, M); } if (ind == M) ind--; s_ind.insert(ind); } int i = start; for (std::set<ITyp>::iterator itr = s_ind.begin(); itr != s_ind.end(); itr++, i++) { eio->indices[i] = *itr; } //set iterator gives elements in sorted order //std::sort(&eio->indices[start], &eio->indices[end]); } eio->U = -1; eio->mb_offsets = (ITyp*)my_malloc(NS * sizeof(ITyp), alignment); eio->mb_indices = (ITyp*)my_malloc(NS * sizeof(ITyp), alignment); eio->wt_indices = (ITyp*)my_malloc(NS * sizeof(ITyp), alignment); init_zero(NS, eio->mb_offsets); init_zero(NS, eio->mb_indices); init_zero(NS, eio->wt_indices); auto t0 = get_time(); sparse_transpose_radix(eio); auto t1 = get_time(); #ifdef DEBUG_TIME printf("Trans Time = %.3f ms\n", t1-t0); #endif } void free_buffers(EmbeddingInOut *eio) { //my_free(eio->grads); my_free(eio->indices); my_free(eio->gradout); my_free(eio->output); my_free(eio->offsets); my_free(eio->mb_offsets); my_free(eio->mb_indices); my_free(eio->wt_indices); } int iters = 100; int N = 2048; int E = 64; int P = 100; int M = 1000000; int S = 8; double alpha = 0.0; #define my_printf(fmt, args...) printf(fmt, args) int main(int argc, char * argv[]) { if(argc > 1 && strncmp(argv[1], "-h", 3) == 0) { printf("Usage: %s iters N E M S P alpha \n", argv[0]); printf("iters: Number of iterations (= %d)\n", iters); printf("N: Minibatch (= %d)\n", N); printf("E: embedding row width (= %d)\n", E); printf("M: Number of rows per table (= %d)\n", M); printf("S: Number of Tables (= %d)\n", S); printf("P: Average number of indices per look up (= %d)\n", P); printf("alpha: Alpha value for Zipf distribution to generate Indices. Use 0 for uniform distribution"); exit(0); } { int i = 1; if(argc > i) iters = atoi(argv[i++]); if(argc > i) N = atoi(argv[i++]); if(argc > i) E = atoi(argv[i++]); if(argc > i) M = atoi(argv[i++]); if(argc > i) S = atoi(argv[i++]); if(argc > i) P = atoi(argv[i++]); if(argc > i) alpha = atof(argv[i++]); } printf("Using: iters: %d N: %d E: %d M: %d S: %d P: %d alpha: %f\n", iters, N, E, M, S, P, alpha); double checksum = 0.0; int LS = S; int LN = N; set_random_seed(777); #ifdef USE_PERF_COUNTERS ctrs_skx_uc a, b, s; bw_gibs bw_avg; #ifdef USE_LLC_COUNTERS setup_skx_uc_ctrs( CTRS_EXP_CHA_LLC_LOOKUP ); #else setup_skx_uc_ctrs( CTRS_EXP_DRAM_CAS ); #endif zero_skx_uc_ctrs( &a ); zero_skx_uc_ctrs( &b ); zero_skx_uc_ctrs( &s ); #endif EmbeddingInOut *eio[iters][LS]; EmbeddingBag *eb[LS]; size_t tNS = 0; size_t tU = 0; for(int i = 0; i < LS; i++) { eb[i] = new EmbeddingBag(M, E); eb[i]->init(); for(int j = 0; j < iters; j++) { eio[j][i] = new EmbeddingInOut(); auto t0 = get_time(); allocate_buffers_and_generte_rnd_input(N, P, alpha, eb[i], eio[j][i]); auto t1 = get_time(); #ifdef DEBUG_TIME printf("Rand init time = %.3f ms\n", t1 - t0); #endif tNS += eio[j][i]->NS; tU += eio[j][i]->U; } } int warmup = (iters > 2 ? 2 : iters); for(int i = 0; i < warmup; i++) { double t0 = get_time(); for(int s = 0; s < LS; s++) { eb[s]->fused_backward_update_adagrad(eio[i][s]->U, eio[i][s]->NS, N, eio[i][s]->mb_offsets, eio[i][s]->mb_indices, eio[i][s]->wt_indices, eio[i][s]->gradout, -0.1, 1.0e-6); } double t1 = get_time(); #ifdef DEBUG_TIME printf("Warmup Iter %4d: Time = %.3f ms\n", i, t1-t0); #endif } #ifdef USE_PERF_COUNTERS read_skx_uc_ctrs( &a ); #endif double t0 = get_time(); double bwdupdTime = 0.0; for(int i = 0; i < iters; i++) { double t0 = get_time(); for(int s = 0; s < LS; s++) { //printf("Gradout checksum = %g\n", get_checksum(eio[i][s]->gradout, N*E)); eb[s]->fused_backward_update_adagrad(eio[i][s]->U, eio[i][s]->NS, N, eio[i][s]->mb_offsets, eio[i][s]->mb_indices, eio[i][s]->wt_indices, eio[i][s]->gradout, -0.1, 1.0e-6); } double t1 = get_time(); //printf("Iter %4d: Time = %.3f ms\n", i, t1-t0); bwdupdTime += t1-t0; } double t1 = get_time(); #ifdef USE_PERF_COUNTERS read_skx_uc_ctrs( &b ); difa_skx_uc_ctrs( &a, &b, &s ); divi_skx_uc_ctrs( &s, iters ); #endif #ifdef VERIFY_CORRECTNESS for(int s = 0; s < LS; s++) { double psum = get_checksum(eb[s]->weight_, (size_t)M*E); //my_printf("PSUM %d: %g\n", s, psum); checksum += psum; } #endif // tU*E wt RW + N*E gO R + N mb_offsets + NS mb_ind + U wt_ind size_t bwdupdBytesMinRd = ((size_t)tU*(E+1)) * sizeof(FTyp) + ((size_t)tNS+tU) * sizeof(ITyp) + ((size_t)iters*LS*N*E) * sizeof(FTyp) + ((size_t)iters*LS*N) * sizeof(ITyp); size_t bwdupdBytesMaxRd = ((size_t)tU*(E+16)) * sizeof(FTyp) + ((size_t)tNS+tU) * sizeof(ITyp) + ((size_t)iters*LS*N*E) * sizeof(FTyp) + ((size_t)iters*LS*N) * sizeof(ITyp); size_t bwdupdBytesMinWr = ((size_t)tU*(E+1)) * sizeof(FTyp); size_t bwdupdBytesMaxWr = ((size_t)tU*(E+16)) * sizeof(FTyp); size_t bwdupdBytesMin = bwdupdBytesMinRd + bwdupdBytesMinWr; size_t bwdupdBytesMax = bwdupdBytesMaxRd + bwdupdBytesMaxWr; my_printf("Iters = %d, LS = %d, N = %d, M = %d, E = %d, avgNS = %ld, avgU = %ld, P = %d\n", iters, LS, N, M, E, tNS/(iters*LS), tU/(iters*LS), P); my_printf("Per Iter Time: %.3f ms Total: %.3f ms\n", bwdupdTime/(iters), (t1-t0)/(iters)); my_printf("Per Table Time: %.3f ms Total: %.3f ms\n", bwdupdTime/(iters*LS), (t1-t0)/(iters*LS)); double scale = 1000.0/(1024.0*1024.0*1024.0); my_printf("BW: RD Min: %.3f GB/s Max: %.3f GB/s \n", bwdupdBytesMinRd*scale/bwdupdTime, bwdupdBytesMaxRd*scale/bwdupdTime); my_printf("BW: WR Min: %.3f GB/s Max: %.3f GB/s \n", bwdupdBytesMinWr*scale/bwdupdTime, bwdupdBytesMaxWr*scale/bwdupdTime); my_printf("BW: TT Min: %.3f GB/s Max: %.3f GB/s \n", bwdupdBytesMin*scale/bwdupdTime, bwdupdBytesMax*scale/bwdupdTime); #ifdef USE_PERF_COUNTERS #ifdef USE_LLC_COUNTERS get_llc_bw_skx( &s, bwdupdTime/iters/1000.0, &bw_avg ); printf("Measured LLC AVG GB/s: RD %f WR %f TT %f\n", bw_avg.rd, bw_avg.wr, bw_avg.rd + bw_avg.wr); #else get_cas_ddr_bw_skx( &s, bwdupdTime/iters/1000.0, &bw_avg ); printf("Measured MEM AVG GB/s: RD %f WR %f TT %f\n", bw_avg.rd, bw_avg.wr, bw_avg.rd + bw_avg.wr); #endif #endif #ifdef VERIFY_CORRECTNESS printf("Checksum = %g\n", checksum); #endif for(int i = 0; i < LS; i++) { for(int j = 0; j < iters; j++) { free_buffers(eio[j][i]); delete eio[j][i]; } delete eb[i]; } return 0; }
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/worker_host/dedicated_worker_service_impl.h" #include <memory> #include <utility> #include "base/callback_helpers.h" #include "base/run_loop.h" #include "base/scoped_observation.h" #include "base/test/scoped_feature_list.h" #include "content/browser/site_instance_impl.h" #include "content/browser/worker_host/dedicated_worker_host.h" #include "content/browser/worker_host/dedicated_worker_host_factory_impl.h" #include "content/public/browser/storage_partition.h" #include "content/public/test/test_browser_context.h" #include "content/test/test_render_view_host.h" #include "content/test/test_web_contents.h" #include "mojo/public/cpp/bindings/remote.h" #include "mojo/public/cpp/bindings/self_owned_receiver.h" #include "net/base/isolation_info.h" #include "third_party/blink/public/common/features.h" #include "third_party/blink/public/common/storage_key/storage_key.h" #include "third_party/blink/public/common/tokens/tokens.h" #include "third_party/blink/public/common/tokens/tokens_mojom_traits.h" #include "third_party/blink/public/mojom/loader/fetch_client_settings_object.mojom.h" #include "third_party/blink/public/mojom/service_worker/controller_service_worker.mojom.h" #include "third_party/blink/public/mojom/service_worker/service_worker_container.mojom.h" #include "third_party/blink/public/mojom/worker/dedicated_worker_host_factory.mojom.h" #include "third_party/blink/public/mojom/worker/worker_main_script_load_params.mojom.h" namespace content { // Mocks a dedicated worker living in a renderer process. class MockDedicatedWorker : public blink::mojom::DedicatedWorkerHostFactoryClient { public: MockDedicatedWorker(int worker_process_id, GlobalRenderFrameHostId render_frame_host_id) { // The COEP reporter is replaced by a placeholder connection. Reports are // ignored. auto coep_reporter = std::make_unique<CrossOriginEmbedderPolicyReporter>( RenderFrameHostImpl::FromID(render_frame_host_id) ->GetStoragePartition() ->GetWeakPtr(), GURL(), absl::nullopt, absl::nullopt, base::UnguessableToken::Create(), net::NetworkIsolationKey()); mojo::MakeSelfOwnedReceiver( std::make_unique<DedicatedWorkerHostFactoryImpl>( worker_process_id, render_frame_host_id, /*creator_worker_token=*/absl::nullopt, render_frame_host_id, blink::StorageKey(), net::IsolationInfo::CreateTransient(), network::CrossOriginEmbedderPolicy(), coep_reporter->GetWeakPtr(), coep_reporter->GetWeakPtr()), factory_.BindNewPipeAndPassReceiver()); if (base::FeatureList::IsEnabled(blink::features::kPlzDedicatedWorker)) { factory_->CreateWorkerHostAndStartScriptLoad( blink::DedicatedWorkerToken(), /*script_url=*/GURL(), network::mojom::CredentialsMode::kSameOrigin, blink::mojom::FetchClientSettingsObject::New(), mojo::PendingRemote<blink::mojom::BlobURLToken>(), receiver_.BindNewPipeAndPassRemote()); } else { factory_->CreateWorkerHost( blink::DedicatedWorkerToken(), /*script_url=*/GURL(), browser_interface_broker_.BindNewPipeAndPassReceiver(), remote_host_.BindNewPipeAndPassReceiver(), base::DoNothing()); } } ~MockDedicatedWorker() override = default; // Non-copyable. MockDedicatedWorker(const MockDedicatedWorker& other) = delete; // blink::mojom::DedicatedWorkerHostFactoryClient: void OnWorkerHostCreated( mojo::PendingRemote<blink::mojom::BrowserInterfaceBroker> browser_interface_broker, mojo::PendingRemote<blink::mojom::DedicatedWorkerHost>) override { browser_interface_broker_.Bind(std::move(browser_interface_broker)); } void OnScriptLoadStarted( blink::mojom::ServiceWorkerContainerInfoForClientPtr service_worker_container_info, blink::mojom::WorkerMainScriptLoadParamsPtr main_script_load_params, std::unique_ptr<blink::PendingURLLoaderFactoryBundle> pending_subresource_loader_factory_bundle, mojo::PendingReceiver<blink::mojom::SubresourceLoaderUpdater> subresource_loader_updater, blink::mojom::ControllerServiceWorkerInfoPtr controller_info, mojo::PendingRemote<blink::mojom::BackForwardCacheControllerHost> back_forward_cache_controller_host) override {} void OnScriptLoadStartFailed() override {} private: // Only used with the kPlzDedicatedWorker feature. mojo::Receiver<blink::mojom::DedicatedWorkerHostFactoryClient> receiver_{ this}; // Allows creating the dedicated worker host. mojo::Remote<blink::mojom::DedicatedWorkerHostFactory> factory_; mojo::Remote<blink::mojom::BrowserInterfaceBroker> browser_interface_broker_; mojo::Remote<blink::mojom::DedicatedWorkerHost> remote_host_; }; class DedicatedWorkerServiceImplTest : public RenderViewHostImplTestHarness, public testing::WithParamInterface<bool> { public: DedicatedWorkerServiceImplTest() = default; ~DedicatedWorkerServiceImplTest() override = default; // Non-copyable. DedicatedWorkerServiceImplTest(const DedicatedWorkerServiceImplTest& other) = delete; DedicatedWorkerServiceImplTest& operator=( const DedicatedWorkerServiceImplTest& other) = delete; void SetUp() override { scoped_feature_list_.InitWithFeatureState( blink::features::kPlzDedicatedWorker, GetParam()); RenderViewHostImplTestHarness::SetUp(); browser_context_ = std::make_unique<TestBrowserContext>(); } void TearDown() override { browser_context_ = nullptr; RenderViewHostImplTestHarness::TearDown(); } std::unique_ptr<TestWebContents> CreateWebContents(const GURL& url) { std::unique_ptr<TestWebContents> web_contents(TestWebContents::Create( browser_context_.get(), SiteInstanceImpl::Create(browser_context_.get()))); web_contents->NavigateAndCommit(url); return web_contents; } DedicatedWorkerService* GetDedicatedWorkerService() const { return browser_context_->GetDefaultStoragePartition() ->GetDedicatedWorkerService(); } private: // Controls the state of the blink::features::kPlzDedicatedWorker feature. base::test::ScopedFeatureList scoped_feature_list_; std::unique_ptr<TestBrowserContext> browser_context_; }; class TestDedicatedWorkerServiceObserver : public DedicatedWorkerService::Observer { public: struct DedicatedWorkerInfo { int worker_process_id; GlobalRenderFrameHostId ancestor_render_frame_host_id; bool operator==(const DedicatedWorkerInfo& other) const { return std::tie(worker_process_id, ancestor_render_frame_host_id) == std::tie(other.worker_process_id, other.ancestor_render_frame_host_id); } }; TestDedicatedWorkerServiceObserver() = default; ~TestDedicatedWorkerServiceObserver() override = default; // Non-copyable. TestDedicatedWorkerServiceObserver( const TestDedicatedWorkerServiceObserver& other) = delete; // DedicatedWorkerService::Observer: void OnWorkerCreated( const blink::DedicatedWorkerToken& token, int worker_process_id, GlobalRenderFrameHostId ancestor_render_frame_host_id) override { bool inserted = dedicated_worker_infos_ .emplace(token, DedicatedWorkerInfo{worker_process_id, ancestor_render_frame_host_id}) .second; DCHECK(inserted); if (on_worker_event_callback_) std::move(on_worker_event_callback_).Run(); } void OnBeforeWorkerDestroyed( const blink::DedicatedWorkerToken& token, GlobalRenderFrameHostId ancestor_render_frame_host_id) override { size_t removed = dedicated_worker_infos_.erase(token); DCHECK_EQ(removed, 1u); if (on_worker_event_callback_) std::move(on_worker_event_callback_).Run(); } void OnFinalResponseURLDetermined(const blink::DedicatedWorkerToken& token, const GURL& url) override {} void RunUntilWorkerEvent() { base::RunLoop run_loop; on_worker_event_callback_ = run_loop.QuitClosure(); run_loop.Run(); } const base::flat_map<blink::DedicatedWorkerToken, DedicatedWorkerInfo>& dedicated_worker_infos() const { return dedicated_worker_infos_; } private: // Used to wait until one of OnWorkerStarted() or OnBeforeWorkerTerminated() // is called. base::OnceClosure on_worker_event_callback_; base::flat_map<blink::DedicatedWorkerToken, DedicatedWorkerInfo> dedicated_worker_infos_; }; TEST_P(DedicatedWorkerServiceImplTest, DedicatedWorkerServiceObserver) { // Set up the observer. TestDedicatedWorkerServiceObserver observer; base::ScopedObservation<DedicatedWorkerService, DedicatedWorkerService::Observer> scoped_dedicated_worker_service_observation_(&observer); scoped_dedicated_worker_service_observation_.Observe( GetDedicatedWorkerService()); std::unique_ptr<TestWebContents> web_contents = CreateWebContents(GURL("http://example.com/")); TestRenderFrameHost* render_frame_host = web_contents->GetMainFrame(); // At first, there is no live dedicated worker. EXPECT_TRUE(observer.dedicated_worker_infos().empty()); // Create the dedicated worker. const GlobalRenderFrameHostId ancestor_render_frame_host_id = render_frame_host->GetGlobalId(); const int render_process_host_id = render_frame_host->GetProcess()->GetID(); auto mock_dedicated_worker = std::make_unique<MockDedicatedWorker>( render_process_host_id, ancestor_render_frame_host_id); observer.RunUntilWorkerEvent(); // The service sent a OnWorkerStarted() notification. { ASSERT_EQ(observer.dedicated_worker_infos().size(), 1u); const auto& dedicated_worker_info = observer.dedicated_worker_infos().begin()->second; EXPECT_EQ(dedicated_worker_info.worker_process_id, render_process_host_id); EXPECT_EQ(dedicated_worker_info.ancestor_render_frame_host_id, ancestor_render_frame_host_id); } // Test EnumerateDedicatedWorkers(). { TestDedicatedWorkerServiceObserver enumeration_observer; EXPECT_TRUE(enumeration_observer.dedicated_worker_infos().empty()); GetDedicatedWorkerService()->EnumerateDedicatedWorkers( &enumeration_observer); ASSERT_EQ(enumeration_observer.dedicated_worker_infos().size(), 1u); const auto& dedicated_worker_info = enumeration_observer.dedicated_worker_infos().begin()->second; EXPECT_EQ(dedicated_worker_info.worker_process_id, render_process_host_id); EXPECT_EQ(dedicated_worker_info.ancestor_render_frame_host_id, ancestor_render_frame_host_id); } // Delete the dedicated worker. mock_dedicated_worker = nullptr; observer.RunUntilWorkerEvent(); // The service sent a OnBeforeWorkerTerminated() notification. EXPECT_TRUE(observer.dedicated_worker_infos().empty()); } // Runs DedicatedWorkerServiceImplTest with both the enabled and disabled state // of the kPlzDedicatedWorker feature. INSTANTIATE_TEST_SUITE_P(, DedicatedWorkerServiceImplTest, testing::Bool()); } // namespace content
#pragma once #include <object.hpp> #include <string_object.hpp> #include <null_object.hpp> #include <memory> #include <vector> namespace walnut { struct TupleObject : Object { std::vector<ObjectPtr> elements; typedef std::vector<ObjectPtr>::iterator ObjectIterator; ObjectIterator iterator; TupleObject() : Object(TUPLE, true), elements({}), iterator(elements.begin()) {} explicit TupleObject(const std::vector<ObjectPtr> &elements) : Object(TUPLE, true), elements(elements), iterator(this->elements.begin()) {} ObjectPtr Copy() override { std::shared_ptr<TupleObject> result = std::make_shared<TupleObject>(); for (auto &element : elements) result->elements.push_back(element->Copy()); result->iterator = result->elements.begin(); result->iterable = true; return result; } void IterableInit() override { iterator = elements.begin(); } ObjectIterator IterableNext() override { if (iterator != elements.end()) iterator = iterator + 1; return iterator; } ObjectPtr IterableCurrentValue() override { if (iterator != elements.end()) return *(iterator); else return std::make_shared<NullObject>(); } std::vector<ObjectPtr>::iterator IterableEnd() override { return elements.end(); } size_t IterableSize() override { return elements.size(); } void IterableAppend(ObjectPtr value) override { elements.push_back(value); } String Inspect() override { String result = ""; result += "("; if (elements.size() == 1) { if (elements[0]->type != ObjectType::STRING) result += elements[0]->Inspect(); else { StringObjectPtr string_element = std::dynamic_pointer_cast<StringObject>(elements[0]); result += "\"" + string_element->Value() + "\""; } } else if (elements.size() > 1) { for (size_t i = 0; i < elements.size() - 1; i++) { if (elements[i]->type != ObjectType::STRING) result += elements[i]->Inspect() + ", "; else { StringObjectPtr string_element = std::dynamic_pointer_cast<StringObject>(elements[i]); result += "\"" + string_element->Value() + "\"" + ", "; } } if (elements[elements.size() - 1]->type != ObjectType::STRING) result += elements[elements.size() - 1]->Inspect(); else { StringObjectPtr string_element = std::dynamic_pointer_cast<StringObject>(elements[elements.size() - 1]); result += "\"" + string_element->Value() + "\""; } } result += ")"; return result; } }; typedef std::shared_ptr<TupleObject> TupleObjectPtr; } // namespace walnut
// Copyright 2014 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #if V8_TARGET_ARCH_S390 #include "src/api/api-arguments.h" #include "src/codegen/code-factory.h" #include "src/codegen/interface-descriptors-inl.h" // For interpreter_entry_return_pc_offset. TODO(jkummerow): Drop. #include "src/codegen/macro-assembler-inl.h" #include "src/codegen/register-configuration.h" #include "src/debug/debug.h" #include "src/deoptimizer/deoptimizer.h" #include "src/execution/frame-constants.h" #include "src/execution/frames.h" #include "src/heap/heap-inl.h" #include "src/logging/counters.h" #include "src/objects/cell.h" #include "src/objects/foreign.h" #include "src/objects/heap-number.h" #include "src/objects/js-generator.h" #include "src/objects/smi.h" #include "src/runtime/runtime.h" #if V8_ENABLE_WEBASSEMBLY #include "src/wasm/wasm-linkage.h" #include "src/wasm/wasm-objects.h" #endif // V8_ENABLE_WEBASSEMBLY namespace v8 { namespace internal { #define __ ACCESS_MASM(masm) void Builtins::Generate_Adaptor(MacroAssembler* masm, Address address) { __ Move(kJavaScriptCallExtraArg1Register, ExternalReference::Create(address)); __ Jump(BUILTIN_CODE(masm->isolate(), AdaptorWithBuiltinExitFrame), RelocInfo::CODE_TARGET); } static void GenerateTailCallToReturnedCode(MacroAssembler* masm, Runtime::FunctionId function_id) { // ----------- S t a t e ------------- // -- r2 : actual argument count // -- r3 : target function (preserved for callee) // -- r5 : new target (preserved for callee) // ----------------------------------- { FrameAndConstantPoolScope scope(masm, StackFrame::INTERNAL); // Push a copy of the target function, the new target and the actual // argument count. // Push function as parameter to the runtime call. __ SmiTag(kJavaScriptCallArgCountRegister); __ Push(kJavaScriptCallTargetRegister, kJavaScriptCallNewTargetRegister, kJavaScriptCallArgCountRegister, kJavaScriptCallTargetRegister); __ CallRuntime(function_id, 1); __ mov(r4, r2); // Restore target function, new target and actual argument count. __ Pop(kJavaScriptCallTargetRegister, kJavaScriptCallNewTargetRegister, kJavaScriptCallArgCountRegister); __ SmiUntag(kJavaScriptCallArgCountRegister); } static_assert(kJavaScriptCallCodeStartRegister == r4, "ABI mismatch"); __ JumpCodeObject(r4); } namespace { void Generate_JSBuiltinsConstructStubHelper(MacroAssembler* masm) { // ----------- S t a t e ------------- // -- r2 : number of arguments // -- r3 : constructor function // -- r5 : new target // -- cp : context // -- lr : return address // -- sp[...]: constructor arguments // ----------------------------------- Register scratch = r4; Label stack_overflow; __ StackOverflowCheck(r2, scratch, &stack_overflow); // Enter a construct frame. { FrameAndConstantPoolScope scope(masm, StackFrame::CONSTRUCT); // Preserve the incoming parameters on the stack. __ SmiTag(r2); __ Push(cp, r2); __ SmiUntag(r2); // TODO(victorgomes): When the arguments adaptor is completely removed, we // should get the formal parameter count and copy the arguments in its // correct position (including any undefined), instead of delaying this to // InvokeFunction. // Set up pointer to last argument (skip receiver). __ la(r6, MemOperand(fp, StandardFrameConstants::kCallerSPOffset + kSystemPointerSize)); // Copy arguments and receiver to the expression stack. __ PushArray(r6, r2, r1, r0); // The receiver for the builtin/api call. __ PushRoot(RootIndex::kTheHoleValue); // Call the function. // r2: number of arguments // r3: constructor function // r5: new target __ InvokeFunctionWithNewTarget(r3, r5, r2, CALL_FUNCTION); // Restore context from the frame. __ LoadU64(cp, MemOperand(fp, ConstructFrameConstants::kContextOffset)); // Restore smi-tagged arguments count from the frame. __ LoadU64(scratch, MemOperand(fp, ConstructFrameConstants::kLengthOffset)); // Leave construct frame. } // Remove caller arguments from the stack and return. STATIC_ASSERT(kSmiTagSize == 1 && kSmiTag == 0); __ SmiToPtrArrayOffset(scratch, scratch); __ AddS64(sp, sp, scratch); __ AddS64(sp, sp, Operand(kSystemPointerSize)); __ Ret(); __ bind(&stack_overflow); { FrameScope scope(masm, StackFrame::INTERNAL); __ CallRuntime(Runtime::kThrowStackOverflow); __ bkpt(0); // Unreachable code. } } } // namespace // The construct stub for ES5 constructor functions and ES6 class constructors. void Builtins::Generate_JSConstructStubGeneric(MacroAssembler* masm) { // ----------- S t a t e ------------- // -- r2: number of arguments (untagged) // -- r3: constructor function // -- r5: new target // -- cp: context // -- lr: return address // -- sp[...]: constructor arguments // ----------------------------------- FrameScope scope(masm, StackFrame::MANUAL); // Enter a construct frame. Label post_instantiation_deopt_entry, not_create_implicit_receiver; __ EnterFrame(StackFrame::CONSTRUCT); // Preserve the incoming parameters on the stack. __ SmiTag(r2); __ Push(cp, r2, r3); __ PushRoot(RootIndex::kUndefinedValue); __ Push(r5); // ----------- S t a t e ------------- // -- sp[0*kSystemPointerSize]: new target // -- sp[1*kSystemPointerSize]: padding // -- r3 and sp[2*kSystemPointerSize]: constructor function // -- sp[3*kSystemPointerSize]: number of arguments (tagged) // -- sp[4*kSystemPointerSize]: context // ----------------------------------- __ LoadTaggedPointerField( r6, FieldMemOperand(r3, JSFunction::kSharedFunctionInfoOffset)); __ LoadU32(r6, FieldMemOperand(r6, SharedFunctionInfo::kFlagsOffset)); __ DecodeField<SharedFunctionInfo::FunctionKindBits>(r6); __ JumpIfIsInRange(r6, kDefaultDerivedConstructor, kDerivedConstructor, &not_create_implicit_receiver); // If not derived class constructor: Allocate the new receiver object. __ IncrementCounter(masm->isolate()->counters()->constructed_objects(), 1, r6, r7); __ Call(BUILTIN_CODE(masm->isolate(), FastNewObject), RelocInfo::CODE_TARGET); __ b(&post_instantiation_deopt_entry); // Else: use TheHoleValue as receiver for constructor call __ bind(&not_create_implicit_receiver); __ LoadRoot(r2, RootIndex::kTheHoleValue); // ----------- S t a t e ------------- // -- r2: receiver // -- Slot 4 / sp[0*kSystemPointerSize]: new target // -- Slot 3 / sp[1*kSystemPointerSize]: padding // -- Slot 2 / sp[2*kSystemPointerSize]: constructor function // -- Slot 1 / sp[3*kSystemPointerSize]: number of arguments (tagged) // -- Slot 0 / sp[4*kSystemPointerSize]: context // ----------------------------------- // Deoptimizer enters here. masm->isolate()->heap()->SetConstructStubCreateDeoptPCOffset( masm->pc_offset()); __ bind(&post_instantiation_deopt_entry); // Restore new target. __ Pop(r5); // Push the allocated receiver to the stack. __ Push(r2); // We need two copies because we may have to return the original one // and the calling conventions dictate that the called function pops the // receiver. The second copy is pushed after the arguments, we saved in r6 // since r0 needs to store the number of arguments before // InvokingFunction. __ mov(r8, r2); // Set up pointer to first argument (skip receiver). __ la(r6, MemOperand(fp, StandardFrameConstants::kCallerSPOffset + kSystemPointerSize)); // ----------- S t a t e ------------- // -- r5: new target // -- sp[0*kSystemPointerSize]: implicit receiver // -- sp[1*kSystemPointerSize]: implicit receiver // -- sp[2*kSystemPointerSize]: padding // -- sp[3*kSystemPointerSize]: constructor function // -- sp[4*kSystemPointerSize]: number of arguments (tagged) // -- sp[5*kSystemPointerSize]: context // ----------------------------------- // Restore constructor function and argument count. __ LoadU64(r3, MemOperand(fp, ConstructFrameConstants::kConstructorOffset)); __ LoadU64(r2, MemOperand(fp, ConstructFrameConstants::kLengthOffset)); __ SmiUntag(r2); Label stack_overflow; __ StackOverflowCheck(r2, r7, &stack_overflow); // Copy arguments and receiver to the expression stack. __ PushArray(r6, r2, r1, r0); // Push implicit receiver. __ Push(r8); // Call the function. __ InvokeFunctionWithNewTarget(r3, r5, r2, CALL_FUNCTION); // ----------- S t a t e ------------- // -- r0: constructor result // -- sp[0*kSystemPointerSize]: implicit receiver // -- sp[1*kSystemPointerSize]: padding // -- sp[2*kSystemPointerSize]: constructor function // -- sp[3*kSystemPointerSize]: number of arguments // -- sp[4*kSystemPointerSize]: context // ----------------------------------- // Store offset of return address for deoptimizer. masm->isolate()->heap()->SetConstructStubInvokeDeoptPCOffset( masm->pc_offset()); // If the result is an object (in the ECMA sense), we should get rid // of the receiver and use the result; see ECMA-262 section 13.2.2-7 // on page 74. Label use_receiver, do_throw, leave_and_return, check_receiver; // If the result is undefined, we jump out to using the implicit receiver. __ JumpIfNotRoot(r2, RootIndex::kUndefinedValue, &check_receiver); // Otherwise we do a smi check and fall through to check if the return value // is a valid receiver. // Throw away the result of the constructor invocation and use the // on-stack receiver as the result. __ bind(&use_receiver); __ LoadU64(r2, MemOperand(sp)); __ JumpIfRoot(r2, RootIndex::kTheHoleValue, &do_throw); __ bind(&leave_and_return); // Restore smi-tagged arguments count from the frame. __ LoadU64(r3, MemOperand(fp, ConstructFrameConstants::kLengthOffset)); // Leave construct frame. __ LeaveFrame(StackFrame::CONSTRUCT); // Remove caller arguments from the stack and return. STATIC_ASSERT(kSmiTagSize == 1 && kSmiTag == 0); __ SmiToPtrArrayOffset(r3, r3); __ AddS64(sp, sp, r3); __ AddS64(sp, sp, Operand(kSystemPointerSize)); __ Ret(); __ bind(&check_receiver); // If the result is a smi, it is *not* an object in the ECMA sense. __ JumpIfSmi(r2, &use_receiver); // If the type of the result (stored in its map) is less than // FIRST_JS_RECEIVER_TYPE, it is not an object in the ECMA sense. STATIC_ASSERT(LAST_JS_RECEIVER_TYPE == LAST_TYPE); __ CompareObjectType(r2, r6, r6, FIRST_JS_RECEIVER_TYPE); __ bge(&leave_and_return); __ b(&use_receiver); __ bind(&do_throw); // Restore the context from the frame. __ LoadU64(cp, MemOperand(fp, ConstructFrameConstants::kContextOffset)); __ CallRuntime(Runtime::kThrowConstructorReturnedNonObject); __ bkpt(0); __ bind(&stack_overflow); // Restore the context from the frame. __ LoadU64(cp, MemOperand(fp, ConstructFrameConstants::kContextOffset)); __ CallRuntime(Runtime::kThrowStackOverflow); // Unreachable code. __ bkpt(0); } void Builtins::Generate_JSBuiltinsConstructStub(MacroAssembler* masm) { Generate_JSBuiltinsConstructStubHelper(masm); } static void GetSharedFunctionInfoBytecode(MacroAssembler* masm, Register sfi_data, Register scratch1) { Label done; __ CompareObjectType(sfi_data, scratch1, scratch1, INTERPRETER_DATA_TYPE); __ bne(&done, Label::kNear); __ LoadTaggedPointerField( sfi_data, FieldMemOperand(sfi_data, InterpreterData::kBytecodeArrayOffset)); __ bind(&done); } // static void Builtins::Generate_ResumeGeneratorTrampoline(MacroAssembler* masm) { // ----------- S t a t e ------------- // -- r2 : the value to pass to the generator // -- r3 : the JSGeneratorObject to resume // -- lr : return address // ----------------------------------- __ AssertGeneratorObject(r3); // Store input value into generator object. __ StoreTaggedField( r2, FieldMemOperand(r3, JSGeneratorObject::kInputOrDebugPosOffset), r0); __ RecordWriteField(r3, JSGeneratorObject::kInputOrDebugPosOffset, r2, r5, kLRHasNotBeenSaved, kDontSaveFPRegs); // Load suspended function and context. __ LoadTaggedPointerField( r6, FieldMemOperand(r3, JSGeneratorObject::kFunctionOffset)); __ LoadTaggedPointerField(cp, FieldMemOperand(r6, JSFunction::kContextOffset)); // Flood function if we are stepping. Label prepare_step_in_if_stepping, prepare_step_in_suspended_generator; Label stepping_prepared; Register scratch = r7; ExternalReference debug_hook = ExternalReference::debug_hook_on_function_call_address(masm->isolate()); __ Move(scratch, debug_hook); __ LoadS8(scratch, MemOperand(scratch)); __ CmpSmiLiteral(scratch, Smi::zero(), r0); __ bne(&prepare_step_in_if_stepping); // Flood function if we need to continue stepping in the suspended generator. ExternalReference debug_suspended_generator = ExternalReference::debug_suspended_generator_address(masm->isolate()); __ Move(scratch, debug_suspended_generator); __ LoadU64(scratch, MemOperand(scratch)); __ CmpS64(scratch, r3); __ beq(&prepare_step_in_suspended_generator); __ bind(&stepping_prepared); // Check the stack for overflow. We are not trying to catch interruptions // (i.e. debug break and preemption) here, so check the "real stack limit". Label stack_overflow; __ LoadU64(scratch, __ StackLimitAsMemOperand(StackLimitKind::kRealStackLimit)); __ CmpU64(sp, scratch); __ blt(&stack_overflow); // ----------- S t a t e ------------- // -- r3 : the JSGeneratorObject to resume // -- r6 : generator function // -- cp : generator context // -- lr : return address // ----------------------------------- // Copy the function arguments from the generator object's register file. __ LoadTaggedPointerField( r5, FieldMemOperand(r6, JSFunction::kSharedFunctionInfoOffset)); __ LoadU16( r5, FieldMemOperand(r5, SharedFunctionInfo::kFormalParameterCountOffset)); __ LoadTaggedPointerField( r4, FieldMemOperand(r3, JSGeneratorObject::kParametersAndRegistersOffset)); { Label done_loop, loop; __ mov(r8, r5); __ bind(&loop); __ SubS64(r8, r8, Operand(1)); __ blt(&done_loop); __ ShiftLeftU64(r1, r8, Operand(kTaggedSizeLog2)); __ la(scratch, MemOperand(r4, r1)); __ LoadAnyTaggedField(scratch, FieldMemOperand(scratch, FixedArray::kHeaderSize)); __ Push(scratch); __ b(&loop); __ bind(&done_loop); // Push receiver. __ LoadAnyTaggedField( scratch, FieldMemOperand(r3, JSGeneratorObject::kReceiverOffset)); __ Push(scratch); } // Underlying function needs to have bytecode available. if (FLAG_debug_code) { __ LoadTaggedPointerField( r5, FieldMemOperand(r6, JSFunction::kSharedFunctionInfoOffset)); __ LoadTaggedPointerField( r5, FieldMemOperand(r5, SharedFunctionInfo::kFunctionDataOffset)); GetSharedFunctionInfoBytecode(masm, r5, ip); __ CompareObjectType(r5, r5, r5, BYTECODE_ARRAY_TYPE); __ Assert(eq, AbortReason::kMissingBytecodeArray); } // Resume (Ignition/TurboFan) generator object. { __ LoadTaggedPointerField( r2, FieldMemOperand(r6, JSFunction::kSharedFunctionInfoOffset)); __ LoadS16( r2, FieldMemOperand(r2, SharedFunctionInfo::kFormalParameterCountOffset)); // We abuse new.target both to indicate that this is a resume call and to // pass in the generator object. In ordinary calls, new.target is always // undefined because generator functions are non-constructable. __ mov(r5, r3); __ mov(r3, r6); static_assert(kJavaScriptCallCodeStartRegister == r4, "ABI mismatch"); __ LoadTaggedPointerField(r4, FieldMemOperand(r3, JSFunction::kCodeOffset)); __ JumpCodeObject(r4); } __ bind(&prepare_step_in_if_stepping); { FrameAndConstantPoolScope scope(masm, StackFrame::INTERNAL); __ Push(r3, r6); // Push hole as receiver since we do not use it for stepping. __ PushRoot(RootIndex::kTheHoleValue); __ CallRuntime(Runtime::kDebugOnFunctionCall); __ Pop(r3); __ LoadTaggedPointerField( r6, FieldMemOperand(r3, JSGeneratorObject::kFunctionOffset)); } __ b(&stepping_prepared); __ bind(&prepare_step_in_suspended_generator); { FrameAndConstantPoolScope scope(masm, StackFrame::INTERNAL); __ Push(r3); __ CallRuntime(Runtime::kDebugPrepareStepInSuspendedGenerator); __ Pop(r3); __ LoadTaggedPointerField( r6, FieldMemOperand(r3, JSGeneratorObject::kFunctionOffset)); } __ b(&stepping_prepared); __ bind(&stack_overflow); { FrameScope scope(masm, StackFrame::INTERNAL); __ CallRuntime(Runtime::kThrowStackOverflow); __ bkpt(0); // This should be unreachable. } } void Builtins::Generate_ConstructedNonConstructable(MacroAssembler* masm) { FrameAndConstantPoolScope scope(masm, StackFrame::INTERNAL); __ push(r3); __ CallRuntime(Runtime::kThrowConstructedNonConstructable); } namespace { constexpr int kPushedStackSpace = (kNumCalleeSaved + 2) * kSystemPointerSize + kNumCalleeSavedDoubles * kDoubleSize + 5 * kSystemPointerSize + EntryFrameConstants::kCallerFPOffset - kSystemPointerSize; // Called with the native C calling convention. The corresponding function // signature is either: // // using JSEntryFunction = GeneratedCode<Address( // Address root_register_value, Address new_target, Address target, // Address receiver, intptr_t argc, Address** args)>; // or // using JSEntryFunction = GeneratedCode<Address( // Address root_register_value, MicrotaskQueue* microtask_queue)>; void Generate_JSEntryVariant(MacroAssembler* masm, StackFrame::Type type, Builtins::Name entry_trampoline) { // The register state is either: // r2: root register value // r3: code entry // r4: function // r5: receiver // r6: argc // [sp + 20 * kSystemPointerSize]: argv // or // r2: root_register_value // r3: microtask_queue Label invoke, handler_entry, exit; int pushed_stack_space = 0; { NoRootArrayScope no_root_array(masm); // saving floating point registers // 64bit ABI requires f8 to f15 be saved // http://refspecs.linuxbase.org/ELF/zSeries/lzsabi0_zSeries.html __ lay(sp, MemOperand(sp, -8 * kDoubleSize)); __ std(d8, MemOperand(sp)); __ std(d9, MemOperand(sp, 1 * kDoubleSize)); __ std(d10, MemOperand(sp, 2 * kDoubleSize)); __ std(d11, MemOperand(sp, 3 * kDoubleSize)); __ std(d12, MemOperand(sp, 4 * kDoubleSize)); __ std(d13, MemOperand(sp, 5 * kDoubleSize)); __ std(d14, MemOperand(sp, 6 * kDoubleSize)); __ std(d15, MemOperand(sp, 7 * kDoubleSize)); pushed_stack_space += kNumCalleeSavedDoubles * kDoubleSize; // zLinux ABI // Incoming parameters: // r2: root register value // r3: code entry // r4: function // r5: receiver // r6: argc // [sp + 20 * kSystemPointerSize]: argv // Requires us to save the callee-preserved registers r6-r13 // General convention is to also save r14 (return addr) and // sp/r15 as well in a single STM/STMG __ lay(sp, MemOperand(sp, -10 * kSystemPointerSize)); __ StoreMultipleP(r6, sp, MemOperand(sp, 0)); pushed_stack_space += (kNumCalleeSaved + 2) * kSystemPointerSize; // Initialize the root register. // C calling convention. The first argument is passed in r2. __ mov(kRootRegister, r2); } // save r6 to r1 __ mov(r0, r6); // Push a frame with special values setup to mark it as an entry frame. // Bad FP (-1) // SMI Marker // SMI Marker // kCEntryFPAddress // Frame type __ lay(sp, MemOperand(sp, -5 * kSystemPointerSize)); pushed_stack_space += 5 * kSystemPointerSize; // Push a bad frame pointer to fail if it is used. __ mov(r9, Operand(-1)); __ mov(r8, Operand(StackFrame::TypeToMarker(type))); __ mov(r7, Operand(StackFrame::TypeToMarker(type))); // Save copies of the top frame descriptor on the stack. __ Move(r1, ExternalReference::Create(IsolateAddressId::kCEntryFPAddress, masm->isolate())); __ LoadU64(r6, MemOperand(r1)); __ StoreMultipleP(r6, r9, MemOperand(sp, kSystemPointerSize)); // Clear c_entry_fp, now we've pushed its previous value to the stack. // If the c_entry_fp is not already zero and we don't clear it, the // SafeStackFrameIterator will assume we are executing C++ and miss the JS // frames on top. __ mov(r6, Operand::Zero()); __ StoreU64(r6, MemOperand(r1)); Register scrach = r8; // Set up frame pointer for the frame to be pushed. // Need to add kSystemPointerSize, because sp has one extra // frame already for the frame type being pushed later. __ lay(fp, MemOperand(sp, -EntryFrameConstants::kCallerFPOffset + kSystemPointerSize)); pushed_stack_space += EntryFrameConstants::kCallerFPOffset - kSystemPointerSize; // restore r6 __ mov(r6, r0); // If this is the outermost JS call, set js_entry_sp value. Label non_outermost_js; ExternalReference js_entry_sp = ExternalReference::Create(IsolateAddressId::kJSEntrySPAddress, masm->isolate()); __ Move(r7, js_entry_sp); __ LoadAndTestP(scrach, MemOperand(r7)); __ bne(&non_outermost_js, Label::kNear); __ StoreU64(fp, MemOperand(r7)); __ mov(scrach, Operand(StackFrame::OUTERMOST_JSENTRY_FRAME)); Label cont; __ b(&cont, Label::kNear); __ bind(&non_outermost_js); __ mov(scrach, Operand(StackFrame::INNER_JSENTRY_FRAME)); __ bind(&cont); __ StoreU64(scrach, MemOperand(sp)); // frame-type // Jump to a faked try block that does the invoke, with a faked catch // block that sets the pending exception. __ b(&invoke, Label::kNear); __ bind(&handler_entry); // Store the current pc as the handler offset. It's used later to create the // handler table. masm->isolate()->builtins()->SetJSEntryHandlerOffset(handler_entry.pos()); // Caught exception: Store result (exception) in the pending exception // field in the JSEnv and return a failure sentinel. Coming in here the // fp will be invalid because the PushStackHandler below sets it to 0 to // signal the existence of the JSEntry frame. __ Move(scrach, ExternalReference::Create(IsolateAddressId::kPendingExceptionAddress, masm->isolate())); __ StoreU64(r2, MemOperand(scrach)); __ LoadRoot(r2, RootIndex::kException); __ b(&exit, Label::kNear); // Invoke: Link this frame into the handler chain. __ bind(&invoke); // Must preserve r2-r6. __ PushStackHandler(); // If an exception not caught by another handler occurs, this handler // returns control to the code after the b(&invoke) above, which // restores all kCalleeSaved registers (including cp and fp) to their // saved values before returning a failure to C. // Invoke the function by calling through JS entry trampoline builtin. // Notice that we cannot store a reference to the trampoline code directly in // this stub, because runtime stubs are not traversed when doing GC. // Invoke the function by calling through JS entry trampoline builtin and // pop the faked function when we return. Handle<Code> trampoline_code = masm->isolate()->builtins()->builtin_handle(entry_trampoline); DCHECK_EQ(kPushedStackSpace, pushed_stack_space); __ Call(trampoline_code, RelocInfo::CODE_TARGET); // Unlink this frame from the handler chain. __ PopStackHandler(); __ bind(&exit); // r2 holds result // Check if the current stack frame is marked as the outermost JS frame. Label non_outermost_js_2; __ pop(r7); __ CmpS64(r7, Operand(StackFrame::OUTERMOST_JSENTRY_FRAME)); __ bne(&non_outermost_js_2, Label::kNear); __ mov(scrach, Operand::Zero()); __ Move(r7, js_entry_sp); __ StoreU64(scrach, MemOperand(r7)); __ bind(&non_outermost_js_2); // Restore the top frame descriptors from the stack. __ pop(r5); __ Move(scrach, ExternalReference::Create(IsolateAddressId::kCEntryFPAddress, masm->isolate())); __ StoreU64(r5, MemOperand(scrach)); // Reset the stack to the callee saved registers. __ lay(sp, MemOperand(sp, -EntryFrameConstants::kCallerFPOffset)); // Reload callee-saved preserved regs, return address reg (r14) and sp __ LoadMultipleP(r6, sp, MemOperand(sp, 0)); __ la(sp, MemOperand(sp, 10 * kSystemPointerSize)); // saving floating point registers #if V8_TARGET_ARCH_S390X // 64bit ABI requires f8 to f15 be saved __ ld(d8, MemOperand(sp)); __ ld(d9, MemOperand(sp, 1 * kDoubleSize)); __ ld(d10, MemOperand(sp, 2 * kDoubleSize)); __ ld(d11, MemOperand(sp, 3 * kDoubleSize)); __ ld(d12, MemOperand(sp, 4 * kDoubleSize)); __ ld(d13, MemOperand(sp, 5 * kDoubleSize)); __ ld(d14, MemOperand(sp, 6 * kDoubleSize)); __ ld(d15, MemOperand(sp, 7 * kDoubleSize)); __ la(sp, MemOperand(sp, 8 * kDoubleSize)); #else // 31bit ABI requires you to store f4 and f6: // http://refspecs.linuxbase.org/ELF/zSeries/lzsabi0_s390.html#AEN417 __ ld(d4, MemOperand(sp)); __ ld(d6, MemOperand(sp, kDoubleSize)); __ la(sp, MemOperand(sp, 2 * kDoubleSize)); #endif __ b(r14); } } // namespace void Builtins::Generate_JSEntry(MacroAssembler* masm) { Generate_JSEntryVariant(masm, StackFrame::ENTRY, Builtins::kJSEntryTrampoline); } void Builtins::Generate_JSConstructEntry(MacroAssembler* masm) { Generate_JSEntryVariant(masm, StackFrame::CONSTRUCT_ENTRY, Builtins::kJSConstructEntryTrampoline); } void Builtins::Generate_JSRunMicrotasksEntry(MacroAssembler* masm) { Generate_JSEntryVariant(masm, StackFrame::ENTRY, Builtins::kRunMicrotasksTrampoline); } static void Generate_JSEntryTrampolineHelper(MacroAssembler* masm, bool is_construct) { // Called from Generate_JS_Entry // r3: new.target // r4: function // r5: receiver // r6: argc // [fp + kPushedStackSpace + 20 * kSystemPointerSize]: argv // r0,r2,r7-r9, cp may be clobbered __ mov(r2, r6); // Load argv from the stack. __ LoadU64( r6, MemOperand(fp, kPushedStackSpace + EntryFrameConstants::kArgvOffset)); // r2: argc // r3: new.target // r4: function // r5: receiver // r6: argv // Enter an internal frame. { // FrameScope ends up calling MacroAssembler::EnterFrame here FrameScope scope(masm, StackFrame::INTERNAL); // Setup the context (we need to use the caller context from the isolate). ExternalReference context_address = ExternalReference::Create( IsolateAddressId::kContextAddress, masm->isolate()); __ Move(cp, context_address); __ LoadU64(cp, MemOperand(cp)); // Push the function __ Push(r4); // Check if we have enough stack space to push all arguments. Label enough_stack_space, stack_overflow; __ AddS64(r7, r2, Operand(1)); __ StackOverflowCheck(r7, r1, &stack_overflow); __ b(&enough_stack_space); __ bind(&stack_overflow); __ CallRuntime(Runtime::kThrowStackOverflow); // Unreachable code. __ bkpt(0); __ bind(&enough_stack_space); // Copy arguments to the stack in a loop from argv to sp. // The arguments are actually placed in reverse order on sp // compared to argv (i.e. arg1 is highest memory in sp). // r2: argc // r3: function // r5: new.target // r6: argv, i.e. points to first arg // r7: scratch reg to hold scaled argc // r8: scratch reg to hold arg handle // r9: scratch reg to hold index into argv Label argLoop, argExit; __ ShiftLeftU64(r9, r2, Operand(kSystemPointerSizeLog2)); __ lay(r9, MemOperand(r6, r9, -kSystemPointerSize)); // point to last arg __ ltgr(r7, r2); __ beq(&argExit, Label::kNear); __ bind(&argLoop); __ LoadU64(r8, MemOperand(r9)); // read next parameter __ LoadU64(r0, MemOperand(r8)); // dereference handle __ Push(r0); __ lay(r9, MemOperand(r9, -kSystemPointerSize)); // r9++; __ SubS64(r7, r7, Operand(1)); __ bgt(&argLoop); __ bind(&argExit); // Push the receiver. __ Push(r5); // Setup new.target, argc and function. __ mov(r5, r3); __ mov(r3, r4); // r2: argc // r3: function // r5: new.target // Initialize all JavaScript callee-saved registers, since they will be seen // by the garbage collector as part of handlers. __ LoadRoot(r4, RootIndex::kUndefinedValue); __ mov(r6, r4); __ mov(r7, r6); __ mov(r8, r6); __ mov(r9, r6); // Invoke the code. Handle<Code> builtin = is_construct ? BUILTIN_CODE(masm->isolate(), Construct) : masm->isolate()->builtins()->Call(); __ Call(builtin, RelocInfo::CODE_TARGET); // Exit the JS frame and remove the parameters (except function), and // return. } __ b(r14); // r2: result } void Builtins::Generate_JSEntryTrampoline(MacroAssembler* masm) { Generate_JSEntryTrampolineHelper(masm, false); } void Builtins::Generate_JSConstructEntryTrampoline(MacroAssembler* masm) { Generate_JSEntryTrampolineHelper(masm, true); } void Builtins::Generate_RunMicrotasksTrampoline(MacroAssembler* masm) { // This expects two C++ function parameters passed by Invoke() in // execution.cc. // r2: root_register_value // r3: microtask_queue __ mov(RunMicrotasksDescriptor::MicrotaskQueueRegister(), r3); __ Jump(BUILTIN_CODE(masm->isolate(), RunMicrotasks), RelocInfo::CODE_TARGET); } static void ReplaceClosureCodeWithOptimizedCode(MacroAssembler* masm, Register optimized_code, Register closure, Register scratch1, Register scratch2) { // Store code entry in the closure. __ StoreTaggedField(optimized_code, FieldMemOperand(closure, JSFunction::kCodeOffset), r0); __ mov(scratch1, optimized_code); // Write barrier clobbers scratch1 below. __ RecordWriteField(closure, JSFunction::kCodeOffset, scratch1, scratch2, kLRHasNotBeenSaved, kDontSaveFPRegs, OMIT_REMEMBERED_SET, OMIT_SMI_CHECK); } static void LeaveInterpreterFrame(MacroAssembler* masm, Register scratch1, Register scratch2) { Register params_size = scratch1; // Get the size of the formal parameters + receiver (in bytes). __ LoadU64(params_size, MemOperand(fp, InterpreterFrameConstants::kBytecodeArrayFromFp)); __ LoadU32(params_size, FieldMemOperand(params_size, BytecodeArray::kParameterSizeOffset)); Register actual_params_size = scratch2; // Compute the size of the actual parameters + receiver (in bytes). __ LoadU64(actual_params_size, MemOperand(fp, StandardFrameConstants::kArgCOffset)); __ ShiftLeftU64(actual_params_size, actual_params_size, Operand(kSystemPointerSizeLog2)); __ AddS64(actual_params_size, actual_params_size, Operand(kSystemPointerSize)); // If actual is bigger than formal, then we should use it to free up the stack // arguments. Label corrected_args_count; __ CmpS64(params_size, actual_params_size); __ bge(&corrected_args_count); __ mov(params_size, actual_params_size); __ bind(&corrected_args_count); // Leave the frame (also dropping the register file). __ LeaveFrame(StackFrame::INTERPRETED); __ AddS64(sp, sp, params_size); } // Tail-call |function_id| if |actual_marker| == |expected_marker| static void TailCallRuntimeIfMarkerEquals(MacroAssembler* masm, Register actual_marker, OptimizationMarker expected_marker, Runtime::FunctionId function_id) { Label no_match; __ CmpS64(actual_marker, Operand(expected_marker)); __ bne(&no_match); GenerateTailCallToReturnedCode(masm, function_id); __ bind(&no_match); } static void TailCallOptimizedCodeSlot(MacroAssembler* masm, Register optimized_code_entry, Register scratch) { // ----------- S t a t e ------------- // -- r2 : actual argument count // -- r5 : new target (preserved for callee if needed, and caller) // -- r3 : target function (preserved for callee if needed, and caller) // ----------------------------------- DCHECK(!AreAliased(r3, r5, optimized_code_entry, scratch)); Register closure = r3; Label heal_optimized_code_slot; // If the optimized code is cleared, go to runtime to update the optimization // marker field. __ LoadWeakValue(optimized_code_entry, optimized_code_entry, &heal_optimized_code_slot); // Check if the optimized code is marked for deopt. If it is, call the // runtime to clear it. __ LoadTaggedPointerField( scratch, FieldMemOperand(optimized_code_entry, Code::kCodeDataContainerOffset)); __ LoadS32(scratch, FieldMemOperand( scratch, CodeDataContainer::kKindSpecificFlagsOffset)); __ TestBit(scratch, Code::kMarkedForDeoptimizationBit, r0); __ bne(&heal_optimized_code_slot); // Optimized code is good, get it into the closure and link the closure // into the optimized functions list, then tail call the optimized code. ReplaceClosureCodeWithOptimizedCode(masm, optimized_code_entry, closure, scratch, r7); static_assert(kJavaScriptCallCodeStartRegister == r4, "ABI mismatch"); __ LoadCodeObjectEntry(r4, optimized_code_entry); __ Jump(r4); // Optimized code slot contains deoptimized code or code is cleared and // optimized code marker isn't updated. Evict the code, update the marker // and re-enter the closure's code. __ bind(&heal_optimized_code_slot); GenerateTailCallToReturnedCode(masm, Runtime::kHealOptimizedCodeSlot); } static void MaybeOptimizeCode(MacroAssembler* masm, Register feedback_vector, Register optimization_marker) { // ----------- S t a t e ------------- // -- r2 : actual argument count // -- r5 : new target (preserved for callee if needed, and caller) // -- r3 : target function (preserved for callee if needed, and caller) // -- feedback vector (preserved for caller if needed) // -- optimization_marker : a int32 containing a non-zero optimization // marker. // ----------------------------------- DCHECK(!AreAliased(feedback_vector, r3, r5, optimization_marker)); // TODO(v8:8394): The logging of first execution will break if // feedback vectors are not allocated. We need to find a different way of // logging these events if required. TailCallRuntimeIfMarkerEquals(masm, optimization_marker, OptimizationMarker::kLogFirstExecution, Runtime::kFunctionFirstExecution); TailCallRuntimeIfMarkerEquals(masm, optimization_marker, OptimizationMarker::kCompileOptimized, Runtime::kCompileOptimized_NotConcurrent); TailCallRuntimeIfMarkerEquals(masm, optimization_marker, OptimizationMarker::kCompileOptimizedConcurrent, Runtime::kCompileOptimized_Concurrent); // Marker should be one of LogFirstExecution / CompileOptimized / // CompileOptimizedConcurrent. InOptimizationQueue and None shouldn't reach // here. if (FLAG_debug_code) { __ stop(); } } // Advance the current bytecode offset. This simulates what all bytecode // handlers do upon completion of the underlying operation. Will bail out to a // label if the bytecode (without prefix) is a return bytecode. Will not advance // the bytecode offset if the current bytecode is a JumpLoop, instead just // re-executing the JumpLoop to jump to the correct bytecode. static void AdvanceBytecodeOffsetOrReturn(MacroAssembler* masm, Register bytecode_array, Register bytecode_offset, Register bytecode, Register scratch1, Register scratch2, Label* if_return) { Register bytecode_size_table = scratch1; Register scratch3 = bytecode; // The bytecode offset value will be increased by one in wide and extra wide // cases. In the case of having a wide or extra wide JumpLoop bytecode, we // will restore the original bytecode. In order to simplify the code, we have // a backup of it. Register original_bytecode_offset = scratch2; DCHECK(!AreAliased(bytecode_array, bytecode_offset, bytecode_size_table, bytecode, original_bytecode_offset)); __ Move(bytecode_size_table, ExternalReference::bytecode_size_table_address()); __ Move(original_bytecode_offset, bytecode_offset); // Check if the bytecode is a Wide or ExtraWide prefix bytecode. Label process_bytecode, extra_wide; STATIC_ASSERT(0 == static_cast<int>(interpreter::Bytecode::kWide)); STATIC_ASSERT(1 == static_cast<int>(interpreter::Bytecode::kExtraWide)); STATIC_ASSERT(2 == static_cast<int>(interpreter::Bytecode::kDebugBreakWide)); STATIC_ASSERT(3 == static_cast<int>(interpreter::Bytecode::kDebugBreakExtraWide)); __ CmpS64(bytecode, Operand(0x3)); __ bgt(&process_bytecode); __ tmll(bytecode, Operand(0x1)); __ bne(&extra_wide); // Load the next bytecode and update table to the wide scaled table. __ AddS64(bytecode_offset, bytecode_offset, Operand(1)); __ LoadU8(bytecode, MemOperand(bytecode_array, bytecode_offset)); __ AddS64(bytecode_size_table, bytecode_size_table, Operand(kByteSize * interpreter::Bytecodes::kBytecodeCount)); __ b(&process_bytecode); __ bind(&extra_wide); // Load the next bytecode and update table to the extra wide scaled table. __ AddS64(bytecode_offset, bytecode_offset, Operand(1)); __ LoadU8(bytecode, MemOperand(bytecode_array, bytecode_offset)); __ AddS64(bytecode_size_table, bytecode_size_table, Operand(2 * kByteSize * interpreter::Bytecodes::kBytecodeCount)); // Load the size of the current bytecode. __ bind(&process_bytecode); // Bailout to the return label if this is a return bytecode. #define JUMP_IF_EQUAL(NAME) \ __ CmpS64(bytecode, \ Operand(static_cast<int>(interpreter::Bytecode::k##NAME))); \ __ beq(if_return); RETURN_BYTECODE_LIST(JUMP_IF_EQUAL) #undef JUMP_IF_EQUAL // If this is a JumpLoop, re-execute it to perform the jump to the beginning // of the loop. Label end, not_jump_loop; __ CmpS64(bytecode, Operand(static_cast<int>(interpreter::Bytecode::kJumpLoop))); __ bne(&not_jump_loop); // We need to restore the original bytecode_offset since we might have // increased it to skip the wide / extra-wide prefix bytecode. __ Move(bytecode_offset, original_bytecode_offset); __ b(&end); __ bind(&not_jump_loop); // Otherwise, load the size of the current bytecode and advance the offset. __ LoadU8(scratch3, MemOperand(bytecode_size_table, bytecode)); __ AddS64(bytecode_offset, bytecode_offset, scratch3); __ bind(&end); } static void MaybeOptimizeCodeOrTailCallOptimizedCodeSlot( MacroAssembler* masm, Register optimization_state, Register feedback_vector) { Label maybe_has_optimized_code; // Check if optimized code is available __ TestBitMask(optimization_state, FeedbackVector::kHasCompileOptimizedOrLogFirstExecutionMarker, r0); __ beq(&maybe_has_optimized_code); Register optimization_marker = optimization_state; __ DecodeField<FeedbackVector::OptimizationMarkerBits>(optimization_marker); MaybeOptimizeCode(masm, feedback_vector, optimization_marker); __ bind(&maybe_has_optimized_code); Register optimized_code_entry = optimization_state; __ LoadAnyTaggedField( optimization_marker, FieldMemOperand(feedback_vector, FeedbackVector::kMaybeOptimizedCodeOffset)); TailCallOptimizedCodeSlot(masm, optimized_code_entry, r8); } // Generate code for entering a JS function with the interpreter. // On entry to the function the receiver and arguments have been pushed on the // stack left to right. // // The live registers are: // o r2: actual argument count (not including the receiver) // o r3: the JS function object being called. // o r5: the incoming new target or generator object // o cp: our context // o pp: the caller's constant pool pointer (if enabled) // o fp: the caller's frame pointer // o sp: stack pointer // o lr: return address // // The function builds an interpreter frame. See InterpreterFrameConstants in // frames.h for its layout. void Builtins::Generate_InterpreterEntryTrampoline(MacroAssembler* masm) { Register closure = r3; Register feedback_vector = r4; // Get the bytecode array from the function object and load it into // kInterpreterBytecodeArrayRegister. __ LoadTaggedPointerField( r6, FieldMemOperand(closure, JSFunction::kSharedFunctionInfoOffset)); // Load original bytecode array or the debug copy. __ LoadTaggedPointerField( kInterpreterBytecodeArrayRegister, FieldMemOperand(r6, SharedFunctionInfo::kFunctionDataOffset)); GetSharedFunctionInfoBytecode(masm, kInterpreterBytecodeArrayRegister, ip); // The bytecode array could have been flushed from the shared function info, // if so, call into CompileLazy. Label compile_lazy; __ CompareObjectType(kInterpreterBytecodeArrayRegister, r6, no_reg, BYTECODE_ARRAY_TYPE); __ bne(&compile_lazy); // Load the feedback vector from the closure. __ LoadTaggedPointerField( feedback_vector, FieldMemOperand(closure, JSFunction::kFeedbackCellOffset)); __ LoadTaggedPointerField( feedback_vector, FieldMemOperand(feedback_vector, Cell::kValueOffset)); Label push_stack_frame; // Check if feedback vector is valid. If valid, check for optimized code // and update invocation count. Otherwise, setup the stack frame. __ LoadTaggedPointerField( r6, FieldMemOperand(feedback_vector, HeapObject::kMapOffset)); __ LoadU16(r6, FieldMemOperand(r6, Map::kInstanceTypeOffset)); __ CmpS64(r6, Operand(FEEDBACK_VECTOR_TYPE)); __ bne(&push_stack_frame); Register optimization_state = r6; // Read off the optimization state in the feedback vector. __ LoadS32(optimization_state, FieldMemOperand(feedback_vector, FeedbackVector::kFlagsOffset)); // Check if the optimized code slot is not empty or has a optimization marker. Label has_optimized_code_or_marker; __ TestBitMask(optimization_state, FeedbackVector::kHasOptimizedCodeOrCompileOptimizedMarkerMask, r0); __ bne(&has_optimized_code_or_marker); Label not_optimized; __ bind(&not_optimized); // Increment invocation count for the function. __ LoadS32(r1, FieldMemOperand(feedback_vector, FeedbackVector::kInvocationCountOffset)); __ AddS64(r1, r1, Operand(1)); __ StoreU32(r1, FieldMemOperand(feedback_vector, FeedbackVector::kInvocationCountOffset)); // Open a frame scope to indicate that there is a frame on the stack. The // MANUAL indicates that the scope shouldn't actually generate code to set up // the frame (that is done below). __ bind(&push_stack_frame); FrameScope frame_scope(masm, StackFrame::MANUAL); __ PushStandardFrame(closure); // Reset code age and the OSR arming. The OSR field and BytecodeAgeOffset are // 8-bit fields next to each other, so we could just optimize by writing a // 16-bit. These static asserts guard our assumption is valid. STATIC_ASSERT(BytecodeArray::kBytecodeAgeOffset == BytecodeArray::kOsrNestingLevelOffset + kCharSize); STATIC_ASSERT(BytecodeArray::kNoAgeBytecodeAge == 0); __ mov(r1, Operand(0)); __ StoreU16(r1, FieldMemOperand(kInterpreterBytecodeArrayRegister, BytecodeArray::kOsrNestingLevelOffset), r0); // Load the initial bytecode offset. __ mov(kInterpreterBytecodeOffsetRegister, Operand(BytecodeArray::kHeaderSize - kHeapObjectTag)); // Push bytecode array and Smi tagged bytecode array offset. __ SmiTag(r4, kInterpreterBytecodeOffsetRegister); __ Push(kInterpreterBytecodeArrayRegister, r4); // Allocate the local and temporary register file on the stack. Label stack_overflow; { // Load frame size (word) from the BytecodeArray object. __ LoadU32(r4, FieldMemOperand(kInterpreterBytecodeArrayRegister, BytecodeArray::kFrameSizeOffset)); // Do a stack check to ensure we don't go over the limit. __ SubS64(r8, sp, r4); __ CmpU64(r8, __ StackLimitAsMemOperand(StackLimitKind::kRealStackLimit)); __ blt(&stack_overflow); // If ok, push undefined as the initial value for all register file entries. // TODO(rmcilroy): Consider doing more than one push per loop iteration. Label loop, no_args; __ LoadRoot(kInterpreterAccumulatorRegister, RootIndex::kUndefinedValue); __ ShiftRightU64(r4, r4, Operand(kSystemPointerSizeLog2)); __ LoadAndTestP(r4, r4); __ beq(&no_args); __ mov(r1, r4); __ bind(&loop); __ push(kInterpreterAccumulatorRegister); __ SubS64(r1, Operand(1)); __ bne(&loop); __ bind(&no_args); } // If the bytecode array has a valid incoming new target or generator object // register, initialize it with incoming value which was passed in r5. Label no_incoming_new_target_or_generator_register; __ LoadS32(r8, FieldMemOperand( kInterpreterBytecodeArrayRegister, BytecodeArray::kIncomingNewTargetOrGeneratorRegisterOffset)); __ CmpS64(r8, Operand::Zero()); __ beq(&no_incoming_new_target_or_generator_register); __ ShiftLeftU64(r8, r8, Operand(kSystemPointerSizeLog2)); __ StoreU64(r5, MemOperand(fp, r8)); __ bind(&no_incoming_new_target_or_generator_register); // Perform interrupt stack check. // TODO(solanes): Merge with the real stack limit check above. Label stack_check_interrupt, after_stack_check_interrupt; __ LoadU64(r0, __ StackLimitAsMemOperand(StackLimitKind::kInterruptStackLimit)); __ CmpU64(sp, r0); __ blt(&stack_check_interrupt); __ bind(&after_stack_check_interrupt); // The accumulator is already loaded with undefined. // Load the dispatch table into a register and dispatch to the bytecode // handler at the current bytecode offset. Label do_dispatch; __ bind(&do_dispatch); __ Move( kInterpreterDispatchTableRegister, ExternalReference::interpreter_dispatch_table_address(masm->isolate())); __ LoadU8(r5, MemOperand(kInterpreterBytecodeArrayRegister, kInterpreterBytecodeOffsetRegister)); __ ShiftLeftU64(r5, r5, Operand(kSystemPointerSizeLog2)); __ LoadU64(kJavaScriptCallCodeStartRegister, MemOperand(kInterpreterDispatchTableRegister, r5)); __ Call(kJavaScriptCallCodeStartRegister); masm->isolate()->heap()->SetInterpreterEntryReturnPCOffset(masm->pc_offset()); // Any returns to the entry trampoline are either due to the return bytecode // or the interpreter tail calling a builtin and then a dispatch. // Get bytecode array and bytecode offset from the stack frame. __ LoadU64(kInterpreterBytecodeArrayRegister, MemOperand(fp, InterpreterFrameConstants::kBytecodeArrayFromFp)); __ LoadU64(kInterpreterBytecodeOffsetRegister, MemOperand(fp, InterpreterFrameConstants::kBytecodeOffsetFromFp)); __ SmiUntag(kInterpreterBytecodeOffsetRegister); // Either return, or advance to the next bytecode and dispatch. Label do_return; __ LoadU8(r3, MemOperand(kInterpreterBytecodeArrayRegister, kInterpreterBytecodeOffsetRegister)); AdvanceBytecodeOffsetOrReturn(masm, kInterpreterBytecodeArrayRegister, kInterpreterBytecodeOffsetRegister, r3, r4, r5, &do_return); __ b(&do_dispatch); __ bind(&do_return); // The return value is in r2. LeaveInterpreterFrame(masm, r4, r6); __ Ret(); __ bind(&stack_check_interrupt); // Modify the bytecode offset in the stack to be kFunctionEntryBytecodeOffset // for the call to the StackGuard. __ mov(kInterpreterBytecodeOffsetRegister, Operand(Smi::FromInt(BytecodeArray::kHeaderSize - kHeapObjectTag + kFunctionEntryBytecodeOffset))); __ StoreU64(kInterpreterBytecodeOffsetRegister, MemOperand(fp, InterpreterFrameConstants::kBytecodeOffsetFromFp)); __ CallRuntime(Runtime::kStackGuard); // After the call, restore the bytecode array, bytecode offset and accumulator // registers again. Also, restore the bytecode offset in the stack to its // previous value. __ LoadU64(kInterpreterBytecodeArrayRegister, MemOperand(fp, InterpreterFrameConstants::kBytecodeArrayFromFp)); __ mov(kInterpreterBytecodeOffsetRegister, Operand(BytecodeArray::kHeaderSize - kHeapObjectTag)); __ LoadRoot(kInterpreterAccumulatorRegister, RootIndex::kUndefinedValue); __ SmiTag(r0, kInterpreterBytecodeOffsetRegister); __ StoreU64(r0, MemOperand(fp, InterpreterFrameConstants::kBytecodeOffsetFromFp)); __ jmp(&after_stack_check_interrupt); __ bind(&has_optimized_code_or_marker); MaybeOptimizeCodeOrTailCallOptimizedCodeSlot(masm, optimization_state, feedback_vector); __ bind(&compile_lazy); GenerateTailCallToReturnedCode(masm, Runtime::kCompileLazy); __ bind(&stack_overflow); __ CallRuntime(Runtime::kThrowStackOverflow); __ bkpt(0); // Should not return. } static void Generate_InterpreterPushArgs(MacroAssembler* masm, Register num_args, Register start_address, Register scratch) { __ SubS64(scratch, num_args, Operand(1)); __ ShiftLeftU64(scratch, scratch, Operand(kSystemPointerSizeLog2)); __ SubS64(start_address, start_address, scratch); // Push the arguments. __ PushArray(start_address, num_args, r1, scratch, TurboAssembler::PushArrayOrder::kReverse); } // static void Builtins::Generate_InterpreterPushArgsThenCallImpl( MacroAssembler* masm, ConvertReceiverMode receiver_mode, InterpreterPushArgsMode mode) { DCHECK(mode != InterpreterPushArgsMode::kArrayFunction); // ----------- S t a t e ------------- // -- r2 : the number of arguments (not including the receiver) // -- r4 : the address of the first argument to be pushed. Subsequent // arguments should be consecutive above this, in the same order as // they are to be pushed onto the stack. // -- r3 : the target to call (can be any Object). // ----------------------------------- Label stack_overflow; if (mode == InterpreterPushArgsMode::kWithFinalSpread) { // The spread argument should not be pushed. __ SubS64(r2, r2, Operand(1)); } // Calculate number of arguments (AddS64 one for receiver). __ AddS64(r5, r2, Operand(1)); __ StackOverflowCheck(r5, ip, &stack_overflow); if (receiver_mode == ConvertReceiverMode::kNullOrUndefined) { // Don't copy receiver. Argument count is correct. __ mov(r5, r2); } // Push the arguments. Generate_InterpreterPushArgs(masm, r5, r4, r6); if (receiver_mode == ConvertReceiverMode::kNullOrUndefined) { __ PushRoot(RootIndex::kUndefinedValue); } if (mode == InterpreterPushArgsMode::kWithFinalSpread) { // Pass the spread in the register r2. // r2 already points to the penultimate argument, the spread // lies in the next interpreter register. __ LoadU64(r4, MemOperand(r4, -kSystemPointerSize)); } // Call the target. if (mode == InterpreterPushArgsMode::kWithFinalSpread) { __ Jump(BUILTIN_CODE(masm->isolate(), CallWithSpread), RelocInfo::CODE_TARGET); } else { __ Jump(masm->isolate()->builtins()->Call(ConvertReceiverMode::kAny), RelocInfo::CODE_TARGET); } __ bind(&stack_overflow); { __ TailCallRuntime(Runtime::kThrowStackOverflow); // Unreachable Code. __ bkpt(0); } } // static void Builtins::Generate_InterpreterPushArgsThenConstructImpl( MacroAssembler* masm, InterpreterPushArgsMode mode) { // ----------- S t a t e ------------- // -- r2 : argument count (not including receiver) // -- r5 : new target // -- r3 : constructor to call // -- r4 : allocation site feedback if available, undefined otherwise. // -- r6 : address of the first argument // ----------------------------------- Label stack_overflow; __ AddS64(r7, r2, Operand(1)); __ StackOverflowCheck(r7, ip, &stack_overflow); if (mode == InterpreterPushArgsMode::kWithFinalSpread) { // The spread argument should not be pushed. __ SubS64(r2, r2, Operand(1)); } // Push the arguments. r4 and r5 will be modified. Generate_InterpreterPushArgs(masm, r2, r6, r7); // Push a slot for the receiver to be constructed. __ mov(r0, Operand::Zero()); __ push(r0); if (mode == InterpreterPushArgsMode::kWithFinalSpread) { // Pass the spread in the register r2. // r4 already points to the penultimate argument, the spread // lies in the next interpreter register. __ lay(r6, MemOperand(r6, -kSystemPointerSize)); __ LoadU64(r4, MemOperand(r6)); } else { __ AssertUndefinedOrAllocationSite(r4, r7); } if (mode == InterpreterPushArgsMode::kArrayFunction) { __ AssertFunction(r3); // Tail call to the array construct stub (still in the caller // context at this point). Handle<Code> code = BUILTIN_CODE(masm->isolate(), ArrayConstructorImpl); __ Jump(code, RelocInfo::CODE_TARGET); } else if (mode == InterpreterPushArgsMode::kWithFinalSpread) { // Call the constructor with r2, r3, and r5 unmodified. __ Jump(BUILTIN_CODE(masm->isolate(), ConstructWithSpread), RelocInfo::CODE_TARGET); } else { DCHECK_EQ(InterpreterPushArgsMode::kOther, mode); // Call the constructor with r2, r3, and r5 unmodified. __ Jump(BUILTIN_CODE(masm->isolate(), Construct), RelocInfo::CODE_TARGET); } __ bind(&stack_overflow); { __ TailCallRuntime(Runtime::kThrowStackOverflow); // Unreachable Code. __ bkpt(0); } } static void Generate_InterpreterEnterBytecode(MacroAssembler* masm) { // Set the return address to the correct point in the interpreter entry // trampoline. Label builtin_trampoline, trampoline_loaded; Smi interpreter_entry_return_pc_offset( masm->isolate()->heap()->interpreter_entry_return_pc_offset()); DCHECK_NE(interpreter_entry_return_pc_offset, Smi::zero()); // If the SFI function_data is an InterpreterData, the function will have a // custom copy of the interpreter entry trampoline for profiling. If so, // get the custom trampoline, otherwise grab the entry address of the global // trampoline. __ LoadU64(r4, MemOperand(fp, StandardFrameConstants::kFunctionOffset)); __ LoadTaggedPointerField( r4, FieldMemOperand(r4, JSFunction::kSharedFunctionInfoOffset)); __ LoadTaggedPointerField( r4, FieldMemOperand(r4, SharedFunctionInfo::kFunctionDataOffset)); __ CompareObjectType(r4, kInterpreterDispatchTableRegister, kInterpreterDispatchTableRegister, INTERPRETER_DATA_TYPE); __ bne(&builtin_trampoline); __ LoadTaggedPointerField( r4, FieldMemOperand(r4, InterpreterData::kInterpreterTrampolineOffset)); __ AddS64(r4, r4, Operand(Code::kHeaderSize - kHeapObjectTag)); __ b(&trampoline_loaded); __ bind(&builtin_trampoline); __ Move(r4, ExternalReference:: address_of_interpreter_entry_trampoline_instruction_start( masm->isolate())); __ LoadU64(r4, MemOperand(r4)); __ bind(&trampoline_loaded); __ AddS64(r14, r4, Operand(interpreter_entry_return_pc_offset.value())); // Initialize the dispatch table register. __ Move( kInterpreterDispatchTableRegister, ExternalReference::interpreter_dispatch_table_address(masm->isolate())); // Get the bytecode array pointer from the frame. __ LoadU64(kInterpreterBytecodeArrayRegister, MemOperand(fp, InterpreterFrameConstants::kBytecodeArrayFromFp)); if (FLAG_debug_code) { // Check function data field is actually a BytecodeArray object. __ TestIfSmi(kInterpreterBytecodeArrayRegister); __ Assert( ne, AbortReason::kFunctionDataShouldBeBytecodeArrayOnInterpreterEntry); __ CompareObjectType(kInterpreterBytecodeArrayRegister, r3, no_reg, BYTECODE_ARRAY_TYPE); __ Assert( eq, AbortReason::kFunctionDataShouldBeBytecodeArrayOnInterpreterEntry); } // Get the target bytecode offset from the frame. __ LoadU64(kInterpreterBytecodeOffsetRegister, MemOperand(fp, InterpreterFrameConstants::kBytecodeOffsetFromFp)); __ SmiUntag(kInterpreterBytecodeOffsetRegister); if (FLAG_debug_code) { Label okay; __ CmpS64(kInterpreterBytecodeOffsetRegister, Operand(BytecodeArray::kHeaderSize - kHeapObjectTag)); __ bge(&okay); __ bkpt(0); __ bind(&okay); } // Dispatch to the target bytecode. UseScratchRegisterScope temps(masm); Register scratch = temps.Acquire(); __ LoadU8(scratch, MemOperand(kInterpreterBytecodeArrayRegister, kInterpreterBytecodeOffsetRegister)); __ ShiftLeftU64(scratch, scratch, Operand(kSystemPointerSizeLog2)); __ LoadU64(kJavaScriptCallCodeStartRegister, MemOperand(kInterpreterDispatchTableRegister, scratch)); __ Jump(kJavaScriptCallCodeStartRegister); } void Builtins::Generate_InterpreterEnterAtNextBytecode(MacroAssembler* masm) { // Get bytecode array and bytecode offset from the stack frame. __ LoadU64(kInterpreterBytecodeArrayRegister, MemOperand(fp, InterpreterFrameConstants::kBytecodeArrayFromFp)); __ LoadU64(kInterpreterBytecodeOffsetRegister, MemOperand(fp, InterpreterFrameConstants::kBytecodeOffsetFromFp)); __ SmiUntag(kInterpreterBytecodeOffsetRegister); Label enter_bytecode, function_entry_bytecode; __ CmpS64(kInterpreterBytecodeOffsetRegister, Operand(BytecodeArray::kHeaderSize - kHeapObjectTag + kFunctionEntryBytecodeOffset)); __ beq(&function_entry_bytecode); // Load the current bytecode. __ LoadU8(r3, MemOperand(kInterpreterBytecodeArrayRegister, kInterpreterBytecodeOffsetRegister)); // Advance to the next bytecode. Label if_return; AdvanceBytecodeOffsetOrReturn(masm, kInterpreterBytecodeArrayRegister, kInterpreterBytecodeOffsetRegister, r3, r4, r5, &if_return); __ bind(&enter_bytecode); // Convert new bytecode offset to a Smi and save in the stackframe. __ SmiTag(r4, kInterpreterBytecodeOffsetRegister); __ StoreU64(r4, MemOperand(fp, InterpreterFrameConstants::kBytecodeOffsetFromFp)); Generate_InterpreterEnterBytecode(masm); __ bind(&function_entry_bytecode); // If the code deoptimizes during the implicit function entry stack interrupt // check, it will have a bailout ID of kFunctionEntryBytecodeOffset, which is // not a valid bytecode offset. Detect this case and advance to the first // actual bytecode. __ mov(kInterpreterBytecodeOffsetRegister, Operand(BytecodeArray::kHeaderSize - kHeapObjectTag)); __ b(&enter_bytecode); // We should never take the if_return path. __ bind(&if_return); __ Abort(AbortReason::kInvalidBytecodeAdvance); } void Builtins::Generate_InterpreterEnterAtBytecode(MacroAssembler* masm) { Generate_InterpreterEnterBytecode(masm); } namespace { void Generate_ContinueToBuiltinHelper(MacroAssembler* masm, bool java_script_builtin, bool with_result) { const RegisterConfiguration* config(RegisterConfiguration::Default()); int allocatable_register_count = config->num_allocatable_general_registers(); Register scratch = ip; if (with_result) { if (java_script_builtin) { __ mov(scratch, r2); } else { // Overwrite the hole inserted by the deoptimizer with the return value // from the LAZY deopt point. __ StoreU64( r2, MemOperand( sp, config->num_allocatable_general_registers() * kSystemPointerSize + BuiltinContinuationFrameConstants::kFixedFrameSize)); } } for (int i = allocatable_register_count - 1; i >= 0; --i) { int code = config->GetAllocatableGeneralCode(i); __ Pop(Register::from_code(code)); if (java_script_builtin && code == kJavaScriptCallArgCountRegister.code()) { __ SmiUntag(Register::from_code(code)); } } if (java_script_builtin && with_result) { // Overwrite the hole inserted by the deoptimizer with the return value from // the LAZY deopt point. r0 contains the arguments count, the return value // from LAZY is always the last argument. __ AddS64(r2, r2, Operand(BuiltinContinuationFrameConstants::kFixedSlotCount)); __ ShiftLeftU64(r1, r2, Operand(kSystemPointerSizeLog2)); __ StoreU64(scratch, MemOperand(sp, r1)); // Recover arguments count. __ SubS64(r2, r2, Operand(BuiltinContinuationFrameConstants::kFixedSlotCount)); } __ LoadU64( fp, MemOperand(sp, BuiltinContinuationFrameConstants::kFixedFrameSizeFromFp)); // Load builtin index (stored as a Smi) and use it to get the builtin start // address from the builtins table. UseScratchRegisterScope temps(masm); Register builtin = temps.Acquire(); __ Pop(builtin); __ AddS64(sp, sp, Operand(BuiltinContinuationFrameConstants::kFixedFrameSizeFromFp)); __ Pop(r0); __ mov(r14, r0); __ LoadEntryFromBuiltinIndex(builtin); __ Jump(builtin); } } // namespace void Builtins::Generate_ContinueToCodeStubBuiltin(MacroAssembler* masm) { Generate_ContinueToBuiltinHelper(masm, false, false); } void Builtins::Generate_ContinueToCodeStubBuiltinWithResult( MacroAssembler* masm) { Generate_ContinueToBuiltinHelper(masm, false, true); } void Builtins::Generate_ContinueToJavaScriptBuiltin(MacroAssembler* masm) { Generate_ContinueToBuiltinHelper(masm, true, false); } void Builtins::Generate_ContinueToJavaScriptBuiltinWithResult( MacroAssembler* masm) { Generate_ContinueToBuiltinHelper(masm, true, true); } void Builtins::Generate_NotifyDeoptimized(MacroAssembler* masm) { { FrameScope scope(masm, StackFrame::INTERNAL); __ CallRuntime(Runtime::kNotifyDeoptimized); } DCHECK_EQ(kInterpreterAccumulatorRegister.code(), r2.code()); __ pop(r2); __ Ret(); } void Builtins::Generate_InterpreterOnStackReplacement(MacroAssembler* masm) { { FrameScope scope(masm, StackFrame::INTERNAL); __ CallRuntime(Runtime::kCompileForOnStackReplacement); } // If the code object is null, just return to the caller. Label skip; __ CmpSmiLiteral(r2, Smi::zero(), r0); __ bne(&skip); __ Ret(); __ bind(&skip); // Drop the handler frame that is be sitting on top of the actual // JavaScript frame. This is the case then OSR is triggered from bytecode. __ LeaveFrame(StackFrame::STUB); // Load deoptimization data from the code object. // <deopt_data> = <code>[#deoptimization_data_offset] __ LoadTaggedPointerField( r3, FieldMemOperand(r2, Code::kDeoptimizationDataOffset)); // Load the OSR entrypoint offset from the deoptimization data. // <osr_offset> = <deopt_data>[#header_size + #osr_pc_offset] __ SmiUntagField( r3, FieldMemOperand(r3, FixedArray::OffsetOfElementAt( DeoptimizationData::kOsrPcOffsetIndex))); // Compute the target address = code_obj + header_size + osr_offset // <entry_addr> = <code_obj> + #header_size + <osr_offset> __ AddS64(r2, r3); __ AddS64(r0, r2, Operand(Code::kHeaderSize - kHeapObjectTag)); __ mov(r14, r0); // And "return" to the OSR entry point of the function. __ Ret(); } // static void Builtins::Generate_FunctionPrototypeApply(MacroAssembler* masm) { // ----------- S t a t e ------------- // -- r2 : argc // -- sp[0] : receiver // -- sp[4] : thisArg // -- sp[8] : argArray // ----------------------------------- // 1. Load receiver into r3, argArray into r4 (if present), remove all // arguments from the stack (including the receiver), and push thisArg (if // present) instead. { __ LoadRoot(r7, RootIndex::kUndefinedValue); __ mov(r4, r7); Label done; __ LoadU64(r3, MemOperand(sp)); // receiver __ cghi(r2, Operand(1)); __ blt(&done); __ LoadU64(r7, MemOperand(sp, kSystemPointerSize)); // thisArg __ cghi(r2, Operand(2)); __ blt(&done); __ LoadU64(r4, MemOperand(sp, 2 * kSystemPointerSize)); // argArray __ bind(&done); __ ShiftLeftU64(r1, r2, Operand(kSystemPointerSizeLog2)); __ lay(sp, MemOperand(sp, r1)); __ StoreU64(r7, MemOperand(sp)); } // ----------- S t a t e ------------- // -- r4 : argArray // -- r3 : receiver // -- sp[0] : thisArg // ----------------------------------- // 2. We don't need to check explicitly for callable receiver here, // since that's the first thing the Call/CallWithArrayLike builtins // will do. // 3. Tail call with no arguments if argArray is null or undefined. Label no_arguments; __ JumpIfRoot(r4, RootIndex::kNullValue, &no_arguments); __ JumpIfRoot(r4, RootIndex::kUndefinedValue, &no_arguments); // 4a. Apply the receiver to the given argArray. __ Jump(BUILTIN_CODE(masm->isolate(), CallWithArrayLike), RelocInfo::CODE_TARGET); // 4b. The argArray is either null or undefined, so we tail call without any // arguments to the receiver. __ bind(&no_arguments); { __ mov(r2, Operand::Zero()); __ Jump(masm->isolate()->builtins()->Call(), RelocInfo::CODE_TARGET); } } // static void Builtins::Generate_FunctionPrototypeCall(MacroAssembler* masm) { // 1. Get the callable to call (passed as receiver) from the stack. __ Pop(r3); // 2. Make sure we have at least one argument. // r2: actual number of arguments { Label done; __ cghi(r2, Operand::Zero()); __ b(ne, &done); __ PushRoot(RootIndex::kUndefinedValue); __ AddS64(r2, r2, Operand(1)); __ bind(&done); } // 3. Adjust the actual number of arguments. __ SubS64(r2, r2, Operand(1)); // 4. Call the callable. __ Jump(masm->isolate()->builtins()->Call(), RelocInfo::CODE_TARGET); } void Builtins::Generate_ReflectApply(MacroAssembler* masm) { // ----------- S t a t e ------------- // -- r2 : argc // -- sp[0] : receiver // -- sp[4] : target (if argc >= 1) // -- sp[8] : thisArgument (if argc >= 2) // -- sp[12] : argumentsList (if argc == 3) // ----------------------------------- // 1. Load target into r3 (if present), argumentsList into r4 (if present), // remove all arguments from the stack (including the receiver), and push // thisArgument (if present) instead. { __ LoadRoot(r3, RootIndex::kUndefinedValue); __ mov(r7, r3); __ mov(r4, r3); Label done; __ cghi(r2, Operand(1)); __ blt(&done); __ LoadU64(r3, MemOperand(sp, kSystemPointerSize)); // thisArg __ cghi(r2, Operand(2)); __ blt(&done); __ LoadU64(r7, MemOperand(sp, 2 * kSystemPointerSize)); // argArray __ cghi(r2, Operand(3)); __ blt(&done); __ LoadU64(r4, MemOperand(sp, 3 * kSystemPointerSize)); // argArray __ bind(&done); __ ShiftLeftU64(r1, r2, Operand(kSystemPointerSizeLog2)); __ lay(sp, MemOperand(sp, r1)); __ StoreU64(r7, MemOperand(sp)); } // ----------- S t a t e ------------- // -- r4 : argumentsList // -- r3 : target // -- sp[0] : thisArgument // ----------------------------------- // 2. We don't need to check explicitly for callable target here, // since that's the first thing the Call/CallWithArrayLike builtins // will do. // 3 Apply the target to the given argumentsList. __ Jump(BUILTIN_CODE(masm->isolate(), CallWithArrayLike), RelocInfo::CODE_TARGET); } void Builtins::Generate_ReflectConstruct(MacroAssembler* masm) { // ----------- S t a t e ------------- // -- r2 : argc // -- sp[0] : receiver // -- sp[4] : target // -- sp[8] : argumentsList // -- sp[12] : new.target (optional) // ----------------------------------- // 1. Load target into r3 (if present), argumentsList into r4 (if present), // new.target into r5 (if present, otherwise use target), remove all // arguments from the stack (including the receiver), and push thisArgument // (if present) instead. { __ LoadRoot(r3, RootIndex::kUndefinedValue); __ mov(r4, r3); Label done; __ mov(r6, r3); __ cghi(r2, Operand(1)); __ blt(&done); __ LoadU64(r3, MemOperand(sp, kSystemPointerSize)); // thisArg __ mov(r5, r3); __ cghi(r2, Operand(2)); __ blt(&done); __ LoadU64(r4, MemOperand(sp, 2 * kSystemPointerSize)); // argArray __ cghi(r2, Operand(3)); __ blt(&done); __ LoadU64(r5, MemOperand(sp, 3 * kSystemPointerSize)); // argArray __ bind(&done); __ ShiftLeftU64(r1, r2, Operand(kSystemPointerSizeLog2)); __ lay(sp, MemOperand(sp, r1)); __ StoreU64(r6, MemOperand(sp)); } // ----------- S t a t e ------------- // -- r4 : argumentsList // -- r5 : new.target // -- r3 : target // -- sp[0] : receiver (undefined) // ----------------------------------- // 2. We don't need to check explicitly for constructor target here, // since that's the first thing the Construct/ConstructWithArrayLike // builtins will do. // 3. We don't need to check explicitly for constructor new.target here, // since that's the second thing the Construct/ConstructWithArrayLike // builtins will do. // 4. Construct the target with the given new.target and argumentsList. __ Jump(BUILTIN_CODE(masm->isolate(), ConstructWithArrayLike), RelocInfo::CODE_TARGET); } // static // TODO(v8:11615): Observe Code::kMaxArguments in CallOrConstructVarargs void Builtins::Generate_CallOrConstructVarargs(MacroAssembler* masm, Handle<Code> code) { // ----------- S t a t e ------------- // -- r3 : target // -- r2 : number of parameters on the stack (not including the receiver) // -- r4 : arguments list (a FixedArray) // -- r6 : len (number of elements to push from args) // -- r5 : new.target (for [[Construct]]) // ----------------------------------- Register scratch = ip; if (FLAG_debug_code) { // Allow r4 to be a FixedArray, or a FixedDoubleArray if r6 == 0. Label ok, fail; __ AssertNotSmi(r4); __ LoadTaggedPointerField(scratch, FieldMemOperand(r4, HeapObject::kMapOffset)); __ LoadS16(scratch, FieldMemOperand(scratch, Map::kInstanceTypeOffset)); __ CmpS64(scratch, Operand(FIXED_ARRAY_TYPE)); __ beq(&ok); __ CmpS64(scratch, Operand(FIXED_DOUBLE_ARRAY_TYPE)); __ bne(&fail); __ CmpS64(r6, Operand::Zero()); __ beq(&ok); // Fall through. __ bind(&fail); __ Abort(AbortReason::kOperandIsNotAFixedArray); __ bind(&ok); } // Check for stack overflow. Label stack_overflow; __ StackOverflowCheck(r6, scratch, &stack_overflow); // Move the arguments already in the stack, // including the receiver and the return address. { Label copy, check; Register num = ip, src = r8, dest = r7; __ mov(src, sp); __ ShiftLeftU64(r1, r6, Operand(kSystemPointerSizeLog2)); __ SubS64(sp, sp, r1); // Update stack pointer. __ mov(dest, sp); __ ltgr(num, r2); __ b(&check); __ bind(&copy); __ LoadU64(r0, MemOperand(src)); __ lay(src, MemOperand(src, kSystemPointerSize)); __ StoreU64(r0, MemOperand(dest)); __ lay(dest, MemOperand(dest, kSystemPointerSize)); __ SubS64(num, num, Operand(1)); __ bind(&check); __ b(ge, &copy); } // Push arguments onto the stack (thisArgument is already on the stack). { Label loop, no_args, skip; __ CmpS64(r6, Operand::Zero()); __ beq(&no_args); __ AddS64(r4, r4, Operand(FixedArray::kHeaderSize - kHeapObjectTag - kTaggedSize)); __ mov(r1, r6); __ bind(&loop); __ LoadAnyTaggedField(scratch, MemOperand(r4, kTaggedSize), r0); __ la(r4, MemOperand(r4, kTaggedSize)); __ CompareRoot(scratch, RootIndex::kTheHoleValue); __ bne(&skip, Label::kNear); __ LoadRoot(scratch, RootIndex::kUndefinedValue); __ bind(&skip); __ StoreU64(scratch, MemOperand(r7)); __ lay(r7, MemOperand(r7, kSystemPointerSize)); __ BranchOnCount(r1, &loop); __ bind(&no_args); __ AddS64(r2, r2, r6); } // Tail-call to the actual Call or Construct builtin. __ Jump(code, RelocInfo::CODE_TARGET); __ bind(&stack_overflow); __ TailCallRuntime(Runtime::kThrowStackOverflow); } // static void Builtins::Generate_CallOrConstructForwardVarargs(MacroAssembler* masm, CallOrConstructMode mode, Handle<Code> code) { // ----------- S t a t e ------------- // -- r2 : the number of arguments (not including the receiver) // -- r5 : the new.target (for [[Construct]] calls) // -- r3 : the target to call (can be any Object) // -- r4 : start index (to support rest parameters) // ----------------------------------- Register scratch = r8; if (mode == CallOrConstructMode::kConstruct) { Label new_target_constructor, new_target_not_constructor; __ JumpIfSmi(r5, &new_target_not_constructor); __ LoadTaggedPointerField(scratch, FieldMemOperand(r5, HeapObject::kMapOffset)); __ LoadU8(scratch, FieldMemOperand(scratch, Map::kBitFieldOffset)); __ tmll(scratch, Operand(Map::Bits1::IsConstructorBit::kShift)); __ bne(&new_target_constructor); __ bind(&new_target_not_constructor); { FrameScope scope(masm, StackFrame::MANUAL); __ EnterFrame(StackFrame::INTERNAL); __ Push(r5); __ CallRuntime(Runtime::kThrowNotConstructor); } __ bind(&new_target_constructor); } Label stack_done, stack_overflow; __ LoadU64(r7, MemOperand(fp, StandardFrameConstants::kArgCOffset)); __ SubS64(r7, r7, r4); __ ble(&stack_done); { // ----------- S t a t e ------------- // -- r2 : the number of arguments already in the stack (not including the // receiver) // -- r3 : the target to call (can be any Object) // -- r4 : start index (to support rest parameters) // -- r5 : the new.target (for [[Construct]] calls) // -- r6 : point to the caller stack frame // -- r7 : number of arguments to copy, i.e. arguments count - start index // ----------------------------------- // Check for stack overflow. __ StackOverflowCheck(r7, scratch, &stack_overflow); // Forward the arguments from the caller frame. __ mov(r5, r5); // Point to the first argument to copy (skipping the receiver). __ AddS64(r6, fp, Operand(CommonFrameConstants::kFixedFrameSizeAboveFp + kSystemPointerSize)); __ ShiftLeftU64(scratch, r4, Operand(kSystemPointerSizeLog2)); __ AddS64(r6, r6, scratch); // Move the arguments already in the stack, // including the receiver and the return address. { Label copy, check; Register num = r1, src = ip, dest = r4; // r7 and r10 are context and root. __ mov(src, sp); // Update stack pointer. __ ShiftLeftU64(scratch, r7, Operand(kSystemPointerSizeLog2)); __ SubS64(sp, sp, scratch); __ mov(dest, sp); __ ltgr(num, r2); __ b(&check); __ bind(&copy); __ LoadU64(r0, MemOperand(src)); __ lay(src, MemOperand(src, kSystemPointerSize)); __ StoreU64(r0, MemOperand(dest)); __ lay(dest, MemOperand(dest, kSystemPointerSize)); __ SubS64(num, num, Operand(1)); __ bind(&check); __ b(ge, &copy); } // Copy arguments from the caller frame. // TODO(victorgomes): Consider using forward order as potentially more cache // friendly. { Label loop; __ AddS64(r2, r2, r7); __ bind(&loop); { __ SubS64(r7, r7, Operand(1)); __ ShiftLeftU64(r1, r7, Operand(kSystemPointerSizeLog2)); __ LoadU64(scratch, MemOperand(r6, r1)); __ StoreU64(scratch, MemOperand(r4, r1)); __ CmpS64(r7, Operand::Zero()); __ bne(&loop); } } } __ b(&stack_done); __ bind(&stack_overflow); __ TailCallRuntime(Runtime::kThrowStackOverflow); __ bind(&stack_done); // Tail-call to the {code} handler. __ Jump(code, RelocInfo::CODE_TARGET); } // static void Builtins::Generate_CallFunction(MacroAssembler* masm, ConvertReceiverMode mode) { // ----------- S t a t e ------------- // -- r2 : the number of arguments (not including the receiver) // -- r3 : the function to call (checked to be a JSFunction) // ----------------------------------- __ AssertFunction(r3); // See ES6 section 9.2.1 [[Call]] ( thisArgument, argumentsList) // Check that the function is not a "classConstructor". Label class_constructor; __ LoadTaggedPointerField( r4, FieldMemOperand(r3, JSFunction::kSharedFunctionInfoOffset)); __ LoadU32(r5, FieldMemOperand(r4, SharedFunctionInfo::kFlagsOffset)); __ TestBitMask(r5, SharedFunctionInfo::IsClassConstructorBit::kMask, r0); __ bne(&class_constructor); // Enter the context of the function; ToObject has to run in the function // context, and we also need to take the global proxy from the function // context in case of conversion. __ LoadTaggedPointerField(cp, FieldMemOperand(r3, JSFunction::kContextOffset)); // We need to convert the receiver for non-native sloppy mode functions. Label done_convert; __ AndP(r0, r5, Operand(SharedFunctionInfo::IsStrictBit::kMask | SharedFunctionInfo::IsNativeBit::kMask)); __ bne(&done_convert); { // ----------- S t a t e ------------- // -- r2 : the number of arguments (not including the receiver) // -- r3 : the function to call (checked to be a JSFunction) // -- r4 : the shared function info. // -- cp : the function context. // ----------------------------------- if (mode == ConvertReceiverMode::kNullOrUndefined) { // Patch receiver to global proxy. __ LoadGlobalProxy(r5); } else { Label convert_to_object, convert_receiver; __ LoadReceiver(r5, r2); __ JumpIfSmi(r5, &convert_to_object); STATIC_ASSERT(LAST_JS_RECEIVER_TYPE == LAST_TYPE); __ CompareObjectType(r5, r6, r6, FIRST_JS_RECEIVER_TYPE); __ bge(&done_convert); if (mode != ConvertReceiverMode::kNotNullOrUndefined) { Label convert_global_proxy; __ JumpIfRoot(r5, RootIndex::kUndefinedValue, &convert_global_proxy); __ JumpIfNotRoot(r5, RootIndex::kNullValue, &convert_to_object); __ bind(&convert_global_proxy); { // Patch receiver to global proxy. __ LoadGlobalProxy(r5); } __ b(&convert_receiver); } __ bind(&convert_to_object); { // Convert receiver using ToObject. // TODO(bmeurer): Inline the allocation here to avoid building the frame // in the fast case? (fall back to AllocateInNewSpace?) FrameAndConstantPoolScope scope(masm, StackFrame::INTERNAL); __ SmiTag(r2); __ Push(r2, r3); __ mov(r2, r5); __ Push(cp); __ Call(BUILTIN_CODE(masm->isolate(), ToObject), RelocInfo::CODE_TARGET); __ Pop(cp); __ mov(r5, r2); __ Pop(r2, r3); __ SmiUntag(r2); } __ LoadTaggedPointerField( r4, FieldMemOperand(r3, JSFunction::kSharedFunctionInfoOffset)); __ bind(&convert_receiver); } __ StoreReceiver(r5, r2, r6); } __ bind(&done_convert); // ----------- S t a t e ------------- // -- r2 : the number of arguments (not including the receiver) // -- r3 : the function to call (checked to be a JSFunction) // -- r4 : the shared function info. // -- cp : the function context. // ----------------------------------- __ LoadU16( r4, FieldMemOperand(r4, SharedFunctionInfo::kFormalParameterCountOffset)); __ InvokeFunctionCode(r3, no_reg, r4, r2, JUMP_FUNCTION); // The function is a "classConstructor", need to raise an exception. __ bind(&class_constructor); { FrameAndConstantPoolScope frame(masm, StackFrame::INTERNAL); __ push(r3); __ CallRuntime(Runtime::kThrowConstructorNonCallableError); } } namespace { void Generate_PushBoundArguments(MacroAssembler* masm) { // ----------- S t a t e ------------- // -- r2 : the number of arguments (not including the receiver) // -- r3 : target (checked to be a JSBoundFunction) // -- r5 : new.target (only in case of [[Construct]]) // ----------------------------------- // Load [[BoundArguments]] into r4 and length of that into r6. Label no_bound_arguments; __ LoadTaggedPointerField( r4, FieldMemOperand(r3, JSBoundFunction::kBoundArgumentsOffset)); __ SmiUntagField(r6, FieldMemOperand(r4, FixedArray::kLengthOffset)); __ LoadAndTestP(r6, r6); __ beq(&no_bound_arguments); { // ----------- S t a t e ------------- // -- r2 : the number of arguments (not including the receiver) // -- r3 : target (checked to be a JSBoundFunction) // -- r4 : the [[BoundArguments]] (implemented as FixedArray) // -- r5 : new.target (only in case of [[Construct]]) // -- r6 : the number of [[BoundArguments]] // ----------------------------------- Register scratch = r8; // Reserve stack space for the [[BoundArguments]]. { Label done; __ ShiftLeftU64(r9, r6, Operand(kSystemPointerSizeLog2)); __ SubS64(r1, sp, r9); // Check the stack for overflow. We are not trying to catch interruptions // (i.e. debug break and preemption) here, so check the "real stack // limit". __ CmpU64(r1, __ StackLimitAsMemOperand(StackLimitKind::kRealStackLimit)); __ bgt(&done); // Signed comparison. // Restore the stack pointer. { FrameScope scope(masm, StackFrame::MANUAL); __ EnterFrame(StackFrame::INTERNAL); __ CallRuntime(Runtime::kThrowStackOverflow); } __ bind(&done); } // Pop receiver. __ Pop(r7); // Push [[BoundArguments]]. { Label loop, done; __ AddS64(r2, r2, r6); // Adjust effective number of arguments. __ AddS64(r4, r4, Operand(FixedArray::kHeaderSize - kHeapObjectTag)); __ bind(&loop); __ SubS64(r1, r6, Operand(1)); __ ShiftLeftU64(r1, r1, Operand(kTaggedSizeLog2)); __ LoadAnyTaggedField(scratch, MemOperand(r4, r1), r0); __ Push(scratch); __ SubS64(r6, r6, Operand(1)); __ bgt(&loop); __ bind(&done); } // Push receiver. __ Push(r7); } __ bind(&no_bound_arguments); } } // namespace // static void Builtins::Generate_CallBoundFunctionImpl(MacroAssembler* masm) { // ----------- S t a t e ------------- // -- r2 : the number of arguments (not including the receiver) // -- r3 : the function to call (checked to be a JSBoundFunction) // ----------------------------------- __ AssertBoundFunction(r3); // Patch the receiver to [[BoundThis]]. __ LoadAnyTaggedField(r5, FieldMemOperand(r3, JSBoundFunction::kBoundThisOffset)); __ StoreReceiver(r5, r2, r1); // Push the [[BoundArguments]] onto the stack. Generate_PushBoundArguments(masm); // Call the [[BoundTargetFunction]] via the Call builtin. __ LoadTaggedPointerField( r3, FieldMemOperand(r3, JSBoundFunction::kBoundTargetFunctionOffset)); __ Jump(BUILTIN_CODE(masm->isolate(), Call_ReceiverIsAny), RelocInfo::CODE_TARGET); } // static void Builtins::Generate_Call(MacroAssembler* masm, ConvertReceiverMode mode) { // ----------- S t a t e ------------- // -- r2 : the number of arguments (not including the receiver) // -- r3 : the target to call (can be any Object). // ----------------------------------- Label non_callable, non_smi; __ JumpIfSmi(r3, &non_callable); __ bind(&non_smi); __ LoadMap(r6, r3); __ CompareInstanceTypeRange(r6, r7, FIRST_JS_FUNCTION_TYPE, LAST_JS_FUNCTION_TYPE); __ Jump(masm->isolate()->builtins()->CallFunction(mode), RelocInfo::CODE_TARGET, le); __ CmpS64(r7, Operand(JS_BOUND_FUNCTION_TYPE)); __ Jump(BUILTIN_CODE(masm->isolate(), CallBoundFunction), RelocInfo::CODE_TARGET, eq); // Check if target has a [[Call]] internal method. __ LoadU8(r6, FieldMemOperand(r6, Map::kBitFieldOffset)); __ TestBit(r6, Map::Bits1::IsCallableBit::kShift); __ beq(&non_callable); // Check if target is a proxy and call CallProxy external builtin __ CmpS64(r7, Operand(JS_PROXY_TYPE)); __ Jump(BUILTIN_CODE(masm->isolate(), CallProxy), RelocInfo::CODE_TARGET, eq); // 2. Call to something else, which might have a [[Call]] internal method (if // not we raise an exception). // Overwrite the original receiver the (original) target. __ StoreReceiver(r3, r2, r7); // Let the "call_as_function_delegate" take care of the rest. __ LoadNativeContextSlot(r3, Context::CALL_AS_FUNCTION_DELEGATE_INDEX); __ Jump(masm->isolate()->builtins()->CallFunction( ConvertReceiverMode::kNotNullOrUndefined), RelocInfo::CODE_TARGET); // 3. Call to something that is not callable. __ bind(&non_callable); { FrameAndConstantPoolScope scope(masm, StackFrame::INTERNAL); __ Push(r3); __ CallRuntime(Runtime::kThrowCalledNonCallable); } } // static void Builtins::Generate_ConstructFunction(MacroAssembler* masm) { // ----------- S t a t e ------------- // -- r2 : the number of arguments (not including the receiver) // -- r3 : the constructor to call (checked to be a JSFunction) // -- r5 : the new target (checked to be a constructor) // ----------------------------------- __ AssertConstructor(r3, r1); __ AssertFunction(r3); // Calling convention for function specific ConstructStubs require // r4 to contain either an AllocationSite or undefined. __ LoadRoot(r4, RootIndex::kUndefinedValue); Label call_generic_stub; // Jump to JSBuiltinsConstructStub or JSConstructStubGeneric. __ LoadTaggedPointerField( r6, FieldMemOperand(r3, JSFunction::kSharedFunctionInfoOffset)); __ LoadU32(r6, FieldMemOperand(r6, SharedFunctionInfo::kFlagsOffset)); __ AndP(r6, Operand(SharedFunctionInfo::ConstructAsBuiltinBit::kMask)); __ beq(&call_generic_stub); __ Jump(BUILTIN_CODE(masm->isolate(), JSBuiltinsConstructStub), RelocInfo::CODE_TARGET); __ bind(&call_generic_stub); __ Jump(BUILTIN_CODE(masm->isolate(), JSConstructStubGeneric), RelocInfo::CODE_TARGET); } // static void Builtins::Generate_ConstructBoundFunction(MacroAssembler* masm) { // ----------- S t a t e ------------- // -- r2 : the number of arguments (not including the receiver) // -- r3 : the function to call (checked to be a JSBoundFunction) // -- r5 : the new target (checked to be a constructor) // ----------------------------------- __ AssertConstructor(r3, r1); __ AssertBoundFunction(r3); // Push the [[BoundArguments]] onto the stack. Generate_PushBoundArguments(masm); // Patch new.target to [[BoundTargetFunction]] if new.target equals target. Label skip; __ CompareTagged(r3, r5); __ bne(&skip); __ LoadTaggedPointerField( r5, FieldMemOperand(r3, JSBoundFunction::kBoundTargetFunctionOffset)); __ bind(&skip); // Construct the [[BoundTargetFunction]] via the Construct builtin. __ LoadTaggedPointerField( r3, FieldMemOperand(r3, JSBoundFunction::kBoundTargetFunctionOffset)); __ Jump(BUILTIN_CODE(masm->isolate(), Construct), RelocInfo::CODE_TARGET); } // static void Builtins::Generate_Construct(MacroAssembler* masm) { // ----------- S t a t e ------------- // -- r2 : the number of arguments (not including the receiver) // -- r3 : the constructor to call (can be any Object) // -- r5 : the new target (either the same as the constructor or // the JSFunction on which new was invoked initially) // ----------------------------------- // Check if target is a Smi. Label non_constructor, non_proxy; __ JumpIfSmi(r3, &non_constructor); // Check if target has a [[Construct]] internal method. __ LoadTaggedPointerField(r6, FieldMemOperand(r3, HeapObject::kMapOffset)); __ LoadU8(r4, FieldMemOperand(r6, Map::kBitFieldOffset)); __ TestBit(r4, Map::Bits1::IsConstructorBit::kShift); __ beq(&non_constructor); // Dispatch based on instance type. __ CompareInstanceTypeRange(r6, r7, FIRST_JS_FUNCTION_TYPE, LAST_JS_FUNCTION_TYPE); __ Jump(BUILTIN_CODE(masm->isolate(), ConstructFunction), RelocInfo::CODE_TARGET, le); // Only dispatch to bound functions after checking whether they are // constructors. __ CmpS64(r7, Operand(JS_BOUND_FUNCTION_TYPE)); __ Jump(BUILTIN_CODE(masm->isolate(), ConstructBoundFunction), RelocInfo::CODE_TARGET, eq); // Only dispatch to proxies after checking whether they are constructors. __ CmpS64(r7, Operand(JS_PROXY_TYPE)); __ bne(&non_proxy); __ Jump(BUILTIN_CODE(masm->isolate(), ConstructProxy), RelocInfo::CODE_TARGET); // Called Construct on an exotic Object with a [[Construct]] internal method. __ bind(&non_proxy); { // Overwrite the original receiver with the (original) target. __ StoreReceiver(r3, r2, r7); // Let the "call_as_constructor_delegate" take care of the rest. __ LoadNativeContextSlot(r3, Context::CALL_AS_CONSTRUCTOR_DELEGATE_INDEX); __ Jump(masm->isolate()->builtins()->CallFunction(), RelocInfo::CODE_TARGET); } // Called Construct on an Object that doesn't have a [[Construct]] internal // method. __ bind(&non_constructor); __ Jump(BUILTIN_CODE(masm->isolate(), ConstructedNonConstructable), RelocInfo::CODE_TARGET); } #if V8_ENABLE_WEBASSEMBLY void Builtins::Generate_WasmCompileLazy(MacroAssembler* masm) { // The function index was put in a register by the jump table trampoline. // Convert to Smi for the runtime call. __ SmiTag(kWasmCompileLazyFuncIndexRegister, kWasmCompileLazyFuncIndexRegister); { HardAbortScope hard_abort(masm); // Avoid calls to Abort. FrameAndConstantPoolScope scope(masm, StackFrame::WASM_COMPILE_LAZY); // Save all parameter registers (see wasm-linkage.h). They might be // overwritten in the runtime call below. We don't have any callee-saved // registers in wasm, so no need to store anything else. RegList gp_regs = 0; for (Register gp_param_reg : wasm::kGpParamRegisters) { gp_regs |= gp_param_reg.bit(); } RegList fp_regs = 0; for (DoubleRegister fp_param_reg : wasm::kFpParamRegisters) { fp_regs |= fp_param_reg.bit(); } CHECK_EQ(NumRegs(gp_regs), arraysize(wasm::kGpParamRegisters)); CHECK_EQ(NumRegs(fp_regs), arraysize(wasm::kFpParamRegisters)); CHECK_EQ(WasmCompileLazyFrameConstants::kNumberOfSavedGpParamRegs, NumRegs(gp_regs)); CHECK_EQ(WasmCompileLazyFrameConstants::kNumberOfSavedFpParamRegs, NumRegs(fp_regs)); __ MultiPush(gp_regs); // Check if machine has simd enabled, if so push vector registers. If not // then only push double registers. Label push_doubles, simd_pushed; __ Move(r1, ExternalReference::supports_wasm_simd_128_address()); __ LoadU8(r1, MemOperand(r1)); __ LoadAndTestP(r1, r1); // If > 0 then simd is available. __ ble(&push_doubles, Label::kNear); // Save vector registers, don't save double registers anymore. __ MultiPushV128(fp_regs); __ b(&simd_pushed); __ bind(&push_doubles); // Simd not supported, only save double registers. __ MultiPushDoubles(fp_regs); // kFixedFrameSizeFromFp is hard coded to include space for Simd // registers, so we still need to allocate extra (unused) space on the stack // as if they were saved. __ lay(sp, MemOperand(sp, -(NumRegs(fp_regs) * kDoubleSize))); __ bind(&simd_pushed); // Pass instance and function index as explicit arguments to the runtime // function. __ Push(kWasmInstanceRegister, r7); // Initialize the JavaScript context with 0. CEntry will use it to // set the current context on the isolate. __ LoadSmiLiteral(cp, Smi::zero()); __ CallRuntime(Runtime::kWasmCompileLazy, 2); // The entrypoint address is the return value. __ mov(ip, r2); // Restore registers. __ Move(r1, ExternalReference::supports_wasm_simd_128_address()); __ LoadU8(r1, MemOperand(r1)); Label pop_doubles, simd_popped; __ LoadAndTestP(r1, r1); // If > 0 then simd is available. __ ble(&pop_doubles, Label::kNear); // Pop vector registers, don't pop double registers anymore. __ MultiPopV128(fp_regs); __ b(&simd_popped); __ bind(&pop_doubles); // Simd not supported, only pop double registers. __ lay(sp, MemOperand(sp, NumRegs(fp_regs) * kDoubleSize)); __ MultiPopDoubles(fp_regs); __ bind(&simd_popped); __ MultiPop(gp_regs); } // Finally, jump to the entrypoint. __ Jump(ip); } void Builtins::Generate_WasmDebugBreak(MacroAssembler* masm) { HardAbortScope hard_abort(masm); // Avoid calls to Abort. { FrameAndConstantPoolScope scope(masm, StackFrame::WASM_DEBUG_BREAK); // Save all parameter registers. They might hold live values, we restore // them after the runtime call. __ MultiPush(WasmDebugBreakFrameConstants::kPushedGpRegs); __ MultiPushDoubles(WasmDebugBreakFrameConstants::kPushedFpRegs); // Initialize the JavaScript context with 0. CEntry will use it to // set the current context on the isolate. __ LoadSmiLiteral(cp, Smi::zero()); __ CallRuntime(Runtime::kWasmDebugBreak, 0); // Restore registers. __ MultiPopDoubles(WasmDebugBreakFrameConstants::kPushedFpRegs); __ MultiPop(WasmDebugBreakFrameConstants::kPushedGpRegs); } __ Ret(); } void Builtins::Generate_GenericJSToWasmWrapper(MacroAssembler* masm) { // TODO(v8:10701): Implement for this platform. __ Trap(); } void Builtins::Generate_WasmOnStackReplace(MacroAssembler* masm) { // Only needed on x64. __ Trap(); } #endif // V8_ENABLE_WEBASSEMBLY void Builtins::Generate_CEntry(MacroAssembler* masm, int result_size, SaveFPRegsMode save_doubles, ArgvMode argv_mode, bool builtin_exit_frame) { // Called from JavaScript; parameters are on stack as if calling JS function. // r2: number of arguments including receiver // r3: pointer to builtin function // fp: frame pointer (restored after C call) // sp: stack pointer (restored as callee's sp after C call) // cp: current context (C callee-saved) // // If argv_mode == kArgvInRegister: // r4: pointer to the first argument __ mov(r7, r3); if (argv_mode == kArgvInRegister) { // Move argv into the correct register. __ mov(r3, r4); } else { // Compute the argv pointer. __ ShiftLeftU64(r3, r2, Operand(kSystemPointerSizeLog2)); __ lay(r3, MemOperand(r3, sp, -kSystemPointerSize)); } // Enter the exit frame that transitions from JavaScript to C++. FrameScope scope(masm, StackFrame::MANUAL); // Need at least one extra slot for return address location. int arg_stack_space = 1; // Pass buffer for return value on stack if necessary bool needs_return_buffer = result_size == 2 && !ABI_RETURNS_OBJECTPAIR_IN_REGS; if (needs_return_buffer) { arg_stack_space += result_size; } #if V8_TARGET_ARCH_S390X // 64-bit linux pass Argument object by reference not value arg_stack_space += 2; #endif __ EnterExitFrame( save_doubles, arg_stack_space, builtin_exit_frame ? StackFrame::BUILTIN_EXIT : StackFrame::EXIT); // Store a copy of argc, argv in callee-saved registers for later. __ mov(r6, r2); __ mov(r8, r3); // r2, r6: number of arguments including receiver (C callee-saved) // r3, r8: pointer to the first argument // r7: pointer to builtin function (C callee-saved) // Result returned in registers or stack, depending on result size and ABI. Register isolate_reg = r4; if (needs_return_buffer) { // The return value is 16-byte non-scalar value. // Use frame storage reserved by calling function to pass return // buffer as implicit first argument in R2. Shfit original parameters // by one register each. __ mov(r4, r3); __ mov(r3, r2); __ la(r2, MemOperand(sp, (kStackFrameExtraParamSlot + 1) * kSystemPointerSize)); isolate_reg = r5; // Clang doesn't preserve r2 (result buffer) // write to r8 (preserved) before entry __ mov(r8, r2); } // Call C built-in. __ Move(isolate_reg, ExternalReference::isolate_address(masm->isolate())); __ StoreReturnAddressAndCall(r7); // If return value is on the stack, pop it to registers. if (needs_return_buffer) { __ mov(r2, r8); __ LoadU64(r3, MemOperand(r2, kSystemPointerSize)); __ LoadU64(r2, MemOperand(r2)); } // Check result for exception sentinel. Label exception_returned; __ CompareRoot(r2, RootIndex::kException); __ beq(&exception_returned, Label::kNear); // Check that there is no pending exception, otherwise we // should have returned the exception sentinel. if (FLAG_debug_code) { Label okay; ExternalReference pending_exception_address = ExternalReference::Create( IsolateAddressId::kPendingExceptionAddress, masm->isolate()); __ Move(r1, pending_exception_address); __ LoadU64(r1, MemOperand(r1)); __ CompareRoot(r1, RootIndex::kTheHoleValue); // Cannot use check here as it attempts to generate call into runtime. __ beq(&okay, Label::kNear); __ stop(); __ bind(&okay); } // Exit C frame and return. // r2:r3: result // sp: stack pointer // fp: frame pointer Register argc = argv_mode == kArgvInRegister // We don't want to pop arguments so set argc to no_reg. ? no_reg // r6: still holds argc (callee-saved). : r6; __ LeaveExitFrame(save_doubles, argc); __ b(r14); // Handling of exception. __ bind(&exception_returned); ExternalReference pending_handler_context_address = ExternalReference::Create( IsolateAddressId::kPendingHandlerContextAddress, masm->isolate()); ExternalReference pending_handler_entrypoint_address = ExternalReference::Create( IsolateAddressId::kPendingHandlerEntrypointAddress, masm->isolate()); ExternalReference pending_handler_fp_address = ExternalReference::Create( IsolateAddressId::kPendingHandlerFPAddress, masm->isolate()); ExternalReference pending_handler_sp_address = ExternalReference::Create( IsolateAddressId::kPendingHandlerSPAddress, masm->isolate()); // Ask the runtime for help to determine the handler. This will set r3 to // contain the current pending exception, don't clobber it. ExternalReference find_handler = ExternalReference::Create(Runtime::kUnwindAndFindExceptionHandler); { FrameScope scope(masm, StackFrame::MANUAL); __ PrepareCallCFunction(3, 0, r2); __ mov(r2, Operand::Zero()); __ mov(r3, Operand::Zero()); __ Move(r4, ExternalReference::isolate_address(masm->isolate())); __ CallCFunction(find_handler, 3); } // Retrieve the handler context, SP and FP. __ Move(cp, pending_handler_context_address); __ LoadU64(cp, MemOperand(cp)); __ Move(sp, pending_handler_sp_address); __ LoadU64(sp, MemOperand(sp)); __ Move(fp, pending_handler_fp_address); __ LoadU64(fp, MemOperand(fp)); // If the handler is a JS frame, restore the context to the frame. Note that // the context will be set to (cp == 0) for non-JS frames. Label skip; __ CmpS64(cp, Operand::Zero()); __ beq(&skip, Label::kNear); __ StoreU64(cp, MemOperand(fp, StandardFrameConstants::kContextOffset)); __ bind(&skip); // Reset the masking register. This is done independent of the underlying // feature flag {FLAG_untrusted_code_mitigations} to make the snapshot work // with both configurations. It is safe to always do this, because the // underlying register is caller-saved and can be arbitrarily clobbered. __ ResetSpeculationPoisonRegister(); // Clear c_entry_fp, like we do in `LeaveExitFrame`. { UseScratchRegisterScope temps(masm); __ Move(r1, ExternalReference::Create(IsolateAddressId::kCEntryFPAddress, masm->isolate())); __ mov(r0, Operand::Zero()); __ StoreU64(r0, MemOperand(r1)); } // Compute the handler entry address and jump to it. __ Move(r3, pending_handler_entrypoint_address); __ LoadU64(r3, MemOperand(r3)); __ Jump(r3); } void Builtins::Generate_DoubleToI(MacroAssembler* masm) { Label out_of_range, only_low, negate, done, fastpath_done; Register result_reg = r2; HardAbortScope hard_abort(masm); // Avoid calls to Abort. // Immediate values for this stub fit in instructions, so it's safe to use ip. Register scratch = GetRegisterThatIsNotOneOf(result_reg); Register scratch_low = GetRegisterThatIsNotOneOf(result_reg, scratch); Register scratch_high = GetRegisterThatIsNotOneOf(result_reg, scratch, scratch_low); DoubleRegister double_scratch = kScratchDoubleReg; __ Push(result_reg, scratch); // Account for saved regs. int argument_offset = 2 * kSystemPointerSize; // Load double input. __ LoadF64(double_scratch, MemOperand(sp, argument_offset)); // Do fast-path convert from double to int. __ ConvertDoubleToInt64(result_reg, double_scratch); // Test for overflow __ TestIfInt32(result_reg); __ beq(&fastpath_done, Label::kNear); __ Push(scratch_high, scratch_low); // Account for saved regs. argument_offset += 2 * kSystemPointerSize; __ LoadU32(scratch_high, MemOperand(sp, argument_offset + Register::kExponentOffset)); __ LoadU32(scratch_low, MemOperand(sp, argument_offset + Register::kMantissaOffset)); __ ExtractBitMask(scratch, scratch_high, HeapNumber::kExponentMask); // Load scratch with exponent - 1. This is faster than loading // with exponent because Bias + 1 = 1024 which is a *S390* immediate value. STATIC_ASSERT(HeapNumber::kExponentBias + 1 == 1024); __ SubS64(scratch, Operand(HeapNumber::kExponentBias + 1)); // If exponent is greater than or equal to 84, the 32 less significant // bits are 0s (2^84 = 1, 52 significant bits, 32 uncoded bits), // the result is 0. // Compare exponent with 84 (compare exponent - 1 with 83). __ CmpS64(scratch, Operand(83)); __ bge(&out_of_range, Label::kNear); // If we reach this code, 31 <= exponent <= 83. // So, we don't have to handle cases where 0 <= exponent <= 20 for // which we would need to shift right the high part of the mantissa. // Scratch contains exponent - 1. // Load scratch with 52 - exponent (load with 51 - (exponent - 1)). __ mov(r0, Operand(51)); __ SubS64(scratch, r0, scratch); __ CmpS64(scratch, Operand::Zero()); __ ble(&only_low, Label::kNear); // 21 <= exponent <= 51, shift scratch_low and scratch_high // to generate the result. __ ShiftRightU32(scratch_low, scratch_low, scratch); // Scratch contains: 52 - exponent. // We needs: exponent - 20. // So we use: 32 - scratch = 32 - 52 + exponent = exponent - 20. __ mov(r0, Operand(32)); __ SubS64(scratch, r0, scratch); __ ExtractBitMask(result_reg, scratch_high, HeapNumber::kMantissaMask); // Set the implicit 1 before the mantissa part in scratch_high. STATIC_ASSERT(HeapNumber::kMantissaBitsInTopWord >= 16); __ mov(r0, Operand(1 << ((HeapNumber::kMantissaBitsInTopWord)-16))); __ ShiftLeftU64(r0, r0, Operand(16)); __ OrP(result_reg, result_reg, r0); __ ShiftLeftU32(r0, result_reg, scratch); __ OrP(result_reg, scratch_low, r0); __ b(&negate, Label::kNear); __ bind(&out_of_range); __ mov(result_reg, Operand::Zero()); __ b(&done, Label::kNear); __ bind(&only_low); // 52 <= exponent <= 83, shift only scratch_low. // On entry, scratch contains: 52 - exponent. __ lcgr(scratch, scratch); __ ShiftLeftU32(result_reg, scratch_low, scratch); __ bind(&negate); // If input was positive, scratch_high ASR 31 equals 0 and // scratch_high LSR 31 equals zero. // New result = (result eor 0) + 0 = result. // If the input was negative, we have to negate the result. // Input_high ASR 31 equals 0xFFFFFFFF and scratch_high LSR 31 equals 1. // New result = (result eor 0xFFFFFFFF) + 1 = 0 - result. __ ShiftRightS32(r0, scratch_high, Operand(31)); #if V8_TARGET_ARCH_S390X __ lgfr(r0, r0); __ ShiftRightU64(r0, r0, Operand(32)); #endif __ XorP(result_reg, r0); __ ShiftRightU32(r0, scratch_high, Operand(31)); __ AddS64(result_reg, r0); __ bind(&done); __ Pop(scratch_high, scratch_low); argument_offset -= 2 * kSystemPointerSize; __ bind(&fastpath_done); __ StoreU64(result_reg, MemOperand(sp, argument_offset)); __ Pop(result_reg, scratch); __ Ret(); } namespace { static int AddressOffset(ExternalReference ref0, ExternalReference ref1) { return ref0.address() - ref1.address(); } // Calls an API function. Allocates HandleScope, extracts returned value // from handle and propagates exceptions. Restores context. stack_space // - space to be unwound on exit (includes the call JS arguments space and // the additional space allocated for the fast call). static void CallApiFunctionAndReturn(MacroAssembler* masm, Register function_address, ExternalReference thunk_ref, int stack_space, MemOperand* stack_space_operand, MemOperand return_value_operand) { Isolate* isolate = masm->isolate(); ExternalReference next_address = ExternalReference::handle_scope_next_address(isolate); const int kNextOffset = 0; const int kLimitOffset = AddressOffset( ExternalReference::handle_scope_limit_address(isolate), next_address); const int kLevelOffset = AddressOffset( ExternalReference::handle_scope_level_address(isolate), next_address); // Additional parameter is the address of the actual callback. DCHECK(function_address == r3 || function_address == r4); Register scratch = r5; __ Move(scratch, ExternalReference::is_profiling_address(isolate)); __ LoadU8(scratch, MemOperand(scratch, 0)); __ CmpS64(scratch, Operand::Zero()); Label profiler_enabled, end_profiler_check; __ bne(&profiler_enabled, Label::kNear); __ Move(scratch, ExternalReference::address_of_runtime_stats_flag()); __ LoadU32(scratch, MemOperand(scratch, 0)); __ CmpS64(scratch, Operand::Zero()); __ bne(&profiler_enabled, Label::kNear); { // Call the api function directly. __ mov(scratch, function_address); __ b(&end_profiler_check, Label::kNear); } __ bind(&profiler_enabled); { // Additional parameter is the address of the actual callback. __ Move(scratch, thunk_ref); } __ bind(&end_profiler_check); // Allocate HandleScope in callee-save registers. // r9 - next_address // r6 - next_address->kNextOffset // r7 - next_address->kLimitOffset // r8 - next_address->kLevelOffset __ Move(r9, next_address); __ LoadU64(r6, MemOperand(r9, kNextOffset)); __ LoadU64(r7, MemOperand(r9, kLimitOffset)); __ LoadU32(r8, MemOperand(r9, kLevelOffset)); __ AddS64(r8, Operand(1)); __ StoreU32(r8, MemOperand(r9, kLevelOffset)); __ StoreReturnAddressAndCall(scratch); Label promote_scheduled_exception; Label delete_allocated_handles; Label leave_exit_frame; Label return_value_loaded; // load value from ReturnValue __ LoadU64(r2, return_value_operand); __ bind(&return_value_loaded); // No more valid handles (the result handle was the last one). Restore // previous handle scope. __ StoreU64(r6, MemOperand(r9, kNextOffset)); if (FLAG_debug_code) { __ LoadU32(r3, MemOperand(r9, kLevelOffset)); __ CmpS64(r3, r8); __ Check(eq, AbortReason::kUnexpectedLevelAfterReturnFromApiCall); } __ SubS64(r8, Operand(1)); __ StoreU32(r8, MemOperand(r9, kLevelOffset)); __ CmpS64(r7, MemOperand(r9, kLimitOffset)); __ bne(&delete_allocated_handles, Label::kNear); // Leave the API exit frame. __ bind(&leave_exit_frame); // LeaveExitFrame expects unwind space to be in a register. if (stack_space_operand == nullptr) { DCHECK_NE(stack_space, 0); __ mov(r6, Operand(stack_space)); } else { DCHECK_EQ(stack_space, 0); __ LoadU64(r6, *stack_space_operand); } __ LeaveExitFrame(false, r6, stack_space_operand != nullptr); // Check if the function scheduled an exception. __ Move(r7, ExternalReference::scheduled_exception_address(isolate)); __ LoadU64(r7, MemOperand(r7)); __ CompareRoot(r7, RootIndex::kTheHoleValue); __ bne(&promote_scheduled_exception, Label::kNear); __ b(r14); // Re-throw by promoting a scheduled exception. __ bind(&promote_scheduled_exception); __ TailCallRuntime(Runtime::kPromoteScheduledException); // HandleScope limit has changed. Delete allocated extensions. __ bind(&delete_allocated_handles); __ StoreU64(r7, MemOperand(r9, kLimitOffset)); __ mov(r6, r2); __ PrepareCallCFunction(1, r7); __ Move(r2, ExternalReference::isolate_address(isolate)); __ CallCFunction(ExternalReference::delete_handle_scope_extensions(), 1); __ mov(r2, r6); __ b(&leave_exit_frame, Label::kNear); } } // namespace void Builtins::Generate_CallApiCallback(MacroAssembler* masm) { // ----------- S t a t e ------------- // -- cp : context // -- r4 : api function address // -- r4 : arguments count (not including the receiver) // -- r5 : call data // -- r2 : holder // -- sp[0] : receiver // -- sp[8] : first argument // -- ... // -- sp[(argc) * 8] : last argument // ----------------------------------- Register api_function_address = r3; Register argc = r4; Register call_data = r5; Register holder = r2; Register scratch = r6; DCHECK(!AreAliased(api_function_address, argc, call_data, holder, scratch)); using FCA = FunctionCallbackArguments; STATIC_ASSERT(FCA::kArgsLength == 6); STATIC_ASSERT(FCA::kNewTargetIndex == 5); STATIC_ASSERT(FCA::kDataIndex == 4); STATIC_ASSERT(FCA::kReturnValueOffset == 3); STATIC_ASSERT(FCA::kReturnValueDefaultValueIndex == 2); STATIC_ASSERT(FCA::kIsolateIndex == 1); STATIC_ASSERT(FCA::kHolderIndex == 0); // Set up FunctionCallbackInfo's implicit_args on the stack as follows: // // Target state: // sp[0 * kSystemPointerSize]: kHolder // sp[1 * kSystemPointerSize]: kIsolate // sp[2 * kSystemPointerSize]: undefined (kReturnValueDefaultValue) // sp[3 * kSystemPointerSize]: undefined (kReturnValue) // sp[4 * kSystemPointerSize]: kData // sp[5 * kSystemPointerSize]: undefined (kNewTarget) // Reserve space on the stack. __ lay(sp, MemOperand(sp, -(FCA::kArgsLength * kSystemPointerSize))); // kHolder. __ StoreU64(holder, MemOperand(sp, 0 * kSystemPointerSize)); // kIsolate. __ Move(scratch, ExternalReference::isolate_address(masm->isolate())); __ StoreU64(scratch, MemOperand(sp, 1 * kSystemPointerSize)); // kReturnValueDefaultValue and kReturnValue. __ LoadRoot(scratch, RootIndex::kUndefinedValue); __ StoreU64(scratch, MemOperand(sp, 2 * kSystemPointerSize)); __ StoreU64(scratch, MemOperand(sp, 3 * kSystemPointerSize)); // kData. __ StoreU64(call_data, MemOperand(sp, 4 * kSystemPointerSize)); // kNewTarget. __ StoreU64(scratch, MemOperand(sp, 5 * kSystemPointerSize)); // Keep a pointer to kHolder (= implicit_args) in a scratch register. // We use it below to set up the FunctionCallbackInfo object. __ mov(scratch, sp); // Allocate the v8::Arguments structure in the arguments' space since // it's not controlled by GC. // S390 LINUX ABI: // // Create 4 extra slots on stack: // [0] space for DirectCEntryStub's LR save // [1-3] FunctionCallbackInfo // [4] number of bytes to drop from the stack after returning static constexpr int kApiStackSpace = 5; static constexpr bool kDontSaveDoubles = false; FrameScope frame_scope(masm, StackFrame::MANUAL); __ EnterExitFrame(kDontSaveDoubles, kApiStackSpace); // FunctionCallbackInfo::implicit_args_ (points at kHolder as set up above). // Arguments are after the return address (pushed by EnterExitFrame()). __ StoreU64(scratch, MemOperand(sp, (kStackFrameExtraParamSlot + 1) * kSystemPointerSize)); // FunctionCallbackInfo::values_ (points at the first varargs argument passed // on the stack). __ AddS64(scratch, scratch, Operand((FCA::kArgsLength + 1) * kSystemPointerSize)); __ StoreU64(scratch, MemOperand(sp, (kStackFrameExtraParamSlot + 2) * kSystemPointerSize)); // FunctionCallbackInfo::length_. __ StoreU32(argc, MemOperand(sp, (kStackFrameExtraParamSlot + 3) * kSystemPointerSize)); // We also store the number of bytes to drop from the stack after returning // from the API function here. __ mov(scratch, Operand((FCA::kArgsLength + 1 /* receiver */) * kSystemPointerSize)); __ ShiftLeftU64(r1, argc, Operand(kSystemPointerSizeLog2)); __ AddS64(scratch, r1); __ StoreU64(scratch, MemOperand(sp, (kStackFrameExtraParamSlot + 4) * kSystemPointerSize)); // v8::InvocationCallback's argument. __ lay(r2, MemOperand(sp, (kStackFrameExtraParamSlot + 1) * kSystemPointerSize)); ExternalReference thunk_ref = ExternalReference::invoke_function_callback(); // There are two stack slots above the arguments we constructed on the stack. // TODO(jgruber): Document what these arguments are. static constexpr int kStackSlotsAboveFCA = 2; MemOperand return_value_operand( fp, (kStackSlotsAboveFCA + FCA::kReturnValueOffset) * kSystemPointerSize); static constexpr int kUseStackSpaceOperand = 0; MemOperand stack_space_operand( sp, (kStackFrameExtraParamSlot + 4) * kSystemPointerSize); AllowExternalCallThatCantCauseGC scope(masm); CallApiFunctionAndReturn(masm, api_function_address, thunk_ref, kUseStackSpaceOperand, &stack_space_operand, return_value_operand); } void Builtins::Generate_CallApiGetter(MacroAssembler* masm) { int arg0Slot = 0; int accessorInfoSlot = 0; int apiStackSpace = 0; // Build v8::PropertyCallbackInfo::args_ array on the stack and push property // name below the exit frame to make GC aware of them. STATIC_ASSERT(PropertyCallbackArguments::kShouldThrowOnErrorIndex == 0); STATIC_ASSERT(PropertyCallbackArguments::kHolderIndex == 1); STATIC_ASSERT(PropertyCallbackArguments::kIsolateIndex == 2); STATIC_ASSERT(PropertyCallbackArguments::kReturnValueDefaultValueIndex == 3); STATIC_ASSERT(PropertyCallbackArguments::kReturnValueOffset == 4); STATIC_ASSERT(PropertyCallbackArguments::kDataIndex == 5); STATIC_ASSERT(PropertyCallbackArguments::kThisIndex == 6); STATIC_ASSERT(PropertyCallbackArguments::kArgsLength == 7); Register receiver = ApiGetterDescriptor::ReceiverRegister(); Register holder = ApiGetterDescriptor::HolderRegister(); Register callback = ApiGetterDescriptor::CallbackRegister(); Register scratch = r6; DCHECK(!AreAliased(receiver, holder, callback, scratch)); Register api_function_address = r4; __ push(receiver); // Push data from AccessorInfo. __ LoadAnyTaggedField( scratch, FieldMemOperand(callback, AccessorInfo::kDataOffset), r1); __ push(scratch); __ LoadRoot(scratch, RootIndex::kUndefinedValue); __ Push(scratch, scratch); __ Move(scratch, ExternalReference::isolate_address(masm->isolate())); __ Push(scratch, holder); __ Push(Smi::zero()); // should_throw_on_error -> false __ LoadTaggedPointerField( scratch, FieldMemOperand(callback, AccessorInfo::kNameOffset), r1); __ push(scratch); // v8::PropertyCallbackInfo::args_ array and name handle. const int kStackUnwindSpace = PropertyCallbackArguments::kArgsLength + 1; // Load address of v8::PropertyAccessorInfo::args_ array and name handle. __ mov(r2, sp); // r2 = Handle<Name> __ AddS64(r3, r2, Operand(1 * kSystemPointerSize)); // r3 = v8::PCI::args_ // If ABI passes Handles (pointer-sized struct) in a register: // // Create 2 extra slots on stack: // [0] space for DirectCEntryStub's LR save // [1] AccessorInfo& // // Otherwise: // // Create 3 extra slots on stack: // [0] space for DirectCEntryStub's LR save // [1] copy of Handle (first arg) // [2] AccessorInfo& if (ABI_PASSES_HANDLES_IN_REGS) { accessorInfoSlot = kStackFrameExtraParamSlot + 1; apiStackSpace = 2; } else { arg0Slot = kStackFrameExtraParamSlot + 1; accessorInfoSlot = arg0Slot + 1; apiStackSpace = 3; } FrameScope frame_scope(masm, StackFrame::MANUAL); __ EnterExitFrame(false, apiStackSpace); if (!ABI_PASSES_HANDLES_IN_REGS) { // pass 1st arg by reference __ StoreU64(r2, MemOperand(sp, arg0Slot * kSystemPointerSize)); __ AddS64(r2, sp, Operand(arg0Slot * kSystemPointerSize)); } // Create v8::PropertyCallbackInfo object on the stack and initialize // it's args_ field. __ StoreU64(r3, MemOperand(sp, accessorInfoSlot * kSystemPointerSize)); __ AddS64(r3, sp, Operand(accessorInfoSlot * kSystemPointerSize)); // r3 = v8::PropertyCallbackInfo& ExternalReference thunk_ref = ExternalReference::invoke_accessor_getter_callback(); __ LoadTaggedPointerField( scratch, FieldMemOperand(callback, AccessorInfo::kJsGetterOffset)); __ LoadU64(api_function_address, FieldMemOperand(scratch, Foreign::kForeignAddressOffset)); // +3 is to skip prolog, return address and name handle. MemOperand return_value_operand( fp, (PropertyCallbackArguments::kReturnValueOffset + 3) * kSystemPointerSize); MemOperand* const kUseStackSpaceConstant = nullptr; CallApiFunctionAndReturn(masm, api_function_address, thunk_ref, kStackUnwindSpace, kUseStackSpaceConstant, return_value_operand); } void Builtins::Generate_DirectCEntry(MacroAssembler* masm) { // Unused. __ stop(); } namespace { // This code tries to be close to ia32 code so that any changes can be // easily ported. void Generate_DeoptimizationEntry(MacroAssembler* masm, DeoptimizeKind deopt_kind) { Isolate* isolate = masm->isolate(); // Save all the registers onto the stack const int kNumberOfRegisters = Register::kNumRegisters; RegList restored_regs = kJSCallerSaved | kCalleeSaved; const int kDoubleRegsSize = kDoubleSize * DoubleRegister::kNumRegisters; // Save all double registers before messing with them. __ lay(sp, MemOperand(sp, -kDoubleRegsSize)); const RegisterConfiguration* config = RegisterConfiguration::Default(); for (int i = 0; i < config->num_allocatable_double_registers(); ++i) { int code = config->GetAllocatableDoubleCode(i); const DoubleRegister dreg = DoubleRegister::from_code(code); int offset = code * kDoubleSize; __ StoreF64(dreg, MemOperand(sp, offset)); } // Push all GPRs onto the stack __ lay(sp, MemOperand(sp, -kNumberOfRegisters * kSystemPointerSize)); __ StoreMultipleP(r0, sp, MemOperand(sp)); // Save all 16 registers __ Move(r1, ExternalReference::Create(IsolateAddressId::kCEntryFPAddress, isolate)); __ StoreU64(fp, MemOperand(r1)); static constexpr int kSavedRegistersAreaSize = (kNumberOfRegisters * kSystemPointerSize) + kDoubleRegsSize; __ mov(r4, Operand(Deoptimizer::kFixedExitSizeMarker)); // Cleanse the Return address for 31-bit __ CleanseP(r14); // Get the address of the location in the code object (r5)(return // address for lazy deoptimization) and compute the fp-to-sp delta in // register r6. __ mov(r5, r14); __ la(r6, MemOperand(sp, kSavedRegistersAreaSize)); __ SubS64(r6, fp, r6); // Allocate a new deoptimizer object. // Pass six arguments in r2 to r7. __ PrepareCallCFunction(6, r7); __ mov(r2, Operand::Zero()); Label context_check; __ LoadU64(r3, MemOperand(fp, CommonFrameConstants::kContextOrFrameTypeOffset)); __ JumpIfSmi(r3, &context_check); __ LoadU64(r2, MemOperand(fp, StandardFrameConstants::kFunctionOffset)); __ bind(&context_check); __ mov(r3, Operand(static_cast<int>(deopt_kind))); // r4: bailout id already loaded. // r5: code address or 0 already loaded. // r6: Fp-to-sp delta. // Parm6: isolate is passed on the stack. __ Move(r7, ExternalReference::isolate_address(isolate)); __ StoreU64(r7, MemOperand(sp, kStackFrameExtraParamSlot * kSystemPointerSize)); // Call Deoptimizer::New(). { AllowExternalCallThatCantCauseGC scope(masm); __ CallCFunction(ExternalReference::new_deoptimizer_function(), 6); } // Preserve "deoptimizer" object in register r2 and get the input // frame descriptor pointer to r3 (deoptimizer->input_); __ LoadU64(r3, MemOperand(r2, Deoptimizer::input_offset())); // Copy core registers into FrameDescription::registers_[kNumRegisters]. // DCHECK_EQ(Register::kNumRegisters, kNumberOfRegisters); // __ mvc(MemOperand(r3, FrameDescription::registers_offset()), // MemOperand(sp), kNumberOfRegisters * kSystemPointerSize); // Copy core registers into FrameDescription::registers_[kNumRegisters]. // TODO(john.yan): optimize the following code by using mvc instruction DCHECK_EQ(Register::kNumRegisters, kNumberOfRegisters); for (int i = 0; i < kNumberOfRegisters; i++) { int offset = (i * kSystemPointerSize) + FrameDescription::registers_offset(); __ LoadU64(r4, MemOperand(sp, i * kSystemPointerSize)); __ StoreU64(r4, MemOperand(r3, offset)); } int double_regs_offset = FrameDescription::double_registers_offset(); // Copy double registers to // double_registers_[DoubleRegister::kNumRegisters] for (int i = 0; i < config->num_allocatable_double_registers(); ++i) { int code = config->GetAllocatableDoubleCode(i); int dst_offset = code * kDoubleSize + double_regs_offset; int src_offset = code * kDoubleSize + kNumberOfRegisters * kSystemPointerSize; // TODO(joransiu): MVC opportunity __ LoadF64(d0, MemOperand(sp, src_offset)); __ StoreF64(d0, MemOperand(r3, dst_offset)); } // Mark the stack as not iterable for the CPU profiler which won't be able to // walk the stack without the return address. { UseScratchRegisterScope temps(masm); Register is_iterable = temps.Acquire(); Register zero = r6; __ Move(is_iterable, ExternalReference::stack_is_iterable_address(isolate)); __ lhi(zero, Operand(0)); __ StoreU8(zero, MemOperand(is_iterable)); } // Remove the saved registers from the stack. __ la(sp, MemOperand(sp, kSavedRegistersAreaSize)); // Compute a pointer to the unwinding limit in register r4; that is // the first stack slot not part of the input frame. __ LoadU64(r4, MemOperand(r3, FrameDescription::frame_size_offset())); __ AddS64(r4, sp); // Unwind the stack down to - but not including - the unwinding // limit and copy the contents of the activation frame to the input // frame description. __ la(r5, MemOperand(r3, FrameDescription::frame_content_offset())); Label pop_loop; Label pop_loop_header; __ b(&pop_loop_header, Label::kNear); __ bind(&pop_loop); __ pop(r6); __ StoreU64(r6, MemOperand(r5, 0)); __ la(r5, MemOperand(r5, kSystemPointerSize)); __ bind(&pop_loop_header); __ CmpS64(r4, sp); __ bne(&pop_loop); // Compute the output frame in the deoptimizer. __ push(r2); // Preserve deoptimizer object across call. // r2: deoptimizer object; r3: scratch. __ PrepareCallCFunction(1, r3); // Call Deoptimizer::ComputeOutputFrames(). { AllowExternalCallThatCantCauseGC scope(masm); __ CallCFunction(ExternalReference::compute_output_frames_function(), 1); } __ pop(r2); // Restore deoptimizer object (class Deoptimizer). __ LoadU64(sp, MemOperand(r2, Deoptimizer::caller_frame_top_offset())); // Replace the current (input) frame with the output frames. Label outer_push_loop, inner_push_loop, outer_loop_header, inner_loop_header; // Outer loop state: r6 = current "FrameDescription** output_", // r3 = one past the last FrameDescription**. __ LoadU32(r3, MemOperand(r2, Deoptimizer::output_count_offset())); __ LoadU64(r6, MemOperand(r2, Deoptimizer::output_offset())); // r6 is output_. __ ShiftLeftU64(r3, r3, Operand(kSystemPointerSizeLog2)); __ AddS64(r3, r6, r3); __ b(&outer_loop_header, Label::kNear); __ bind(&outer_push_loop); // Inner loop state: r4 = current FrameDescription*, r5 = loop index. __ LoadU64(r4, MemOperand(r6, 0)); // output_[ix] __ LoadU64(r5, MemOperand(r4, FrameDescription::frame_size_offset())); __ b(&inner_loop_header, Label::kNear); __ bind(&inner_push_loop); __ SubS64(r5, Operand(sizeof(intptr_t))); __ AddS64(r8, r4, r5); __ LoadU64(r8, MemOperand(r8, FrameDescription::frame_content_offset())); __ push(r8); __ bind(&inner_loop_header); __ CmpS64(r5, Operand::Zero()); __ bne(&inner_push_loop); // test for gt? __ AddS64(r6, r6, Operand(kSystemPointerSize)); __ bind(&outer_loop_header); __ CmpS64(r6, r3); __ blt(&outer_push_loop); __ LoadU64(r3, MemOperand(r2, Deoptimizer::input_offset())); for (int i = 0; i < config->num_allocatable_double_registers(); ++i) { int code = config->GetAllocatableDoubleCode(i); const DoubleRegister dreg = DoubleRegister::from_code(code); int src_offset = code * kDoubleSize + double_regs_offset; __ ld(dreg, MemOperand(r3, src_offset)); } // Push pc and continuation from the last output frame. __ LoadU64(r8, MemOperand(r4, FrameDescription::pc_offset())); __ push(r8); __ LoadU64(r8, MemOperand(r4, FrameDescription::continuation_offset())); __ push(r8); // Restore the registers from the last output frame. __ mov(r1, r4); for (int i = kNumberOfRegisters - 1; i > 0; i--) { int offset = (i * kSystemPointerSize) + FrameDescription::registers_offset(); if ((restored_regs & (1 << i)) != 0) { __ LoadU64(ToRegister(i), MemOperand(r1, offset)); } } { UseScratchRegisterScope temps(masm); Register is_iterable = temps.Acquire(); Register one = r6; __ Move(is_iterable, ExternalReference::stack_is_iterable_address(isolate)); __ lhi(one, Operand(1)); __ StoreU8(one, MemOperand(is_iterable)); } __ pop(ip); // get continuation, leave pc on stack __ pop(r14); __ Jump(ip); __ stop(); } } // namespace void Builtins::Generate_DeoptimizationEntry_Eager(MacroAssembler* masm) { Generate_DeoptimizationEntry(masm, DeoptimizeKind::kEager); } void Builtins::Generate_DeoptimizationEntry_Soft(MacroAssembler* masm) { Generate_DeoptimizationEntry(masm, DeoptimizeKind::kSoft); } void Builtins::Generate_DeoptimizationEntry_Bailout(MacroAssembler* masm) { Generate_DeoptimizationEntry(masm, DeoptimizeKind::kBailout); } void Builtins::Generate_DeoptimizationEntry_Lazy(MacroAssembler* masm) { Generate_DeoptimizationEntry(masm, DeoptimizeKind::kLazy); } void Builtins::Generate_BaselineEnterAtBytecode(MacroAssembler* masm) { // Implement on this platform, https://crrev.com/c/2695591. __ bkpt(0); } void Builtins::Generate_BaselineEnterAtNextBytecode(MacroAssembler* masm) { // Implement on this platform, https://crrev.com/c/2695591. __ bkpt(0); } void Builtins::Generate_InterpreterOnStackReplacement_ToBaseline( MacroAssembler* masm) { // Implement on this platform, https://crrev.com/c/2800112. __ bkpt(0); } void Builtins::Generate_DynamicCheckMapsTrampoline(MacroAssembler* masm) { FrameScope scope(masm, StackFrame::MANUAL); __ EnterFrame(StackFrame::INTERNAL); // Only save the registers that the DynamicCheckMaps builtin can clobber. DynamicCheckMapsDescriptor descriptor; RegList registers = descriptor.allocatable_registers(); // FLAG_debug_code is enabled CSA checks will call C function and so we need // to save all CallerSaved registers too. if (FLAG_debug_code) registers |= kJSCallerSaved; __ SaveRegisters(registers); // Load the immediate arguments from the deopt exit to pass to the builtin. Register slot_arg = descriptor.GetRegisterParameter(DynamicCheckMapsDescriptor::kSlot); Register handler_arg = descriptor.GetRegisterParameter(DynamicCheckMapsDescriptor::kHandler); __ LoadP(handler_arg, MemOperand(fp, CommonFrameConstants::kCallerPCOffset)); __ LoadP( slot_arg, MemOperand(handler_arg, Deoptimizer::kEagerWithResumeImmedArgs1PcOffset)); __ LoadP( handler_arg, MemOperand(handler_arg, Deoptimizer::kEagerWithResumeImmedArgs2PcOffset)); __ Call(BUILTIN_CODE(masm->isolate(), DynamicCheckMaps), RelocInfo::CODE_TARGET); Label deopt, bailout; __ CmpS64(r2, Operand(static_cast<int>(DynamicCheckMapsStatus::kSuccess))); __ bne(&deopt); __ RestoreRegisters(registers); __ LeaveFrame(StackFrame::INTERNAL); __ Ret(); __ bind(&deopt); __ CmpS64(r2, Operand(static_cast<int>(DynamicCheckMapsStatus::kBailout))); __ beq(&bailout); if (FLAG_debug_code) { __ CmpS64(r2, Operand(static_cast<int>(DynamicCheckMapsStatus::kDeopt))); __ Assert(eq, AbortReason::kUnexpectedDynamicCheckMapsStatus); } __ RestoreRegisters(registers); __ LeaveFrame(StackFrame::INTERNAL); Handle<Code> deopt_eager = masm->isolate()->builtins()->builtin_handle( Deoptimizer::GetDeoptimizationEntry(DeoptimizeKind::kEager)); __ Jump(deopt_eager, RelocInfo::CODE_TARGET); __ bind(&bailout); __ RestoreRegisters(registers); __ LeaveFrame(StackFrame::INTERNAL); Handle<Code> deopt_bailout = masm->isolate()->builtins()->builtin_handle( Deoptimizer::GetDeoptimizationEntry(DeoptimizeKind::kBailout)); __ Jump(deopt_bailout, RelocInfo::CODE_TARGET); } #undef __ } // namespace internal } // namespace v8 #endif // V8_TARGET_ARCH_S390
/* $Id$ */ /* * This file is part of OpenTTD. * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2. * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>. */ /** @file ai_info_dummy.cpp Implementation of a dummy AI. */ #include <squirrel.h> #include "../stdafx.h" #include "../string_func.h" #include "../strings_func.h" #include "table/strings.h" /* The reason this exists in C++, is that a user can trash his ai/ dir, * leaving no AIs available. The complexity to solve this is insane, and * therefor the alternative is used, and make sure there is always an AI * available, no matter what the situation is. By defining it in C++, there * is simply now way a user can delete it, and therefor safe to use. It has * to be noted that this AI is complete invisible for the user, and impossible * to select manual. It is a fail-over in case no AIs are available. */ /** info.nut for the dummy AI. */ const SQChar _dummy_script_info[] = _SC(" \n\ class DummyAI extends AIInfo { \n\ function GetAuthor() { return \"OpenTTD NoAI Developers Team\"; } \n\ function GetName() { return \"DummyAI\"; } \n\ function GetShortName() { return \"DUMM\"; } \n\ function GetDescription() { return \"A Dummy AI that is loaded when your ai/ dir is empty\"; }\n\ function GetVersion() { return 1; } \n\ function GetDate() { return \"2008-07-26\"; } \n\ function CreateInstance() { return \"DummyAI\"; } \n\ } \n\ \n\ RegisterDummyAI(DummyAI()); \n\ "); /** Run the dummy info.nut. */ void AI_CreateAIInfoDummy(HSQUIRRELVM vm) { sq_pushroottable(vm); /* Load and run the script */ if (SQ_SUCCEEDED(sq_compilebuffer(vm, _dummy_script_info, scstrlen(_dummy_script_info), _SC("dummy"), SQTrue))) { sq_push(vm, -2); if (SQ_SUCCEEDED(sq_call(vm, 1, SQFalse, SQTrue))) { sq_pop(vm, 1); return; } } NOT_REACHED(); } /** Run the dummy AI and let it generate an error message. */ void AI_CreateAIDummy(HSQUIRRELVM vm) { /* We want to translate the error message. * We do this in three steps: * 1) We get the error message */ char error_message[1024]; GetString(error_message, STR_ERROR_AI_NO_AI_FOUND, lastof(error_message)); /* Make escapes for all quotes and slashes. */ char safe_error_message[1024]; char *q = safe_error_message; for (const char *p = error_message; *p != '\0' && q < lastof(safe_error_message) - 2; p++, q++) { if (*p == '"' || *p == '\\') *q++ = '\\'; *q = *p; } *q = '\0'; /* 2) We construct the AI's code. This is done by merging a header, body and footer */ char dummy_script[4096]; char *dp = dummy_script; dp = strecpy(dp, "class DummyAI extends AIController {\n function Start()\n {\n", lastof(dummy_script)); /* As special trick we need to split the error message on newlines and * emit each newline as a separate error printing string. */ char *newline; char *p = safe_error_message; do { newline = strchr(p, '\n'); if (newline != NULL) *newline = '\0'; dp += seprintf(dp, lastof(dummy_script), " AILog.Error(\"%s\");\n", p); p = newline + 1; } while (newline != NULL); dp = strecpy(dp, " }\n}\n", lastof(dummy_script)); /* 3) We translate the error message in the character format that Squirrel wants. * We can use the fact that the wchar string printing also uses %s to print * old style char strings, which is what was generated during the script generation. */ const SQChar *sq_dummy_script = OTTD2SQ(dummy_script); /* And finally we load and run the script */ sq_pushroottable(vm); if (SQ_SUCCEEDED(sq_compilebuffer(vm, sq_dummy_script, scstrlen(sq_dummy_script), _SC("dummy"), SQTrue))) { sq_push(vm, -2); if (SQ_SUCCEEDED(sq_call(vm, 1, SQFalse, SQTrue))) { sq_pop(vm, 1); return; } } NOT_REACHED(); }
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "goose.h" namespace { // The maximum speed of a goose. Measured in meters/second. const double kMaxSpeed = 2.0; // The maximum force that can be applied to turn a goose when computing the // aligment. Measured in meters/second/second. const double kMaxTurningForce = 0.05; // The neighbour radius of a goose. Only geese within this radius will affect // the flocking computations of this goose. Measured in pixels. const double kNeighbourRadius = 64.0; // The minimum distance that a goose can be from this goose. If another goose // comes within this distance of this goose, the flocking algorithm tries to // move the geese apart. Measured in pixels. const double kPersonalSpace = 32.0; // The distance at which attractors have effect on a goose's direction. const double kAttractorRadius = 320.0; // The goose will try to turn towards geese within this distance (computed // during the cohesion phase). Measured in pixels. const double kMaxTurningDistance = 100.0; // The weights used when computing the weighted sum the three flocking // components. const double kSeparationWeight = 2.0; const double kAlignmentWeight = 1.0; const double kCohesionWeight = 1.0; } // namespace Goose::Goose() : location_(0, 0), velocity_(0, 0) { } Goose::Goose(const Vector2& location, const Vector2& velocity) : location_(location), velocity_(velocity) { } void Goose::SimulationTick(const std::vector<Goose>& geese, const std::vector<Vector2>& attractors, const pp::Rect& flock_box) { Vector2 acceleration = DesiredVector(geese, attractors); velocity_.Add(acceleration); // Limit the velocity to a maximum speed. velocity_.Clamp(kMaxSpeed); location_.Add(velocity_); // Wrap the goose location to the flock box. if (!flock_box.IsEmpty()) { while (location_.x() < flock_box.x()) location_.set_x(location_.x() + flock_box.width()); while (location_.x() >= flock_box.right()) location_.set_x(location_.x() - flock_box.width()); while (location_.y() < flock_box.y()) location_.set_y(location_.y() + flock_box.height()); while (location_.y() >= flock_box.bottom()) location_.set_y(location_.y() - flock_box.height()); } } Vector2 Goose::DesiredVector(const std::vector<Goose>& geese, const std::vector<Vector2>& attractors) { // Loop over all the neighbouring geese in the flock, accumulating // the separation mean, the alignment mean and the cohesion mean. int32_t separation_count = 0; Vector2 separation; int32_t align_count = 0; Vector2 alignment; int32_t cohesion_count = 0; Vector2 cohesion; for (std::vector<Goose>::const_iterator goose_it = geese.begin(); goose_it < geese.end(); ++goose_it) { const Goose& goose = *goose_it; // Compute the distance from this goose to its neighbour. Vector2 goose_delta = Vector2::Difference( location_, goose.location()); double distance = goose_delta.Magnitude(); separation_count = AccumulateSeparation( distance, goose_delta, &separation, separation_count); align_count = AccumulateAlignment( distance, goose, &alignment, align_count); cohesion_count = AccumulateCohesion( distance, goose, &cohesion, cohesion_count); } // Compute the means and create a weighted sum. This becomes the goose's new // acceleration. if (separation_count > 0) { separation.Scale(1.0 / static_cast<double>(separation_count)); } if (align_count > 0) { alignment.Scale(1.0 / static_cast<double>(align_count)); // Limit the effect that alignment has on the final acceleration. The // alignment component can overpower the others if there is a big // difference between this goose's velocity and its neighbours'. alignment.Clamp(kMaxTurningForce); } // Compute the effect of the attractors and blend this in with the flock // cohesion component. An attractor has to be within kAttractorRadius to // effect the heading of a goose. for (size_t i = 0; i < attractors.size(); ++i) { Vector2 attractor_direction = Vector2::Difference( attractors[i], location_); double distance = attractor_direction.Magnitude(); if (distance < kAttractorRadius) { attractor_direction.Scale(1000); // Each attractor acts like 1000 geese. cohesion.Add(attractor_direction); cohesion_count++; } } // If there is a non-0 cohesion component, steer the goose so that it tries // to follow the flock. if (cohesion_count > 0) { cohesion.Scale(1.0 / static_cast<double>(cohesion_count)); cohesion = TurnTowardsTarget(cohesion); } // Compute the weighted sum. separation.Scale(kSeparationWeight); alignment.Scale(kAlignmentWeight); cohesion.Scale(kCohesionWeight); Vector2 weighted_sum = cohesion; weighted_sum.Add(alignment); weighted_sum.Add(separation); return weighted_sum; } Vector2 Goose::TurnTowardsTarget(const Vector2& target) { Vector2 desired_direction = Vector2::Difference(target, location_); double distance = desired_direction.Magnitude(); Vector2 new_direction; if (distance > 0.0) { desired_direction.Normalize(); // If the target is within the turning affinity distance, then make the // desired direction based on distance to the target. Otherwise, base // the desired direction on MAX_SPEED. if (distance < kMaxTurningDistance) { // Some pretty arbitrary dampening. desired_direction.Scale(kMaxSpeed * distance / 100.0); } else { desired_direction.Scale(kMaxSpeed); } new_direction = Vector2::Difference(desired_direction, velocity_); new_direction.Clamp(kMaxTurningForce); } return new_direction; } int32_t Goose::AccumulateSeparation(double distance, const Vector2& goose_delta, Vector2* separation, /* inout */ int32_t separation_count) { if (distance > 0.0 && distance < kPersonalSpace) { Vector2 weighted_direction = goose_delta; weighted_direction.Normalize(); weighted_direction.Scale(1.0 / distance); separation->Add(weighted_direction); separation_count++; } return separation_count; } int32_t Goose::AccumulateAlignment(double distance, const Goose& goose, Vector2* alignment, /* inout */ int32_t align_count) { if (distance > 0.0 && distance < kNeighbourRadius) { alignment->Add(goose.velocity()); align_count++; } return align_count; } int32_t Goose::AccumulateCohesion(double distance, const Goose& goose, Vector2* cohesion, /* inout */ int32_t cohesion_count) { if (distance > 0.0 && distance < kNeighbourRadius) { cohesion->Add(goose.location()); cohesion_count++; } return cohesion_count; }
// // Copyright (C) 2011 Denis V Chapligin // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // #define BOOST_TEST_MODULE "STLCachePolicyLFUAging*" #ifndef _MSC_VER #include <unistd.h> #define WAIT_A_SECOND sleep(2); #else #include <windows.h> #define WAIT_A_SECOND Sleep(2000); #endif /* _MSC_VER */ #include <boost/test/unit_test.hpp> #include <stlcache/stlcache.hpp> using namespace stlcache; BOOST_AUTO_TEST_SUITE(STLCacheSuite) BOOST_AUTO_TEST_CASE(lastInserted) { cache<int,string,policy_lfuagingstar<3600> > c1(3); c1.insert(1,"data1"); c1.insert(2,"data2"); c1.insert(3,"data3"); c1.insert(4,"data4"); BOOST_CHECK(c1.size()==3); } BOOST_AUTO_TEST_CASE(touch) { cache<int,string,policy_lfuagingstar<3600> > c1(3); c1.insert(1,"data1"); c1.insert(2,"data2"); c1.insert(3,"data3"); c1.touch(1); c1.touch(2); c1.insert(4,"data4"); BOOST_REQUIRE_THROW(c1.fetch(3),exception_invalid_key); //Must be removed by LFU* policy (cause 1&2 are touched) } BOOST_AUTO_TEST_CASE(veryfrequent) { cache<int,string,policy_lfuagingstar<3600> > c1(3); c1.insert(1,"data1"); c1.insert(2,"data2"); c1.insert(3,"data3"); c1.touch(1); c1.touch(2); c1.touch(3); BOOST_REQUIRE_THROW(c1.insert(4,"data4"),exception_cache_full); //Because every entry in cache have reference counter bigger then one and //lfu* policy works only on entries with refcount equal to 1 c1.erase(1); BOOST_REQUIRE_NO_THROW(c1.insert(4,"data4")); BOOST_REQUIRE_THROW(c1.fetch(1),exception_invalid_key); BOOST_REQUIRE_NO_THROW(c1.fetch(4)); } BOOST_AUTO_TEST_CASE(expire) { cache<int,string,policy_lfuagingstar<1> > c1(3); c1.insert(1,"data1"); c1.insert(2,"data2"); c1.insert(3,"data3"); c1.touch(1); //For key one refcount is 3 now c1.touch(1); c1.touch(2); //For key two refcount is 3 now c1.touch(2); c1.touch(3); //For key three refcount is 2 now WAIT_A_SECOND; c1.insert(4,"data4"); BOOST_REQUIRE_THROW(c1.fetch(3),exception_invalid_key); //Must be removed by LFU policy (cause every item have been touched and refcount for key 3 is 1) } BOOST_AUTO_TEST_CASE(expirefail) { cache<int,string,policy_lfuagingstar<1> > c1(3); c1.insert(1,"data1"); c1.insert(2,"data2"); c1.insert(3,"data3"); c1.touch(1); //For key one refcount is 4 now c1.touch(1); c1.touch(1); c1.touch(2); //For key two refcount is 4 now c1.touch(2); c1.touch(2); c1.touch(3); //For key three refcount is 3 now c1.touch(3); WAIT_A_SECOND; BOOST_REQUIRE_THROW(c1.insert(4,"data4"),exception_cache_full); //Cause even in expired cache there are no entries with refcount 1 WAIT_A_SECOND; BOOST_REQUIRE_NO_THROW(c1.insert(4,"data4")); BOOST_REQUIRE_THROW(c1.fetch(3),exception_invalid_key); //Must be removed by LFU policy (cause every item have been expired again and refcount for key 3 is 1) } BOOST_AUTO_TEST_SUITE_END();
/* +----------------------------------------------------------------------+ | Swoole | +----------------------------------------------------------------------+ | This source file is subject to version 2.0 of the Apache license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.apache.org/licenses/LICENSE-2.0.html | | If you did not receive a copy of the Apache2.0 license and are unable| | to obtain it through the world-wide-web, please send a note to | | license@swoole.com so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: Xinyu Zhu <xyzhu1120@gmail.com> | | shiguangqi <shiguangqi2008@gmail.com> | | Twosee <twose@qq.com> | | Tianfeng Han <rango@swoole.com> | +----------------------------------------------------------------------+ */ #include "php_swoole_cxx.h" using namespace swoole; #define PHP_CORO_TASK_SLOT ((int)((ZEND_MM_ALIGNED_SIZE(sizeof(php_coro_task)) + ZEND_MM_ALIGNED_SIZE(sizeof(zval)) - 1) / ZEND_MM_ALIGNED_SIZE(sizeof(zval)))) bool PHPCoroutine::active = false; uint64_t PHPCoroutine::max_num = SW_DEFAULT_MAX_CORO_NUM; php_coro_task PHPCoroutine::main_task = {0}; bool PHPCoroutine::schedule_thread_created = false; static zend_bool* zend_vm_interrupt = nullptr; static pthread_t pidt; static void (*orig_interrupt_function)(zend_execute_data *execute_data); static void swoole_interrupt_resume(void *data) { Coroutine *co = (Coroutine *) data; if (co && !co->is_end()) { swTraceLog(SW_TRACE_COROUTINE, "interrupt_callback cid=%ld ", co->get_cid()); co->resume(); } } static void swoole_interrupt_function(zend_execute_data *execute_data) { php_coro_task *task = PHPCoroutine::get_task(); if (task && task->co && PHPCoroutine::is_schedulable(task)) { SwooleG.main_reactor->defer(SwooleG.main_reactor, swoole_interrupt_resume, (void *) task->co); task->co->yield(); } if (orig_interrupt_function) { orig_interrupt_function(execute_data); } } void PHPCoroutine::init() { Coroutine::set_on_yield(on_yield); Coroutine::set_on_resume(on_resume); Coroutine::set_on_close(on_close); orig_interrupt_function = zend_interrupt_function; zend_interrupt_function = swoole_interrupt_function; } void PHPCoroutine::shutdown() { if (schedule_thread_created) { //wait thread if (pthread_join(pidt, NULL) < 0) { swSysWarn("pthread_join(%ld) failed", (ulong_t )pidt); } } Coroutine::bailout(nullptr); } void PHPCoroutine::create_scheduler_thread() { if (schedule_thread_created) { return; } zend_vm_interrupt = &EG(vm_interrupt); if (pthread_create(&pidt, NULL, (void * (*)(void *)) schedule, NULL) < 0) { swSysError("pthread_create[PHPCoroutine Scheduler] failed"); } schedule_thread_created = true; } void PHPCoroutine::schedule() { static const useconds_t interval = (MAX_EXEC_MSEC / 2) * 1000; swSignal_none(); while (SwooleG.running) { *zend_vm_interrupt = 1; usleep(interval); } pthread_exit(0); } inline void PHPCoroutine::vm_stack_init(void) { uint32_t size = SW_DEFAULT_PHP_STACK_PAGE_SIZE; zend_vm_stack page = (zend_vm_stack) emalloc(size); page->top = ZEND_VM_STACK_ELEMENTS(page); page->end = (zval*) ((char*) page + size); page->prev = NULL; EG(vm_stack) = page; EG(vm_stack)->top++; EG(vm_stack_top) = EG(vm_stack)->top; EG(vm_stack_end) = EG(vm_stack)->end; #if PHP_VERSION_ID >= 70300 EG(vm_stack_page_size) = size; #endif } inline void PHPCoroutine::vm_stack_destroy(void) { zend_vm_stack stack = EG(vm_stack); while (stack != NULL) { zend_vm_stack p = stack->prev; efree(stack); stack = p; } } /** * The meaning of the task argument in coro switch functions * * create: origin_task * yield: current_task * resume: target_task * close: current_task * */ inline void PHPCoroutine::save_vm_stack(php_coro_task *task) { #ifdef SW_CORO_SWAP_BAILOUT task->bailout = EG(bailout); #endif task->vm_stack_top = EG(vm_stack_top); task->vm_stack_end = EG(vm_stack_end); task->vm_stack = EG(vm_stack); #if PHP_VERSION_ID >= 70300 task->vm_stack_page_size = EG(vm_stack_page_size); #endif task->execute_data = EG(current_execute_data); task->error_handling = EG(error_handling); task->exception_class = EG(exception_class); task->exception = EG(exception); SW_SAVE_EG_SCOPE(task->scope); } inline void PHPCoroutine::restore_vm_stack(php_coro_task *task) { #ifdef SW_CORO_SWAP_BAILOUT EG(bailout) = task->bailout; #endif EG(vm_stack_top) = task->vm_stack_top; EG(vm_stack_end) = task->vm_stack_end; EG(vm_stack) = task->vm_stack; #if PHP_VERSION_ID >= 70300 EG(vm_stack_page_size) = task->vm_stack_page_size; #endif EG(current_execute_data) = task->execute_data; EG(error_handling) = task->error_handling; EG(exception_class) = task->exception_class; EG(exception) = task->exception; SW_SET_EG_SCOPE(task->scope); } inline void PHPCoroutine::save_og(php_coro_task *task) { if (OG(handlers).elements) { task->output_ptr = (zend_output_globals *) emalloc(sizeof(zend_output_globals)); memcpy(task->output_ptr, SWOG, sizeof(zend_output_globals)); php_output_activate(); } else { task->output_ptr = NULL; } } inline void PHPCoroutine::restore_og(php_coro_task *task) { if (task->output_ptr) { memcpy(SWOG, task->output_ptr, sizeof(zend_output_globals)); efree(task->output_ptr); task->output_ptr = NULL; } } void PHPCoroutine::save_task(php_coro_task *task) { save_vm_stack(task); save_og(task); } void PHPCoroutine::restore_task(php_coro_task *task) { restore_vm_stack(task); restore_og(task); } void PHPCoroutine::on_yield(void *arg) { php_coro_task *task = (php_coro_task *) arg; php_coro_task *origin_task = get_origin_task(task); swTraceLog(SW_TRACE_COROUTINE,"php_coro_yield from cid=%ld to cid=%ld", task->co->get_cid(), task->co->get_origin_cid()); save_task(task); restore_task(origin_task); } void PHPCoroutine::on_resume(void *arg) { php_coro_task *task = (php_coro_task *) arg; php_coro_task *current_task = get_task(); save_task(current_task); restore_task(task); record_last_msec(task); swTraceLog(SW_TRACE_COROUTINE,"php_coro_resume from cid=%ld to cid=%ld", Coroutine::get_current_cid(), task->co->get_cid()); } void PHPCoroutine::on_close(void *arg) { php_coro_task *task = (php_coro_task *) arg; php_coro_task *origin_task = get_origin_task(task); #ifdef SW_LOG_TRACE_OPEN long cid = task->co->get_cid(); long origin_cid = task->co->get_origin_cid(); #endif if (SwooleG.hooks[SW_GLOBAL_HOOK_ON_CORO_STOP]) { swoole_call_hook(SW_GLOBAL_HOOK_ON_CORO_STOP, task); } if (OG(handlers).elements) { if (OG(active)) { php_output_end_all(); } php_output_deactivate(); php_output_activate(); } vm_stack_destroy(); restore_task(origin_task); swTraceLog( SW_TRACE_COROUTINE, "coro close cid=%ld and resume to %ld, %zu remained. usage size: %zu. malloc size: %zu", cid, origin_cid, (uintmax_t) Coroutine::count() - 1, (uintmax_t) zend_memory_usage(0), (uintmax_t) zend_memory_usage(1) ); } void PHPCoroutine::create_func(void *arg) { #ifdef SW_CORO_SUPPORT_BAILOUT zend_first_try { #endif int i; php_coro_args *php_arg = (php_coro_args *) arg; zend_fcall_info_cache fci_cache = *php_arg->fci_cache; zend_function *func = fci_cache.function_handler; zval *argv = php_arg->argv; int argc = php_arg->argc; php_coro_task *task; zend_execute_data *call; zval _retval, *retval = &_retval; if (fci_cache.object) { GC_ADDREF(fci_cache.object); } vm_stack_init(); call = (zend_execute_data *) (EG(vm_stack_top)); task = (php_coro_task *) EG(vm_stack_top); EG(vm_stack_top) = (zval *) ((char *) call + PHP_CORO_TASK_SLOT * sizeof(zval)); #if PHP_VERSION_ID < 70400 call = zend_vm_stack_push_call_frame( ZEND_CALL_TOP_FUNCTION | ZEND_CALL_ALLOCATED, func, argc, fci_cache.called_scope, fci_cache.object ); #else do { uint32_t call_info; void *object_or_called_scope; if ((func->common.fn_flags & ZEND_ACC_STATIC) || !fci_cache.object) { object_or_called_scope = fci_cache.called_scope; call_info = ZEND_CALL_TOP_FUNCTION | ZEND_CALL_DYNAMIC; } else { object_or_called_scope = fci_cache.object; call_info = ZEND_CALL_TOP_FUNCTION | ZEND_CALL_DYNAMIC | ZEND_CALL_HAS_THIS; } call = zend_vm_stack_push_call_frame(call_info, func, argc, object_or_called_scope); } while (0); #endif SW_SET_EG_SCOPE(func->common.scope); for (i = 0; i < argc; ++i) { zval *param; zval *arg = &argv[i]; if (Z_ISREF_P(arg) && !(func->common.fn_flags & ZEND_ACC_CALL_VIA_TRAMPOLINE)) { /* don't separate references for __call */ arg = Z_REFVAL_P(arg); } param = ZEND_CALL_ARG(call, i + 1); ZVAL_COPY(param, arg); } call->symbol_table = NULL; if (func->op_array.fn_flags & ZEND_ACC_CLOSURE) { uint32_t call_info; GC_ADDREF(ZEND_CLOSURE_OBJECT(func)); call_info = ZEND_CALL_CLOSURE; ZEND_ADD_CALL_FLAG(call, call_info); } #if defined(SW_CORO_SWAP_BAILOUT) && !defined(SW_CORO_SUPPORT_BAILOUT) EG(bailout) = NULL; #endif EG(current_execute_data) = call; EG(error_handling) = EH_NORMAL; EG(exception_class) = NULL; EG(exception) = NULL; save_vm_stack(task); record_last_msec(task); task->output_ptr = NULL; task->co = Coroutine::get_current(); task->co->set_task((void *) task); task->defer_tasks = nullptr; task->pcid = task->co->get_origin_cid(); task->context = nullptr; swTraceLog( SW_TRACE_COROUTINE, "Create coro id: %ld, origin cid: %ld, coro total count: %zu, heap size: %zu", task->co->get_cid(), task->co->get_origin_cid(), (uintmax_t) Coroutine::count(), (uintmax_t) zend_memory_usage(0) ); if (SwooleG.hooks[SW_GLOBAL_HOOK_ON_CORO_START]) { swoole_call_hook(SW_GLOBAL_HOOK_ON_CORO_START, task); } if (EXPECTED(func->type == ZEND_USER_FUNCTION)) { ZVAL_UNDEF(retval); // TODO: enhancement it, separate execute data is necessary, but we lose the backtrace EG(current_execute_data) = NULL; #if PHP_VERSION_ID >= 70200 zend_init_func_execute_data(call, &func->op_array, retval); #else zend_init_execute_data(call, &func->op_array, retval); #endif zend_execute_ex(EG(current_execute_data)); } else /* ZEND_INTERNAL_FUNCTION */ { ZVAL_NULL(retval); call->prev_execute_data = NULL; call->return_value = NULL; /* this is not a constructor call */ execute_internal(call, retval); zend_vm_stack_free_args(call); } if (task->defer_tasks) { std::stack<php_swoole_fci *> *tasks = task->defer_tasks; while (!tasks->empty()) { php_swoole_fci *defer_fci = tasks->top(); tasks->pop(); defer_fci->fci.param_count = 1; defer_fci->fci.params = retval; if (UNEXPECTED(sw_call_function_anyway(&defer_fci->fci, &defer_fci->fci_cache) == FAILURE)) { swoole_php_fatal_error(E_WARNING, "defer callback handler error"); } sw_fci_cache_discard(&defer_fci->fci_cache); efree(defer_fci); } delete task->defer_tasks; task->defer_tasks = nullptr; } // resources release zval_ptr_dtor(retval); if (fci_cache.object) { OBJ_RELEASE(fci_cache.object); } if (task->context) { OBJ_RELEASE(task->context); } if (UNEXPECTED(EG(exception))) { zend_exception_error(EG(exception), E_ERROR); } #ifdef SW_CORO_SUPPORT_BAILOUT } zend_catch { Coroutine::bailout([](){ sw_zend_bailout(); }); } zend_end_try(); #endif } long PHPCoroutine::create(zend_fcall_info_cache *fci_cache, uint32_t argc, zval *argv) { if (unlikely(Coroutine::count() >= max_num)) { swoole_php_fatal_error(E_WARNING, "exceed max number of coroutine %zu", (uintmax_t) Coroutine::count()); return SW_CORO_ERR_LIMIT; } if (unlikely(!fci_cache || !fci_cache->function_handler)) { swoole_php_fatal_error(E_ERROR, "invalid function call info cache"); return SW_CORO_ERR_INVALID; } zend_uchar type = fci_cache->function_handler->type; if (unlikely(type != ZEND_USER_FUNCTION && type != ZEND_INTERNAL_FUNCTION)) { swoole_php_fatal_error(E_ERROR, "invalid function type %u", fci_cache->function_handler->type); return SW_CORO_ERR_INVALID; } if (unlikely(!active)) { if (SWOOLE_G(enable_preemptive_scheduler)) { // create a thread to interrupt the coroutine that takes up too much time create_scheduler_thread(); } if (zend_hash_str_find_ptr(&module_registry, ZEND_STRL("xdebug"))) { swoole_php_fatal_error(E_WARNING, "Using Xdebug in coroutines is extremely dangerous, please notice that it may lead to coredump!"); } inject_function(); // init reactor and register event wait php_swoole_check_reactor(); // TODO: enable hook in v5.0.0 // enable_hook(SW_HOOK_ALL); active = true; } php_coro_args php_coro_args; php_coro_args.fci_cache = fci_cache; php_coro_args.argv = argv; php_coro_args.argc = argc; save_task(get_task()); return Coroutine::create(create_func, (void*) &php_coro_args); } void PHPCoroutine::defer(php_swoole_fci *fci) { php_coro_task *task = get_task(); if (task->defer_tasks == nullptr) { task->defer_tasks = new std::stack<php_swoole_fci *>; } task->defer_tasks->push(fci); } void PHPCoroutine::yield_m(zval *return_value, php_coro_context *sw_current_context) { Coroutine::get_current_safe(); php_coro_task *task = get_task(); sw_current_context->current_coro_return_value_ptr = return_value; sw_current_context->current_task = task; on_yield(task); task->co->yield_naked(); } int PHPCoroutine::resume_m(php_coro_context *sw_current_context, zval *retval, zval *coro_retval) { php_coro_task *task = sw_current_context->current_task; on_resume(task); if (retval) { ZVAL_COPY(sw_current_context->current_coro_return_value_ptr, retval); } task->co->resume_naked(); return SW_CORO_ERR_END; }
//================================================================================================== /*! @file @copyright 2016 NumScale SAS Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) */ //================================================================================================== #ifndef BOOST_SIMD_FUNCTION_DEFINITION_IFNOT_MINUS_HPP_INCLUDED #define BOOST_SIMD_FUNCTION_DEFINITION_IFNOT_MINUS_HPP_INCLUDED #include <boost/simd/config.hpp> #include <boost/simd/detail/dispatch/function/make_callable.hpp> #include <boost/simd/detail/dispatch/hierarchy/functions.hpp> #include <boost/simd/detail/dispatch.hpp> namespace boost { namespace simd { namespace tag { BOOST_DISPATCH_MAKE_TAG(ext, ifnot_minus_, boost::dispatch::elementwise_<ifnot_minus_>); } namespace ext { BOOST_DISPATCH_FUNCTION_DECLARATION(tag, ifnot_minus_) } BOOST_DISPATCH_CALLABLE_DEFINITION(tag::ifnot_minus_,ifnot_minus); } } #endif
#include "Composite.h" Component::Component() { } Component::~Component() { } void Component::Add(const Component& com) { } Component* Component::GetChild(int index) { return 0; } void Component::Remove(const Component& com) { } Composite::Composite() { } Composite::~Composite() { vector<Component*>::iterator comIter = comVec.begin(); for (; comIter != comVec.end();) { if (NULL != *comIter){ delete *comIter; comIter = comVec.erase(comIter); // 删除元素,返回值指向已删除元素的下一个位置 }else { ++comIter; } } } void Composite::Operation() { vector<Component*>::iterator comIter = comVec.begin(); for (; comIter != comVec.end(); comIter++) { (*comIter)->Operation(); } } void Composite::Add(Component* com) { comVec.push_back(com); } void Composite::Remove(Component* com) { vector<Component*>::iterator comIter = comVec.begin(); for (; comIter != comVec.end(); comIter++) { if (*comIter == com){ comIter = comVec.erase(comIter); delete com; break; } } } Component* Composite::GetChild(int index){ return comVec[index]; } Leaf::Leaf() { } Leaf::~Leaf() { cout << "Leaf::~Leaf()" << endl; } void Leaf::Operation() { cout << "Leaf operation....." << endl; }
/* * NAppGUI Cross-platform C SDK * 2015-2021 Francisco Garcia Collado * MIT Licence * https://nappgui.com/en/legal/license.html * * File: col2d.hpp * */ /* 2D Collision detection */ #ifndef __COL2D_HPP__ #define __COL2D_HPP__ #include "cir2d.hpp" #include "box2d.hpp" #include "obb2d.hpp" #include "pol2d.hpp" #include "v2d.hpp" template<typename real> struct Col2D { static bool_t (*point_point)(const V2D<real> *pnt1, const V2D<real> *pnt2, const real tol, Col2D<real> *col); static bool_t (*segment_point)(const Seg2D<real> *seg, const V2D<real> *pnt, const real tol, Col2D<real> *col); static bool_t (*segment_segment)(const Seg2D<real> *seg1, const Seg2D<real> *seg2, Col2D<real> *col); static bool_t (*circle_point)(const Cir2D<real> *cir, const V2D<real> *p, Col2D<real> *col); static bool_t (*circle_segment)(const Cir2D<real> *cir, const Seg2D<real> *seg, Col2D<real> *col); static bool_t (*circle_circle)(const Cir2D<real> *cir1, const Cir2D<real> *cir2, Col2D<real> *col); static bool_t (*box_point)(const Box2D<real> *box, const V2D<real> *pt, Col2D<real> *col); static bool_t (*box_segment)(const Box2D<real> *box, const Seg2D<real> *seg, Col2D<real> *col); static bool_t (*box_circle)(const Box2D<real> *box, const Cir2D<real> *cir, Col2D<real> *col); static bool_t (*box_box)(const Box2D<real> *box1, const Box2D<real> *box2, Col2D<real> *col); static bool_t (*obb_point)(const OBB2D<real> *obb, const V2D<real> *pt, Col2D<real> *col); static bool_t (*obb_segment)(const OBB2D<real> *obb, const Seg2D<real> *seg, Col2D<real> *col); static bool_t (*obb_circle)(const OBB2D<real> *obb, const Cir2D<real> *cir, Col2D<real> *col); static bool_t (*obb_box)(const OBB2D<real> *obb, const Box2D<real> *box, Col2D<real> *col); static bool_t (*obb_obb)(const OBB2D<real> *obb1, const OBB2D<real> *obb2, Col2D<real> *col); static bool_t (*tri_point)(const Tri2D<real> *tri, const V2D<real> *pnt, Col2D<real> *col); static bool_t (*tri_segment)(const Tri2D<real> *tri, const Seg2D<real> *seg, Col2D<real> *col); static bool_t (*tri_circle)(const Tri2D<real> *tri, const Cir2D<real> *cir, Col2D<real> *col); static bool_t (*tri_box)(const Tri2D<real> *tri, const Box2D<real> *box, Col2D<real> *col); static bool_t (*tri_obb)(const Tri2D<real> *tri, const OBB2D<real> *obb, Col2D<real> *col); static bool_t (*tri_tri)(const Tri2D<real> *tri1, const Tri2D<real> *tri2, Col2D<real> *col); static bool_t (*poly_point)(const Pol2D<real> *poly, const V2D<real> *pt, Col2D<real> *col); static bool_t (*poly_segment)(const Pol2D<real> *poly, const Seg2D<real> *seg, Col2D<real> *col); static bool_t (*poly_circle)(const Pol2D<real> *poly, const Cir2D<real> *cir, Col2D<real> *col); static bool_t (*poly_box)(const Pol2D<real> *poly, const Box2D<real> *box, Col2D<real> *col); static bool_t (*poly_obb)(const Pol2D<real> *poly, const OBB2D<real> *obb, Col2D<real> *col); static bool_t (*poly_tri)(const Pol2D<real> *poly, const Tri2D<real> *tri, Col2D<real> *col); static bool_t (*poly_poly)(const Pol2D<real> *poly1, const Pol2D<real> *poly2, Col2D<real> *col); V2D<real> p; V2D<real> n; real d; }; #endif
/* * If not stated otherwise in this file or this component's LICENSE file the * following copyright and licenses apply: * * Copyright 2014 RDK Management * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "cmThreadBase.h" #include "string.h" #include "rdk_debug.h" #include "rmf_osal_mem.h" #if USE_SYSRES_MLT #include "rpl_new.h" #endif CMThread::CMThread (char *name) { thread_running = 0; thread_name = NULL; tid = 0; if (name) { rmf_osal_memAllocP(RMF_OSAL_MEM_POD, (strlen(name) + 1), (void**) &this->thread_name); this->thread_name[0] = 0; strcpy(this->thread_name, name); } } CMThread::~CMThread () { rmf_osal_memFreeP(RMF_OSAL_MEM_POD, this->thread_name); } void CMThread::entry_point (void *parameters) { CMThread *pt = (CMThread *) parameters; // execute the thread pt->thread_running = 1; pt->run (); pt->thread_running = 0; } void CMThread::start () { rmf_Error err = rmf_osal_threadCreate (CMThread::entry_point, this, RMF_OSAL_THREAD_PRIOR_DFLT, RMF_OSAL_THREAD_STACK_SIZE, &tid, thread_name); if(RMF_SUCCESS != err) { RDK_LOG(RDK_LOG_ERROR, "LOG.RDK.POD", "cardManager thread creation Failed %s\n", thread_name); } } void CMThread::end () // need to join after this if synchronous { } uint8_t CMThread::running () { return thread_running; }
#include "GeneratedTypes.h" #ifdef PORTAL_JSON #include "jsoncpp/json/json.h" int MemServerRequestJson_addrTrans ( struct PortalInternal *p, const uint32_t sglId, const uint32_t offset ) { Json::Value request; request.append(Json::Value("addrTrans")); request.append((Json::UInt64)sglId); request.append((Json::UInt64)offset); std::string requestjson = Json::FastWriter().write(request);; connectalJsonSend(p, requestjson.c_str(), (int)CHAN_NUM_MemServerRequest_addrTrans); return 0; }; int MemServerRequestJson_setTileState ( struct PortalInternal *p, const TileControl tc ) { Json::Value request; request.append(Json::Value("setTileState")); Json::Value _tcValue; _tcValue["__type__"]="TileControl"; _tcValue["tile"] = (Json::UInt64)tc.tile; _tcValue["state"] = (int)tc.state; request.append(_tcValue); std::string requestjson = Json::FastWriter().write(request);; connectalJsonSend(p, requestjson.c_str(), (int)CHAN_NUM_MemServerRequest_setTileState); return 0; }; int MemServerRequestJson_stateDbg ( struct PortalInternal *p, const ChannelType rc ) { Json::Value request; request.append(Json::Value("stateDbg")); request.append((int)rc); std::string requestjson = Json::FastWriter().write(request);; connectalJsonSend(p, requestjson.c_str(), (int)CHAN_NUM_MemServerRequest_stateDbg); return 0; }; int MemServerRequestJson_memoryTraffic ( struct PortalInternal *p, const ChannelType rc ) { Json::Value request; request.append(Json::Value("memoryTraffic")); request.append((int)rc); std::string requestjson = Json::FastWriter().write(request);; connectalJsonSend(p, requestjson.c_str(), (int)CHAN_NUM_MemServerRequest_memoryTraffic); return 0; }; MemServerRequestCb MemServerRequestJsonProxyReq = { portal_disconnect, MemServerRequestJson_addrTrans, MemServerRequestJson_setTileState, MemServerRequestJson_stateDbg, MemServerRequestJson_memoryTraffic, }; MemServerRequestCb *pMemServerRequestJsonProxyReq = &MemServerRequestJsonProxyReq; const char * MemServerRequestJson_methodSignatures() { return "{\"stateDbg\": [\"long\"], \"addrTrans\": [\"long\", \"long\"], \"memoryTraffic\": [\"long\"], \"setTileState\": [\"long\"]}"; } int MemServerRequestJson_handleMessage(struct PortalInternal *p, unsigned int channel, int messageFd) { static int runaway = 0; int tmp __attribute__ ((unused)); int tmpfd __attribute__ ((unused)); MemServerRequestData tempdata __attribute__ ((unused)); memset(&tempdata, 0, sizeof(tempdata)); Json::Value msg = Json::Value(connectalJsonReceive(p)); switch (channel) { case CHAN_NUM_MemServerRequest_addrTrans: { ((MemServerRequestCb *)p->cb)->addrTrans(p, tempdata.addrTrans.sglId, tempdata.addrTrans.offset); } break; case CHAN_NUM_MemServerRequest_setTileState: { ((MemServerRequestCb *)p->cb)->setTileState(p, tempdata.setTileState.tc); } break; case CHAN_NUM_MemServerRequest_stateDbg: { ((MemServerRequestCb *)p->cb)->stateDbg(p, tempdata.stateDbg.rc); } break; case CHAN_NUM_MemServerRequest_memoryTraffic: { ((MemServerRequestCb *)p->cb)->memoryTraffic(p, tempdata.memoryTraffic.rc); } break; default: PORTAL_PRINTF("MemServerRequestJson_handleMessage: unknown channel 0x%x\n", channel); if (runaway++ > 10) { PORTAL_PRINTF("MemServerRequestJson_handleMessage: too many bogus indications, exiting\n"); #ifndef __KERNEL__ exit(-1); #endif } return 0; } return 0; } #endif /* PORTAL_JSON */
#include "utils/string.hpp" #include "common/test.hpp" using namespace polybar; TEST(String, ends_with) { EXPECT_TRUE(string_util::ends_with("foo", "foo")); EXPECT_TRUE(string_util::ends_with("foobar", "bar")); EXPECT_TRUE(string_util::ends_with("foobar", "")); EXPECT_FALSE(string_util::ends_with("foo", "bar")); EXPECT_FALSE(string_util::ends_with("foo", "Foo")); EXPECT_FALSE(string_util::ends_with("", "Foo")); } TEST(String, upper) { EXPECT_EQ("FOO", string_util::upper("FOO")); EXPECT_EQ("FOO", string_util::upper("FoO")); EXPECT_EQ("FOO", string_util::upper("FOo")); EXPECT_EQ("FOO", string_util::upper("Foo")); } TEST(String, lower) { EXPECT_EQ("bar", string_util::lower("BAR")); } TEST(String, compare) { EXPECT_TRUE(string_util::compare("foo", "foo")); EXPECT_TRUE(string_util::compare("foo", "Foo")); EXPECT_FALSE(string_util::compare("foo", "bar")); } TEST(String, contains) { EXPECT_TRUE(string_util::contains("fooooobar", "foo")); EXPECT_TRUE(string_util::contains("barrrrrrfoo", "foo")); EXPECT_TRUE(string_util::contains("barrfoobazzz", "foo")); EXPECT_TRUE(string_util::contains("foo", "foo")); EXPECT_TRUE(string_util::contains("foobar", "foo")); EXPECT_TRUE(string_util::contains("foobar", "bar")); EXPECT_FALSE(string_util::contains("foo", "Foo")); EXPECT_FALSE(string_util::contains("foo", "bar")); EXPECT_FALSE(string_util::contains("foobar", "baz")); EXPECT_FALSE(string_util::contains("foobAr", "bar")); } TEST(String, contains_ignore_case) { EXPECT_TRUE(string_util::contains_ignore_case("fooooobar", "foo")); EXPECT_TRUE(string_util::contains_ignore_case("barrrrrrfoo", "foo")); EXPECT_TRUE(string_util::contains_ignore_case("barrfoobazzz", "foo")); EXPECT_TRUE(string_util::contains_ignore_case("fooooobar", "fOO")); EXPECT_TRUE(string_util::contains_ignore_case("barrrrrrfoo", "FOo")); EXPECT_TRUE(string_util::contains_ignore_case("barrfoobazzz", "FoO")); EXPECT_TRUE(string_util::contains_ignore_case("foo", "Foo")); EXPECT_FALSE(string_util::contains_ignore_case("foo", "bar")); EXPECT_TRUE(string_util::contains_ignore_case("foo", "")); EXPECT_FALSE(string_util::contains_ignore_case("", "bar")); } TEST(String, replace) { EXPECT_EQ("a.c", string_util::replace("abc", "b", ".")); EXPECT_EQ("a.a", string_util::replace("aaa", "a", ".", 1, 2)); EXPECT_EQ(".aa", string_util::replace("aaa", "a", ".", 0, 2)); EXPECT_EQ("Foo bxr baz", string_util::replace("Foo bar baz", "a", "x")); EXPECT_EQ("foxoobar", string_util::replace("foooobar", "o", "x", 2, 3)); EXPECT_EQ("foooobar", string_util::replace("foooobar", "o", "x", 0, 1)); } TEST(String, replaceAll) { EXPECT_EQ("Foo bxr bxzx", string_util::replace_all("Foo bar baza", "a", "x")); EXPECT_EQ("hoohoohoo", string_util::replace_all("hehehe", "he", "hoo")); EXPECT_EQ("hoohehe", string_util::replace_all("hehehe", "he", "hoo", 0, 2)); EXPECT_EQ("hehehoo", string_util::replace_all("hehehe", "he", "hoo", 4)); EXPECT_EQ("hehehe", string_util::replace_all("hehehe", "he", "hoo", 0, 1)); EXPECT_EQ("113113113", string_util::replace_all("131313", "3", "13")); } TEST(String, squeeze) { EXPECT_EQ("Squeze", string_util::squeeze("Squeeeeeze", 'e')); EXPECT_EQ("bar baz foobar", string_util::squeeze("bar baz foobar", ' ')); } TEST(String, strip) { EXPECT_EQ("Strp", string_util::strip("Striip", 'i')); EXPECT_EQ("test\n", string_util::strip_trailing_newline("test\n\n")); } TEST(String, trim) { EXPECT_EQ("x x", string_util::trim(" x x ")); EXPECT_EQ("testxx", string_util::ltrim("xxtestxx", 'x')); EXPECT_EQ("xxtest", string_util::rtrim("xxtestxx", 'x')); EXPECT_EQ("test", string_util::trim("xxtestxx", 'x')); } TEST(String, trimPredicate) { EXPECT_EQ("x\t x", string_util::trim("\t x\t x ", isspace)); EXPECT_EQ("x\t x", string_util::trim("x\t x ", isspace)); } TEST(String, join) { EXPECT_EQ("A, B, C", string_util::join({"A", "B", "C"}, ", ")); } TEST(String, split) { { vector<string> strings = string_util::split("A,B,C", ','); EXPECT_EQ(3, strings.size()); EXPECT_EQ("A", strings[0]); EXPECT_EQ("B", strings[1]); EXPECT_EQ("C", strings[2]); } { vector<string> strings = string_util::split(",A,,B,,C,", ','); EXPECT_EQ(3, strings.size()); EXPECT_EQ("A", strings[0]); EXPECT_EQ("B", strings[1]); EXPECT_EQ("C", strings[2]); } } TEST(String, tokenize) { { vector<string> strings = string_util::tokenize("A,B,C", ','); EXPECT_EQ(3, strings.size()); EXPECT_EQ("A", strings[0]); EXPECT_EQ("B", strings[1]); EXPECT_EQ("C", strings[2]); } { using namespace std::string_literals; vector<string> strings = string_util::tokenize(",A,,B,,C,", ','); vector<string> result{""s, "A"s, ""s, "B"s, ""s, "C"s, ""s}; EXPECT_TRUE(strings == result); } } TEST(String, findNth) { EXPECT_EQ(0, string_util::find_nth("foobarfoobar", 0, "f", 1)); EXPECT_EQ(6, string_util::find_nth("foobarfoobar", 0, "f", 2)); EXPECT_EQ(7, string_util::find_nth("foobarfoobar", 0, "o", 3)); } TEST(String, hash) { unsigned long hashA1{string_util::hash("foo")}; unsigned long hashA2{string_util::hash("foo")}; unsigned long hashB1{string_util::hash("Foo")}; unsigned long hashB2{string_util::hash("Bar")}; EXPECT_EQ(hashA2, hashA1); EXPECT_NE(hashB1, hashA1); EXPECT_NE(hashB2, hashA1); EXPECT_NE(hashB2, hashB1); } TEST(String, floatingPoint) { EXPECT_EQ("1.26", string_util::floating_point(1.2599, 2)); EXPECT_EQ("2", string_util::floating_point(1.7, 0)); EXPECT_EQ("1.7770000000", string_util::floating_point(1.777, 10)); } TEST(String, filesize) { EXPECT_EQ("3.000 MiB", string_util::filesize_mib(3 * 1024, 3)); EXPECT_EQ("3.195 MiB", string_util::filesize_mib(3 * 1024 + 200, 3)); EXPECT_EQ("3 MiB", string_util::filesize_mib(3 * 1024 + 400)); EXPECT_EQ("4 MiB", string_util::filesize_mib(3 * 1024 + 800)); EXPECT_EQ("3.195 GiB", string_util::filesize_gib(3 * 1024 * 1024 + 200 * 1024, 3)); EXPECT_EQ("3 GiB", string_util::filesize_gib(3 * 1024 * 1024 + 400 * 1024)); EXPECT_EQ("4 GiB", string_util::filesize_gib(3 * 1024 * 1024 + 800 * 1024)); EXPECT_EQ("3 B", string_util::filesize(3)); EXPECT_EQ("3 KB", string_util::filesize(3 * 1024)); EXPECT_EQ("3 MB", string_util::filesize(3 * 1024 * 1024)); EXPECT_EQ("3 GB", string_util::filesize((unsigned long long)3 * 1024 * 1024 * 1024)); EXPECT_EQ("3 TB", string_util::filesize((unsigned long long)3 * 1024 * 1024 * 1024 * 1024)); }
/* * Copyright (c) 2015 Andrew Kelley * * This file is part of zig, which is MIT licensed. * See http://opensource.org/licenses/MIT */ #include "parser.hpp" #include "errmsg.hpp" #include "analyze.hpp" #include <stdarg.h> #include <stdio.h> #include <limits.h> #include <errno.h> struct ParseContext { Buf *buf; // Shortcut to `owner->data.structure.root_struct->token_ids`. TokenId *token_ids; // Shortcut to `owner->data.structure.root_struct->token_locs`. TokenLoc *token_locs; ZigType *owner; TokenIndex current_token; ErrColor err_color; // Shortcut to `owner->data.structure.root_struct->token_count`. uint32_t token_count; }; struct PtrPayload { TokenIndex asterisk; TokenIndex payload; }; struct PtrIndexPayload { TokenIndex asterisk; TokenIndex payload; TokenIndex index; }; static AstNode *ast_parse_root(ParseContext *pc); static AstNodeContainerDecl ast_parse_container_members(ParseContext *pc); static AstNode *ast_parse_test_decl(ParseContext *pc); static AstNode *ast_parse_top_level_comptime(ParseContext *pc); static AstNode *ast_parse_top_level_decl(ParseContext *pc, VisibMod visib_mod, TokenIndex doc_comments); static AstNode *ast_parse_fn_proto(ParseContext *pc); static AstNode *ast_parse_var_decl(ParseContext *pc); static AstNode *ast_parse_container_field(ParseContext *pc); static AstNode *ast_parse_statement(ParseContext *pc); static AstNode *ast_parse_if_statement(ParseContext *pc); static AstNode *ast_parse_labeled_statement(ParseContext *pc); static AstNode *ast_parse_loop_statement(ParseContext *pc); static AstNode *ast_parse_for_statement(ParseContext *pc); static AstNode *ast_parse_while_statement(ParseContext *pc); static AstNode *ast_parse_block_expr_statement(ParseContext *pc); static AstNode *ast_parse_block_expr(ParseContext *pc); static AstNode *ast_parse_assign_expr(ParseContext *pc); static AstNode *ast_parse_expr(ParseContext *pc); static AstNode *ast_parse_bool_or_expr(ParseContext *pc); static AstNode *ast_parse_bool_and_expr(ParseContext *pc); static AstNode *ast_parse_compare_expr(ParseContext *pc); static AstNode *ast_parse_bitwise_expr(ParseContext *pc); static AstNode *ast_parse_bit_shift_expr(ParseContext *pc); static AstNode *ast_parse_addition_expr(ParseContext *pc); static AstNode *ast_parse_multiply_expr(ParseContext *pc); static AstNode *ast_parse_prefix_expr(ParseContext *pc); static AstNode *ast_parse_primary_expr(ParseContext *pc); static AstNode *ast_parse_if_expr(ParseContext *pc); static AstNode *ast_parse_block(ParseContext *pc); static AstNode *ast_parse_loop_expr(ParseContext *pc); static AstNode *ast_parse_for_expr(ParseContext *pc); static AstNode *ast_parse_while_expr(ParseContext *pc); static AstNode *ast_parse_curly_suffix_expr(ParseContext *pc); static AstNode *ast_parse_init_list(ParseContext *pc); static AstNode *ast_parse_type_expr(ParseContext *pc); static AstNode *ast_parse_error_union_expr(ParseContext *pc); static AstNode *ast_parse_suffix_expr(ParseContext *pc); static AstNode *ast_parse_primary_type_expr(ParseContext *pc); static AstNode *ast_parse_container_decl(ParseContext *pc); static AstNode *ast_parse_error_set_decl(ParseContext *pc); static AstNode *ast_parse_grouped_expr(ParseContext *pc); static AstNode *ast_parse_if_type_expr(ParseContext *pc); static AstNode *ast_parse_labeled_type_expr(ParseContext *pc); static AstNode *ast_parse_loop_type_expr(ParseContext *pc); static AstNode *ast_parse_for_type_expr(ParseContext *pc); static AstNode *ast_parse_while_type_expr(ParseContext *pc); static AstNode *ast_parse_switch_expr(ParseContext *pc); static AstNode *ast_parse_asm_expr(ParseContext *pc); static AstNode *ast_parse_anon_lit(ParseContext *pc); static AstNode *ast_parse_asm_output(ParseContext *pc); static AsmOutput *ast_parse_asm_output_item(ParseContext *pc); static AstNode *ast_parse_asm_input(ParseContext *pc); static AsmInput *ast_parse_asm_input_item(ParseContext *pc); static AstNode *ast_parse_asm_clobbers(ParseContext *pc); static TokenIndex ast_parse_break_label(ParseContext *pc); static TokenIndex ast_parse_block_label(ParseContext *pc); static AstNode *ast_parse_field_init(ParseContext *pc); static AstNode *ast_parse_while_continue_expr(ParseContext *pc); static AstNode *ast_parse_link_section(ParseContext *pc); static AstNode *ast_parse_callconv(ParseContext *pc); static AstNode *ast_parse_param_decl(ParseContext *pc); static AstNode *ast_parse_param_type(ParseContext *pc); static AstNode *ast_parse_if_prefix(ParseContext *pc); static AstNode *ast_parse_while_prefix(ParseContext *pc); static AstNode *ast_parse_for_prefix(ParseContext *pc); static TokenIndex ast_parse_payload(ParseContext *pc); static Optional<PtrPayload> ast_parse_ptr_payload(ParseContext *pc); static Optional<PtrIndexPayload> ast_parse_ptr_index_payload(ParseContext *pc); static AstNode *ast_parse_switch_prong(ParseContext *pc); static AstNode *ast_parse_switch_case(ParseContext *pc); static AstNode *ast_parse_switch_item(ParseContext *pc); static AstNode *ast_parse_assign_op(ParseContext *pc); static AstNode *ast_parse_compare_op(ParseContext *pc); static AstNode *ast_parse_bitwise_op(ParseContext *pc); static AstNode *ast_parse_bit_shift_op(ParseContext *pc); static AstNode *ast_parse_addition_op(ParseContext *pc); static AstNode *ast_parse_multiply_op(ParseContext *pc); static AstNode *ast_parse_prefix_op(ParseContext *pc); static AstNode *ast_parse_prefix_type_op(ParseContext *pc); static AstNode *ast_parse_suffix_op(ParseContext *pc); static AstNode *ast_parse_fn_call_arguments(ParseContext *pc); static AstNode *ast_parse_array_type_start(ParseContext *pc); static AstNode *ast_parse_ptr_type_start(ParseContext *pc); static AstNode *ast_parse_container_decl_auto(ParseContext *pc); static AstNode *ast_parse_container_decl_type(ParseContext *pc); static AstNode *ast_parse_byte_align(ParseContext *pc); ATTRIBUTE_NORETURN static void ast_error_offset(RootStruct *root_struct, ErrColor err_color, TokenIndex token, size_t bad_index, Buf *msg) { assert(token < root_struct->token_count); uint32_t byte_offset = root_struct->token_locs[token].offset; ErrorMsg *err = err_msg_create_with_offset(root_struct->path, byte_offset + bad_index, buf_ptr(root_struct->source_code), msg); print_err_msg(err, err_color); exit(EXIT_FAILURE); } ATTRIBUTE_PRINTF(3, 4) ATTRIBUTE_NORETURN static void ast_error(ParseContext *pc, TokenIndex token, const char *format, ...) { va_list ap; va_start(ap, format); Buf *msg = buf_vprintf(format, ap); va_end(ap); RootStruct *root_struct = pc->owner->data.structure.root_struct; ast_error_offset(root_struct, pc->err_color, token, 0, msg); } ATTRIBUTE_NORETURN static void ast_invalid_token_error(ParseContext *pc, TokenIndex token) { ast_error(pc, token, "invalid token: '%s'", token_name(pc->token_ids[token])); } static AstNode *ast_create_node_no_line_info(ParseContext *pc, NodeType type) { AstNode *node = heap::c_allocator.create<AstNode>(); node->type = type; node->owner = pc->owner; return node; } static AstNode *ast_create_node(ParseContext *pc, NodeType type, TokenIndex first_token) { assert(first_token); AstNode *node = ast_create_node_no_line_info(pc, type); node->main_token = first_token; return node; } static AstNode *ast_create_node_copy_line_info(ParseContext *pc, NodeType type, AstNode *from) { assert(from); AstNode *node = ast_create_node_no_line_info(pc, type); node->main_token = from->main_token; return node; } static TokenIndex peek_token(ParseContext *pc) { return pc->current_token; } static TokenIndex eat_token(ParseContext *pc) { TokenIndex res = peek_token(pc); pc->current_token += 1; return res; } static TokenIndex eat_token_if(ParseContext *pc, TokenId id) { TokenIndex res = peek_token(pc); if (pc->token_ids[res] == id) { return eat_token(pc); } return 0; } static TokenIndex expect_token(ParseContext *pc, TokenId id) { TokenIndex res = eat_token(pc); TokenId actual_id = pc->token_ids[res]; if (actual_id != id) ast_error(pc, res, "expected token '%s', found '%s'", token_name(id), token_name(actual_id)); return res; } static void put_back_token(ParseContext *pc) { pc->current_token -= 1; } static Buf *token_buf(ParseContext *pc, TokenIndex token) { Error err; if (token == 0) return nullptr; RootStruct *root_struct = pc->owner->data.structure.root_struct; if (root_struct->token_ids[token] == TokenIdIdentifier) { return token_identifier_buf(root_struct, token); } else if (root_struct->token_ids[token] == TokenIdStringLiteral) { assert(root_struct->token_ids[token] == TokenIdStringLiteral); const char *source = buf_ptr(root_struct->source_code); size_t byte_offset = root_struct->token_locs[token].offset; size_t bad_index; Buf *str = buf_alloc(); if ((err = source_string_literal_buf(source + byte_offset, str, &bad_index))) { ast_error_offset(root_struct, pc->err_color, token, bad_index, buf_create_from_str("invalid string literal character")); } return str; } else { zig_unreachable(); } } static AstNode *token_identifier(ParseContext *pc, TokenIndex token) { assert(pc->token_ids[token] == TokenIdIdentifier); return ast_create_node(pc, NodeTypeIdentifier, token); } // (Rule SEP)* Rule? template<typename T> static ZigList<T *> ast_parse_list(ParseContext *pc, TokenId sep, T *(*parser)(ParseContext*)) { ZigList<T *> res = {}; while (true) { T *curr = parser(pc); if (curr == nullptr) break; res.append(curr); if (eat_token_if(pc, sep) == 0) break; } return res; } static AstNode *ast_expect(ParseContext *pc, AstNode *(*parser)(ParseContext*)) { AstNode *res = parser(pc); if (res == nullptr) ast_invalid_token_error(pc, peek_token(pc)); return res; } enum BinOpChain { BinOpChainOnce, BinOpChainInf, }; // Op* Child static AstNode *ast_parse_prefix_op_expr( ParseContext *pc, AstNode *(*op_parser)(ParseContext *), AstNode *(*child_parser)(ParseContext *) ) { AstNode *res = nullptr; AstNode **right = &res; while (true) { AstNode *prefix = op_parser(pc); if (prefix == nullptr) break; *right = prefix; switch (prefix->type) { case NodeTypePrefixOpExpr: right = &prefix->data.prefix_op_expr.primary_expr; break; case NodeTypeReturnExpr: right = &prefix->data.return_expr.expr; break; case NodeTypeAwaitExpr: right = &prefix->data.await_expr.expr; break; case NodeTypeAnyFrameType: right = &prefix->data.anyframe_type.payload_type; break; case NodeTypeArrayType: right = &prefix->data.array_type.child_type; break; case NodeTypeInferredArrayType: right = &prefix->data.inferred_array_type.child_type; break; case NodeTypePointerType: { // We might get two pointers from *_ptr_type_start AstNode *child = prefix->data.pointer_type.op_expr; if (child == nullptr) child = prefix; right = &child->data.pointer_type.op_expr; break; } default: zig_unreachable(); } } // If we have already consumed a token, and determined that // this node is a prefix op, then we expect that the node has // a child. if (res != nullptr) { *right = ast_expect(pc, child_parser); } else { // Otherwise, if we didn't consume a token, then we can return // null, if the child expr did. *right = child_parser(pc); if (*right == nullptr) return nullptr; } return res; } // Child (Op Child)(*/?) static AstNode *ast_parse_bin_op_expr( ParseContext *pc, BinOpChain chain, AstNode *(*op_parse)(ParseContext*), AstNode *(*child_parse)(ParseContext*) ) { AstNode *res = child_parse(pc); if (res == nullptr) return nullptr; do { AstNode *op = op_parse(pc); if (op == nullptr) break; AstNode *left = res; AstNode *right = ast_expect(pc, child_parse); res = op; switch (op->type) { case NodeTypeBinOpExpr: op->data.bin_op_expr.op1 = left; op->data.bin_op_expr.op2 = right; break; case NodeTypeCatchExpr: op->data.unwrap_err_expr.op1 = left; op->data.unwrap_err_expr.op2 = right; break; default: zig_unreachable(); } } while (chain == BinOpChainInf); return res; } // IfPrefix Body (KEYWORD_else Payload? Body)? static AstNode *ast_parse_if_expr_helper(ParseContext *pc, AstNode *(*body_parser)(ParseContext*)) { AstNode *res = ast_parse_if_prefix(pc); if (res == nullptr) return nullptr; AstNode *body = ast_expect(pc, body_parser); TokenIndex err_payload = 0; AstNode *else_body = nullptr; if (eat_token_if(pc, TokenIdKeywordElse) != 0) { err_payload = ast_parse_payload(pc); else_body = ast_expect(pc, body_parser); } assert(res->type == NodeTypeIfOptional); if (err_payload != 0) { AstNodeTestExpr old = res->data.test_expr; res->type = NodeTypeIfErrorExpr; res->data.if_err_expr.target_node = old.target_node; res->data.if_err_expr.var_is_ptr = old.var_is_ptr; res->data.if_err_expr.var_symbol = old.var_symbol; res->data.if_err_expr.then_node = body; res->data.if_err_expr.err_symbol = token_buf(pc, err_payload); res->data.if_err_expr.else_node = else_body; return res; } if (res->data.test_expr.var_symbol != nullptr) { res->data.test_expr.then_node = body; res->data.test_expr.else_node = else_body; return res; } AstNodeTestExpr old = res->data.test_expr; res->type = NodeTypeIfBoolExpr; res->data.if_bool_expr.condition = old.target_node; res->data.if_bool_expr.then_block = body; res->data.if_bool_expr.else_node = else_body; return res; } // KEYWORD_inline? (ForLoop / WhileLoop) static AstNode *ast_parse_loop_expr_helper( ParseContext *pc, AstNode *(*for_parser)(ParseContext *), AstNode *(*while_parser)(ParseContext *) ) { TokenIndex inline_token = eat_token_if(pc, TokenIdKeywordInline); AstNode *for_expr = for_parser(pc); if (for_expr != nullptr) { assert(for_expr->type == NodeTypeForExpr); for_expr->data.for_expr.is_inline = inline_token != 0; return for_expr; } AstNode *while_expr = while_parser(pc); if (while_expr != nullptr) { assert(while_expr->type == NodeTypeWhileExpr); while_expr->data.while_expr.is_inline = inline_token != 0; return while_expr; } if (inline_token != 0) ast_invalid_token_error(pc, peek_token(pc)); return nullptr; } // ForPrefix Body (KEYWORD_else Body)? static AstNode *ast_parse_for_expr_helper(ParseContext *pc, AstNode *(*body_parser)(ParseContext*)) { AstNode *res = ast_parse_for_prefix(pc); if (res == nullptr) return nullptr; AstNode *body = ast_expect(pc, body_parser); AstNode *else_body = nullptr; if (eat_token_if(pc, TokenIdKeywordElse) != 0) else_body = ast_expect(pc, body_parser); assert(res->type == NodeTypeForExpr); res->data.for_expr.body = body; res->data.for_expr.else_node = else_body; return res; } // WhilePrefix Body (KEYWORD_else Payload? Body)? static AstNode *ast_parse_while_expr_helper(ParseContext *pc, AstNode *(*body_parser)(ParseContext*)) { AstNode *res = ast_parse_while_prefix(pc); if (res == nullptr) return nullptr; AstNode *body = ast_expect(pc, body_parser); TokenIndex err_payload = 0; AstNode *else_body = nullptr; if (eat_token_if(pc, TokenIdKeywordElse) != 0) { err_payload = ast_parse_payload(pc); else_body = ast_expect(pc, body_parser); } assert(res->type == NodeTypeWhileExpr); res->data.while_expr.body = body; res->data.while_expr.err_symbol = token_buf(pc, err_payload); res->data.while_expr.else_node = else_body; return res; } template<TokenId id, BinOpType op> AstNode *ast_parse_bin_op_simple(ParseContext *pc) { TokenIndex op_token = eat_token_if(pc, id); if (op_token == 0) return nullptr; AstNode *res = ast_create_node(pc, NodeTypeBinOpExpr, op_token); res->data.bin_op_expr.bin_op = op; return res; } AstNode *ast_parse(Buf *buf, ZigType *owner, ErrColor err_color) { RootStruct *root_struct = owner->data.structure.root_struct; ParseContext pc = {}; pc.err_color = err_color; pc.owner = owner; pc.buf = buf; pc.token_ids = root_struct->token_ids; pc.token_locs = root_struct->token_locs; pc.token_count = root_struct->token_count; pc.current_token = 1; // Skip over the first (invalid) token. return ast_parse_root(&pc); } // Root <- skip ContainerMembers eof static AstNode *ast_parse_root(ParseContext *pc) { TokenIndex first = peek_token(pc); AstNodeContainerDecl members = ast_parse_container_members(pc); if (pc->current_token != pc->token_count - 1) ast_invalid_token_error(pc, peek_token(pc)); AstNode *node = ast_create_node(pc, NodeTypeContainerDecl, first); node->data.container_decl.fields = members.fields; node->data.container_decl.decls = members.decls; node->data.container_decl.layout = ContainerLayoutAuto; node->data.container_decl.kind = ContainerKindStruct; node->data.container_decl.is_root = true; node->data.container_decl.doc_comments = members.doc_comments; return node; } static TokenIndex ast_parse_multi_tok(ParseContext *pc, TokenId token_id) { TokenIndex first_token = eat_token_if(pc, token_id); TokenIndex token = first_token; while (token != 0) { token = eat_token_if(pc, token_id); } return first_token; } static TokenIndex ast_parse_doc_comments(ParseContext *pc) { return ast_parse_multi_tok(pc, TokenIdDocComment); } static TokenIndex ast_parse_container_doc_comments(ParseContext *pc) { return ast_parse_multi_tok(pc, TokenIdContainerDocComment); } enum ContainerFieldState { // no fields have been seen ContainerFieldStateNone, // currently parsing fields ContainerFieldStateSeen, // saw fields and then a declaration after them ContainerFieldStateEnd, }; // ContainerMembers // <- TestDecl ContainerMembers // / TopLevelComptime ContainerMembers // / KEYWORD_pub? TopLevelDecl ContainerMembers // / ContainerField COMMA ContainerMembers // / ContainerField // / static AstNodeContainerDecl ast_parse_container_members(ParseContext *pc) { AstNodeContainerDecl res = {}; ContainerFieldState field_state = ContainerFieldStateNone; TokenIndex first_token = 0; res.doc_comments = ast_parse_container_doc_comments(pc); for (;;) { TokenIndex peeked_token = peek_token(pc); AstNode *test_decl = ast_parse_test_decl(pc); if (test_decl != nullptr) { if (field_state == ContainerFieldStateSeen) { field_state = ContainerFieldStateEnd; first_token = peeked_token; } res.decls.append(test_decl); continue; } AstNode *top_level_comptime = ast_parse_top_level_comptime(pc); if (top_level_comptime != nullptr) { if (field_state == ContainerFieldStateSeen) { field_state = ContainerFieldStateEnd; first_token = peeked_token; } res.decls.append(top_level_comptime); continue; } TokenIndex first_doc_token = ast_parse_doc_comments(pc); peeked_token = peek_token(pc); TokenIndex visib_token = eat_token_if(pc, TokenIdKeywordPub); VisibMod visib_mod = (visib_token != 0) ? VisibModPub : VisibModPrivate; AstNode *top_level_decl = ast_parse_top_level_decl(pc, visib_mod, first_doc_token); if (top_level_decl != nullptr) { if (field_state == ContainerFieldStateSeen) { field_state = ContainerFieldStateEnd; first_token = peeked_token; } res.decls.append(top_level_decl); continue; } if (visib_token != 0) { ast_error(pc, peek_token(pc), "expected function or variable declaration after pub"); } TokenIndex comptime_token = eat_token_if(pc, TokenIdKeywordCompTime); AstNode *container_field = ast_parse_container_field(pc); if (container_field != nullptr) { switch (field_state) { case ContainerFieldStateNone: field_state = ContainerFieldStateSeen; break; case ContainerFieldStateSeen: break; case ContainerFieldStateEnd: ast_error(pc, first_token, "declarations are not allowed between container fields"); } assert(container_field->type == NodeTypeStructField); container_field->data.struct_field.doc_comments = first_doc_token; container_field->data.struct_field.comptime_token = comptime_token; res.fields.append(container_field); if (eat_token_if(pc, TokenIdComma) != 0) { continue; } else { break; } } break; } return res; } // TestDecl <- KEYWORD_test STRINGLITERALSINGLE? Block static AstNode *ast_parse_test_decl(ParseContext *pc) { TokenIndex test = eat_token_if(pc, TokenIdKeywordTest); if (test == 0) return nullptr; TokenIndex name = eat_token_if(pc, TokenIdStringLiteral); AstNode *block = ast_expect(pc, ast_parse_block); AstNode *res = ast_create_node(pc, NodeTypeTestDecl, test); res->data.test_decl.name = name ? token_buf(pc, name) : nullptr; res->data.test_decl.body = block; return res; } // TopLevelComptime <- KEYWORD_comptime BlockExpr static AstNode *ast_parse_top_level_comptime(ParseContext *pc) { TokenIndex comptime = eat_token_if(pc, TokenIdKeywordCompTime); if (comptime == 0) return nullptr; // 1 token lookahead because it could be a comptime struct field TokenIndex lbrace = peek_token(pc); if (pc->token_ids[lbrace] != TokenIdLBrace) { put_back_token(pc); return nullptr; } AstNode *block = ast_expect(pc, ast_parse_block_expr); AstNode *res = ast_create_node(pc, NodeTypeCompTime, comptime); res->data.comptime_expr.expr = block; return res; } // TopLevelDecl // <- (KEYWORD_export / KEYWORD_extern STRINGLITERALSINGLE? / (KEYWORD_inline / KEYWORD_noinline))? FnProto (SEMICOLON / Block) // / (KEYWORD_export / KEYWORD_extern STRINGLITERALSINGLE?)? KEYWORD_threadlocal? VarDecl // / KEYWORD_use Expr SEMICOLON static AstNode *ast_parse_top_level_decl(ParseContext *pc, VisibMod visib_mod, TokenIndex doc_comments) { TokenIndex first = eat_token_if(pc, TokenIdKeywordExport); if (first == 0) first = eat_token_if(pc, TokenIdKeywordExtern); if (first == 0) first = eat_token_if(pc, TokenIdKeywordInline); if (first == 0) first = eat_token_if(pc, TokenIdKeywordNoInline); if (first != 0) { TokenIndex lib_name = 0; if (pc->token_ids[first] == TokenIdKeywordExtern) lib_name = eat_token_if(pc, TokenIdStringLiteral); if (pc->token_ids[first] != TokenIdKeywordNoInline && pc->token_ids[first] != TokenIdKeywordInline) { TokenIndex thread_local_kw = eat_token_if(pc, TokenIdKeywordThreadLocal); AstNode *var_decl = ast_parse_var_decl(pc); if (var_decl != nullptr) { assert(var_decl->type == NodeTypeVariableDeclaration); if (pc->token_ids[first] == TokenIdKeywordExtern && var_decl->data.variable_declaration.expr != nullptr) { ast_error(pc, first, "extern variables have no initializers"); } var_decl->main_token = first; var_decl->data.variable_declaration.threadlocal_tok = thread_local_kw; var_decl->data.variable_declaration.visib_mod = visib_mod; var_decl->data.variable_declaration.doc_comments = doc_comments; var_decl->data.variable_declaration.is_extern = pc->token_ids[first] == TokenIdKeywordExtern; var_decl->data.variable_declaration.is_export = pc->token_ids[first] == TokenIdKeywordExport; var_decl->data.variable_declaration.lib_name = token_buf(pc, lib_name); return var_decl; } if (thread_local_kw != 0) put_back_token(pc); } AstNode *fn_proto = ast_parse_fn_proto(pc); if (fn_proto != nullptr) { AstNode *body = ast_parse_block(pc); if (body == nullptr) expect_token(pc, TokenIdSemicolon); assert(fn_proto->type == NodeTypeFnProto); fn_proto->main_token = first; fn_proto->data.fn_proto.visib_mod = visib_mod; fn_proto->data.fn_proto.doc_comments = doc_comments; if (!fn_proto->data.fn_proto.is_extern) fn_proto->data.fn_proto.is_extern = pc->token_ids[first] == TokenIdKeywordExtern; fn_proto->data.fn_proto.is_export = pc->token_ids[first] == TokenIdKeywordExport; switch (pc->token_ids[first]) { case TokenIdKeywordInline: fn_proto->data.fn_proto.fn_inline = FnInlineAlways; break; case TokenIdKeywordNoInline: fn_proto->data.fn_proto.fn_inline = FnInlineNever; break; default: fn_proto->data.fn_proto.fn_inline = FnInlineAuto; break; } fn_proto->data.fn_proto.lib_name = token_buf(pc, lib_name); AstNode *res = fn_proto; if (body != nullptr) { if (fn_proto->data.fn_proto.is_extern) { ast_error(pc, first, "extern functions have no body"); } res = ast_create_node_copy_line_info(pc, NodeTypeFnDef, fn_proto); res->data.fn_def.fn_proto = fn_proto; res->data.fn_def.body = body; fn_proto->data.fn_proto.fn_def_node = res; } return res; } ast_invalid_token_error(pc, peek_token(pc)); } TokenIndex thread_local_kw = eat_token_if(pc, TokenIdKeywordThreadLocal); AstNode *var_decl = ast_parse_var_decl(pc); if (var_decl != nullptr) { assert(var_decl->type == NodeTypeVariableDeclaration); var_decl->data.variable_declaration.visib_mod = visib_mod; var_decl->data.variable_declaration.doc_comments = doc_comments; var_decl->data.variable_declaration.threadlocal_tok = thread_local_kw; return var_decl; } if (thread_local_kw != 0) put_back_token(pc); AstNode *fn_proto = ast_parse_fn_proto(pc); if (fn_proto != nullptr) { AstNode *body = ast_parse_block(pc); if (body == nullptr) expect_token(pc, TokenIdSemicolon); assert(fn_proto->type == NodeTypeFnProto); fn_proto->data.fn_proto.visib_mod = visib_mod; fn_proto->data.fn_proto.doc_comments = doc_comments; AstNode *res = fn_proto; if (body != nullptr) { res = ast_create_node_copy_line_info(pc, NodeTypeFnDef, fn_proto); res->data.fn_def.fn_proto = fn_proto; res->data.fn_def.body = body; fn_proto->data.fn_proto.fn_def_node = res; } return res; } TokenIndex usingnamespace = eat_token_if(pc, TokenIdKeywordUsingNamespace); if (usingnamespace != 0) { AstNode *expr = ast_expect(pc, ast_parse_expr); expect_token(pc, TokenIdSemicolon); AstNode *res = ast_create_node(pc, NodeTypeUsingNamespace, usingnamespace); res->data.using_namespace.visib_mod = visib_mod; res->data.using_namespace.expr = expr; return res; } return nullptr; } // FnProto <- KEYWORD_fn IDENTIFIER? LPAREN ParamDeclList RPAREN ByteAlign? LinkSection? EXCLAMATIONMARK? (KEYWORD_anytype / TypeExpr) static AstNode *ast_parse_fn_proto(ParseContext *pc) { TokenIndex first = eat_token_if(pc, TokenIdKeywordFn); if (first == 0) { return nullptr; } TokenIndex identifier = eat_token_if(pc, TokenIdIdentifier); expect_token(pc, TokenIdLParen); ZigList<AstNode *> params = ast_parse_list(pc, TokenIdComma, ast_parse_param_decl); expect_token(pc, TokenIdRParen); AstNode *align_expr = ast_parse_byte_align(pc); AstNode *section_expr = ast_parse_link_section(pc); AstNode *callconv_expr = ast_parse_callconv(pc); TokenIndex exmark = 0; AstNode *return_type = nullptr; exmark = eat_token_if(pc, TokenIdBang); return_type = ast_parse_type_expr(pc); if (return_type == nullptr) { TokenIndex next = peek_token(pc); ast_error( pc, next, "expected return type (use 'void' to return nothing), found: '%s'", token_name(pc->token_ids[next]) ); } AstNode *res = ast_create_node(pc, NodeTypeFnProto, first); res->data.fn_proto = {}; res->data.fn_proto.name = token_buf(pc, identifier); res->data.fn_proto.params = params; res->data.fn_proto.align_expr = align_expr; res->data.fn_proto.section_expr = section_expr; res->data.fn_proto.callconv_expr = callconv_expr; res->data.fn_proto.auto_err_set = exmark != 0; res->data.fn_proto.return_type = return_type; for (size_t i = 0; i < params.length; i++) { AstNode *param_decl = params.at(i); assert(param_decl->type == NodeTypeParamDecl); if (param_decl->data.param_decl.is_var_args) res->data.fn_proto.is_var_args = true; if (i != params.length - 1 && res->data.fn_proto.is_var_args) ast_error(pc, first, "Function prototype have varargs as a none last parameter."); } return res; } // VarDecl <- (KEYWORD_const / KEYWORD_var) IDENTIFIER (COLON TypeExpr)? ByteAlign? LinkSection? (EQUAL Expr)? SEMICOLON static AstNode *ast_parse_var_decl(ParseContext *pc) { TokenIndex mut_kw = eat_token_if(pc, TokenIdKeywordConst); if (mut_kw == 0) mut_kw = eat_token_if(pc, TokenIdKeywordVar); if (mut_kw == 0) return nullptr; TokenIndex identifier = expect_token(pc, TokenIdIdentifier); AstNode *type_expr = nullptr; if (eat_token_if(pc, TokenIdColon) != 0) type_expr = ast_expect(pc, ast_parse_type_expr); AstNode *align_expr = ast_parse_byte_align(pc); AstNode *section_expr = ast_parse_link_section(pc); AstNode *expr = nullptr; if (eat_token_if(pc, TokenIdEq) != 0) expr = ast_expect(pc, ast_parse_expr); expect_token(pc, TokenIdSemicolon); AstNode *res = ast_create_node(pc, NodeTypeVariableDeclaration, mut_kw); res->data.variable_declaration.is_const = pc->token_ids[mut_kw] == TokenIdKeywordConst; res->data.variable_declaration.symbol = token_buf(pc, identifier); res->data.variable_declaration.type = type_expr; res->data.variable_declaration.align_expr = align_expr; res->data.variable_declaration.section_expr = section_expr; res->data.variable_declaration.expr = expr; return res; } // ContainerField <- KEYWORD_comptime? IDENTIFIER (COLON TypeExpr ByteAlign?)? (EQUAL Expr)? static AstNode *ast_parse_container_field(ParseContext *pc) { TokenIndex identifier = eat_token_if(pc, TokenIdIdentifier); if (identifier == 0) return nullptr; AstNode *type_expr = nullptr; if (eat_token_if(pc, TokenIdColon) != 0) { TokenIndex anytype_tok = eat_token_if(pc, TokenIdKeywordAnyType); if (anytype_tok != 0) { type_expr = ast_create_node(pc, NodeTypeAnyTypeField, anytype_tok); } else { type_expr = ast_expect(pc, ast_parse_type_expr); } } AstNode *align_expr = ast_parse_byte_align(pc); AstNode *expr = nullptr; if (eat_token_if(pc, TokenIdEq) != 0) expr = ast_expect(pc, ast_parse_expr); AstNode *res = ast_create_node(pc, NodeTypeStructField, identifier); res->data.struct_field.name = token_buf(pc, identifier); res->data.struct_field.type = type_expr; res->data.struct_field.value = expr; res->data.struct_field.align_expr = align_expr; return res; } // Statement // <- KEYWORD_comptime? VarDecl // / KEYWORD_comptime BlockExprStatement // / KEYWORD_nosuspend BlockExprStatement // / KEYWORD_suspend (SEMICOLON / BlockExprStatement) // / KEYWORD_defer BlockExprStatement // / KEYWORD_errdefer Payload? BlockExprStatement // / IfStatement // / LabeledStatement // / SwitchExpr // / AssignExpr SEMICOLON static AstNode *ast_parse_statement(ParseContext *pc) { TokenIndex comptime = eat_token_if(pc, TokenIdKeywordCompTime); AstNode *var_decl = ast_parse_var_decl(pc); if (var_decl != nullptr) { assert(var_decl->type == NodeTypeVariableDeclaration); var_decl->data.variable_declaration.is_comptime = comptime != 0; return var_decl; } if (comptime != 0) { AstNode *statement = ast_expect(pc, ast_parse_block_expr_statement); AstNode *res = ast_create_node(pc, NodeTypeCompTime, comptime); res->data.comptime_expr.expr = statement; return res; } TokenIndex nosuspend = eat_token_if(pc, TokenIdKeywordNoSuspend); if (nosuspend != 0) { AstNode *statement = ast_expect(pc, ast_parse_block_expr_statement); AstNode *res = ast_create_node(pc, NodeTypeNoSuspend, nosuspend); res->data.nosuspend_expr.expr = statement; return res; } TokenIndex suspend = eat_token_if(pc, TokenIdKeywordSuspend); if (suspend != 0) { AstNode *statement = ast_expect(pc, ast_parse_block_expr_statement); AstNode *res = ast_create_node(pc, NodeTypeSuspend, suspend); res->data.suspend.block = statement; return res; } TokenIndex defer = eat_token_if(pc, TokenIdKeywordDefer); if (defer == 0) defer = eat_token_if(pc, TokenIdKeywordErrdefer); if (defer != 0) { TokenIndex payload = (pc->token_ids[defer] == TokenIdKeywordErrdefer) ? ast_parse_payload(pc) : 0; AstNode *statement = ast_expect(pc, ast_parse_block_expr_statement); AstNode *res = ast_create_node(pc, NodeTypeDefer, defer); res->data.defer.kind = ReturnKindUnconditional; res->data.defer.expr = statement; if (pc->token_ids[defer] == TokenIdKeywordErrdefer) { res->data.defer.kind = ReturnKindError; if (payload != 0) res->data.defer.err_payload = token_identifier(pc, payload); } return res; } AstNode *if_statement = ast_parse_if_statement(pc); if (if_statement != nullptr) return if_statement; AstNode *labeled_statement = ast_parse_labeled_statement(pc); if (labeled_statement != nullptr) return labeled_statement; AstNode *switch_expr = ast_parse_switch_expr(pc); if (switch_expr != nullptr) return switch_expr; AstNode *assign = ast_parse_assign_expr(pc); if (assign != nullptr) { expect_token(pc, TokenIdSemicolon); return assign; } return nullptr; } // IfStatement // <- IfPrefix BlockExpr ( KEYWORD_else Payload? Statement )? // / IfPrefix AssignExpr ( SEMICOLON / KEYWORD_else Payload? Statement ) static AstNode *ast_parse_if_statement(ParseContext *pc) { AstNode *res = ast_parse_if_prefix(pc); if (res == nullptr) return nullptr; AstNode *body = ast_parse_block_expr(pc); bool requires_semi = false; if (body == nullptr) { requires_semi = true; body = ast_parse_assign_expr(pc); } if (body == nullptr) { TokenIndex tok = eat_token(pc); ast_error(pc, tok, "expected if body, found '%s'", token_name(pc->token_ids[tok])); } TokenIndex err_payload = 0; AstNode *else_body = nullptr; if (eat_token_if(pc, TokenIdKeywordElse) != 0) { err_payload = ast_parse_payload(pc); else_body = ast_expect(pc, ast_parse_statement); } if (requires_semi && else_body == nullptr) expect_token(pc, TokenIdSemicolon); assert(res->type == NodeTypeIfOptional); if (err_payload != 0) { AstNodeTestExpr old = res->data.test_expr; res->type = NodeTypeIfErrorExpr; res->data.if_err_expr.target_node = old.target_node; res->data.if_err_expr.var_is_ptr = old.var_is_ptr; res->data.if_err_expr.var_symbol = old.var_symbol; res->data.if_err_expr.then_node = body; res->data.if_err_expr.err_symbol = token_buf(pc, err_payload); res->data.if_err_expr.else_node = else_body; return res; } if (res->data.test_expr.var_symbol != nullptr) { res->data.test_expr.then_node = body; res->data.test_expr.else_node = else_body; return res; } AstNodeTestExpr old = res->data.test_expr; res->type = NodeTypeIfBoolExpr; res->data.if_bool_expr.condition = old.target_node; res->data.if_bool_expr.then_block = body; res->data.if_bool_expr.else_node = else_body; return res; } // LabeledStatement <- BlockLabel? (Block / LoopStatement) static AstNode *ast_parse_labeled_statement(ParseContext *pc) { TokenIndex label = ast_parse_block_label(pc); AstNode *block = ast_parse_block(pc); if (block != nullptr) { assert(block->type == NodeTypeBlock); block->data.block.name = token_buf(pc, label); return block; } AstNode *loop = ast_parse_loop_statement(pc); if (loop != nullptr) { switch (loop->type) { case NodeTypeForExpr: loop->data.for_expr.name = token_buf(pc, label); break; case NodeTypeWhileExpr: loop->data.while_expr.name = token_buf(pc, label); break; default: zig_unreachable(); } return loop; } if (label != 0) ast_invalid_token_error(pc, peek_token(pc)); return nullptr; } // LoopStatement <- KEYWORD_inline? (ForStatement / WhileStatement) static AstNode *ast_parse_loop_statement(ParseContext *pc) { TokenIndex inline_token = eat_token_if(pc, TokenIdKeywordInline); AstNode *for_statement = ast_parse_for_statement(pc); if (for_statement != nullptr) { assert(for_statement->type == NodeTypeForExpr); for_statement->data.for_expr.is_inline = inline_token != 0; return for_statement; } AstNode *while_statement = ast_parse_while_statement(pc); if (while_statement != nullptr) { assert(while_statement->type == NodeTypeWhileExpr); while_statement->data.while_expr.is_inline = inline_token != 0; return while_statement; } if (inline_token != 0) ast_invalid_token_error(pc, peek_token(pc)); return nullptr; } // ForStatement // <- ForPrefix BlockExpr ( KEYWORD_else Statement )? // / ForPrefix AssignExpr ( SEMICOLON / KEYWORD_else Statement ) static AstNode *ast_parse_for_statement(ParseContext *pc) { AstNode *res = ast_parse_for_prefix(pc); if (res == nullptr) return nullptr; AstNode *body = ast_parse_block_expr(pc); bool requires_semi = false; if (body == nullptr) { requires_semi = true; body = ast_parse_assign_expr(pc); } if (body == nullptr) { TokenIndex tok = eat_token(pc); ast_error(pc, tok, "expected loop body, found '%s'", token_name(pc->token_ids[tok])); } AstNode *else_body = nullptr; if (eat_token_if(pc, TokenIdKeywordElse) != 0) { else_body = ast_expect(pc, ast_parse_statement); } if (requires_semi && else_body == nullptr) expect_token(pc, TokenIdSemicolon); assert(res->type == NodeTypeForExpr); res->data.for_expr.body = body; res->data.for_expr.else_node = else_body; return res; } // WhileStatement // <- WhilePrefix BlockExpr ( KEYWORD_else Payload? Statement )? // / WhilePrefix AssignExpr ( SEMICOLON / KEYWORD_else Payload? Statement ) static AstNode *ast_parse_while_statement(ParseContext *pc) { AstNode *res = ast_parse_while_prefix(pc); if (res == nullptr) return nullptr; AstNode *body = ast_parse_block_expr(pc); bool requires_semi = false; if (body == nullptr) { requires_semi = true; body = ast_parse_assign_expr(pc); } if (body == nullptr) { TokenIndex tok = eat_token(pc); ast_error(pc, tok, "expected loop body, found '%s'", token_name(pc->token_ids[tok])); } TokenIndex err_payload = 0; AstNode *else_body = nullptr; if (eat_token_if(pc, TokenIdKeywordElse) != 0) { err_payload = ast_parse_payload(pc); else_body = ast_expect(pc, ast_parse_statement); } if (requires_semi && else_body == nullptr) expect_token(pc, TokenIdSemicolon); assert(res->type == NodeTypeWhileExpr); res->data.while_expr.body = body; res->data.while_expr.err_symbol = token_buf(pc, err_payload); res->data.while_expr.else_node = else_body; return res; } // BlockExprStatement // <- BlockExpr // / AssignExpr SEMICOLON static AstNode *ast_parse_block_expr_statement(ParseContext *pc) { AstNode *block = ast_parse_block_expr(pc); if (block != nullptr) return block; AstNode *assign_expr = ast_parse_assign_expr(pc); if (assign_expr != nullptr) { expect_token(pc, TokenIdSemicolon); return assign_expr; } return nullptr; } // BlockExpr <- BlockLabel? Block static AstNode *ast_parse_block_expr(ParseContext *pc) { TokenIndex label = ast_parse_block_label(pc); if (label != 0) { AstNode *res = ast_expect(pc, ast_parse_block); assert(res->type == NodeTypeBlock); res->data.block.name = token_buf(pc, label); return res; } return ast_parse_block(pc); } // AssignExpr <- Expr (AssignOp Expr)? static AstNode *ast_parse_assign_expr(ParseContext *pc) { return ast_parse_bin_op_expr(pc, BinOpChainOnce, ast_parse_assign_op, ast_parse_expr); } // Expr <- KEYWORD_try* BoolOrExpr static AstNode *ast_parse_expr(ParseContext *pc) { return ast_parse_prefix_op_expr( pc, [](ParseContext *context) { TokenIndex try_token = eat_token_if(context, TokenIdKeywordTry); if (try_token != 0) { AstNode *res = ast_create_node(context, NodeTypeReturnExpr, try_token); res->data.return_expr.kind = ReturnKindError; return res; } return (AstNode*)nullptr; }, ast_parse_bool_or_expr ); } // BoolOrExpr <- BoolAndExpr (KEYWORD_or BoolAndExpr)* static AstNode *ast_parse_bool_or_expr(ParseContext *pc) { return ast_parse_bin_op_expr( pc, BinOpChainInf, ast_parse_bin_op_simple<TokenIdKeywordOr, BinOpTypeBoolOr>, ast_parse_bool_and_expr ); } // BoolAndExpr <- CompareExpr (KEYWORD_and CompareExpr)* static AstNode *ast_parse_bool_and_expr(ParseContext *pc) { return ast_parse_bin_op_expr( pc, BinOpChainInf, ast_parse_bin_op_simple<TokenIdKeywordAnd, BinOpTypeBoolAnd>, ast_parse_compare_expr ); } // CompareExpr <- BitwiseExpr (CompareOp BitwiseExpr)? static AstNode *ast_parse_compare_expr(ParseContext *pc) { return ast_parse_bin_op_expr(pc, BinOpChainOnce, ast_parse_compare_op, ast_parse_bitwise_expr); } // BitwiseExpr <- BitShiftExpr (BitwiseOp BitShiftExpr)* static AstNode *ast_parse_bitwise_expr(ParseContext *pc) { return ast_parse_bin_op_expr(pc, BinOpChainInf, ast_parse_bitwise_op, ast_parse_bit_shift_expr); } // BitShiftExpr <- AdditionExpr (BitShiftOp AdditionExpr)* static AstNode *ast_parse_bit_shift_expr(ParseContext *pc) { return ast_parse_bin_op_expr(pc, BinOpChainInf, ast_parse_bit_shift_op, ast_parse_addition_expr); } // AdditionExpr <- MultiplyExpr (AdditionOp MultiplyExpr)* static AstNode *ast_parse_addition_expr(ParseContext *pc) { return ast_parse_bin_op_expr(pc, BinOpChainInf, ast_parse_addition_op, ast_parse_multiply_expr); } // MultiplyExpr <- PrefixExpr (MultiplyOp PrefixExpr)* static AstNode *ast_parse_multiply_expr(ParseContext *pc) { return ast_parse_bin_op_expr(pc, BinOpChainInf, ast_parse_multiply_op, ast_parse_prefix_expr); } // PrefixExpr <- PrefixOp* PrimaryExpr static AstNode *ast_parse_prefix_expr(ParseContext *pc) { return ast_parse_prefix_op_expr( pc, ast_parse_prefix_op, ast_parse_primary_expr ); } // PrimaryExpr // <- AsmExpr // / IfExpr // / KEYWORD_break BreakLabel? Expr? // / KEYWORD_comptime Expr // / KEYWORD_nosuspend Expr // / KEYWORD_continue BreakLabel? // / KEYWORD_resume Expr // / KEYWORD_return Expr? // / BlockLabel? LoopExpr // / Block // / CurlySuffixExpr static AstNode *ast_parse_primary_expr(ParseContext *pc) { AstNode *asm_expr = ast_parse_asm_expr(pc); if (asm_expr != nullptr) return asm_expr; AstNode *if_expr = ast_parse_if_expr(pc); if (if_expr != nullptr) return if_expr; TokenIndex break_token = eat_token_if(pc, TokenIdKeywordBreak); if (break_token != 0) { TokenIndex label = ast_parse_break_label(pc); AstNode *expr = ast_parse_expr(pc); AstNode *res = ast_create_node(pc, NodeTypeBreak, break_token); res->data.break_expr.name = token_buf(pc, label); res->data.break_expr.expr = expr; return res; } TokenIndex comptime = eat_token_if(pc, TokenIdKeywordCompTime); if (comptime != 0) { AstNode *expr = ast_expect(pc, ast_parse_expr); AstNode *res = ast_create_node(pc, NodeTypeCompTime, comptime); res->data.comptime_expr.expr = expr; return res; } TokenIndex nosuspend = eat_token_if(pc, TokenIdKeywordNoSuspend); if (nosuspend != 0) { AstNode *expr = ast_expect(pc, ast_parse_expr); AstNode *res = ast_create_node(pc, NodeTypeNoSuspend, nosuspend); res->data.nosuspend_expr.expr = expr; return res; } TokenIndex continue_token = eat_token_if(pc, TokenIdKeywordContinue); if (continue_token != 0) { TokenIndex label = ast_parse_break_label(pc); AstNode *res = ast_create_node(pc, NodeTypeContinue, continue_token); res->data.continue_expr.name = token_buf(pc, label); return res; } TokenIndex resume = eat_token_if(pc, TokenIdKeywordResume); if (resume != 0) { AstNode *expr = ast_expect(pc, ast_parse_expr); AstNode *res = ast_create_node(pc, NodeTypeResume, resume); res->data.resume_expr.expr = expr; return res; } TokenIndex return_token = eat_token_if(pc, TokenIdKeywordReturn); if (return_token != 0) { AstNode *expr = ast_parse_expr(pc); AstNode *res = ast_create_node(pc, NodeTypeReturnExpr, return_token); res->data.return_expr.expr = expr; return res; } TokenIndex label = ast_parse_block_label(pc); AstNode *loop = ast_parse_loop_expr(pc); if (loop != nullptr) { switch (loop->type) { case NodeTypeForExpr: loop->data.for_expr.name = token_buf(pc, label); break; case NodeTypeWhileExpr: loop->data.while_expr.name = token_buf(pc, label); break; default: zig_unreachable(); } return loop; } else if (label != 0) { // Restore the tokens that we eaten by ast_parse_block_label. put_back_token(pc); put_back_token(pc); } AstNode *block = ast_parse_block(pc); if (block != nullptr) return block; AstNode *curly_suffix = ast_parse_curly_suffix_expr(pc); if (curly_suffix != nullptr) return curly_suffix; return nullptr; } // IfExpr <- IfPrefix Expr (KEYWORD_else Payload? Expr)? static AstNode *ast_parse_if_expr(ParseContext *pc) { return ast_parse_if_expr_helper(pc, ast_parse_expr); } // Block <- LBRACE Statement* RBRACE static AstNode *ast_parse_block(ParseContext *pc) { TokenIndex lbrace = eat_token_if(pc, TokenIdLBrace); if (lbrace == 0) return nullptr; ZigList<AstNode *> statements = {}; AstNode *statement; while ((statement = ast_parse_statement(pc)) != nullptr) statements.append(statement); expect_token(pc, TokenIdRBrace); AstNode *res = ast_create_node(pc, NodeTypeBlock, lbrace); res->data.block.statements = statements; return res; } // LoopExpr <- KEYWORD_inline? (ForExpr / WhileExpr) static AstNode *ast_parse_loop_expr(ParseContext *pc) { return ast_parse_loop_expr_helper( pc, ast_parse_for_expr, ast_parse_while_expr ); } // ForExpr <- ForPrefix Expr (KEYWORD_else Expr)? static AstNode *ast_parse_for_expr(ParseContext *pc) { return ast_parse_for_expr_helper(pc, ast_parse_expr); } // WhileExpr <- WhilePrefix Expr (KEYWORD_else Payload? Expr)? static AstNode *ast_parse_while_expr(ParseContext *pc) { return ast_parse_while_expr_helper(pc, ast_parse_expr); } // CurlySuffixExpr <- TypeExpr InitList? static AstNode *ast_parse_curly_suffix_expr(ParseContext *pc) { AstNode *type_expr = ast_parse_type_expr(pc); if (type_expr == nullptr) return nullptr; AstNode *res = ast_parse_init_list(pc); if (res == nullptr) return type_expr; assert(res->type == NodeTypeContainerInitExpr); res->data.container_init_expr.type = type_expr; return res; } // InitList // <- LBRACE FieldInit (COMMA FieldInit)* COMMA? RBRACE // / LBRACE Expr (COMMA Expr)* COMMA? RBRACE // / LBRACE RBRACE static AstNode *ast_parse_init_list(ParseContext *pc) { TokenIndex lbrace = eat_token_if(pc, TokenIdLBrace); if (lbrace == 0) return nullptr; AstNode *first = ast_parse_field_init(pc); if (first != nullptr) { AstNode *res = ast_create_node(pc, NodeTypeContainerInitExpr, lbrace); res->data.container_init_expr.kind = ContainerInitKindStruct; res->data.container_init_expr.entries.append(first); while (eat_token_if(pc, TokenIdComma) != 0) { AstNode *field_init = ast_parse_field_init(pc); if (field_init == nullptr) break; res->data.container_init_expr.entries.append(field_init); } expect_token(pc, TokenIdRBrace); return res; } AstNode *res = ast_create_node(pc, NodeTypeContainerInitExpr, lbrace); res->data.container_init_expr.kind = ContainerInitKindArray; first = ast_parse_expr(pc); if (first != nullptr) { res->data.container_init_expr.entries.append(first); while (eat_token_if(pc, TokenIdComma) != 0) { AstNode *expr = ast_parse_expr(pc); if (expr == nullptr) break; res->data.container_init_expr.entries.append(expr); } expect_token(pc, TokenIdRBrace); return res; } expect_token(pc, TokenIdRBrace); return res; } // TypeExpr <- PrefixTypeOp* ErrorUnionExpr static AstNode *ast_parse_type_expr(ParseContext *pc) { return ast_parse_prefix_op_expr( pc, ast_parse_prefix_type_op, ast_parse_error_union_expr ); } // ErrorUnionExpr <- SuffixExpr (EXCLAMATIONMARK TypeExpr)? static AstNode *ast_parse_error_union_expr(ParseContext *pc) { AstNode *res = ast_parse_suffix_expr(pc); if (res == nullptr) return nullptr; AstNode *op = ast_parse_bin_op_simple<TokenIdBang, BinOpTypeErrorUnion>(pc); if (op == nullptr) return res; AstNode *right = ast_expect(pc, ast_parse_type_expr); assert(op->type == NodeTypeBinOpExpr); op->data.bin_op_expr.op1 = res; op->data.bin_op_expr.op2 = right; return op; } // SuffixExpr // <- KEYWORD_async PrimaryTypeExpr SuffixOp* FnCallArguments // / PrimaryTypeExpr (SuffixOp / FnCallArguments)* static AstNode *ast_parse_suffix_expr(ParseContext *pc) { TokenIndex async_token = eat_token_if(pc, TokenIdKeywordAsync); if (async_token) { AstNode *child = ast_expect(pc, ast_parse_primary_type_expr); while (true) { AstNode *suffix = ast_parse_suffix_op(pc); if (suffix == nullptr) break; switch (suffix->type) { case NodeTypeSliceExpr: suffix->data.slice_expr.array_ref_expr = child; break; case NodeTypeArrayAccessExpr: suffix->data.array_access_expr.array_ref_expr = child; break; case NodeTypeFieldAccessExpr: suffix->data.field_access_expr.struct_expr = child; break; case NodeTypeUnwrapOptional: suffix->data.unwrap_optional.expr = child; break; case NodeTypePtrDeref: suffix->data.ptr_deref_expr.target = child; break; default: zig_unreachable(); } child = suffix; } // TODO: Both *_async_prefix and *_fn_call_arguments returns an // AstNode *. All we really want here is the arguments of // the call we parse. We therefor "leak" the node for now. // Wait till we get async rework to fix this. AstNode *args = ast_parse_fn_call_arguments(pc); if (args == nullptr) ast_invalid_token_error(pc, peek_token(pc)); assert(args->type == NodeTypeFnCallExpr); AstNode *res = ast_create_node(pc, NodeTypeFnCallExpr, async_token); res->data.fn_call_expr.modifier = CallModifierAsync; res->data.fn_call_expr.seen = false; res->data.fn_call_expr.fn_ref_expr = child; res->data.fn_call_expr.params = args->data.fn_call_expr.params; return res; } AstNode *res = ast_parse_primary_type_expr(pc); if (res == nullptr) return nullptr; while (true) { AstNode *suffix = ast_parse_suffix_op(pc); if (suffix != nullptr) { switch (suffix->type) { case NodeTypeSliceExpr: suffix->data.slice_expr.array_ref_expr = res; break; case NodeTypeArrayAccessExpr: suffix->data.array_access_expr.array_ref_expr = res; break; case NodeTypeFieldAccessExpr: suffix->data.field_access_expr.struct_expr = res; break; case NodeTypeUnwrapOptional: suffix->data.unwrap_optional.expr = res; break; case NodeTypePtrDeref: suffix->data.ptr_deref_expr.target = res; break; default: zig_unreachable(); } res = suffix; continue; } AstNode * call = ast_parse_fn_call_arguments(pc); if (call != nullptr) { assert(call->type == NodeTypeFnCallExpr); call->data.fn_call_expr.fn_ref_expr = res; res = call; continue; } break; } return res; } // PrimaryTypeExpr // <- BUILTINIDENTIFIER FnCallArguments // / CHAR_LITERAL // / ContainerDecl // / DOT IDENTIFIER // / ErrorSetDecl // / FLOAT // / FnProto // / GroupedExpr // / LabeledTypeExpr // / IDENTIFIER // / IfTypeExpr // / INTEGER // / KEYWORD_comptime TypeExpr // / KEYWORD_error DOT IDENTIFIER // / KEYWORD_false // / KEYWORD_null // / KEYWORD_promise // / KEYWORD_true // / KEYWORD_undefined // / KEYWORD_unreachable // / STRINGLITERAL // / SwitchExpr static AstNode *ast_parse_primary_type_expr(ParseContext *pc) { TokenIndex builtin_tok = eat_token_if(pc, TokenIdBuiltin); if (builtin_tok != 0) { AstNode *res = ast_expect(pc, ast_parse_fn_call_arguments); AstNode *name_sym = ast_create_node(pc, NodeTypeIdentifier, builtin_tok); assert(res->type == NodeTypeFnCallExpr); res->main_token = builtin_tok; res->data.fn_call_expr.fn_ref_expr = name_sym; res->data.fn_call_expr.modifier = CallModifierBuiltin; return res; } TokenIndex char_lit = eat_token_if(pc, TokenIdCharLiteral); if (char_lit != 0) { return ast_create_node(pc, NodeTypeCharLiteral, char_lit); } AstNode *container_decl = ast_parse_container_decl(pc); if (container_decl != nullptr) return container_decl; AstNode *anon_lit = ast_parse_anon_lit(pc); if (anon_lit != nullptr) return anon_lit; AstNode *error_set_decl = ast_parse_error_set_decl(pc); if (error_set_decl != nullptr) return error_set_decl; TokenIndex float_lit = eat_token_if(pc, TokenIdFloatLiteral); if (float_lit != 0) { return ast_create_node(pc, NodeTypeFloatLiteral, float_lit); } AstNode *fn_proto = ast_parse_fn_proto(pc); if (fn_proto != nullptr) return fn_proto; AstNode *grouped_expr = ast_parse_grouped_expr(pc); if (grouped_expr != nullptr) return grouped_expr; AstNode *labeled_type_expr = ast_parse_labeled_type_expr(pc); if (labeled_type_expr != nullptr) return labeled_type_expr; TokenIndex identifier = eat_token_if(pc, TokenIdIdentifier); if (identifier != 0) return token_identifier(pc, identifier); AstNode *if_type_expr = ast_parse_if_type_expr(pc); if (if_type_expr != nullptr) return if_type_expr; TokenIndex int_lit = eat_token_if(pc, TokenIdIntLiteral); if (int_lit != 0) { return ast_create_node(pc, NodeTypeIntLiteral, int_lit); } TokenIndex comptime = eat_token_if(pc, TokenIdKeywordCompTime); if (comptime != 0) { AstNode *expr = ast_expect(pc, ast_parse_type_expr); AstNode *res = ast_create_node(pc, NodeTypeCompTime, comptime); res->data.comptime_expr.expr = expr; return res; } TokenIndex error = eat_token_if(pc, TokenIdKeywordError); if (error != 0) { TokenIndex dot = expect_token(pc, TokenIdDot); TokenIndex name = expect_token(pc, TokenIdIdentifier); AstNode *left = ast_create_node(pc, NodeTypeErrorType, error); AstNode *res = ast_create_node(pc, NodeTypeFieldAccessExpr, dot); res->data.field_access_expr.struct_expr = left; res->data.field_access_expr.field_name = token_buf(pc, name); return res; } TokenIndex false_token = eat_token_if(pc, TokenIdKeywordFalse); if (false_token != 0) { AstNode *res = ast_create_node(pc, NodeTypeBoolLiteral, false_token); res->data.bool_literal.value = false; return res; } TokenIndex null = eat_token_if(pc, TokenIdKeywordNull); if (null != 0) return ast_create_node(pc, NodeTypeNullLiteral, null); TokenIndex anyframe = eat_token_if(pc, TokenIdKeywordAnyFrame); if (anyframe != 0) return ast_create_node(pc, NodeTypeAnyFrameType, anyframe); TokenIndex true_token = eat_token_if(pc, TokenIdKeywordTrue); if (true_token != 0) { AstNode *res = ast_create_node(pc, NodeTypeBoolLiteral, true_token); res->data.bool_literal.value = true; return res; } TokenIndex undefined = eat_token_if(pc, TokenIdKeywordUndefined); if (undefined != 0) return ast_create_node(pc, NodeTypeUndefinedLiteral, undefined); TokenIndex unreachable = eat_token_if(pc, TokenIdKeywordUnreachable); if (unreachable != 0) return ast_create_node(pc, NodeTypeUnreachable, unreachable); TokenIndex string_lit = eat_token_if(pc, TokenIdStringLiteral); if (string_lit != 0) { return ast_create_node(pc, NodeTypeStringLiteral, string_lit); } TokenIndex multiline_str_lit = ast_parse_multi_tok(pc, TokenIdMultilineStringLiteralLine); if (multiline_str_lit != 0) { return ast_create_node(pc, NodeTypeStringLiteral, multiline_str_lit); } AstNode *switch_expr = ast_parse_switch_expr(pc); if (switch_expr != nullptr) return switch_expr; return nullptr; } // ContainerDecl <- (KEYWORD_extern / KEYWORD_packed)? ContainerDeclAuto static AstNode *ast_parse_container_decl(ParseContext *pc) { TokenIndex layout_token = eat_token_if(pc, TokenIdKeywordExtern); if (layout_token == 0) layout_token = eat_token_if(pc, TokenIdKeywordPacked); AstNode *res = ast_parse_container_decl_auto(pc); if (res == nullptr) { if (layout_token != 0) put_back_token(pc); return nullptr; } assert(res->type == NodeTypeContainerDecl); if (layout_token != 0) { res->main_token = layout_token; res->data.container_decl.layout = pc->token_ids[layout_token] == TokenIdKeywordExtern ? ContainerLayoutExtern : ContainerLayoutPacked; } return res; } // ErrorSetDecl <- KEYWORD_error LBRACE IdentifierList RBRACE static AstNode *ast_parse_error_set_decl(ParseContext *pc) { TokenIndex first = eat_token_if(pc, TokenIdKeywordError); if (first == 0) return nullptr; if (eat_token_if(pc, TokenIdLBrace) == 0) { put_back_token(pc); return nullptr; } ZigList<AstNode *> decls = ast_parse_list<AstNode>(pc, TokenIdComma, [](ParseContext *context) { TokenIndex doc_token = ast_parse_doc_comments(context); TokenIndex ident = eat_token_if(context, TokenIdIdentifier); if (ident == 0) return (AstNode*)nullptr; AstNode *symbol_node = token_identifier(context, ident); if (doc_token == 0) return symbol_node; AstNode *field_node = ast_create_node(context, NodeTypeErrorSetField, doc_token); field_node->data.err_set_field.field_name = symbol_node; field_node->data.err_set_field.doc_comments = doc_token; return field_node; }); expect_token(pc, TokenIdRBrace); AstNode *res = ast_create_node(pc, NodeTypeErrorSetDecl, first); res->data.err_set_decl.decls = decls; return res; } // GroupedExpr <- LPAREN Expr RPAREN static AstNode *ast_parse_grouped_expr(ParseContext *pc) { TokenIndex lparen = eat_token_if(pc, TokenIdLParen); if (lparen == 0) return nullptr; AstNode *expr = ast_expect(pc, ast_parse_expr); expect_token(pc, TokenIdRParen); AstNode *res = ast_create_node(pc, NodeTypeGroupedExpr, lparen); res->data.grouped_expr = expr; return res; } // IfTypeExpr <- IfPrefix TypeExpr (KEYWORD_else Payload? TypeExpr)? static AstNode *ast_parse_if_type_expr(ParseContext *pc) { return ast_parse_if_expr_helper(pc, ast_parse_type_expr); } // LabeledTypeExpr // <- BlockLabel Block // / BlockLabel? LoopTypeExpr static AstNode *ast_parse_labeled_type_expr(ParseContext *pc) { TokenIndex label = ast_parse_block_label(pc); if (label != 0) { AstNode *block = ast_parse_block(pc); if (block != nullptr) { assert(block->type == NodeTypeBlock); block->data.block.name = token_buf(pc, label); return block; } } AstNode *loop = ast_parse_loop_type_expr(pc); if (loop != nullptr) { switch (loop->type) { case NodeTypeForExpr: loop->data.for_expr.name = token_buf(pc, label); break; case NodeTypeWhileExpr: loop->data.while_expr.name = token_buf(pc, label); break; default: zig_unreachable(); } return loop; } if (label != 0) { put_back_token(pc); put_back_token(pc); } return nullptr; } // LoopTypeExpr <- KEYWORD_inline? (ForTypeExpr / WhileTypeExpr) static AstNode *ast_parse_loop_type_expr(ParseContext *pc) { return ast_parse_loop_expr_helper( pc, ast_parse_for_type_expr, ast_parse_while_type_expr ); } // ForTypeExpr <- ForPrefix TypeExpr (KEYWORD_else TypeExpr)? static AstNode *ast_parse_for_type_expr(ParseContext *pc) { return ast_parse_for_expr_helper(pc, ast_parse_type_expr); } // WhileTypeExpr <- WhilePrefix TypeExpr (KEYWORD_else Payload? TypeExpr)? static AstNode *ast_parse_while_type_expr(ParseContext *pc) { return ast_parse_while_expr_helper(pc, ast_parse_type_expr); } // SwitchExpr <- KEYWORD_switch LPAREN Expr RPAREN LBRACE SwitchProngList RBRACE static AstNode *ast_parse_switch_expr(ParseContext *pc) { TokenIndex switch_token = eat_token_if(pc, TokenIdKeywordSwitch); if (switch_token == 0) return nullptr; expect_token(pc, TokenIdLParen); AstNode *expr = ast_expect(pc, ast_parse_expr); expect_token(pc, TokenIdRParen); expect_token(pc, TokenIdLBrace); ZigList<AstNode *> prongs = ast_parse_list(pc, TokenIdComma, ast_parse_switch_prong); expect_token(pc, TokenIdRBrace); AstNode *res = ast_create_node(pc, NodeTypeSwitchExpr, switch_token); res->data.switch_expr.expr = expr; res->data.switch_expr.prongs = prongs; return res; } // AsmExpr <- KEYWORD_asm KEYWORD_volatile? LPAREN STRINGLITERAL AsmOutput? RPAREN static AstNode *ast_parse_asm_expr(ParseContext *pc) { TokenIndex asm_token = eat_token_if(pc, TokenIdKeywordAsm); if (asm_token == 0) return nullptr; TokenIndex volatile_token = eat_token_if(pc, TokenIdKeywordVolatile); expect_token(pc, TokenIdLParen); AstNode *asm_template = ast_expect(pc, ast_parse_expr); AstNode *res = ast_parse_asm_output(pc); if (res == nullptr) res = ast_create_node_no_line_info(pc, NodeTypeAsmExpr); expect_token(pc, TokenIdRParen); res->main_token = asm_token; res->data.asm_expr.volatile_token = volatile_token; res->data.asm_expr.asm_template = asm_template; return res; } static AstNode *ast_parse_anon_lit(ParseContext *pc) { TokenIndex period = eat_token_if(pc, TokenIdDot); if (period == 0) return nullptr; // anon enum literal TokenIndex identifier = eat_token_if(pc, TokenIdIdentifier); if (identifier != 0) { return ast_create_node(pc, NodeTypeEnumLiteral, period); } // anon container literal AstNode *res = ast_parse_init_list(pc); if (res != nullptr) return res; put_back_token(pc); return nullptr; } // AsmOutput <- COLON AsmOutputList AsmInput? static AstNode *ast_parse_asm_output(ParseContext *pc) { if (eat_token_if(pc, TokenIdColon) == 0) return nullptr; ZigList<AsmOutput *> output_list = ast_parse_list(pc, TokenIdComma, ast_parse_asm_output_item); AstNode *res = ast_parse_asm_input(pc); if (res == nullptr) res = ast_create_node_no_line_info(pc, NodeTypeAsmExpr); res->data.asm_expr.output_list = output_list; return res; } // AsmOutputItem <- LBRACKET IDENTIFIER RBRACKET STRINGLITERAL LPAREN (MINUSRARROW TypeExpr / IDENTIFIER) RPAREN static AsmOutput *ast_parse_asm_output_item(ParseContext *pc) { if (eat_token_if(pc, TokenIdLBracket) == 0) return nullptr; TokenIndex sym_name = expect_token(pc, TokenIdIdentifier); expect_token(pc, TokenIdRBracket); TokenIndex str = ast_parse_multi_tok(pc, TokenIdMultilineStringLiteralLine); if (str == 0) str = expect_token(pc, TokenIdStringLiteral); expect_token(pc, TokenIdLParen); TokenIndex var_name = eat_token_if(pc, TokenIdIdentifier); AstNode *return_type = nullptr; if (var_name == 0) { expect_token(pc, TokenIdArrow); return_type = ast_expect(pc, ast_parse_type_expr); } expect_token(pc, TokenIdRParen); AsmOutput *res = heap::c_allocator.create<AsmOutput>(); res->asm_symbolic_name = token_buf(pc, sym_name); res->constraint = token_buf(pc, str); res->variable_name = token_buf(pc, var_name); res->return_type = return_type; return res; } // AsmInput <- COLON AsmInputList AsmClobbers? static AstNode *ast_parse_asm_input(ParseContext *pc) { if (eat_token_if(pc, TokenIdColon) == 0) return nullptr; ZigList<AsmInput *> input_list = ast_parse_list(pc, TokenIdComma, ast_parse_asm_input_item); AstNode *res = ast_parse_asm_clobbers(pc); if (res == nullptr) res = ast_create_node_no_line_info(pc, NodeTypeAsmExpr); res->data.asm_expr.input_list = input_list; return res; } // AsmInputItem <- LBRACKET IDENTIFIER RBRACKET STRINGLITERAL LPAREN Expr RPAREN static AsmInput *ast_parse_asm_input_item(ParseContext *pc) { if (eat_token_if(pc, TokenIdLBracket) == 0) return nullptr; TokenIndex sym_name = expect_token(pc, TokenIdIdentifier); expect_token(pc, TokenIdRBracket); TokenIndex constraint = expect_token(pc, TokenIdStringLiteral); expect_token(pc, TokenIdLParen); AstNode *expr = ast_expect(pc, ast_parse_expr); expect_token(pc, TokenIdRParen); AsmInput *res = heap::c_allocator.create<AsmInput>(); res->asm_symbolic_name = token_buf(pc, sym_name); res->constraint = token_buf(pc, constraint); res->expr = expr; return res; } // AsmClobbers <- COLON StringList static AstNode *ast_parse_asm_clobbers(ParseContext *pc) { if (eat_token_if(pc, TokenIdColon) == 0) return nullptr; ZigList<Buf *> clobber_list = ast_parse_list<Buf>(pc, TokenIdComma, [](ParseContext *context) { TokenIndex str = eat_token_if(context, TokenIdStringLiteral); if (str == 0) str = ast_parse_multi_tok(context, TokenIdMultilineStringLiteralLine); if (str != 0) return token_buf(context, str); return (Buf*)nullptr; }); AstNode *res = ast_create_node_no_line_info(pc, NodeTypeAsmExpr); res->data.asm_expr.clobber_list = clobber_list; return res; } // BreakLabel <- COLON IDENTIFIER static TokenIndex ast_parse_break_label(ParseContext *pc) { if (eat_token_if(pc, TokenIdColon) == 0) return 0; return expect_token(pc, TokenIdIdentifier); } // BlockLabel <- IDENTIFIER COLON static TokenIndex ast_parse_block_label(ParseContext *pc) { TokenIndex ident = eat_token_if(pc, TokenIdIdentifier); if (ident == 0) return 0; // We do 2 token lookahead here, as we don't want to error when // parsing identifiers. if (eat_token_if(pc, TokenIdColon) == 0) { put_back_token(pc); return 0; } return ident; } // FieldInit <- DOT IDENTIFIER EQUAL Expr static AstNode *ast_parse_field_init(ParseContext *pc) { TokenIndex first = eat_token_if(pc, TokenIdDot); if (first == 0) return nullptr; TokenIndex name = eat_token_if(pc, TokenIdIdentifier); if (name == 0) { // Because of anon literals ".{" is also valid. put_back_token(pc); return nullptr; } if (eat_token_if(pc, TokenIdEq) == 0) { // Because ".Name" can also be interpreted as an enum literal, we should put back // those two tokens again so that the parser can try to parse them as the enum // literal later. put_back_token(pc); put_back_token(pc); return nullptr; } AstNode *expr = ast_expect(pc, ast_parse_expr); AstNode *res = ast_create_node(pc, NodeTypeStructValueField, first); res->data.struct_val_field.name = token_buf(pc, name); res->data.struct_val_field.expr = expr; return res; } // WhileContinueExpr <- COLON LPAREN AssignExpr RPAREN static AstNode *ast_parse_while_continue_expr(ParseContext *pc) { TokenIndex first = eat_token_if(pc, TokenIdColon); if (first == 0) return nullptr; expect_token(pc, TokenIdLParen); AstNode *expr = ast_expect(pc, ast_parse_assign_expr); expect_token(pc, TokenIdRParen); return expr; } // LinkSection <- KEYWORD_linksection LPAREN Expr RPAREN static AstNode *ast_parse_link_section(ParseContext *pc) { TokenIndex first = eat_token_if(pc, TokenIdKeywordLinkSection); if (first == 0) return nullptr; expect_token(pc, TokenIdLParen); AstNode *res = ast_expect(pc, ast_parse_expr); expect_token(pc, TokenIdRParen); return res; } // CallConv <- KEYWORD_callconv LPAREN Expr RPAREN static AstNode *ast_parse_callconv(ParseContext *pc) { TokenIndex first = eat_token_if(pc, TokenIdKeywordCallconv); if (first == 0) return nullptr; expect_token(pc, TokenIdLParen); AstNode *res = ast_expect(pc, ast_parse_expr); expect_token(pc, TokenIdRParen); return res; } // ParamDecl <- (KEYWORD_noalias / KEYWORD_comptime)? (IDENTIFIER COLON)? ParamType static AstNode *ast_parse_param_decl(ParseContext *pc) { TokenIndex first_doc_comment = ast_parse_doc_comments(pc); TokenIndex first = eat_token_if(pc, TokenIdKeywordNoAlias); if (first == 0) first = eat_token_if(pc, TokenIdKeywordCompTime); TokenIndex name = eat_token_if(pc, TokenIdIdentifier); if (name != 0) { if (eat_token_if(pc, TokenIdColon) != 0) { if (first == 0) first = name; } else { // We put back the ident, so it can be parsed as a ParamType // later. put_back_token(pc); name = 0; } } AstNode *res; if (first == 0) { first = peek_token(pc); res = ast_parse_param_type(pc); } else { res = ast_expect(pc, ast_parse_param_type); } if (res == nullptr) return nullptr; assert(res->type == NodeTypeParamDecl); res->main_token = first; res->data.param_decl.name = token_buf(pc, name); res->data.param_decl.doc_comments = first_doc_comment; res->data.param_decl.is_noalias = pc->token_ids[first] == TokenIdKeywordNoAlias; res->data.param_decl.is_comptime = pc->token_ids[first] == TokenIdKeywordCompTime; return res; } // ParamType // <- KEYWORD_anytype // / DOT3 // / TypeExpr static AstNode *ast_parse_param_type(ParseContext *pc) { TokenIndex anytype_token = eat_token_if(pc, TokenIdKeywordAnyType); if (anytype_token != 0) { AstNode *res = ast_create_node(pc, NodeTypeParamDecl, anytype_token); res->data.param_decl.anytype_token = anytype_token; return res; } TokenIndex dots = eat_token_if(pc, TokenIdEllipsis3); if (dots != 0) { AstNode *res = ast_create_node(pc, NodeTypeParamDecl, dots); res->data.param_decl.is_var_args = true; return res; } AstNode *type_expr = ast_parse_type_expr(pc); if (type_expr != nullptr) { AstNode *res = ast_create_node_copy_line_info(pc, NodeTypeParamDecl, type_expr); res->data.param_decl.type = type_expr; return res; } return nullptr; } // IfPrefix <- KEYWORD_if LPAREN Expr RPAREN PtrPayload? static AstNode *ast_parse_if_prefix(ParseContext *pc) { TokenIndex first = eat_token_if(pc, TokenIdKeywordIf); if (first == 0) return nullptr; expect_token(pc, TokenIdLParen); AstNode *condition = ast_expect(pc, ast_parse_expr); expect_token(pc, TokenIdRParen); Optional<PtrPayload> opt_payload = ast_parse_ptr_payload(pc); PtrPayload payload; AstNode *res = ast_create_node(pc, NodeTypeIfOptional, first); res->data.test_expr.target_node = condition; if (opt_payload.unwrap(&payload)) { res->data.test_expr.var_symbol = token_buf(pc, payload.payload); res->data.test_expr.var_is_ptr = payload.asterisk != 0; } return res; } // WhilePrefix <- KEYWORD_while LPAREN Expr RPAREN PtrPayload? WhileContinueExpr? static AstNode *ast_parse_while_prefix(ParseContext *pc) { TokenIndex while_token = eat_token_if(pc, TokenIdKeywordWhile); if (while_token == 0) return nullptr; expect_token(pc, TokenIdLParen); AstNode *condition = ast_expect(pc, ast_parse_expr); expect_token(pc, TokenIdRParen); Optional<PtrPayload> opt_payload = ast_parse_ptr_payload(pc); AstNode *continue_expr = ast_parse_while_continue_expr(pc); PtrPayload payload; AstNode *res = ast_create_node(pc, NodeTypeWhileExpr, while_token); res->data.while_expr.condition = condition; res->data.while_expr.continue_expr = continue_expr; if (opt_payload.unwrap(&payload)) { res->data.while_expr.var_symbol = token_buf(pc, payload.payload); res->data.while_expr.var_is_ptr = payload.asterisk != 0; } return res; } // ForPrefix <- KEYWORD_for LPAREN Expr RPAREN PtrIndexPayload static AstNode *ast_parse_for_prefix(ParseContext *pc) { TokenIndex for_token = eat_token_if(pc, TokenIdKeywordFor); if (for_token == 0) return nullptr; expect_token(pc, TokenIdLParen); AstNode *array_expr = ast_expect(pc, ast_parse_expr); expect_token(pc, TokenIdRParen); PtrIndexPayload payload; if (!ast_parse_ptr_index_payload(pc).unwrap(&payload)) ast_invalid_token_error(pc, peek_token(pc)); AstNode *res = ast_create_node(pc, NodeTypeForExpr, for_token); res->data.for_expr.array_expr = array_expr; res->data.for_expr.elem_node = token_identifier(pc, payload.payload); res->data.for_expr.elem_is_ptr = payload.asterisk != 0; if (payload.index != 0) res->data.for_expr.index_node = token_identifier(pc, payload.index); return res; } // Payload <- PIPE IDENTIFIER PIPE static TokenIndex ast_parse_payload(ParseContext *pc) { if (eat_token_if(pc, TokenIdBinOr) == 0) return 0; TokenIndex res = expect_token(pc, TokenIdIdentifier); expect_token(pc, TokenIdBinOr); return res; } // PtrPayload <- PIPE ASTERISK? IDENTIFIER PIPE static Optional<PtrPayload> ast_parse_ptr_payload(ParseContext *pc) { if (eat_token_if(pc, TokenIdBinOr) == 0) return Optional<PtrPayload>::none(); TokenIndex asterisk = eat_token_if(pc, TokenIdStar); TokenIndex payload = expect_token(pc, TokenIdIdentifier); expect_token(pc, TokenIdBinOr); PtrPayload res; res.asterisk = asterisk; res.payload = payload; return Optional<PtrPayload>::some(res); } // PtrIndexPayload <- PIPE ASTERISK? IDENTIFIER (COMMA IDENTIFIER)? PIPE static Optional<PtrIndexPayload> ast_parse_ptr_index_payload(ParseContext *pc) { if (eat_token_if(pc, TokenIdBinOr) == 0) return Optional<PtrIndexPayload>::none(); TokenIndex asterisk = eat_token_if(pc, TokenIdStar); TokenIndex payload = expect_token(pc, TokenIdIdentifier); TokenIndex index = 0; if (eat_token_if(pc, TokenIdComma) != 0) index = expect_token(pc, TokenIdIdentifier); expect_token(pc, TokenIdBinOr); PtrIndexPayload res; res.asterisk = asterisk; res.payload = payload; res.index = index; return Optional<PtrIndexPayload>::some(res); } // SwitchProng <- SwitchCase EQUALRARROW PtrPayload? AssignExpr static AstNode *ast_parse_switch_prong(ParseContext *pc) { AstNode *res = ast_parse_switch_case(pc); if (res == nullptr) return nullptr; expect_token(pc, TokenIdFatArrow); Optional<PtrPayload> opt_payload = ast_parse_ptr_payload(pc); AstNode *expr = ast_expect(pc, ast_parse_assign_expr); PtrPayload payload; assert(res->type == NodeTypeSwitchProng); res->data.switch_prong.expr = expr; if (opt_payload.unwrap(&payload)) { res->data.switch_prong.var_symbol = token_identifier(pc, payload.payload); res->data.switch_prong.var_is_ptr = payload.asterisk != 0; } return res; } // SwitchCase // <- SwitchItem (COMMA SwitchItem)* COMMA? // / KEYWORD_else static AstNode *ast_parse_switch_case(ParseContext *pc) { AstNode *first = ast_parse_switch_item(pc); if (first != nullptr) { AstNode *res = ast_create_node_copy_line_info(pc, NodeTypeSwitchProng, first); res->data.switch_prong.items.append(first); res->data.switch_prong.any_items_are_range = first->type == NodeTypeSwitchRange; while (eat_token_if(pc, TokenIdComma) != 0) { AstNode *item = ast_parse_switch_item(pc); if (item == nullptr) break; res->data.switch_prong.items.append(item); res->data.switch_prong.any_items_are_range |= item->type == NodeTypeSwitchRange; } return res; } TokenIndex else_token = eat_token_if(pc, TokenIdKeywordElse); if (else_token != 0) return ast_create_node(pc, NodeTypeSwitchProng, else_token); return nullptr; } // SwitchItem <- Expr (DOT3 Expr)? static AstNode *ast_parse_switch_item(ParseContext *pc) { AstNode *expr = ast_parse_expr(pc); if (expr == nullptr) return nullptr; TokenIndex dots = eat_token_if(pc, TokenIdEllipsis3); if (dots != 0) { AstNode *expr2 = ast_expect(pc, ast_parse_expr); AstNode *res = ast_create_node(pc, NodeTypeSwitchRange, dots); res->data.switch_range.start = expr; res->data.switch_range.end = expr2; return res; } return expr; } // AssignOp // <- ASTERISKEQUAL // / SLASHEQUAL // / PERCENTEQUAL // / PLUSEQUAL // / MINUSEQUAL // / LARROW2EQUAL // / RARROW2EQUAL // / AMPERSANDEQUAL // / CARETEQUAL // / PIPEEQUAL // / ASTERISKPERCENTEQUAL // / PLUSPERCENTEQUAL // / MINUSPERCENTEQUAL // / EQUAL static AstNode *ast_parse_assign_op(ParseContext *pc) { // In C, we have `T arr[N] = {[i] = T{}};` but it doesn't // seem to work in C++... BinOpType table[TokenIdCount] = {}; table[TokenIdBitAndEq] = BinOpTypeAssignBitAnd; table[TokenIdBitOrEq] = BinOpTypeAssignBitOr; table[TokenIdBitShiftLeftEq] = BinOpTypeAssignBitShiftLeft; table[TokenIdBitShiftRightEq] = BinOpTypeAssignBitShiftRight; table[TokenIdBitXorEq] = BinOpTypeAssignBitXor; table[TokenIdDivEq] = BinOpTypeAssignDiv; table[TokenIdEq] = BinOpTypeAssign; table[TokenIdMinusEq] = BinOpTypeAssignMinus; table[TokenIdMinusPercentEq] = BinOpTypeAssignMinusWrap; table[TokenIdModEq] = BinOpTypeAssignMod; table[TokenIdPlusEq] = BinOpTypeAssignPlus; table[TokenIdPlusPercentEq] = BinOpTypeAssignPlusWrap; table[TokenIdTimesEq] = BinOpTypeAssignTimes; table[TokenIdTimesPercentEq] = BinOpTypeAssignTimesWrap; BinOpType op = table[pc->token_ids[pc->current_token]]; if (op != BinOpTypeInvalid) { TokenIndex op_token = eat_token(pc); AstNode *res = ast_create_node(pc, NodeTypeBinOpExpr, op_token); res->data.bin_op_expr.bin_op = op; return res; } return nullptr; } // CompareOp // <- EQUALEQUAL // / EXCLAMATIONMARKEQUAL // / LARROW // / RARROW // / LARROWEQUAL // / RARROWEQUAL static AstNode *ast_parse_compare_op(ParseContext *pc) { BinOpType table[TokenIdCount] = {}; table[TokenIdCmpEq] = BinOpTypeCmpEq; table[TokenIdCmpNotEq] = BinOpTypeCmpNotEq; table[TokenIdCmpLessThan] = BinOpTypeCmpLessThan; table[TokenIdCmpGreaterThan] = BinOpTypeCmpGreaterThan; table[TokenIdCmpLessOrEq] = BinOpTypeCmpLessOrEq; table[TokenIdCmpGreaterOrEq] = BinOpTypeCmpGreaterOrEq; BinOpType op = table[pc->token_ids[pc->current_token]]; if (op != BinOpTypeInvalid) { TokenIndex op_token = eat_token(pc); AstNode *res = ast_create_node(pc, NodeTypeBinOpExpr, op_token); res->data.bin_op_expr.bin_op = op; return res; } return nullptr; } // BitwiseOp // <- AMPERSAND // / CARET // / PIPE // / KEYWORD_orelse // / KEYWORD_catch Payload? static AstNode *ast_parse_bitwise_op(ParseContext *pc) { BinOpType table[TokenIdCount] = {}; table[TokenIdAmpersand] = BinOpTypeBinAnd; table[TokenIdBinXor] = BinOpTypeBinXor; table[TokenIdBinOr] = BinOpTypeBinOr; table[TokenIdKeywordOrElse] = BinOpTypeUnwrapOptional; BinOpType op = table[pc->token_ids[pc->current_token]]; if (op != BinOpTypeInvalid) { TokenIndex op_token = eat_token(pc); AstNode *res = ast_create_node(pc, NodeTypeBinOpExpr, op_token); res->data.bin_op_expr.bin_op = op; return res; } TokenIndex catch_token = eat_token_if(pc, TokenIdKeywordCatch); if (catch_token != 0) { TokenIndex payload = ast_parse_payload(pc); AstNode *res = ast_create_node(pc, NodeTypeCatchExpr, catch_token); if (payload != 0) res->data.unwrap_err_expr.symbol = token_identifier(pc, payload); return res; } return nullptr; } // BitShiftOp // <- LARROW2 // / RARROW2 static AstNode *ast_parse_bit_shift_op(ParseContext *pc) { BinOpType table[TokenIdCount] = {}; table[TokenIdBitShiftLeft] = BinOpTypeBitShiftLeft; table[TokenIdBitShiftRight] = BinOpTypeBitShiftRight; BinOpType op = table[pc->token_ids[pc->current_token]]; if (op != BinOpTypeInvalid) { TokenIndex op_token = eat_token(pc); AstNode *res = ast_create_node(pc, NodeTypeBinOpExpr, op_token); res->data.bin_op_expr.bin_op = op; return res; } return nullptr; } // AdditionOp // <- PLUS // / MINUS // / PLUS2 // / PLUSPERCENT // / MINUSPERCENT static AstNode *ast_parse_addition_op(ParseContext *pc) { BinOpType table[TokenIdCount] = {}; table[TokenIdPlus] = BinOpTypeAdd; table[TokenIdDash] = BinOpTypeSub; table[TokenIdPlusPlus] = BinOpTypeArrayCat; table[TokenIdPlusPercent] = BinOpTypeAddWrap; table[TokenIdMinusPercent] = BinOpTypeSubWrap; BinOpType op = table[pc->token_ids[pc->current_token]]; if (op != BinOpTypeInvalid) { TokenIndex op_token = eat_token(pc); AstNode *res = ast_create_node(pc, NodeTypeBinOpExpr, op_token); res->data.bin_op_expr.bin_op = op; return res; } return nullptr; } // MultiplyOp // <- PIPE2 // / ASTERISK // / SLASH // / PERCENT // / ASTERISK2 // / ASTERISKPERCENT static AstNode *ast_parse_multiply_op(ParseContext *pc) { BinOpType table[TokenIdCount] = {}; table[TokenIdBarBar] = BinOpTypeMergeErrorSets; table[TokenIdStar] = BinOpTypeMult; table[TokenIdSlash] = BinOpTypeDiv; table[TokenIdPercent] = BinOpTypeMod; table[TokenIdStarStar] = BinOpTypeArrayMult; table[TokenIdTimesPercent] = BinOpTypeMultWrap; BinOpType op = table[pc->token_ids[pc->current_token]]; if (op != BinOpTypeInvalid) { TokenIndex op_token = eat_token(pc); AstNode *res = ast_create_node(pc, NodeTypeBinOpExpr, op_token); res->data.bin_op_expr.bin_op = op; return res; } return nullptr; } // PrefixOp // <- EXCLAMATIONMARK // / MINUS // / TILDE // / MINUSPERCENT // / AMPERSAND // / KEYWORD_try // / KEYWORD_await static AstNode *ast_parse_prefix_op(ParseContext *pc) { PrefixOp table[TokenIdCount] = {}; table[TokenIdBang] = PrefixOpBoolNot; table[TokenIdDash] = PrefixOpNegation; table[TokenIdTilde] = PrefixOpBinNot; table[TokenIdMinusPercent] = PrefixOpNegationWrap; table[TokenIdAmpersand] = PrefixOpAddrOf; PrefixOp op = table[pc->token_ids[pc->current_token]]; if (op != PrefixOpInvalid) { TokenIndex op_token = eat_token(pc); AstNode *res = ast_create_node(pc, NodeTypePrefixOpExpr, op_token); res->data.prefix_op_expr.prefix_op = op; return res; } TokenIndex try_token = eat_token_if(pc, TokenIdKeywordTry); if (try_token != 0) { AstNode *res = ast_create_node(pc, NodeTypeReturnExpr, try_token); res->data.return_expr.kind = ReturnKindError; return res; } TokenIndex await = eat_token_if(pc, TokenIdKeywordAwait); if (await != 0) { AstNode *res = ast_create_node(pc, NodeTypeAwaitExpr, await); return res; } return nullptr; } // PrefixTypeOp // <- QUESTIONMARK // / KEYWORD_anyframe MINUSRARROW // / ArrayTypeStart (ByteAlign / KEYWORD_const / KEYWORD_volatile)* // / PtrTypeStart (KEYWORD_align LPAREN Expr (COLON INTEGER COLON INTEGER)? RPAREN / KEYWORD_const / KEYWORD_volatile)* static AstNode *ast_parse_prefix_type_op(ParseContext *pc) { TokenIndex questionmark = eat_token_if(pc, TokenIdQuestion); if (questionmark != 0) { AstNode *res = ast_create_node(pc, NodeTypePrefixOpExpr, questionmark); res->data.prefix_op_expr.prefix_op = PrefixOpOptional; return res; } TokenIndex anyframe = eat_token_if(pc, TokenIdKeywordAnyFrame); if (anyframe != 0) { if (eat_token_if(pc, TokenIdArrow) != 0) { AstNode *res = ast_create_node(pc, NodeTypeAnyFrameType, anyframe); return res; } put_back_token(pc); } TokenIndex arr_init_lbracket = eat_token_if(pc, TokenIdLBracket); if (arr_init_lbracket != 0) { TokenIndex underscore = eat_token_if(pc, TokenIdIdentifier); if (underscore == 0) { put_back_token(pc); } else if (!buf_eql_str(token_buf(pc, underscore), "_")) { put_back_token(pc); put_back_token(pc); } else { AstNode *sentinel = nullptr; TokenIndex colon = eat_token_if(pc, TokenIdColon); if (colon != 0) { sentinel = ast_expect(pc, ast_parse_expr); } expect_token(pc, TokenIdRBracket); AstNode *node = ast_create_node(pc, NodeTypeInferredArrayType, arr_init_lbracket); node->data.inferred_array_type.sentinel = sentinel; return node; } } AstNode *ptr = ast_parse_ptr_type_start(pc); if (ptr != nullptr) { assert(ptr->type == NodeTypePointerType); // We might get two pointers from *_ptr_type_start AstNode *child = ptr->data.pointer_type.op_expr; if (child == nullptr) child = ptr; while (true) { TokenIndex allowzero_token = eat_token_if(pc, TokenIdKeywordAllowZero); if (allowzero_token != 0) { child->data.pointer_type.allow_zero_token = allowzero_token; continue; } if (eat_token_if(pc, TokenIdKeywordAlign) != 0) { expect_token(pc, TokenIdLParen); AstNode *align_expr = ast_expect(pc, ast_parse_expr); child->data.pointer_type.align_expr = align_expr; if (eat_token_if(pc, TokenIdColon) != 0) { TokenIndex bit_offset_start = expect_token(pc, TokenIdIntLiteral); expect_token(pc, TokenIdColon); TokenIndex host_int_bytes = expect_token(pc, TokenIdIntLiteral); child->data.pointer_type.bit_offset_start = bit_offset_start; child->data.pointer_type.host_int_bytes = host_int_bytes; } expect_token(pc, TokenIdRParen); continue; } if (eat_token_if(pc, TokenIdKeywordConst) != 0) { child->data.pointer_type.is_const = true; continue; } if (eat_token_if(pc, TokenIdKeywordVolatile) != 0) { child->data.pointer_type.is_volatile = true; continue; } break; } return ptr; } AstNode *array = ast_parse_array_type_start(pc); if (array != nullptr) { assert(array->type == NodeTypeArrayType); while (true) { TokenIndex allowzero_token = eat_token_if(pc, TokenIdKeywordAllowZero); if (allowzero_token != 0) { array->data.array_type.allow_zero_token = allowzero_token; continue; } AstNode *align_expr = ast_parse_byte_align(pc); if (align_expr != nullptr) { array->data.array_type.align_expr = align_expr; continue; } if (eat_token_if(pc, TokenIdKeywordConst) != 0) { array->data.array_type.is_const = true; continue; } if (eat_token_if(pc, TokenIdKeywordVolatile) != 0) { array->data.array_type.is_volatile = true; continue; } break; } return array; } return nullptr; } // SuffixOp // <- LBRACKET Expr (DOT2 (Expr (COLON Expr)?)?)? RBRACKET // / DOT IDENTIFIER // / DOTASTERISK // / DOTQUESTIONMARK static AstNode *ast_parse_suffix_op(ParseContext *pc) { TokenIndex lbracket = eat_token_if(pc, TokenIdLBracket); if (lbracket != 0) { AstNode *start = ast_expect(pc, ast_parse_expr); AstNode *end = nullptr; if (eat_token_if(pc, TokenIdEllipsis2) != 0) { AstNode *sentinel = nullptr; end = ast_parse_expr(pc); if (eat_token_if(pc, TokenIdColon) != 0) { sentinel = ast_parse_expr(pc); } expect_token(pc, TokenIdRBracket); AstNode *res = ast_create_node(pc, NodeTypeSliceExpr, lbracket); res->data.slice_expr.start = start; res->data.slice_expr.end = end; res->data.slice_expr.sentinel = sentinel; return res; } expect_token(pc, TokenIdRBracket); AstNode *res = ast_create_node(pc, NodeTypeArrayAccessExpr, lbracket); res->data.array_access_expr.subscript = start; return res; } TokenIndex dot_asterisk = eat_token_if(pc, TokenIdDotStar); if (dot_asterisk != 0) return ast_create_node(pc, NodeTypePtrDeref, dot_asterisk); TokenIndex dot = eat_token_if(pc, TokenIdDot); if (dot != 0) { if (eat_token_if(pc, TokenIdQuestion) != 0) return ast_create_node(pc, NodeTypeUnwrapOptional, dot); TokenIndex ident = expect_token(pc, TokenIdIdentifier); AstNode *res = ast_create_node(pc, NodeTypeFieldAccessExpr, dot); res->data.field_access_expr.field_name = token_buf(pc, ident); return res; } return nullptr; } // FnCallArguments <- LPAREN ExprList RPAREN static AstNode *ast_parse_fn_call_arguments(ParseContext *pc) { TokenIndex paren = eat_token_if(pc, TokenIdLParen); if (paren == 0) return nullptr; ZigList<AstNode *> params = ast_parse_list(pc, TokenIdComma, ast_parse_expr); expect_token(pc, TokenIdRParen); AstNode *res = ast_create_node(pc, NodeTypeFnCallExpr, paren); res->data.fn_call_expr.params = params; res->data.fn_call_expr.seen = false; return res; } // ArrayTypeStart <- LBRACKET Expr? RBRACKET static AstNode *ast_parse_array_type_start(ParseContext *pc) { TokenIndex lbracket = eat_token_if(pc, TokenIdLBracket); if (lbracket == 0) return nullptr; AstNode *size = ast_parse_expr(pc); AstNode *sentinel = nullptr; TokenIndex colon = eat_token_if(pc, TokenIdColon); if (colon != 0) { sentinel = ast_expect(pc, ast_parse_expr); } expect_token(pc, TokenIdRBracket); AstNode *res = ast_create_node(pc, NodeTypeArrayType, lbracket); res->data.array_type.size = size; res->data.array_type.sentinel = sentinel; return res; } // PtrTypeStart // <- ASTERISK // / ASTERISK2 // / PTRUNKNOWN // / PTRC static AstNode *ast_parse_ptr_type_start(ParseContext *pc) { AstNode *sentinel = nullptr; TokenIndex asterisk = eat_token_if(pc, TokenIdStar); if (asterisk != 0) { TokenIndex colon = eat_token_if(pc, TokenIdColon); if (colon != 0) { sentinel = ast_expect(pc, ast_parse_expr); } AstNode *res = ast_create_node(pc, NodeTypePointerType, asterisk); res->data.pointer_type.star_token = asterisk; res->data.pointer_type.sentinel = sentinel; return res; } TokenIndex asterisk2 = eat_token_if(pc, TokenIdStarStar); if (asterisk2 != 0) { TokenIndex colon = eat_token_if(pc, TokenIdColon); if (colon != 0) { sentinel = ast_expect(pc, ast_parse_expr); } AstNode *res = ast_create_node(pc, NodeTypePointerType, asterisk2); AstNode *res2 = ast_create_node(pc, NodeTypePointerType, asterisk2); res->data.pointer_type.star_token = asterisk2; res2->data.pointer_type.star_token = asterisk2; res2->data.pointer_type.sentinel = sentinel; res->data.pointer_type.op_expr = res2; return res; } TokenIndex lbracket = eat_token_if(pc, TokenIdLBracket); if (lbracket != 0) { TokenIndex star = eat_token_if(pc, TokenIdStar); if (star == 0) { put_back_token(pc); } else { TokenIndex c_tok = eat_token_if(pc, TokenIdIdentifier); if (c_tok != 0) { if (!buf_eql_str(token_buf(pc, c_tok), "c")) { put_back_token(pc); // c symbol } else { expect_token(pc, TokenIdRBracket); AstNode *res = ast_create_node(pc, NodeTypePointerType, lbracket); res->data.pointer_type.star_token = c_tok; return res; } } TokenIndex colon = eat_token_if(pc, TokenIdColon); if (colon != 0) { sentinel = ast_expect(pc, ast_parse_expr); } expect_token(pc, TokenIdRBracket); AstNode *res = ast_create_node(pc, NodeTypePointerType, lbracket); res->data.pointer_type.star_token = lbracket; res->data.pointer_type.sentinel = sentinel; return res; } } return nullptr; } // ContainerDeclAuto <- ContainerDeclType LBRACE ContainerMembers RBRACE static AstNode *ast_parse_container_decl_auto(ParseContext *pc) { AstNode *res = ast_parse_container_decl_type(pc); if (res == nullptr) return nullptr; expect_token(pc, TokenIdLBrace); AstNodeContainerDecl members = ast_parse_container_members(pc); expect_token(pc, TokenIdRBrace); res->data.container_decl.fields = members.fields; res->data.container_decl.decls = members.decls; res->data.container_decl.doc_comments = members.doc_comments; return res; } // ContainerDeclType // <- KEYWORD_struct // / KEYWORD_enum (LPAREN Expr RPAREN)? // / KEYWORD_union (LPAREN (KEYWORD_enum (LPAREN Expr RPAREN)? / Expr) RPAREN)? // / KEYWORD_opaque static AstNode *ast_parse_container_decl_type(ParseContext *pc) { TokenIndex first = eat_token_if(pc, TokenIdKeywordStruct); if (first != 0) { AstNode *res = ast_create_node(pc, NodeTypeContainerDecl, first); res->data.container_decl.init_arg_expr = nullptr; res->data.container_decl.kind = ContainerKindStruct; return res; } first = eat_token_if(pc, TokenIdKeywordOpaque); if (first != 0) { AstNode *res = ast_create_node(pc, NodeTypeContainerDecl, first); res->data.container_decl.init_arg_expr = nullptr; res->data.container_decl.kind = ContainerKindOpaque; return res; } first = eat_token_if(pc, TokenIdKeywordEnum); if (first != 0) { AstNode *init_arg_expr = nullptr; if (eat_token_if(pc, TokenIdLParen) != 0) { init_arg_expr = ast_expect(pc, ast_parse_expr); expect_token(pc, TokenIdRParen); } AstNode *res = ast_create_node(pc, NodeTypeContainerDecl, first); res->data.container_decl.init_arg_expr = init_arg_expr; res->data.container_decl.kind = ContainerKindEnum; return res; } first = eat_token_if(pc, TokenIdKeywordUnion); if (first != 0) { AstNode *init_arg_expr = nullptr; bool auto_enum = false; if (eat_token_if(pc, TokenIdLParen) != 0) { if (eat_token_if(pc, TokenIdKeywordEnum) != 0) { auto_enum = true; if (eat_token_if(pc, TokenIdLParen) != 0) { init_arg_expr = ast_expect(pc, ast_parse_expr); expect_token(pc, TokenIdRParen); } } else { init_arg_expr = ast_expect(pc, ast_parse_expr); } expect_token(pc, TokenIdRParen); } AstNode *res = ast_create_node(pc, NodeTypeContainerDecl, first); res->data.container_decl.init_arg_expr = init_arg_expr; res->data.container_decl.auto_enum = auto_enum; res->data.container_decl.kind = ContainerKindUnion; return res; } return nullptr; } // ByteAlign <- KEYWORD_align LPAREN Expr RPAREN static AstNode *ast_parse_byte_align(ParseContext *pc) { if (eat_token_if(pc, TokenIdKeywordAlign) == 0) return nullptr; expect_token(pc, TokenIdLParen); AstNode *res = ast_expect(pc, ast_parse_expr); expect_token(pc, TokenIdRParen); return res; } static void visit_field(AstNode **node, void (*visit)(AstNode **, void *context), void *context) { if (*node) { visit(node, context); } } static void visit_node_list(ZigList<AstNode *> *list, void (*visit)(AstNode **, void *context), void *context) { if (list) { for (size_t i = 0; i < list->length; i += 1) { visit(&list->at(i), context); } } } void ast_visit_node_children(AstNode *node, void (*visit)(AstNode **, void *context), void *context) { switch (node->type) { case NodeTypeFnProto: visit_field(&node->data.fn_proto.return_type, visit, context); visit_node_list(&node->data.fn_proto.params, visit, context); visit_field(&node->data.fn_proto.align_expr, visit, context); visit_field(&node->data.fn_proto.section_expr, visit, context); break; case NodeTypeFnDef: visit_field(&node->data.fn_def.fn_proto, visit, context); visit_field(&node->data.fn_def.body, visit, context); break; case NodeTypeParamDecl: visit_field(&node->data.param_decl.type, visit, context); break; case NodeTypeBlock: visit_node_list(&node->data.block.statements, visit, context); break; case NodeTypeGroupedExpr: visit_field(&node->data.grouped_expr, visit, context); break; case NodeTypeReturnExpr: visit_field(&node->data.return_expr.expr, visit, context); break; case NodeTypeDefer: visit_field(&node->data.defer.expr, visit, context); visit_field(&node->data.defer.err_payload, visit, context); break; case NodeTypeVariableDeclaration: visit_field(&node->data.variable_declaration.type, visit, context); visit_field(&node->data.variable_declaration.expr, visit, context); visit_field(&node->data.variable_declaration.align_expr, visit, context); visit_field(&node->data.variable_declaration.section_expr, visit, context); break; case NodeTypeTestDecl: visit_field(&node->data.test_decl.body, visit, context); break; case NodeTypeBinOpExpr: visit_field(&node->data.bin_op_expr.op1, visit, context); visit_field(&node->data.bin_op_expr.op2, visit, context); break; case NodeTypeCatchExpr: visit_field(&node->data.unwrap_err_expr.op1, visit, context); visit_field(&node->data.unwrap_err_expr.symbol, visit, context); visit_field(&node->data.unwrap_err_expr.op2, visit, context); break; case NodeTypeIntLiteral: // none break; case NodeTypeFloatLiteral: // none break; case NodeTypeStringLiteral: // none break; case NodeTypeCharLiteral: // none break; case NodeTypeIdentifier: // none break; case NodeTypePrefixOpExpr: visit_field(&node->data.prefix_op_expr.primary_expr, visit, context); break; case NodeTypeFnCallExpr: visit_field(&node->data.fn_call_expr.fn_ref_expr, visit, context); visit_node_list(&node->data.fn_call_expr.params, visit, context); break; case NodeTypeArrayAccessExpr: visit_field(&node->data.array_access_expr.array_ref_expr, visit, context); visit_field(&node->data.array_access_expr.subscript, visit, context); break; case NodeTypeSliceExpr: visit_field(&node->data.slice_expr.array_ref_expr, visit, context); visit_field(&node->data.slice_expr.start, visit, context); visit_field(&node->data.slice_expr.end, visit, context); visit_field(&node->data.slice_expr.sentinel, visit, context); break; case NodeTypeFieldAccessExpr: visit_field(&node->data.field_access_expr.struct_expr, visit, context); break; case NodeTypePtrDeref: visit_field(&node->data.ptr_deref_expr.target, visit, context); break; case NodeTypeUnwrapOptional: visit_field(&node->data.unwrap_optional.expr, visit, context); break; case NodeTypeUsingNamespace: visit_field(&node->data.using_namespace.expr, visit, context); break; case NodeTypeBoolLiteral: // none break; case NodeTypeNullLiteral: // none break; case NodeTypeUndefinedLiteral: // none break; case NodeTypeIfBoolExpr: visit_field(&node->data.if_bool_expr.condition, visit, context); visit_field(&node->data.if_bool_expr.then_block, visit, context); visit_field(&node->data.if_bool_expr.else_node, visit, context); break; case NodeTypeIfErrorExpr: visit_field(&node->data.if_err_expr.target_node, visit, context); visit_field(&node->data.if_err_expr.then_node, visit, context); visit_field(&node->data.if_err_expr.else_node, visit, context); break; case NodeTypeIfOptional: visit_field(&node->data.test_expr.target_node, visit, context); visit_field(&node->data.test_expr.then_node, visit, context); visit_field(&node->data.test_expr.else_node, visit, context); break; case NodeTypeWhileExpr: visit_field(&node->data.while_expr.condition, visit, context); visit_field(&node->data.while_expr.body, visit, context); break; case NodeTypeForExpr: visit_field(&node->data.for_expr.elem_node, visit, context); visit_field(&node->data.for_expr.array_expr, visit, context); visit_field(&node->data.for_expr.index_node, visit, context); visit_field(&node->data.for_expr.body, visit, context); break; case NodeTypeSwitchExpr: visit_field(&node->data.switch_expr.expr, visit, context); visit_node_list(&node->data.switch_expr.prongs, visit, context); break; case NodeTypeSwitchProng: visit_node_list(&node->data.switch_prong.items, visit, context); visit_field(&node->data.switch_prong.var_symbol, visit, context); visit_field(&node->data.switch_prong.expr, visit, context); break; case NodeTypeSwitchRange: visit_field(&node->data.switch_range.start, visit, context); visit_field(&node->data.switch_range.end, visit, context); break; case NodeTypeCompTime: visit_field(&node->data.comptime_expr.expr, visit, context); break; case NodeTypeNoSuspend: visit_field(&node->data.comptime_expr.expr, visit, context); break; case NodeTypeBreak: // none break; case NodeTypeContinue: // none break; case NodeTypeUnreachable: // none break; case NodeTypeAsmExpr: for (size_t i = 0; i < node->data.asm_expr.input_list.length; i += 1) { AsmInput *asm_input = node->data.asm_expr.input_list.at(i); visit_field(&asm_input->expr, visit, context); } for (size_t i = 0; i < node->data.asm_expr.output_list.length; i += 1) { AsmOutput *asm_output = node->data.asm_expr.output_list.at(i); visit_field(&asm_output->return_type, visit, context); } break; case NodeTypeContainerDecl: visit_node_list(&node->data.container_decl.fields, visit, context); visit_node_list(&node->data.container_decl.decls, visit, context); visit_field(&node->data.container_decl.init_arg_expr, visit, context); break; case NodeTypeStructField: visit_field(&node->data.struct_field.type, visit, context); visit_field(&node->data.struct_field.value, visit, context); break; case NodeTypeContainerInitExpr: visit_field(&node->data.container_init_expr.type, visit, context); visit_node_list(&node->data.container_init_expr.entries, visit, context); break; case NodeTypeStructValueField: visit_field(&node->data.struct_val_field.expr, visit, context); break; case NodeTypeArrayType: visit_field(&node->data.array_type.size, visit, context); visit_field(&node->data.array_type.sentinel, visit, context); visit_field(&node->data.array_type.child_type, visit, context); visit_field(&node->data.array_type.align_expr, visit, context); break; case NodeTypeInferredArrayType: visit_field(&node->data.array_type.sentinel, visit, context); visit_field(&node->data.array_type.child_type, visit, context); break; case NodeTypeAnyFrameType: visit_field(&node->data.anyframe_type.payload_type, visit, context); break; case NodeTypeErrorType: // none break; case NodeTypePointerType: visit_field(&node->data.pointer_type.sentinel, visit, context); visit_field(&node->data.pointer_type.align_expr, visit, context); visit_field(&node->data.pointer_type.op_expr, visit, context); break; case NodeTypeErrorSetDecl: visit_node_list(&node->data.err_set_decl.decls, visit, context); break; case NodeTypeErrorSetField: visit_field(&node->data.err_set_field.field_name, visit, context); break; case NodeTypeResume: visit_field(&node->data.resume_expr.expr, visit, context); break; case NodeTypeAwaitExpr: visit_field(&node->data.await_expr.expr, visit, context); break; case NodeTypeSuspend: visit_field(&node->data.suspend.block, visit, context); break; case NodeTypeEnumLiteral: case NodeTypeAnyTypeField: break; } } Error source_string_literal_buf(const char *source, Buf *out, size_t *bad_index) { size_t byte_offset = 0; assert(source[byte_offset] == '"'); byte_offset += 1; buf_resize(out, 0); uint32_t codepoint; enum { StateStart, StateBackslash, StateUnicodeLBrace, StateUnicodeDigit, } state = StateStart; for (;;byte_offset += 1) { switch (state) { case StateStart: switch (source[byte_offset]) { case '\\': state = StateBackslash; continue; case '\n': *bad_index = byte_offset; return ErrorInvalidCharacter; case '"': return ErrorNone; default: buf_append_char(out, source[byte_offset]); continue; } case StateBackslash: switch (source[byte_offset]) { case 'n': buf_append_char(out, '\n'); state = StateStart; continue; case 'r': buf_append_char(out, '\r'); state = StateStart; continue; case '\\': buf_append_char(out, '\\'); state = StateStart; continue; case 't': buf_append_char(out, '\t'); state = StateStart; continue; case '\'': buf_append_char(out, '\''); state = StateStart; continue; case '"': buf_append_char(out, '"'); state = StateStart; continue; case 'x': { byte_offset += 1; uint8_t digit1; if (source[byte_offset] >= '0' && source[byte_offset] <= '9') { digit1 = source[byte_offset] - '0'; } else if (source[byte_offset] >= 'a' && source[byte_offset] <= 'z') { digit1 = source[byte_offset] - 'a' + 10; } else if (source[byte_offset] >= 'A' && source[byte_offset] <= 'Z') { digit1 = source[byte_offset] - 'A' + 10; } else { *bad_index = byte_offset; return ErrorInvalidCharacter; } byte_offset += 1; uint8_t digit0; if (source[byte_offset] >= '0' && source[byte_offset] <= '9') { digit0 = source[byte_offset] - '0'; } else if (source[byte_offset] >= 'a' && source[byte_offset] <= 'z') { digit0 = source[byte_offset] - 'a' + 10; } else if (source[byte_offset] >= 'A' && source[byte_offset] <= 'Z') { digit0 = source[byte_offset] - 'A' + 10; } else { *bad_index = byte_offset; return ErrorInvalidCharacter; } buf_append_char(out, digit1 * 16 + digit0); state = StateStart; continue; } case 'u': state = StateUnicodeLBrace; continue; default: *bad_index = byte_offset; return ErrorInvalidCharacter; } case StateUnicodeLBrace: switch (source[byte_offset]) { case '{': state = StateUnicodeDigit; codepoint = 0; continue; default: *bad_index = byte_offset; return ErrorInvalidCharacter; } case StateUnicodeDigit: { uint8_t digit; if (source[byte_offset] >= '0' && source[byte_offset] <= '9') { digit = source[byte_offset] - '0'; } else if (source[byte_offset] >= 'a' && source[byte_offset] <= 'z') { digit = source[byte_offset] - 'a' + 10; } else if (source[byte_offset] >= 'A' && source[byte_offset] <= 'Z') { digit = source[byte_offset] - 'A' + 10; } else if (source[byte_offset] == '}') { if (codepoint < 0x80) { buf_append_char(out, codepoint); } else if (codepoint < 0x800) { buf_append_char(out, 0xc0 | (codepoint >> 6)); buf_append_char(out, 0x80 | (codepoint & 0x3f)); } else if (codepoint < 0x10000) { buf_append_char(out, 0xe0 | (codepoint >> 12)); buf_append_char(out, 0x80 | ((codepoint >> 6) & 0x3f)); buf_append_char(out, 0x80 | (codepoint & 0x3f)); } else if (codepoint < 0x110000) { buf_append_char(out, 0xf0 | (codepoint >> 18)); buf_append_char(out, 0x80 | ((codepoint >> 12) & 0x3f)); buf_append_char(out, 0x80 | ((codepoint >> 6) & 0x3f)); buf_append_char(out, 0x80 | (codepoint & 0x3f)); } else { *bad_index = byte_offset; return ErrorUnicodePointTooLarge; } state = StateStart; continue; } else { *bad_index = byte_offset; return ErrorInvalidCharacter; } codepoint = codepoint * 16 + digit; continue; } } } zig_unreachable(); } static uint32_t utf8_code_point(const uint8_t *bytes) { if (bytes[0] <= 0x7f) { return bytes[0]; } else if (bytes[0] >= 0xc0 && bytes[0] <= 0xdf) { uint32_t result = bytes[0] & 0x1f; result <<= 6; result |= bytes[1] & 0x3f; return result; } else if (bytes[0] >= 0xe0 && bytes[0] <= 0xef) { uint32_t result = bytes[0] & 0xf; result <<= 6; result |= bytes[1] & 0x3f; result <<= 6; result |= bytes[2] & 0x3f; return result; } else if (bytes[0] >= 0xf0 && bytes[0] <= 0xf7) { uint32_t result = bytes[0] & 0x7; result <<= 6; result |= bytes[1] & 0x3f; result <<= 6; result |= bytes[2] & 0x3f; result <<= 6; result |= bytes[3] & 0x3f; return result; } else { zig_unreachable(); } } Error source_char_literal(const char *source, uint32_t *result, size_t *bad_index) { if (source[0] != '\\') { *result = utf8_code_point((const uint8_t *)source); return ErrorNone; } uint32_t byte_offset = 1; uint32_t codepoint; enum State { StateBackslash, StateUnicodeLBrace, StateUnicodeDigit, } state = StateBackslash; for (;;byte_offset += 1) { switch (state) { case StateBackslash: switch (source[byte_offset]) { case 'n': *result = '\n'; return ErrorNone; case 'r': *result = '\r'; return ErrorNone; case '\\': *result = '\\'; return ErrorNone; case 't': *result = '\t'; return ErrorNone; case '\'': *result = '\''; return ErrorNone; case '"': *result = '"'; return ErrorNone; case 'x': { byte_offset += 1; uint8_t digit1; if (source[byte_offset] >= '0' && source[byte_offset] <= '9') { digit1 = source[byte_offset] - '0'; } else if (source[byte_offset] >= 'a' && source[byte_offset] <= 'z') { digit1 = source[byte_offset] - 'a' + 10; } else if (source[byte_offset] >= 'A' && source[byte_offset] <= 'Z') { digit1 = source[byte_offset] - 'A' + 10; } else { *bad_index = byte_offset; return ErrorInvalidCharacter; } byte_offset += 1; uint8_t digit0; if (source[byte_offset] >= '0' && source[byte_offset] <= '9') { digit0 = source[byte_offset] - '0'; } else if (source[byte_offset] >= 'a' && source[byte_offset] <= 'z') { digit0 = source[byte_offset] - 'a' + 10; } else if (source[byte_offset] >= 'A' && source[byte_offset] <= 'Z') { digit0 = source[byte_offset] - 'A' + 10; } else { *bad_index = byte_offset; return ErrorInvalidCharacter; } *result = digit1 * 16 + digit0; return ErrorNone; } case 'u': state = StateUnicodeLBrace; continue; default: *bad_index = byte_offset; return ErrorInvalidCharacter; } case StateUnicodeLBrace: switch (source[byte_offset]) { case '{': state = StateUnicodeDigit; codepoint = 0; continue; default: *bad_index = byte_offset; return ErrorInvalidCharacter; } case StateUnicodeDigit: { uint8_t digit; if (source[byte_offset] >= '0' && source[byte_offset] <= '9') { digit = source[byte_offset] - '0'; } else if (source[byte_offset] >= 'a' && source[byte_offset] <= 'z') { digit = source[byte_offset] - 'a' + 10; } else if (source[byte_offset] >= 'A' && source[byte_offset] <= 'Z') { digit = source[byte_offset] - 'A' + 10; } else if (source[byte_offset] == '}') { if (codepoint < 0x110000) { *result = codepoint; return ErrorNone; } else { *bad_index = byte_offset; return ErrorUnicodePointTooLarge; } } else { *bad_index = byte_offset; return ErrorInvalidCharacter; } codepoint = codepoint * 16 + digit; continue; } } } } static Buf *token_identifier_buf2(RootStruct *root_struct, TokenIndex token, bool *is_at_syntax) { Error err; const char *source = buf_ptr(root_struct->source_code); size_t byte_offset = root_struct->token_locs[token].offset; if (root_struct->token_ids[token] == TokenIdBuiltin) { byte_offset += 1; } else { assert(root_struct->token_ids[token] == TokenIdIdentifier); } assert(source[byte_offset] != '.'); // wrong token index if (source[byte_offset] == '@') { *is_at_syntax = true; size_t bad_index; Buf *str = buf_alloc(); if ((err = source_string_literal_buf(source + byte_offset + 1, str, &bad_index))) { ast_error_offset(root_struct, ErrColorAuto, token, bad_index + 1, buf_create_from_str("invalid string literal character")); } return str; } else { *is_at_syntax = false; size_t start = byte_offset; for (;; byte_offset += 1) { if (source[byte_offset] == 0) break; if ((source[byte_offset] >= 'a' && source[byte_offset] <= 'z') || (source[byte_offset] >= 'A' && source[byte_offset] <= 'Z') || (source[byte_offset] >= '0' && source[byte_offset] <= '9') || source[byte_offset] == '_') { continue; } break; } return buf_create_from_mem(source + start, byte_offset - start); } } Buf *token_identifier_buf(RootStruct *root_struct, TokenIndex token) { bool trash; return token_identifier_buf2(root_struct, token, &trash); } Buf *node_identifier_buf(AstNode *node) { bool trash; return node_identifier_buf2(node, &trash); } Buf *node_identifier_buf2(AstNode *node, bool *is_at_syntax) { assert(node->type == NodeTypeIdentifier); // Currently, stage1 runs astgen for every comptime function call, // resulting the allocation here wasting memory. As a workaround until // the code is adjusted to make astgen run only once per source node, // we memoize the result into the AST here. if (node->data.identifier.name == nullptr) { RootStruct *root_struct = node->owner->data.structure.root_struct; node->data.identifier.name = token_identifier_buf2(root_struct, node->main_token, &node->data.identifier.is_at_syntax); } *is_at_syntax = node->data.identifier.is_at_syntax; return node->data.identifier.name; } void token_number_literal_bigint(RootStruct *root_struct, BigInt *result, TokenIndex token) { const char *source = buf_ptr(root_struct->source_code); uint32_t byte_offset = root_struct->token_locs[token].offset; bigint_init_unsigned(result, 0); BigInt radix_bi; if (source[byte_offset] == '0') { byte_offset += 1; switch (source[byte_offset]) { case 'b': byte_offset += 1; bigint_init_unsigned(&radix_bi, 2); break; case 'o': byte_offset += 1; bigint_init_unsigned(&radix_bi, 8); break; case 'x': byte_offset += 1; bigint_init_unsigned(&radix_bi, 16); break; default: bigint_init_unsigned(&radix_bi, 10); break; } } else { bigint_init_unsigned(&radix_bi, 10); } BigInt digit_value_bi = {}; BigInt multiplied = {}; for (;source[byte_offset] != 0; byte_offset += 1) { uint8_t digit; if (source[byte_offset] >= '0' && source[byte_offset] <= '9') { digit = source[byte_offset] - '0'; } else if (source[byte_offset] >= 'a' && source[byte_offset] <= 'z') { digit = source[byte_offset] - 'a' + 10; } else if (source[byte_offset] >= 'A' && source[byte_offset] <= 'Z') { digit = source[byte_offset] - 'A' + 10; } else if (source[byte_offset] == '_') { continue; } else { break; } bigint_deinit(&digit_value_bi); bigint_init_unsigned(&digit_value_bi, digit); bigint_deinit(&multiplied); bigint_mul(&multiplied, result, &radix_bi); bigint_add(result, &multiplied, &digit_value_bi); } bigint_deinit(&digit_value_bi); bigint_deinit(&multiplied); bigint_deinit(&radix_bi); }
/* file: svd_dense_default_online_fpt_cpu.cpp */ /******************************************************************************* * Copyright 2014-2020 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ /* //++ // Instantiation of SVD algorithm classes. //-- */ #include "src/algorithms/svd/svd_dense_default_kernel.h" #include "src/algorithms/svd/svd_dense_default_online_impl.i" #include "src/algorithms/svd/svd_dense_default_container.h" namespace daal { namespace algorithms { namespace svd { namespace interface1 { template class OnlineContainer<DAAL_FPTYPE, daal::algorithms::svd::defaultDense, DAAL_CPU>; } namespace internal { template class SVDOnlineKernel<DAAL_FPTYPE, defaultDense, DAAL_CPU>; } } // namespace svd } // namespace algorithms } // namespace daal
// Copyright Contributors to the Open Shading Language project. // SPDX-License-Identifier: BSD-3-Clause // https://github.com/AcademySoftwareFoundation/OpenShadingLanguage #include <OSL/oslconfig.h> #include <OpenImageIO/thread.h> #include <OpenImageIO/imagebuf.h> #include <OpenImageIO/imagebufalgo_util.h> #include <OSL/oslexec.h> using namespace OSL; using namespace OSL::pvt; // avoid naming conflict with MSVC macro #ifdef RGB #undef RGB #endif OSL_NAMESPACE_ENTER bool shade_image (ShadingSystem &shadingsys, ShaderGroup &group, const ShaderGlobals *defaultsg, OIIO::ImageBuf &buf, cspan<ustring> outputs, ShadeImageLocations shadelocations, OIIO::ROI roi, OIIO::parallel_options popt) { using namespace OIIO; using namespace ImageBufAlgo; if (! roi.defined()) roi = buf.roi(); if (buf.spec().format != TypeDesc::FLOAT) { #if OIIO_VERSION >= 20300 buf.errorfmt("Cannot OSL::shade_image() into a {} buffer, float is required", buf.spec().format); #else buf.error("Cannot OSL::shade_image() into a %s buffer, float is required", buf.spec().format); #endif return false; } parallel_image (roi, popt, [&](OIIO::ROI roi){ // Request an OSL::PerThreadInfo for this thread. OSL::PerThreadInfo *thread_info = shadingsys.create_thread_info(); // Request a shading context so that we can execute the shader. // We could get_context/release_context for each shading point, // but to save overhead, it's more efficient to reuse a context // within a thread. ShadingContext *ctx = shadingsys.get_context (thread_info); // Ensure the group has already been optimized shadingsys.optimize_group (&group, ctx); Matrix44 Mshad, Mobj; // just let these be identity for now OIIO::ROI roi_full = buf.roi_full(); int xres = roi_full.width(); int yres = roi_full.height(); int zres = roi_full.depth(); // Gather some information about the outputs once, rather than for // each pixel. const ShaderSymbol **output_sym = OIIO_ALLOCA(const ShaderSymbol*, outputs.size()); TypeDesc *output_type = OIIO_ALLOCA(TypeDesc, outputs.size()); int *output_nchans = OIIO_ALLOCA(int, outputs.size()); for (int i = 0; i < int(outputs.size()); ++i) { output_sym[i] = shadingsys.find_symbol (group, outputs[i]); output_type[i] = shadingsys.symbol_typedesc (output_sym[i]); output_nchans[i] = output_type[i].numelements() * output_type[i].aggregate; } // Set up shader globals and a little test grid of points to shade. // Note that some of the fields can be set up once and used for all of // the shades. Others need to be changed for every point shaded. // // Note that because we are shading a single object that is a flat image // plane, a lot of this is simplified. In a real 3D render, most of // these fields would need to be reset for every shade. ShaderGlobals sg; if (defaultsg) { // If the caller passed a default SG template, use it to initialize // the sg and in particular to set all the constant fields. memcpy ((char *)&sg, (const char*)defaultsg, sizeof(ShaderGlobals)); } else { // No SG template was passed, so set up reasonable defaults. memset ((char *)&sg, 0, sizeof(ShaderGlobals)); // Set "shader" space to be Mshad. In a real renderer, this may be // different for each shader group. sg.shader2common = OSL::TransformationPtr (&Mshad); // Set "object" space to be Mobj. In a real renderer, this may be // different for each object. sg.object2common = OSL::TransformationPtr (&Mobj); // Just make it look like all shades are the result of 'raytype' rays. sg.raytype = 0; // default ray type // Set the surface area of the patch to 1 (which it is). This is // only used for light shaders that call the surfacearea() function. sg.surfacearea = 1; // Derivs are constant across the image if (shadelocations == ShadePixelCenters) { sg.dudx = 1.0f / xres; // sg.dudy is already 0 sg.dvdy = 1.0f / yres; // sg.dvdx is already 0 } else { sg.dudx = 1.0f / std::max(1,(xres-1)); sg.dvdy = 1.0f / std::max(1,(yres-1)); } // Derivatives with respect to x,y sg.dPdx = Vec3 (1.0f, 0.0f, 0.0f); sg.dPdy = Vec3 (0.0f, 1.0f, 0.0f); sg.dPdz = Vec3 (0.0f, 0.0f, 1.0f); // Tangents of P with respect to surface u,v sg.dPdu = Vec3 (xres, 0.0f, 0.0f); sg.dPdv = Vec3 (0.0f, yres, 0.0f); sg.dPdz = Vec3 (0.0f, 0.0f, zres); // That also implies that our normal points to (0,0,1) sg.N = Vec3 (0, 0, 1); sg.Ng = Vec3 (0, 0, 1); // In our SimpleRenderer, the "renderstate" itself just a pointer to // the ShaderGlobals. // sg.renderstate = &sg; } // Loop over all pixels in the image (in x and y)... for (OIIO::ImageBuf::Iterator<float> p (buf, roi); ! p.done(); ++p) { // Set the shader globals that vary from point to pixel to pixel sg.P = Vec3 (p.x(), p.y(), p.z()); if (shadelocations == ShadePixelCenters) { sg.u = float(p.x()-roi_full.xbegin+0.5f) / xres; sg.v = float(p.y()-roi_full.ybegin+0.5f) / yres; // float w = float(p.z()-roi_full.zbegin+0.5f) / zres; } else { sg.u = (xres == 1) ? 0.5f : float(p.x()-roi_full.xbegin) / (xres - 1); sg.v = (yres == 1) ? 0.5f : float(p.y()-roi_full.ybegin) / (yres - 1); // float w = (zres == 1) ? 0.5f : float(p.z()-roi_full.zbegin) / (zres - 1); } // Actually run the shader for this point shadingsys.execute (*ctx, group, sg); // Save all the designated outputs. int chan = 0; for (int i = 0; i < int(outputs.size()); ++i) { const void *data = shadingsys.symbol_address (*ctx, output_sym[i]); if (!data) continue; // Skip if symbol isn't found TypeDesc t = output_type[i]; int tvals = output_nchans[i]; if (chan+tvals > buf.nchannels()) break; if (t.basetype == TypeDesc::FLOAT) { for (int c = 0; c < tvals; ++c) p[chan++] = ((const float *)data)[c]; } else if (t.basetype == TypeDesc::INT) { for (int c = 0; c < int(t.numelements())*t.aggregate; ++c) p[chan++] = ((const int *)data)[c]; } // N.B. Drop any outputs that aren't float- or int-based } } // We're done shading with this context. shadingsys.release_context (ctx); shadingsys.destroy_thread_info (thread_info); }); // end of parallel_image return true; } OSL_NAMESPACE_EXIT
//===----------------------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // <regex> // template <class charT, class traits = regex_traits<charT>> class basic_regex; // basic_regex(); #include <regex> #include <cassert> #include "test_macros.h" template <class CharT> void test() { std::basic_regex<CharT> r; assert(r.flags() == 0); assert(r.mark_count() == 0); } int main(int, char**) { test<char>(); test<wchar_t>(); return 0; }
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <utility> #include <vector> #include "base/callback.h" #include "base/callback_helpers.h" #include "base/containers/contains.h" #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/files/scoped_temp_dir.h" #include "base/path_service.h" #include "base/run_loop.h" #include "base/test/bind.h" #include "base/test/scoped_feature_list.h" #include "build/chromeos_buildflags.h" #include "cc/test/pixel_comparator.h" #include "cc/test/pixel_test_utils.h" #include "chrome/browser/apps/app_service/app_icon/app_icon_factory.h" #include "chrome/browser/extensions/chrome_app_icon.h" #include "chrome/browser/web_applications/test/fake_web_app_registry_controller.h" #include "chrome/browser/web_applications/test/test_file_utils.h" #include "chrome/browser/web_applications/test/web_app_icon_test_utils.h" #include "chrome/browser/web_applications/test/web_app_test_utils.h" #include "chrome/browser/web_applications/web_app.h" #include "chrome/browser/web_applications/web_app_constants.h" #include "chrome/browser/web_applications/web_app_helpers.h" #include "chrome/browser/web_applications/web_app_icon_generator.h" #include "chrome/browser/web_applications/web_app_icon_manager.h" #include "chrome/browser/web_applications/web_app_provider.h" #include "chrome/browser/web_applications/web_app_registrar.h" #include "chrome/browser/web_applications/web_app_registry_update.h" #include "chrome/browser/web_applications/web_app_sync_bridge.h" #include "chrome/test/base/chrome_render_view_host_test_harness.h" #include "chrome/test/base/testing_profile.h" #include "components/services/app_service/public/cpp/icon_types.h" #include "content/public/test/browser_task_environment.h" #include "extensions/grit/extensions_browser_resources.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/base/layout.h" #include "ui/base/resource/resource_bundle.h" #include "ui/gfx/codec/png_codec.h" #include "ui/gfx/image/image_skia_operations.h" #include "ui/gfx/image/image_unittest_util.h" #if BUILDFLAG(IS_CHROMEOS_ASH) #include "ash/constants/ash_features.h" #include "chrome/browser/apps/icon_standardizer.h" #include "chrome/browser/ash/arc/icon_decode_request.h" #include "chrome/browser/ui/app_list/md_icon_normalizer.h" #include "chrome/common/chrome_features.h" #include "chrome/grit/chrome_unscaled_resources.h" #include "components/arc/mojom/intent_helper.mojom.h" #endif namespace { const int kSizeInDip = 64; void EnsureRepresentationsLoaded(gfx::ImageSkia& output_image_skia) { for (auto scale_factor : ui::GetSupportedResourceScaleFactors()) { // Force the icon to be loaded. output_image_skia.GetRepresentation( ui::GetScaleForResourceScaleFactor(scale_factor)); } } void LoadDefaultIcon(gfx::ImageSkia& output_image_skia) { base::RunLoop run_loop; apps::LoadIconFromResource( apps::IconType::kUncompressed, kSizeInDip, IDR_APP_DEFAULT_ICON, false /* is_placeholder_icon */, apps::IconEffects::kNone, base::BindOnce( [](gfx::ImageSkia* image, base::OnceClosure load_app_icon_callback, apps::IconValuePtr icon) { *image = icon->uncompressed; std::move(load_app_icon_callback).Run(); }, &output_image_skia, run_loop.QuitClosure())); run_loop.Run(); EnsureRepresentationsLoaded(output_image_skia); } void VerifyIcon(const gfx::ImageSkia& src, const gfx::ImageSkia& dst) { ASSERT_FALSE(src.isNull()); ASSERT_FALSE(dst.isNull()); const std::vector<ui::ResourceScaleFactor>& scale_factors = ui::GetSupportedResourceScaleFactors(); ASSERT_EQ(2U, scale_factors.size()); for (auto& scale_factor : scale_factors) { const float scale = ui::GetScaleForResourceScaleFactor(scale_factor); ASSERT_TRUE(src.HasRepresentation(scale)); ASSERT_TRUE(dst.HasRepresentation(scale)); ASSERT_TRUE( gfx::test::AreBitmapsEqual(src.GetRepresentation(scale).GetBitmap(), dst.GetRepresentation(scale).GetBitmap())); } } void VerifyCompressedIcon(const std::vector<uint8_t>& src_data, const apps::IconValue& icon) { ASSERT_EQ(apps::IconType::kCompressed, icon.icon_type); ASSERT_FALSE(icon.is_placeholder_icon); ASSERT_FALSE(icon.compressed.empty()); ASSERT_EQ(src_data, icon.compressed); } } // namespace class AppIconFactoryTest : public testing::Test { public: base::FilePath GetPath() { return tmp_dir_.GetPath().Append( base::FilePath::FromUTF8Unsafe("icon.file")); } void SetUp() override { ASSERT_TRUE(tmp_dir_.CreateUniqueTempDir()); } void RunLoadIconFromFileWithFallback(apps::IconValuePtr fallback_response, bool* callback_called, bool* fallback_called, apps::IconValuePtr* result) { *callback_called = false; *fallback_called = false; apps::LoadIconFromFileWithFallback( apps::IconType::kUncompressed, 200, GetPath(), apps::IconEffects::kNone, base::BindOnce( [](bool* called, apps::IconValuePtr* result, base::OnceClosure quit, apps::IconValuePtr icon) { *called = true; *result = std::move(icon); std::move(quit).Run(); }, base::Unretained(callback_called), base::Unretained(result), run_loop_.QuitClosure()), base::BindOnce( [](bool* called, apps::IconValuePtr response, apps::LoadIconCallback callback) { *called = true; std::move(callback).Run(std::move(response)); }, base::Unretained(fallback_called), std::move(fallback_response))); run_loop_.Run(); } std::string GetPngData(const std::string file_name) { base::FilePath base_path; std::string png_data_as_string; CHECK(base::PathService::Get(base::DIR_SOURCE_ROOT, &base_path)); base::FilePath icon_file_path = base_path.AppendASCII("components") .AppendASCII("test") .AppendASCII("data") .AppendASCII("arc") .AppendASCII(file_name); CHECK(base::PathExists(icon_file_path)); CHECK(base::ReadFileToString(icon_file_path, &png_data_as_string)); return png_data_as_string; } void RunLoadIconFromCompressedData(const std::string png_data_as_string, apps::IconType icon_type, apps::IconEffects icon_effects, apps::IconValuePtr& output_icon) { apps::LoadIconFromCompressedData( icon_type, kSizeInDip, icon_effects, png_data_as_string, base::BindOnce( [](apps::IconValuePtr* result, base::OnceClosure load_app_icon_callback, apps::IconValuePtr icon) { *result = std::move(icon); std::move(load_app_icon_callback).Run(); }, &output_icon, run_loop_.QuitClosure())); run_loop_.Run(); ASSERT_TRUE(output_icon); ASSERT_EQ(icon_type, output_icon->icon_type); ASSERT_FALSE(output_icon->is_placeholder_icon); ASSERT_FALSE(output_icon->uncompressed.isNull()); EnsureRepresentationsLoaded(output_icon->uncompressed); } void GenerateIconFromCompressedData(const std::string& compressed_icon, float scale, gfx::ImageSkia& output_image_skia) { std::vector<uint8_t> compressed_data(compressed_icon.begin(), compressed_icon.end()); SkBitmap decoded; ASSERT_TRUE(gfx::PNGCodec::Decode(compressed_data.data(), compressed_data.size(), &decoded)); output_image_skia = gfx::ImageSkia::CreateFromBitmap(decoded, scale); #if BUILDFLAG(IS_CHROMEOS_ASH) output_image_skia = apps::CreateStandardIconImage(output_image_skia); #endif EnsureRepresentationsLoaded(output_image_skia); } #if BUILDFLAG(IS_CHROMEOS_ASH) apps::IconValuePtr RunLoadIconFromResource(apps::IconType icon_type, apps::IconEffects icon_effects) { bool is_placeholder_icon = false; apps::IconValuePtr icon_value; apps::LoadIconFromResource( icon_type, kSizeInDip, IDR_LOGO_CROSTINI_DEFAULT, is_placeholder_icon, icon_effects, base::BindLambdaForTesting([&](apps::IconValuePtr icon) { icon_value = std::move(icon); run_loop_.Quit(); })); run_loop_.Run(); return icon_value; } void GenerateCrostiniPenguinIcon(gfx::ImageSkia& output_image_skia) { output_image_skia = *(ui::ResourceBundle::GetSharedInstance().GetImageSkiaNamed( IDR_LOGO_CROSTINI_DEFAULT)); output_image_skia = gfx::ImageSkiaOperations::CreateResizedImage( output_image_skia, skia::ImageOperations::RESIZE_BEST, gfx::Size(kSizeInDip, kSizeInDip)); EnsureRepresentationsLoaded(output_image_skia); } void GenerateCrostiniPenguinCompressedIcon(std::vector<uint8_t>& output) { base::StringPiece data = ui::ResourceBundle::GetSharedInstance().GetRawDataResource( IDR_LOGO_CROSTINI_DEFAULT); output = std::vector<uint8_t>(data.begin(), data.end()); } #endif protected: content::BrowserTaskEnvironment task_env_{}; base::ScopedTempDir tmp_dir_{}; base::RunLoop run_loop_{}; }; TEST_F(AppIconFactoryTest, LoadFromFileSuccess) { gfx::ImageSkia image = gfx::ImageSkia(gfx::ImageSkiaRep(gfx::Size(20, 20), 0.0f)); const SkBitmap* bitmap = image.bitmap(); cc::WritePNGFile(*bitmap, GetPath(), /*discard_transparency=*/false); auto fallback_response = std::make_unique<apps::IconValue>(); auto result = std::make_unique<apps::IconValue>(); bool callback_called, fallback_called; RunLoadIconFromFileWithFallback(std::move(fallback_response), &callback_called, &fallback_called, &result); EXPECT_TRUE(callback_called); EXPECT_FALSE(fallback_called); ASSERT_TRUE(result); EXPECT_TRUE( cc::MatchesBitmap(*bitmap, *result->uncompressed.bitmap(), cc::ExactPixelComparator(/*discard_alpha=*/false))); } TEST_F(AppIconFactoryTest, LoadFromFileFallback) { auto expect_image = gfx::ImageSkia(gfx::ImageSkiaRep(gfx::Size(20, 20), 0.0f)); auto fallback_response = std::make_unique<apps::IconValue>(); fallback_response->icon_type = apps::IconType::kUncompressed; // Create a non-null image so we can check if we get the same image back. fallback_response->uncompressed = expect_image; auto result = std::make_unique<apps::IconValue>(); bool callback_called, fallback_called; RunLoadIconFromFileWithFallback(std::move(fallback_response), &callback_called, &fallback_called, &result); EXPECT_TRUE(callback_called); EXPECT_TRUE(fallback_called); ASSERT_TRUE(result); EXPECT_TRUE(result->uncompressed.BackedBySameObjectAs(expect_image)); } TEST_F(AppIconFactoryTest, LoadFromFileFallbackFailure) { auto fallback_response = std::make_unique<apps::IconValue>(); auto result = std::make_unique<apps::IconValue>(); bool callback_called, fallback_called; RunLoadIconFromFileWithFallback(std::move(fallback_response), &callback_called, &fallback_called, &result); EXPECT_TRUE(callback_called); EXPECT_TRUE(fallback_called); ASSERT_TRUE(result); } TEST_F(AppIconFactoryTest, LoadFromFileFallbackDoesNotReturn) { auto result = std::make_unique<apps::IconValue>(); bool callback_called = false, fallback_called = false; apps::LoadIconFromFileWithFallback( apps::IconType::kUncompressed, 200, GetPath(), apps::IconEffects::kNone, base::BindLambdaForTesting([&](apps::IconValuePtr icon) { callback_called = true; result = std::move(icon); run_loop_.Quit(); }), base::BindLambdaForTesting([&](apps::LoadIconCallback callback) { fallback_called = true; // Drop the callback here, like a buggy fallback might. })); run_loop_.Run(); EXPECT_TRUE(callback_called); EXPECT_TRUE(fallback_called); ASSERT_TRUE(result); } TEST_F(AppIconFactoryTest, LoadIconFromCompressedData) { std::string png_data_as_string = GetPngData("icon_100p.png"); auto icon_type = apps::IconType::kStandard; auto icon_effects = apps::IconEffects::kCrOsStandardIcon; auto result = std::make_unique<apps::IconValue>(); RunLoadIconFromCompressedData(png_data_as_string, icon_type, icon_effects, result); float scale = 1.0; gfx::ImageSkia src_image_skia; GenerateIconFromCompressedData(png_data_as_string, scale, src_image_skia); ASSERT_FALSE(src_image_skia.isNull()); ASSERT_TRUE(src_image_skia.HasRepresentation(scale)); ASSERT_TRUE(result->uncompressed.HasRepresentation(scale)); ASSERT_TRUE(gfx::test::AreBitmapsEqual( src_image_skia.GetRepresentation(scale).GetBitmap(), result->uncompressed.GetRepresentation(scale).GetBitmap())); } #if BUILDFLAG(IS_CHROMEOS_ASH) TEST_F(AppIconFactoryTest, LoadCrostiniPenguinIcon) { auto icon_type = apps::IconType::kStandard; auto icon_effects = apps::IconEffects::kCrOsStandardIcon; auto result = RunLoadIconFromResource(icon_type, icon_effects); ASSERT_TRUE(result); EXPECT_EQ(icon_type, result->icon_type); EXPECT_FALSE(result->is_placeholder_icon); EnsureRepresentationsLoaded(result->uncompressed); gfx::ImageSkia src_image_skia; GenerateCrostiniPenguinIcon(src_image_skia); VerifyIcon(src_image_skia, result->uncompressed); } TEST_F(AppIconFactoryTest, LoadCrostiniPenguinCompressedIcon) { auto icon_effects = apps::IconEffects::kNone; icon_effects = apps::IconEffects::kCrOsStandardIcon; auto result = RunLoadIconFromResource(apps::IconType::kCompressed, icon_effects); std::vector<uint8_t> src_data; GenerateCrostiniPenguinCompressedIcon(src_data); VerifyCompressedIcon(src_data, *result); } TEST_F(AppIconFactoryTest, ArcNonAdaptiveIconToImageSkia) { arc::IconDecodeRequest::DisableSafeDecodingForTesting(); std::string png_data_as_string = GetPngData("icon_100p.png"); arc::mojom::RawIconPngDataPtr icon = arc::mojom::RawIconPngData::New( false, std::vector<uint8_t>(png_data_as_string.begin(), png_data_as_string.end()), std::vector<uint8_t>(), std::vector<uint8_t>()); bool callback_called = false; apps::ArcRawIconPngDataToImageSkia( std::move(icon), 100, base::BindOnce( [](bool* called, base::OnceClosure quit, const gfx::ImageSkia& image) { if (!image.isNull()) { *called = true; } std::move(quit).Run(); }, base::Unretained(&callback_called), run_loop_.QuitClosure())); run_loop_.Run(); EXPECT_TRUE(callback_called); } TEST_F(AppIconFactoryTest, ArcAdaptiveIconToImageSkia) { arc::IconDecodeRequest::DisableSafeDecodingForTesting(); std::string png_data_as_string = GetPngData("icon_100p.png"); arc::mojom::RawIconPngDataPtr icon = arc::mojom::RawIconPngData::New( true, std::vector<uint8_t>(), std::vector<uint8_t>(png_data_as_string.begin(), png_data_as_string.end()), std::vector<uint8_t>(png_data_as_string.begin(), png_data_as_string.end())); bool callback_called = false; apps::ArcRawIconPngDataToImageSkia( std::move(icon), 100, base::BindOnce( [](bool* called, base::OnceClosure quit, const gfx::ImageSkia& image) { if (!image.isNull()) { *called = true; } std::move(quit).Run(); }, base::Unretained(&callback_called), run_loop_.QuitClosure())); run_loop_.Run(); EXPECT_TRUE(callback_called); } TEST_F(AppIconFactoryTest, ArcActivityIconsToImageSkias) { arc::IconDecodeRequest::DisableSafeDecodingForTesting(); std::string png_data_as_string = GetPngData("icon_100p.png"); std::vector<arc::mojom::ActivityIconPtr> icons; icons.emplace_back( arc::mojom::ActivityIcon::New(arc::mojom::ActivityName::New("p0", "a0"), 100, 100, std::vector<uint8_t>())); icons.emplace_back(arc::mojom::ActivityIcon::New( arc::mojom::ActivityName::New("p0", "a0"), 100, 100, std::vector<uint8_t>(), arc::mojom::RawIconPngData::New( false, std::vector<uint8_t>(png_data_as_string.begin(), png_data_as_string.end()), std::vector<uint8_t>(), std::vector<uint8_t>()))); icons.emplace_back(arc::mojom::ActivityIcon::New( arc::mojom::ActivityName::New("p0", "a0"), 201, 201, std::vector<uint8_t>(), arc::mojom::RawIconPngData::New( false, std::vector<uint8_t>(png_data_as_string.begin(), png_data_as_string.end()), std::vector<uint8_t>(), std::vector<uint8_t>()))); icons.emplace_back(arc::mojom::ActivityIcon::New( arc::mojom::ActivityName::New("p1", "a1"), 100, 100, std::vector<uint8_t>(), arc::mojom::RawIconPngData::New( true, std::vector<uint8_t>(), std::vector<uint8_t>(png_data_as_string.begin(), png_data_as_string.end()), std::vector<uint8_t>(png_data_as_string.begin(), png_data_as_string.end())))); std::vector<gfx::ImageSkia> result; bool callback_called = false; apps::ArcActivityIconsToImageSkias( icons, base::BindOnce( [](bool* called, std::vector<gfx::ImageSkia>* result, base::OnceClosure quit, const std::vector<gfx::ImageSkia>& images) { *called = true; for (auto image : images) { result->emplace_back(image); } std::move(quit).Run(); }, base::Unretained(&callback_called), base::Unretained(&result), run_loop_.QuitClosure())); run_loop_.Run(); EXPECT_TRUE(callback_called); EXPECT_EQ(4U, result.size()); EXPECT_TRUE(result[0].isNull()); EXPECT_FALSE(result[1].isNull()); EXPECT_TRUE(result[2].isNull()); EXPECT_FALSE(result[3].isNull()); for (const auto& icon : result) { EXPECT_TRUE(icon.IsThreadSafe()); } } #endif class WebAppIconFactoryTest : public ChromeRenderViewHostTestHarness { public: WebAppIconFactoryTest() { #if BUILDFLAG(IS_CHROMEOS_ASH) scoped_feature_list_.InitWithFeatures( {}, {features::kWebAppsCrosapi, chromeos::features::kLacrosPrimary}); #endif } ~WebAppIconFactoryTest() override = default; void SetUp() override { ChromeRenderViewHostTestHarness::SetUp(); #if BUILDFLAG(IS_CHROMEOS_LACROS) profile()->SetIsMainProfile(true); #endif // BUILDFLAG(IS_CHROMEOS_LACROS) web_app_provider_ = web_app::WebAppProvider::GetForWebApps(profile()); ASSERT_TRUE(web_app_provider_); base::RunLoop run_loop; web_app_provider_->sync_bridge().Init(run_loop.QuitClosure()); run_loop.Run(); icon_manager_ = static_cast<web_app::WebAppIconManager*>( &(web_app_provider_->icon_manager())); ASSERT_TRUE(icon_manager_); sync_bridge_ = &web_app_provider_->sync_bridge(); } void RegisterApp(std::unique_ptr<web_app::WebApp> web_app) { std::unique_ptr<web_app::WebAppRegistryUpdate> update = sync_bridge().BeginUpdate(); update->CreateApp(std::move(web_app)); sync_bridge().CommitUpdate(std::move(update), base::DoNothing()); } void WriteIcons(const std::string& app_id, const std::vector<IconPurpose>& purposes, const std::vector<int>& sizes_px, const std::vector<SkColor>& colors) { ASSERT_EQ(sizes_px.size(), colors.size()); ASSERT_TRUE(!purposes.empty()); IconBitmaps icon_bitmaps; for (size_t i = 0; i < sizes_px.size(); ++i) { if (base::Contains(purposes, IconPurpose::ANY)) { web_app::AddGeneratedIcon(&icon_bitmaps.any, sizes_px[i], colors[i]); } if (base::Contains(purposes, IconPurpose::MASKABLE)) { web_app::AddGeneratedIcon(&icon_bitmaps.maskable, sizes_px[i], colors[i]); } } base::RunLoop run_loop; icon_manager_->WriteData(app_id, std::move(icon_bitmaps), {}, {}, base::BindLambdaForTesting([&](bool success) { EXPECT_TRUE(success); run_loop.Quit(); })); run_loop.Run(); } void GenerateWebAppIcon(const std::string& app_id, IconPurpose purpose, const std::vector<int>& sizes_px, apps::ScaleToSize scale_to_size_in_px, gfx::ImageSkia& output_image_skia) { base::RunLoop run_loop; icon_manager().ReadIcons( app_id, purpose, sizes_px, base::BindOnce( [](gfx::ImageSkia* image_skia, int size_in_dip, apps::ScaleToSize scale_to_size_in_px, base::OnceClosure load_app_icon_callback, std::map<SquareSizePx, SkBitmap> icon_bitmaps) { for (auto it : scale_to_size_in_px) { int icon_size_in_px = gfx::ScaleToFlooredSize(gfx::Size(size_in_dip, size_in_dip), it.first) .width(); SkBitmap bitmap = icon_bitmaps[it.second]; if (bitmap.width() != icon_size_in_px) { bitmap = skia::ImageOperations::Resize( bitmap, skia::ImageOperations::RESIZE_LANCZOS3, icon_size_in_px, icon_size_in_px); } image_skia->AddRepresentation( gfx::ImageSkiaRep(bitmap, it.first)); } std::move(load_app_icon_callback).Run(); }, &output_image_skia, kSizeInDip, scale_to_size_in_px, run_loop.QuitClosure())); run_loop.Run(); extensions::ChromeAppIcon::ResizeFunction resize_function; #if BUILDFLAG(IS_CHROMEOS_ASH) if (purpose == IconPurpose::ANY) { output_image_skia = apps::CreateStandardIconImage(output_image_skia); } if (purpose == IconPurpose::MASKABLE) { output_image_skia = apps::ApplyBackgroundAndMask(output_image_skia); } #endif extensions::ChromeAppIcon::ApplyEffects( kSizeInDip, resize_function, true /* app_launchable */, true /* from_bookmark */, extensions::ChromeAppIcon::Badge::kNone, &output_image_skia); EnsureRepresentationsLoaded(output_image_skia); } void GenerateWebAppCompressedIcon(const std::string& app_id, IconPurpose purpose, const std::vector<int>& sizes_px, apps::ScaleToSize scale_to_size_in_px, std::vector<uint8_t>& result) { gfx::ImageSkia image_skia; GenerateWebAppIcon(app_id, purpose, sizes_px, scale_to_size_in_px, image_skia); const float scale = 1.0; const gfx::ImageSkiaRep& image_skia_rep = image_skia.GetRepresentation(scale); ASSERT_EQ(image_skia_rep.scale(), scale); const SkBitmap& bitmap = image_skia_rep.GetBitmap(); const bool discard_transparency = false; ASSERT_TRUE(gfx::PNGCodec::EncodeBGRASkBitmap(bitmap, discard_transparency, &result)); } void LoadIconFromWebApp(const std::string& app_id, apps::IconEffects icon_effects, gfx::ImageSkia& output_image_skia) { base::RunLoop run_loop; auto icon_type = apps::IconType::kUncompressed; #if BUILDFLAG(IS_CHROMEOS_ASH) icon_type = apps::IconType::kStandard; #endif apps::LoadIconFromWebApp( profile(), icon_type, kSizeInDip, app_id, icon_effects, base::BindOnce( [](gfx::ImageSkia* image, base::OnceClosure load_app_icon_callback, apps::IconValuePtr icon) { *image = icon->uncompressed; std::move(load_app_icon_callback).Run(); }, &output_image_skia, run_loop.QuitClosure())); run_loop.Run(); EnsureRepresentationsLoaded(output_image_skia); } apps::IconValuePtr LoadCompressedIconBlockingFromWebApp( const std::string& app_id, apps::IconEffects icon_effects) { base::RunLoop run_loop; apps::IconValuePtr icon_value; apps::LoadIconFromWebApp( profile(), apps::IconType::kCompressed, kSizeInDip, app_id, icon_effects, base::BindLambdaForTesting([&](apps::IconValuePtr icon) { icon_value = std::move(icon); run_loop.Quit(); })); run_loop.Run(); return icon_value; } web_app::WebAppIconManager& icon_manager() { return *icon_manager_; } web_app::WebAppProvider& web_app_provider() { return *web_app_provider_; } web_app::WebAppSyncBridge& sync_bridge() { return *sync_bridge_; } private: base::test::ScopedFeatureList scoped_feature_list_; web_app::WebAppProvider* web_app_provider_; web_app::WebAppIconManager* icon_manager_; web_app::WebAppSyncBridge* sync_bridge_; }; TEST_F(WebAppIconFactoryTest, LoadNonMaskableIcon) { auto web_app = web_app::test::CreateWebApp(); const std::string app_id = web_app->app_id(); const int kIconSize1 = 96; const int kIconSize2 = 256; const std::vector<int> sizes_px{kIconSize1, kIconSize2}; const std::vector<SkColor> colors{SK_ColorGREEN, SK_ColorYELLOW}; WriteIcons(app_id, {IconPurpose::ANY}, sizes_px, colors); web_app->SetDownloadedIconSizes(IconPurpose::ANY, sizes_px); RegisterApp(std::move(web_app)); ASSERT_TRUE(icon_manager().HasIcons(app_id, IconPurpose::ANY, sizes_px)); gfx::ImageSkia src_image_skia; GenerateWebAppIcon(app_id, IconPurpose::ANY, sizes_px, {{1.0, kIconSize1}, {2.0, kIconSize2}}, src_image_skia); gfx::ImageSkia dst_image_skia; apps::IconEffects icon_effect = apps::IconEffects::kRoundCorners; #if BUILDFLAG(IS_CHROMEOS_ASH) icon_effect |= apps::IconEffects::kCrOsStandardIcon; #endif LoadIconFromWebApp(app_id, icon_effect, dst_image_skia); VerifyIcon(src_image_skia, dst_image_skia); } TEST_F(WebAppIconFactoryTest, LoadNonMaskableCompressedIcon) { auto web_app = web_app::test::CreateWebApp(); const std::string app_id = web_app->app_id(); const int kIconSize1 = 96; const int kIconSize2 = 256; const std::vector<int> sizes_px{kIconSize1, kIconSize2}; const std::vector<SkColor> colors{SK_ColorGREEN, SK_ColorYELLOW}; WriteIcons(app_id, {IconPurpose::ANY}, sizes_px, colors); web_app->SetDownloadedIconSizes(IconPurpose::ANY, sizes_px); RegisterApp(std::move(web_app)); ASSERT_TRUE(icon_manager().HasIcons(app_id, IconPurpose::ANY, sizes_px)); std::vector<uint8_t> src_data; GenerateWebAppCompressedIcon(app_id, IconPurpose::ANY, sizes_px, {{1.0, kIconSize1}, {2.0, kIconSize2}}, src_data); apps::IconEffects icon_effect = apps::IconEffects::kRoundCorners; #if BUILDFLAG(IS_CHROMEOS_ASH) icon_effect |= apps::IconEffects::kCrOsStandardIcon; #endif auto icon = LoadCompressedIconBlockingFromWebApp(app_id, icon_effect); VerifyCompressedIcon(src_data, *icon); } TEST_F(WebAppIconFactoryTest, LoadMaskableIcon) { auto web_app = web_app::test::CreateWebApp(); const std::string app_id = web_app->app_id(); const int kIconSize1 = 128; const int kIconSize2 = 256; const std::vector<int> sizes_px{kIconSize1, kIconSize2}; const std::vector<SkColor> colors{SK_ColorGREEN, SK_ColorYELLOW}; WriteIcons(app_id, {IconPurpose::ANY, IconPurpose::MASKABLE}, sizes_px, colors); web_app->SetDownloadedIconSizes(IconPurpose::ANY, {kIconSize1}); web_app->SetDownloadedIconSizes(IconPurpose::MASKABLE, {kIconSize2}); RegisterApp(std::move(web_app)); gfx::ImageSkia src_image_skia; gfx::ImageSkia dst_image_skia; #if BUILDFLAG(IS_CHROMEOS_ASH) ASSERT_TRUE( icon_manager().HasIcons(app_id, IconPurpose::MASKABLE, {kIconSize2})); GenerateWebAppIcon(app_id, IconPurpose::MASKABLE, {kIconSize2}, {{1.0, kIconSize2}, {2.0, kIconSize2}}, src_image_skia); LoadIconFromWebApp(app_id, apps::IconEffects::kRoundCorners | apps::IconEffects::kCrOsStandardBackground | apps::IconEffects::kCrOsStandardMask, dst_image_skia); VerifyIcon(src_image_skia, dst_image_skia); return; #endif ASSERT_TRUE(icon_manager().HasIcons(app_id, IconPurpose::ANY, {kIconSize1})); GenerateWebAppIcon(app_id, IconPurpose::ANY, {kIconSize1}, {{1.0, kIconSize1}, {2.0, kIconSize1}}, src_image_skia); LoadIconFromWebApp(app_id, apps::IconEffects::kRoundCorners, dst_image_skia); VerifyIcon(src_image_skia, dst_image_skia); } TEST_F(WebAppIconFactoryTest, LoadMaskableCompressedIcon) { auto web_app = web_app::test::CreateWebApp(); const std::string app_id = web_app->app_id(); const int kIconSize1 = 128; const int kIconSize2 = 256; const std::vector<int> sizes_px{kIconSize1, kIconSize2}; const std::vector<SkColor> colors{SK_ColorGREEN, SK_ColorYELLOW}; WriteIcons(app_id, {IconPurpose::ANY, IconPurpose::MASKABLE}, sizes_px, colors); web_app->SetDownloadedIconSizes(IconPurpose::ANY, {kIconSize1}); web_app->SetDownloadedIconSizes(IconPurpose::MASKABLE, {kIconSize2}); RegisterApp(std::move(web_app)); std::vector<uint8_t> src_data; apps::IconEffects icon_effect = apps::IconEffects::kRoundCorners; apps::IconValuePtr icon; #if BUILDFLAG(IS_CHROMEOS_ASH) icon_effect |= apps::IconEffects::kCrOsStandardBackground | apps::IconEffects::kCrOsStandardMask; ASSERT_TRUE( icon_manager().HasIcons(app_id, IconPurpose::MASKABLE, {kIconSize2})); GenerateWebAppCompressedIcon(app_id, IconPurpose::MASKABLE, {kIconSize2}, {{1.0, kIconSize2}, {2.0, kIconSize2}}, src_data); icon = LoadCompressedIconBlockingFromWebApp(app_id, icon_effect); VerifyCompressedIcon(src_data, *icon); return; #endif ASSERT_TRUE(icon_manager().HasIcons(app_id, IconPurpose::ANY, {kIconSize1})); GenerateWebAppCompressedIcon(app_id, IconPurpose::ANY, {kIconSize1}, {{1.0, kIconSize1}, {2.0, kIconSize1}}, src_data); icon = LoadCompressedIconBlockingFromWebApp(app_id, icon_effect); VerifyCompressedIcon(src_data, *icon); } TEST_F(WebAppIconFactoryTest, LoadNonMaskableIconWithMaskableIcon) { auto web_app = web_app::test::CreateWebApp(); const std::string app_id = web_app->app_id(); const int kIconSize1 = 96; const int kIconSize2 = 128; const std::vector<int> sizes_px{kIconSize1, kIconSize2}; const std::vector<SkColor> colors{SK_ColorGREEN, SK_ColorYELLOW}; WriteIcons(app_id, {IconPurpose::ANY, IconPurpose::MASKABLE}, sizes_px, colors); web_app->SetDownloadedIconSizes(IconPurpose::MASKABLE, {kIconSize1}); web_app->SetDownloadedIconSizes(IconPurpose::ANY, {kIconSize2}); RegisterApp(std::move(web_app)); ASSERT_TRUE(icon_manager().HasIcons(app_id, IconPurpose::ANY, {kIconSize2})); gfx::ImageSkia src_image_skia; GenerateWebAppIcon(app_id, IconPurpose::ANY, {kIconSize2}, {{1.0, kIconSize2}, {2.0, kIconSize2}}, src_image_skia); gfx::ImageSkia dst_image_skia; apps::IconEffects icon_effect = apps::IconEffects::kRoundCorners; #if BUILDFLAG(IS_CHROMEOS_ASH) icon_effect |= apps::IconEffects::kCrOsStandardIcon; #endif LoadIconFromWebApp(app_id, icon_effect, dst_image_skia); VerifyIcon(src_image_skia, dst_image_skia); } TEST_F(WebAppIconFactoryTest, LoadSmallMaskableIcon) { auto web_app = web_app::test::CreateWebApp(); const std::string app_id = web_app->app_id(); const int kIconSize1 = 128; const int kIconSize2 = 256; const std::vector<int> sizes_px{kIconSize1, kIconSize2}; const std::vector<SkColor> colors{SK_ColorGREEN, SK_ColorYELLOW}; WriteIcons(app_id, {IconPurpose::ANY, IconPurpose::MASKABLE}, sizes_px, colors); web_app->SetDownloadedIconSizes(IconPurpose::ANY, sizes_px); web_app->SetDownloadedIconSizes(IconPurpose::MASKABLE, sizes_px); RegisterApp(std::move(web_app)); ASSERT_TRUE(icon_manager().HasIcons(app_id, IconPurpose::MASKABLE, sizes_px)); gfx::ImageSkia src_image_skia; GenerateWebAppIcon(app_id, IconPurpose::MASKABLE, sizes_px, {{1.0, kIconSize1}, {2.0, kIconSize1}}, src_image_skia); gfx::ImageSkia dst_image_skia; LoadIconFromWebApp(app_id, apps::IconEffects::kRoundCorners | apps::IconEffects::kCrOsStandardBackground | apps::IconEffects::kCrOsStandardMask, dst_image_skia); VerifyIcon(src_image_skia, dst_image_skia); } TEST_F(WebAppIconFactoryTest, LoadExactSizeIcon) { auto web_app = web_app::test::CreateWebApp(); const std::string app_id = web_app->app_id(); const int kIconSize1 = 48; const int kIconSize2 = 64; const int kIconSize3 = 96; const int kIconSize4 = 128; const int kIconSize5 = 256; const std::vector<int> sizes_px{kIconSize1, kIconSize2, kIconSize3, kIconSize4, kIconSize5}; const std::vector<SkColor> colors{SK_ColorGREEN, SK_ColorYELLOW, SK_ColorBLACK, SK_ColorRED, SK_ColorBLUE}; WriteIcons(app_id, {IconPurpose::ANY}, sizes_px, colors); web_app->SetDownloadedIconSizes(IconPurpose::ANY, sizes_px); RegisterApp(std::move(web_app)); ASSERT_TRUE(icon_manager().HasIcons(app_id, IconPurpose::ANY, sizes_px)); gfx::ImageSkia src_image_skia; GenerateWebAppIcon(app_id, IconPurpose::ANY, sizes_px, {{1.0, kIconSize2}, {2.0, kIconSize4}}, src_image_skia); gfx::ImageSkia dst_image_skia; apps::IconEffects icon_effect = apps::IconEffects::kRoundCorners; #if BUILDFLAG(IS_CHROMEOS_ASH) icon_effect |= apps::IconEffects::kCrOsStandardIcon; #endif LoadIconFromWebApp(app_id, icon_effect, dst_image_skia); VerifyIcon(src_image_skia, dst_image_skia); } TEST_F(WebAppIconFactoryTest, LoadIconFailed) { auto web_app = web_app::test::CreateWebApp(); const std::string app_id = web_app->app_id(); const int kIconSize1 = 48; const int kIconSize2 = 64; const int kIconSize3 = 96; const std::vector<int> sizes_px{kIconSize1, kIconSize2, kIconSize3}; const std::vector<SkColor> colors{SK_ColorGREEN, SK_ColorYELLOW, SK_ColorBLACK}; WriteIcons(app_id, {IconPurpose::ANY}, sizes_px, colors); web_app->SetDownloadedIconSizes(IconPurpose::ANY, sizes_px); RegisterApp(std::move(web_app)); ASSERT_TRUE(icon_manager().HasIcons(app_id, IconPurpose::ANY, sizes_px)); gfx::ImageSkia src_image_skia; LoadDefaultIcon(src_image_skia); gfx::ImageSkia dst_image_skia; LoadIconFromWebApp( app_id, apps::IconEffects::kRoundCorners | apps::IconEffects::kCrOsStandardIcon, dst_image_skia); VerifyIcon(src_image_skia, dst_image_skia); } #if BUILDFLAG(IS_CHROMEOS_ASH) TEST_F(WebAppIconFactoryTest, ConvertSquareBitmapsToImageSkia_Empty) { gfx::ImageSkia converted_image = ConvertSquareBitmapsToImageSkia( /*icon_bitmaps=*/std::map<SquareSizePx, SkBitmap>{}, /*icon_effects=*/apps::IconEffects::kNone, /*size_hint_in_dip=*/32); EXPECT_TRUE(converted_image.isNull()); } TEST_F(WebAppIconFactoryTest, ConvertSquareBitmapsToImageSkia_OneBigIconForDownscale) { std::map<SquareSizePx, SkBitmap> icon_bitmaps; web_app::AddGeneratedIcon(&icon_bitmaps, web_app::icon_size::k512, SK_ColorYELLOW); gfx::ImageSkia converted_image = ConvertSquareBitmapsToImageSkia( icon_bitmaps, /*icon_effects=*/apps::IconEffects::kNone, /*size_hint_in_dip=*/32); const std::vector<ui::ResourceScaleFactor>& scale_factors = ui::GetSupportedResourceScaleFactors(); ASSERT_EQ(2U, scale_factors.size()); for (auto& scale_factor : scale_factors) { const float scale = ui::GetScaleForResourceScaleFactor(scale_factor); ASSERT_TRUE(converted_image.HasRepresentation(scale)); EXPECT_EQ( SK_ColorYELLOW, converted_image.GetRepresentation(scale).GetBitmap().getColor(0, 0)); } } TEST_F(WebAppIconFactoryTest, ConvertSquareBitmapsToImageSkia_OneSmallIconNoUpscale) { std::map<SquareSizePx, SkBitmap> icon_bitmaps; web_app::AddGeneratedIcon(&icon_bitmaps, web_app::icon_size::k16, SK_ColorMAGENTA); gfx::ImageSkia converted_image = ConvertSquareBitmapsToImageSkia( icon_bitmaps, /*icon_effects=*/apps::IconEffects::kNone, /*size_hint_in_dip=*/32); EXPECT_TRUE(converted_image.isNull()); } TEST_F(WebAppIconFactoryTest, ConvertSquareBitmapsToImageSkia_MatchBigger) { const std::vector<SquareSizePx> sizes_px{ web_app::icon_size::k16, web_app::icon_size::k32, web_app::icon_size::k48, web_app::icon_size::k64, web_app::icon_size::k128}; const std::vector<SkColor> colors{SK_ColorBLUE, SK_ColorRED, SK_ColorMAGENTA, SK_ColorGREEN, SK_ColorWHITE}; std::map<SquareSizePx, SkBitmap> icon_bitmaps; for (size_t i = 0; i < sizes_px.size(); ++i) { web_app::AddGeneratedIcon(&icon_bitmaps, sizes_px[i], colors[i]); } gfx::ImageSkia converted_image = ConvertSquareBitmapsToImageSkia( icon_bitmaps, /*icon_effects=*/apps::IconEffects::kNone, /*size_hint_in_dip=*/32); const std::vector<ui::ResourceScaleFactor>& scale_factors = ui::GetSupportedResourceScaleFactors(); ASSERT_EQ(2U, scale_factors.size()); // Expects 32px and 64px to be chosen for 32dip-normal and 32dip-hi-DPI (2.0f // scale). const std::vector<SkColor> expected_colors{SK_ColorRED, SK_ColorGREEN}; for (int i = 0; i < scale_factors.size(); ++i) { const float scale = ui::GetScaleForResourceScaleFactor(scale_factors[i]); ASSERT_TRUE(converted_image.HasRepresentation(scale)); EXPECT_EQ( expected_colors[i], converted_image.GetRepresentation(scale).GetBitmap().getColor(0, 0)); } } TEST_F(WebAppIconFactoryTest, ConvertSquareBitmapsToImageSkia_StandardEffect) { const std::vector<SquareSizePx> sizes_px{web_app::icon_size::k48, web_app::icon_size::k96}; const std::vector<SkColor> colors{SK_ColorBLUE, SK_ColorRED}; std::map<SquareSizePx, SkBitmap> icon_bitmaps; for (size_t i = 0; i < sizes_px.size(); ++i) { web_app::AddGeneratedIcon(&icon_bitmaps, sizes_px[i], colors[i]); } gfx::ImageSkia converted_image = ConvertSquareBitmapsToImageSkia( icon_bitmaps, /*icon_effects=*/apps::IconEffects::kCrOsStandardBackground | apps::IconEffects::kCrOsStandardMask, /*size_hint_in_dip=*/32); EnsureRepresentationsLoaded(converted_image); const std::vector<ui::ResourceScaleFactor>& scale_factors = ui::GetSupportedResourceScaleFactors(); ASSERT_EQ(2U, scale_factors.size()); for (int i = 0; i < scale_factors.size(); ++i) { const float scale = ui::GetScaleForResourceScaleFactor(scale_factors[i]); ASSERT_TRUE(converted_image.HasRepresentation(scale)); // No color in the upper left corner. EXPECT_FALSE( converted_image.GetRepresentation(scale).GetBitmap().getColor(0, 0)); // Has color in the center. const SquareSizePx center_px = sizes_px[i] / 2; EXPECT_TRUE(converted_image.GetRepresentation(scale).GetBitmap().getColor( center_px, center_px)); } } #endif // BUILDFLAG(IS_CHROMEOS_ASH)
#include <iostream> #include <vector> #include <cmath> #include <chrono> int main( int argc, char **argv ) { size_t n = 1 << 26; size_t n0 = 1 << 0; size_t n1 = 1 << 1; size_t n2 = 1 << 2; size_t n3 = 1 << 3; std::cout << " n = " << n << std::endl; std::cout << " n0 = " << n0 << std::endl; std::cout << " n1 = " << n1 << std::endl; std::cout << " n2 = " << n2 << std::endl; std::cout << " n3 = " << n3 << std::endl; auto t0 = std::chrono::steady_clock::now(); float sum = 0; for ( size_t i = 0; i < n; ++ i ) { sum += std::sin(i); } std::cout << " sum = " << sum << std::endl; auto t1 = std::chrono::steady_clock::now(); auto dt = t1 - t0; int64_t ms = std::chrono::duration_cast<std::chrono::milliseconds>(dt).count(); std::cout << "time elapsed: " << ms << " ms" << std::endl; return 0; }
// Copyright 2004-present Facebook. All Rights Reserved. #include "ABI24_0_0JSCExecutor.h" #include <algorithm> #include <condition_variable> #include <fcntl.h> #include <mutex> #include <sstream> #include <string> #include <sys/time.h> #include <sys/socket.h> #include <system_error> #include <arpa/inet.h> #include <folly/Conv.h> #include <folly/Exception.h> #include <folly/json.h> #include <folly/Memory.h> #include <folly/String.h> #include <glog/logging.h> #include <ABI24_0_0jschelpers/ABI24_0_0InspectorInterfaces.h> #include <ABI24_0_0jschelpers/ABI24_0_0JSCHelpers.h> #include <ABI24_0_0jschelpers/ABI24_0_0Value.h> #include "ABI24_0_0JSBigString.h" #include "ABI24_0_0JSBundleType.h" #include "ABI24_0_0JSCLegacyTracing.h" #include "ABI24_0_0JSCMemory.h" #include "ABI24_0_0JSCNativeModules.h" #include "ABI24_0_0JSCPerfStats.h" #include "ABI24_0_0JSCSamplingProfiler.h" #include "ABI24_0_0JSCTracing.h" #include "ABI24_0_0JSCUtils.h" #include "ABI24_0_0JSModulesUnbundle.h" #include "ABI24_0_0ModuleRegistry.h" #include "ABI24_0_0Platform.h" #include "ABI24_0_0RAMBundleRegistry.h" #include "ABI24_0_0RecoverableError.h" #include "ABI24_0_0SystraceSection.h" #if defined(WITH_JSC_MEMORY_PRESSURE) #include <jsc_memory.h> #endif #if defined(WITH_FB_JSC_TUNING) && defined(__ANDROID__) #include <jsc_config_android.h> #endif namespace facebook { namespace ReactABI24_0_0 { namespace { template<JSValueRef (JSCExecutor::*method)(size_t, const JSValueRef[])> inline JSObjectCallAsFunctionCallback exceptionWrapMethod() { struct funcWrapper { static JSValueRef call( JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef *exception) { try { auto executor = Object::getGlobalObject(ctx).getPrivate<JSCExecutor>(); if (executor && executor->getJavaScriptContext()) { // Executor not invalidated return (executor->*method)(argumentCount, arguments); } } catch (...) { *exception = translatePendingCppExceptionToJSError(ctx, function); } return Value::makeUndefined(ctx); } }; return &funcWrapper::call; } template<JSValueRef (JSCExecutor::*method)(JSObjectRef object, JSStringRef propertyName)> inline JSObjectGetPropertyCallback exceptionWrapMethod() { struct funcWrapper { static JSValueRef call( JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef *exception) { try { auto executor = Object::getGlobalObject(ctx).getPrivate<JSCExecutor>(); if (executor && executor->getJavaScriptContext()) { // Executor not invalidated return (executor->*method)(object, propertyName); } } catch (...) { *exception = translatePendingCppExceptionToJSError(ctx, object); } return Value::makeUndefined(ctx); } }; return &funcWrapper::call; } } #if DEBUG static JSValueRef nativeInjectHMRUpdate( JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef *exception) { String execJSString = Value(ctx, arguments[0]).toString(); String jsURL = Value(ctx, arguments[1]).toString(); evaluateScript(ctx, execJSString, jsURL); return Value::makeUndefined(ctx); } #endif std::unique_ptr<JSExecutor> JSCExecutorFactory::createJSExecutor( std::shared_ptr<ExecutorDelegate> delegate, std::shared_ptr<MessageQueueThread> jsQueue) { return folly::make_unique<JSCExecutor>(delegate, jsQueue, m_jscConfig); } JSCExecutor::JSCExecutor(std::shared_ptr<ExecutorDelegate> delegate, std::shared_ptr<MessageQueueThread> messageQueueThread, const folly::dynamic& jscConfig) throw(JSException) : m_delegate(delegate), m_messageQueueThread(messageQueueThread), m_nativeModules(delegate ? delegate->getModuleRegistry() : nullptr), m_jscConfig(jscConfig) { initOnJSVMThread(); { SystraceSection s("nativeModuleProxy object"); installGlobalProxy(m_context, "nativeModuleProxy", exceptionWrapMethod<&JSCExecutor::getNativeModule>()); } } JSCExecutor::~JSCExecutor() { CHECK(*m_isDestroyed) << "JSCExecutor::destroy() must be called before its destructor!"; } void JSCExecutor::destroy() { *m_isDestroyed = true; if (m_messageQueueThread.get()) { m_messageQueueThread->runOnQueueSync([this] () { terminateOnJSVMThread(); }); } else { terminateOnJSVMThread(); } } void JSCExecutor::setContextName(const std::string& name) { String jsName = String(m_context, name.c_str()); JSC_JSGlobalContextSetName(m_context, jsName); } static bool canUseInspector(JSContextRef context) { #ifdef WITH_INSPECTOR #if defined(__APPLE__) return isCustomJSCPtr(context); // WITH_INSPECTOR && Apple #else return true; // WITH_INSPECTOR && Android #endif #else return false; // !WITH_INSPECTOR #endif } static bool canUseSamplingProfiler(JSContextRef context) { #if defined(__APPLE__) || defined(WITH_JSC_EXTRA_TRACING) return JSC_JSSamplingProfilerEnabled(context); #else return false; #endif } void JSCExecutor::initOnJSVMThread() throw(JSException) { SystraceSection s("JSCExecutor::initOnJSVMThread"); #if defined(__APPLE__) const bool useCustomJSC = m_jscConfig.getDefault("UseCustomJSC", false).getBool(); if (useCustomJSC) { JSC_configureJSCForIOS(true, toJson(m_jscConfig)); } #else const bool useCustomJSC = false; #endif #if defined(WITH_FB_JSC_TUNING) && defined(__ANDROID__) configureJSCForAndroid(m_jscConfig); #endif // Create a custom global class, so we can store data in it later using JSObjectSetPrivate JSClassRef globalClass = nullptr; { SystraceSection s_("JSClassCreate"); JSClassDefinition definition = kJSClassDefinitionEmpty; definition.attributes |= kJSClassAttributeNoAutomaticPrototype; globalClass = JSC_JSClassCreate(useCustomJSC, &definition); } { SystraceSection s_("JSGlobalContextCreateInGroup"); m_context = JSC_JSGlobalContextCreateInGroup(useCustomJSC, nullptr, globalClass); } JSC_JSClassRelease(useCustomJSC, globalClass); // Add a pointer to ourselves so we can retrieve it later in our hooks Object::getGlobalObject(m_context).setPrivate(this); if (canUseInspector(m_context)) { const std::string ownerId = m_jscConfig.getDefault("OwnerIdentity", "unknown").getString(); const std::string appId = m_jscConfig.getDefault("AppIdentity", "unknown").getString(); const std::string deviceId = m_jscConfig.getDefault("DeviceIdentity", "unknown").getString(); const std::function<bool()> checkIsInspectedRemote = [&](){ return isNetworkInspected(ownerId, appId, deviceId); }; IInspector* pInspector = JSC_JSInspectorGetInstance(true); pInspector->registerGlobalContext(ownerId, checkIsInspectedRemote, m_context); } installNativeHook<&JSCExecutor::nativeFlushQueueImmediate>("nativeFlushQueueImmediate"); installNativeHook<&JSCExecutor::nativeCallSyncHook>("nativeCallSyncHook"); installGlobalFunction(m_context, "nativeLoggingHook", JSCNativeHooks::loggingHook); installGlobalFunction(m_context, "nativePerformanceNow", JSCNativeHooks::nowHook); #if DEBUG installGlobalFunction(m_context, "nativeInjectHMRUpdate", nativeInjectHMRUpdate); #endif addNativeTracingHooks(m_context); addNativeTracingLegacyHooks(m_context); addJSCMemoryHooks(m_context); addJSCPerfStatsHooks(m_context); JSCNativeHooks::installPerfHooks(m_context); if (canUseSamplingProfiler(m_context)) { initSamplingProfilerOnMainJSCThread(m_context); } } bool JSCExecutor::isNetworkInspected(const std::string &owner, const std::string &app, const std::string &device) { #ifdef WITH_FB_DBG_ATTACH_BEFORE_EXEC auto connect_socket = [](int socket_desc, std::string address, int port) { if (socket_desc < 0) { ::close(socket_desc); return false; } struct timeval tv; tv.tv_sec = 1; tv.tv_usec = 0; auto sock_opt_rcv_resp = setsockopt(socket_desc, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv, sizeof(struct timeval)); if (sock_opt_rcv_resp < 0) { ::close(socket_desc); return false; } auto sock_opt_snd_resp = setsockopt(socket_desc, SOL_SOCKET, SO_SNDTIMEO, (const char*)&tv, sizeof(struct timeval)); if (sock_opt_snd_resp < 0) { ::close(socket_desc); return false; } struct sockaddr_in server; server.sin_addr.s_addr = inet_addr(address.c_str()); server.sin_family = AF_INET; server.sin_port = htons(port); auto connect_resp = ::connect(socket_desc, (struct sockaddr *)&server, sizeof(server)); if (connect_resp < 0) { ::close(socket_desc); return false; } return true; }; int socket_desc = socket(AF_INET, SOCK_STREAM, 0); if (!connect_socket(socket_desc, "127.0.0.1", 8082)) { #if defined(__ANDROID__) socket_desc = socket(AF_INET, SOCK_STREAM, 0); if (!connect_socket(socket_desc, "10.0.2.2", 8082) /* emulator */) { socket_desc = socket(AF_INET, SOCK_STREAM, 0); if (!connect_socket(socket_desc, "10.0.3.2", 8082) /* genymotion */) { return false; } } #else //!defined(__ANDROID__) return false; #endif //defined(__ANDROID__) } std::string escapedOwner = folly::uriEscape<std::string>(owner, folly::UriEscapeMode::QUERY); std::string escapedApp = folly::uriEscape<std::string>(app, folly::UriEscapeMode::QUERY); std::string escapedDevice = folly::uriEscape<std::string>(device, folly::UriEscapeMode::QUERY); std::string msg = folly::to<std::string>( "GET /autoattach?title=", escapedOwner, "&app=" , escapedApp, "&device=" , escapedDevice, " HTTP/1.1\r\n\r\n"); auto send_resp = ::send(socket_desc, msg.c_str(), msg.length(), 0); if (send_resp < 0) { ::close(socket_desc); return false; } char server_reply[200]; server_reply[199] = '\0'; auto recv_resp = ::recv(socket_desc, server_reply, sizeof(server_reply) - 1, 0); if (recv_resp < 0) { ::close(socket_desc); return false; } std::string response(server_reply); if (response.size() < 25) { ::close(socket_desc); return false; } auto responseCandidate = response.substr(response.size() - 25); auto found = responseCandidate.find("{\"autoattach\":true}") != std::string::npos; ::close(socket_desc); return found; #else //!WITH_FB_DBG_ATTACH_BEFORE_EXEC return false; #endif //WITH_FB_DBG_ATTACH_BEFORE_EXEC } void JSCExecutor::terminateOnJSVMThread() { JSGlobalContextRef context = m_context; m_context = nullptr; Object::getGlobalObject(context).setPrivate(nullptr); m_nativeModules.reset(); if (canUseInspector(context)) { IInspector* pInspector = JSC_JSInspectorGetInstance(true); pInspector->unregisterGlobalContext(context); } JSC_JSGlobalContextRelease(context); } #ifdef WITH_FBJSCEXTENSIONS static const char* explainLoadSourceStatus(JSLoadSourceStatus status) { switch (status) { case JSLoadSourceIsCompiled: return "No error encountered during source load"; case JSLoadSourceErrorOnRead: return "Error reading source"; case JSLoadSourceIsNotCompiled: return "Source is not compiled"; case JSLoadSourceErrorVersionMismatch: return "Source version not supported"; default: return "Bad error code"; } } #endif // basename_r isn't in all iOS SDKs, so use this simple version instead. static std::string simpleBasename(const std::string &path) { size_t pos = path.rfind("/"); return (pos != std::string::npos) ? path.substr(pos) : path; } void JSCExecutor::loadApplicationScript(std::unique_ptr<const JSBigString> script, std::string sourceURL) { SystraceSection s("JSCExecutor::loadApplicationScript", "sourceURL", sourceURL); std::string scriptName = simpleBasename(sourceURL); ReactABI24_0_0Marker::logTaggedMarker(ReactABI24_0_0Marker::RUN_JS_BUNDLE_START, scriptName.c_str()); String jsSourceURL(m_context, sourceURL.c_str()); // TODO t15069155: reduce the number of overrides here #ifdef WITH_FBJSCEXTENSIONS if (auto fileStr = dynamic_cast<const JSBigFileString *>(script.get())) { JSContextLock lock(m_context); JSLoadSourceStatus jsStatus; auto bcSourceCode = JSCreateSourceCodeFromFile(fileStr->fd(), jsSourceURL, nullptr, &jsStatus); switch (jsStatus) { case JSLoadSourceIsCompiled: if (!bcSourceCode) { throw std::runtime_error("Unexpected error opening compiled bundle"); } evaluateSourceCode(m_context, bcSourceCode, jsSourceURL); flush(); ReactABI24_0_0Marker::logMarker(ReactABI24_0_0Marker::CREATE_REACT_CONTEXT_STOP); ReactABI24_0_0Marker::logTaggedMarker(ReactABI24_0_0Marker::RUN_JS_BUNDLE_STOP, scriptName.c_str()); return; case JSLoadSourceErrorVersionMismatch: throw RecoverableError(explainLoadSourceStatus(jsStatus)); case JSLoadSourceErrorOnRead: case JSLoadSourceIsNotCompiled: // Not bytecode, fall through. break; } } #elif defined(__APPLE__) BundleHeader header; memcpy(&header, script->c_str(), std::min(script->size(), sizeof(BundleHeader))); auto scriptTag = parseTypeFromHeader(header); if (scriptTag == ScriptTag::BCBundle) { using file_ptr = std::unique_ptr<FILE, decltype(&fclose)>; file_ptr source(fopen(sourceURL.c_str(), "r"), fclose); int sourceFD = fileno(source.get()); JSValueRef jsError; JSValueRef result = JSC_JSEvaluateBytecodeBundle(m_context, NULL, sourceFD, jsSourceURL, &jsError); if (result == nullptr) { throw JSException(m_context, jsError, jsSourceURL); } } else #endif { String jsScript; JSContextLock lock(m_context); { SystraceSection s_("JSCExecutor::loadApplicationScript-createExpectingAscii"); ReactABI24_0_0Marker::logMarker(ReactABI24_0_0Marker::JS_BUNDLE_STRING_CONVERT_START); jsScript = adoptString(std::move(script)); ReactABI24_0_0Marker::logMarker(ReactABI24_0_0Marker::JS_BUNDLE_STRING_CONVERT_STOP); } #ifdef WITH_FBSYSTRACE fbsystrace_end_section(TRACE_TAG_REACT_CXX_BRIDGE); #endif SystraceSection s_("JSCExecutor::loadApplicationScript-evaluateScript"); evaluateScript(m_context, jsScript, jsSourceURL); } flush(); ReactABI24_0_0Marker::logMarker(ReactABI24_0_0Marker::CREATE_REACT_CONTEXT_STOP); ReactABI24_0_0Marker::logTaggedMarker(ReactABI24_0_0Marker::RUN_JS_BUNDLE_STOP, scriptName.c_str()); } void JSCExecutor::setBundleRegistry(std::unique_ptr<RAMBundleRegistry> bundleRegistry) { if (!m_bundleRegistry) { installNativeHook<&JSCExecutor::nativeRequire>("nativeRequire"); } m_bundleRegistry = std::move(bundleRegistry); } void JSCExecutor::bindBridge() throw(JSException) { SystraceSection s("JSCExecutor::bindBridge"); std::call_once(m_bindFlag, [this] { auto global = Object::getGlobalObject(m_context); auto batchedBridgeValue = global.getProperty("__fbBatchedBridge"); if (batchedBridgeValue.isUndefined()) { auto requireBatchedBridge = global.getProperty("__fbRequireBatchedBridge"); if (!requireBatchedBridge.isUndefined()) { batchedBridgeValue = requireBatchedBridge.asObject().callAsFunction({}); } if (batchedBridgeValue.isUndefined()) { throw JSException("Could not get BatchedBridge, make sure your bundle is packaged correctly"); } } auto batchedBridge = batchedBridgeValue.asObject(); m_callFunctionReturnFlushedQueueJS = batchedBridge.getProperty("callFunctionReturnFlushedQueue").asObject(); m_invokeCallbackAndReturnFlushedQueueJS = batchedBridge.getProperty("invokeCallbackAndReturnFlushedQueue").asObject(); m_flushedQueueJS = batchedBridge.getProperty("flushedQueue").asObject(); m_callFunctionReturnResultAndFlushedQueueJS = batchedBridge.getProperty("callFunctionReturnResultAndFlushedQueue").asObject(); }); } void JSCExecutor::callNativeModules(Value&& value) { SystraceSection s("JSCExecutor::callNativeModules"); // If this fails, you need to pass a fully functional delegate with a // module registry to the factory/ctor. CHECK(m_delegate) << "Attempting to use native modules without a delegate"; try { auto calls = value.toJSONString(); m_delegate->callNativeModules(*this, folly::parseJson(calls), true); } catch (...) { std::string message = "Error in callNativeModules()"; try { message += ":" + value.toString().str(); } catch (...) { // ignored } std::throw_with_nested(std::runtime_error(message)); } } void JSCExecutor::flush() { SystraceSection s("JSCExecutor::flush"); if (m_flushedQueueJS) { callNativeModules(m_flushedQueueJS->callAsFunction({})); return; } // When a native module is called from JS, BatchedBridge.enqueueNativeCall() // is invoked. For that to work, require('BatchedBridge') has to be called, // and when that happens, __fbBatchedBridge is set as a side effect. auto global = Object::getGlobalObject(m_context); auto batchedBridgeValue = global.getProperty("__fbBatchedBridge"); // So here, if __fbBatchedBridge doesn't exist, then we know no native calls // have happened, and we were able to determine this without forcing // BatchedBridge to be loaded as a side effect. if (!batchedBridgeValue.isUndefined()) { // If calls were made, we bind to the JS bridge methods, and use them to // get the pending queue of native calls. bindBridge(); callNativeModules(m_flushedQueueJS->callAsFunction({})); } else if (m_delegate) { // If we have a delegate, we need to call it; we pass a null list to // callNativeModules, since we know there are no native calls, without // calling into JS again. If no calls were made and there's no delegate, // nothing happens, which is correct. callNativeModules(Value::makeNull(m_context)); } } void JSCExecutor::callFunction(const std::string& moduleId, const std::string& methodId, const folly::dynamic& arguments) { SystraceSection s("JSCExecutor::callFunction"); // This weird pattern is because Value is not default constructible. // The lambda is inlined, so there's no overhead. auto result = [&] { JSContextLock lock(m_context); try { if (!m_callFunctionReturnResultAndFlushedQueueJS) { bindBridge(); } return m_callFunctionReturnFlushedQueueJS->callAsFunction({ Value(m_context, String::createExpectingAscii(m_context, moduleId)), Value(m_context, String::createExpectingAscii(m_context, methodId)), Value::fromDynamic(m_context, std::move(arguments)) }); } catch (...) { std::throw_with_nested( std::runtime_error("Error calling " + moduleId + "." + methodId)); } }(); callNativeModules(std::move(result)); } void JSCExecutor::invokeCallback(const double callbackId, const folly::dynamic& arguments) { SystraceSection s("JSCExecutor::invokeCallback"); auto result = [&] { JSContextLock lock(m_context); try { if (!m_invokeCallbackAndReturnFlushedQueueJS) { bindBridge(); } return m_invokeCallbackAndReturnFlushedQueueJS->callAsFunction({ Value::makeNumber(m_context, callbackId), Value::fromDynamic(m_context, std::move(arguments)) }); } catch (...) { std::throw_with_nested( std::runtime_error(folly::to<std::string>("Error invoking callback ", callbackId))); } }(); callNativeModules(std::move(result)); } Value JSCExecutor::callFunctionSyncWithValue( const std::string& module, const std::string& method, Value args) { SystraceSection s("JSCExecutor::callFunction"); Object result = [&] { JSContextLock lock(m_context); if (!m_callFunctionReturnResultAndFlushedQueueJS) { bindBridge(); } return m_callFunctionReturnResultAndFlushedQueueJS->callAsFunction({ Value(m_context, String::createExpectingAscii(m_context, module)), Value(m_context, String::createExpectingAscii(m_context, method)), std::move(args), }).asObject(); }(); Value length = result.getProperty("length"); if (!length.isNumber() || length.asInteger() != 2) { std::runtime_error("Return value of a callFunction must be an array of size 2"); } callNativeModules(result.getPropertyAtIndex(1)); return result.getPropertyAtIndex(0); } void JSCExecutor::setGlobalVariable(std::string propName, std::unique_ptr<const JSBigString> jsonValue) { try { SystraceSection s("JSCExecutor::setGlobalVariable", "propName", propName); auto valueToInject = Value::fromJSON(adoptString(std::move(jsonValue))); Object::getGlobalObject(m_context).setProperty(propName.c_str(), valueToInject); } catch (...) { std::throw_with_nested(std::runtime_error("Error setting global variable: " + propName)); } } std::string JSCExecutor::getDescription() { #if defined(__APPLE__) if (isCustomJSCPtr(m_context)) { return "Custom JSC"; } else { return "System JSC"; } #else return "JSC"; #endif } String JSCExecutor::adoptString(std::unique_ptr<const JSBigString> script) { #if defined(WITH_FBJSCEXTENSIONS) const JSBigString* string = script.release(); auto jsString = JSStringCreateAdoptingExternal(string->c_str(), string->size(), (void*)string, [](void* s) { delete static_cast<JSBigString*>(s); }); return String::adopt(m_context, jsString); #else return script->isAscii() ? String::createExpectingAscii(m_context, script->c_str(), script->size()) : String(m_context, script->c_str()); #endif } void* JSCExecutor::getJavaScriptContext() { return m_context; } #ifdef WITH_JSC_MEMORY_PRESSURE void JSCExecutor::handleMemoryPressure(int pressureLevel) { JSHandleMemoryPressure(this, m_context, static_cast<JSMemoryPressure>(pressureLevel)); } #endif void JSCExecutor::flushQueueImmediate(Value&& queue) { auto queueStr = queue.toJSONString(); m_delegate->callNativeModules(*this, folly::parseJson(queueStr), false); } void JSCExecutor::loadModule(uint32_t bundleId, uint32_t moduleId) { auto module = m_bundleRegistry->getModule(bundleId, moduleId); auto sourceUrl = String::createExpectingAscii(m_context, module.name); auto source = adoptString(std::unique_ptr<JSBigString>(new JSBigStdString(module.code))); evaluateScript(m_context, source, sourceUrl); } // Native JS hooks template<JSValueRef (JSCExecutor::*method)(size_t, const JSValueRef[])> void JSCExecutor::installNativeHook(const char* name) { installGlobalFunction(m_context, name, exceptionWrapMethod<method>()); } JSValueRef JSCExecutor::getNativeModule(JSObjectRef object, JSStringRef propertyName) { if (JSC_JSStringIsEqualToUTF8CString(m_context, propertyName, "name")) { return Value(m_context, String(m_context, "NativeModules")); } return m_nativeModules.getModule(m_context, propertyName); } JSValueRef JSCExecutor::nativeRequire( size_t argumentCount, const JSValueRef arguments[]) { uint32_t bundleId, moduleId; std::tie(bundleId, moduleId) = parseNativeRequireParameters(m_context, arguments, argumentCount); ReactABI24_0_0Marker::logMarker(ReactABI24_0_0Marker::NATIVE_REQUIRE_START); loadModule(bundleId, moduleId); ReactABI24_0_0Marker::logMarker(ReactABI24_0_0Marker::NATIVE_REQUIRE_STOP); return Value::makeUndefined(m_context); } JSValueRef JSCExecutor::nativeFlushQueueImmediate( size_t argumentCount, const JSValueRef arguments[]) { if (argumentCount != 1) { throw std::invalid_argument("Got wrong number of args"); } flushQueueImmediate(Value(m_context, arguments[0])); return Value::makeUndefined(m_context); } JSValueRef JSCExecutor::nativeCallSyncHook( size_t argumentCount, const JSValueRef arguments[]) { if (argumentCount != 3) { throw std::invalid_argument("Got wrong number of args"); } unsigned int moduleId = Value(m_context, arguments[0]).asUnsignedInteger(); unsigned int methodId = Value(m_context, arguments[1]).asUnsignedInteger(); folly::dynamic args = folly::parseJson(Value(m_context, arguments[2]).toJSONString()); if (!args.isArray()) { throw std::invalid_argument( folly::to<std::string>("method parameters should be array, but are ", args.typeName())); } MethodCallResult result = m_delegate->callSerializableNativeHook( *this, moduleId, methodId, std::move(args)); if (!result.hasValue()) { return Value::makeUndefined(m_context); } return Value::fromDynamic(m_context, result.value()); } } }
/************************************************************************************ Filename : OptionMenu.h Content : Option selection and editing for OculusWorldDemo Created : March 7, 2014 Authors : Michael Antonov, Caleb Leak Copyright : Copyright 2012 Oculus VR, Inc. All Rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *************************************************************************************/ #include "OptionMenu.h" // Embed the font. #include "../Render/Render_FontEmbed_DejaVu48.h" //------------------------------------------------------------------------------------- bool OptionShortcut::MatchKey(OVR::KeyCode key, bool shift) const { for (uint32_t i = 0; i < Keys.GetSize(); i++) { if (Keys[i].Key != key) continue; if (!shift && Keys[i].ShiftUsage == ShortcutKey::Shift_RequireOn) continue; if (shift && Keys[i].ShiftUsage == ShortcutKey::Shift_RequireOff) continue; if(Keys[i].ShiftUsage == ShortcutKey::Shift_Modify) { pNotify->CallNotify(&shift); } else { pNotify->CallNotify(); } return true; } return false; } bool OptionShortcut::MatchGamepadButton(uint32_t gamepadButtonMask) const { for (uint32_t i = 0; i < GamepadButtons.GetSize(); i++) { if (GamepadButtons[i] & gamepadButtonMask) { if (pNotify != NULL) { pNotify->CallNotify(); } return true; } } return false; } //------------------------------------------------------------------------------------- String OptionMenuItem::PopNamespaceFrom(OptionMenuItem* menuItem) { String label = menuItem->Label; for (uint32_t i = 0; i < label.GetLength(); i++) { if (label.GetCharAt(i) == '.') { String ns = label.Substring(0, i); menuItem->Label = label.Substring(i + 1, label.GetLength()); return ns; } } return ""; } //------------------------------------------------------------------------------------- String OptionVar::FormatEnum(OptionVar* var) { uint32_t index = var->GetEnumIndex(); if (index < var->EnumValues.GetSize()) return var->EnumValues[index].Name; return String("<Bad enum index>"); } String OptionVar::FormatInt(OptionVar* var) { char buff[64]; OVR_sprintf(buff, sizeof(buff), var->FormatString, *var->AsInt()); return String(buff); } String OptionVar::FormatFloat(OptionVar* var) { char buff[64]; OVR_sprintf(buff, sizeof(buff), var->FormatString, *var->AsFloat() * var->FormatScale); return String(buff); } String OptionVar::FormatBool(OptionVar* var) { return *var->AsBool() ? "On" : "Off"; } String OptionVar::FormatTrigger(OptionVar* var) { OVR_UNUSED(var); return "[Trigger]"; } OptionVar::OptionVar(const char* name, void* pvar, VarType type, FormatFunction formatFunction, UpdateFunction updateFunction) { Label = name; Type = type; this->pVar = pvar; fFormat = ((Type == Type_Trigger) && !formatFunction) ? FormatTrigger : formatFunction; fUpdate = updateFunction; pNotify = 0; FormatString= 0; MaxFloat = MATH_FLOAT_MAXVALUE; MinFloat = -MATH_FLOAT_MAXVALUE; StepFloat = 1.0f; FormatScale = 1.0f; MaxInt = 0x7FFFFFFF; MinInt = -(MaxInt) - 1; StepInt = 1; SelectedIndex = 0; ShortcutUp.pNotify = new FunctionNotifyContext<OptionVar, bool>(this, &OptionVar::NextValue); ShortcutDown.pNotify = new FunctionNotifyContext<OptionVar, bool>(this, &OptionVar::PrevValue); } OptionVar::OptionVar(const char* name, int32_t* pvar, int32_t min, int32_t max, int32_t stepSize, const char* formatString, FormatFunction formatFunction, UpdateFunction updateFunction) { Label = name; Type = Type_Int; this->pVar = pvar; fFormat = formatFunction ? formatFunction : FormatInt; fUpdate = updateFunction; pNotify = 0; FormatString= formatString; MinInt = min; MaxInt = max; StepInt = stepSize; SelectedIndex = 0; ShortcutUp.pNotify = new FunctionNotifyContext<OptionVar, bool>(this, &OptionVar::NextValue); ShortcutDown.pNotify = new FunctionNotifyContext<OptionVar, bool>(this, &OptionVar::PrevValue); } // Float with range and step size. OptionVar::OptionVar(const char* name, float* pvar, float minf, float maxf, float stepSize, const char* formatString, float formatScale, FormatFunction formatFunction, UpdateFunction updateFunction) { Label = name; Type = Type_Float; this->pVar = pvar; fFormat = formatFunction ? formatFunction : FormatFloat; fUpdate = updateFunction; pNotify = 0; FormatString= formatString ? formatString : "%.3f"; MinFloat = minf; MaxFloat = maxf; StepFloat = stepSize; FormatScale = formatScale; SelectedIndex = 0; ShortcutUp.pNotify = new FunctionNotifyContext<OptionVar, bool>(this, &OptionVar::NextValue); ShortcutDown.pNotify = new FunctionNotifyContext<OptionVar, bool>(this, &OptionVar::PrevValue); } OptionVar::~OptionVar() { if (pNotify) delete pNotify; } void OptionVar::NextValue(bool* pFastStep) { bool fastStep = (pFastStep != NULL && *pFastStep); switch (Type) { case Type_Enum: *AsInt() = ((GetEnumIndex() + 1) % EnumValues.GetSize()); break; case Type_Int: *AsInt() = Alg::Min<int32_t>(*AsInt() + StepInt * (fastStep ? 5 : 1), MaxInt); break; case Type_Float: // TODO: Will behave strange with NaN values. *AsFloat() = Alg::Min<float>(*AsFloat() + StepFloat * (fastStep ? 5.0f : 1.0f), MaxFloat); break; case Type_Bool: *AsBool() = !*AsBool(); break; case Type_Trigger: break; // nothing to do default: OVR_ASSERT(false); break; // unhandled } SignalUpdate(); } void OptionVar::PrevValue(bool* pFastStep) { bool fastStep = (pFastStep != NULL && *pFastStep); switch (Type) { case Type_Enum: *AsInt() = ((GetEnumIndex() + (uint32_t)EnumValues.GetSize() - 1) % EnumValues.GetSize()); break; case Type_Int: *AsInt() = Alg::Max<int32_t>(*AsInt() - StepInt * (fastStep ? 5 : 1), MinInt); break; case Type_Float: // TODO: Will behave strange with NaN values. *AsFloat() = Alg::Max<float>(*AsFloat() - StepFloat * (fastStep ? 5.0f : 1.0f), MinFloat); break; case Type_Bool: *AsBool() = !*AsBool(); break; case Type_Trigger: break; // nothing to do default: OVR_ASSERT(false); break; // unhandled } SignalUpdate(); } String OptionVar::HandleShortcutUpdate() { if(Type != Type_Trigger) { SignalUpdate(); return Label + " - " + GetValue(); } else { // Avoid double trigger (shortcut key already triggers NextValue()) return String("Triggered: ") + Label; } } String OptionVar::ProcessShortcutKey(OVR::KeyCode key, bool shift) { if (ShortcutUp.MatchKey(key, shift) || ShortcutDown.MatchKey(key, shift)) { return HandleShortcutUpdate(); } return String(); } String OptionVar::ProcessShortcutButton(uint32_t buttonMask) { if (ShortcutUp.MatchGamepadButton(buttonMask) || ShortcutDown.MatchGamepadButton(buttonMask)) { return HandleShortcutUpdate(); } return String(); } OptionVar& OptionVar::AddEnumValue(const char* displayName, int32_t value) { EnumEntry entry; entry.Name = displayName; entry.Value = value; EnumValues.PushBack(entry); return *this; } String OptionVar::GetValue() { if(fFormat == NULL) return String(); else return fFormat(this); } uint32_t OptionVar::GetEnumIndex() { OVR_ASSERT(Type == Type_Enum); OVR_ASSERT(EnumValues.GetSize() > 0); // TODO: Change this from a linear search to binary or a hash. for (uint32_t i = 0; i < EnumValues.GetSize(); i++) { if (EnumValues[i].Value == *AsInt()) return i; } // Enum values should always be found. OVR_ASSERT(false); return 0; } //------------------------------------------------------------------------------------- OptionSelectionMenu::OptionSelectionMenu(OptionSelectionMenu* parentMenu) { DisplayState = Display_None; SelectedIndex = 0; SelectionActive = false; ParentMenu = parentMenu; PopupMessageTimeout = 0.0; PopupMessageBorder = false; // Setup handlers for menu navigation actions. NavShortcuts[Nav_Up].pNotify = new FunctionNotifyContext<OptionSelectionMenu, bool>(this, &OptionSelectionMenu::HandleUp); NavShortcuts[Nav_Down].pNotify = new FunctionNotifyContext<OptionSelectionMenu, bool>(this, &OptionSelectionMenu::HandleDown); NavShortcuts[Nav_Left].pNotify = new FunctionNotifySimple<OptionSelectionMenu>(this, &OptionSelectionMenu::HandleLeft); NavShortcuts[Nav_Right].pNotify = new FunctionNotifySimple<OptionSelectionMenu>(this, &OptionSelectionMenu::HandleRight); NavShortcuts[Nav_Select].pNotify = new FunctionNotifySimple<OptionSelectionMenu>(this, &OptionSelectionMenu::HandleSelect); NavShortcuts[Nav_Back].pNotify = new FunctionNotifySimple<OptionSelectionMenu>(this, &OptionSelectionMenu::HandleBack); ToggleShortcut.pNotify = new FunctionNotifySimple<OptionSelectionMenu>(this, &OptionSelectionMenu::HandleMenuToggle); ToggleSingleItemShortcut.pNotify = new FunctionNotifySimple<OptionSelectionMenu>(this, &OptionSelectionMenu::HandleSingleItemToggle); // Bind keys and buttons to menu navigation actions. NavShortcuts[Nav_Up].AddShortcut(ShortcutKey(Key_Up, ShortcutKey::Shift_Modify)); NavShortcuts[Nav_Up].AddShortcut(Gamepad_Up); NavShortcuts[Nav_Down].AddShortcut(ShortcutKey(Key_Down, ShortcutKey::Shift_Modify)); NavShortcuts[Nav_Down].AddShortcut(Gamepad_Down); NavShortcuts[Nav_Left].AddShortcut(ShortcutKey(Key_Left)); NavShortcuts[Nav_Left].AddShortcut(Gamepad_Left); NavShortcuts[Nav_Right].AddShortcut(ShortcutKey(Key_Right)); NavShortcuts[Nav_Right].AddShortcut(Gamepad_Right); NavShortcuts[Nav_Select].AddShortcut(ShortcutKey(Key_Return)); NavShortcuts[Nav_Select].AddShortcut(Gamepad_A); NavShortcuts[Nav_Back].AddShortcut(ShortcutKey(Key_Escape)); NavShortcuts[Nav_Back].AddShortcut(Gamepad_B); ToggleShortcut.AddShortcut(ShortcutKey(Key_Tab, ShortcutKey::Shift_Ignore)); ToggleShortcut.AddShortcut(Gamepad_Start); ToggleSingleItemShortcut.AddShortcut(ShortcutKey(Key_Backspace, ShortcutKey::Shift_Ignore)); } OptionSelectionMenu::~OptionSelectionMenu() { for (uint32_t i = 0; i < Items.GetSize(); i++) delete Items[i]; } bool OptionSelectionMenu::OnKey(OVR::KeyCode key, int chr, bool down, int modifiers) { bool shift = ((modifiers & Mod_Shift) != 0); if (down) { String s = ProcessShortcutKey(key, shift); if (!s.IsEmpty()) { PopupMessage = s; PopupMessageTimeout = ovr_GetTimeInSeconds() + 4.0f; PopupMessageBorder = false; return true; } } if (GetSubmenu() != NULL) { return GetSubmenu()->OnKey(key, chr, down, modifiers); } if (down) { if (ToggleShortcut.MatchKey(key, shift)) return true; if (ToggleSingleItemShortcut.MatchKey(key, shift)) return true; if (DisplayState == Display_None) return false; for (int i = 0; i < Nav_LAST; i++) { if (NavShortcuts[i].MatchKey(key, shift)) return true; } } // Let the caller process keystroke return false; } bool OptionSelectionMenu::OnGamepad(uint32_t buttonMask) { // Check global shortcuts first. String s = ProcessShortcutButton(buttonMask); if (!s.IsEmpty()) { PopupMessage = s; PopupMessageTimeout = ovr_GetTimeInSeconds() + 4.0f; return true; } if (GetSubmenu() != NULL) { return GetSubmenu()->OnGamepad(buttonMask); } if (ToggleShortcut.MatchGamepadButton(buttonMask)) return true; if (DisplayState == Display_None) return false; for (int i = 0; i < Nav_LAST; i++) { if (NavShortcuts[i].MatchGamepadButton(buttonMask)) return true; } // Let the caller process keystroke return false; } String OptionSelectionMenu::ProcessShortcutKey(OVR::KeyCode key, bool shift) { String s; for (size_t i = 0; (i < Items.GetSize()) && s.IsEmpty(); i++) { s = Items[i]->ProcessShortcutKey(key, shift); } return s; } String OptionSelectionMenu::ProcessShortcutButton(uint32_t buttonMask) { String s; for (size_t i = 0; (i < Items.GetSize()) && s.IsEmpty(); i++) { s = Items[i]->ProcessShortcutButton(buttonMask); } return s; } // Fills in inclusive character range; returns false if line not found. bool FindLineCharRange(const char* text, int searchLine, size_t charRange[2]) { size_t i = 0; for (int line = 0; line <= searchLine; line ++) { if (line == searchLine) { charRange[0] = i; } // Find end of line. while (text[i] != '\n' && text[i] != 0) { i++; } if (line == searchLine) { charRange[1] = (charRange[0] == i) ? charRange[0] : i-1; return true; } if (text[i] == 0) break; // Skip newline i++; } return false; } void OptionSelectionMenu::Render(RenderDevice* prender, String title) { // If we are invisible, render shortcut notifications. // Both child and parent have visible == true even if only child is shown. if (DisplayState == Display_None) { renderShortcutChangeMessage(prender); return; } title += Label; // Delegate to sub-menu if active. if (GetSubmenu() != NULL) { if (title.GetSize() > 0) title += " > "; GetSubmenu()->Render(prender, title); return; } Color focusColor(180, 80, 20, 210); Color pickedColor(120, 55, 10, 140); Color titleColor(0x18, 0x1A, 0x4D, 210); Color titleOutlineColor(0x18, 0x18, 0x18, 240); float labelsSize[2] = {0.0f, 0.0f}; float bufferSize[2] = {0.0f, 0.0f}; float valuesSize[2] = {0.0f, 0.0f}; float maxValueWidth = 0.0f; size_t selection[2] = { 0, 0 }; Vector2f labelSelectionRect[2]; Vector2f valueSelectionRect[2]; float textSize = 22.0f; prender->MeasureText(&DejaVu, " ", textSize, bufferSize); String values; String menuItems; int highlightIndex = 0; if (DisplayState == Display_Menu) { highlightIndex = SelectedIndex; for (uint32_t i = 0; i < Items.GetSize(); i++) { if (i > 0) values += "\n"; values += Items[i]->GetValue(); } for (uint32_t i = 0; i < Items.GetSize(); i++) { if (i > 0) menuItems += "\n"; menuItems += Items[i]->GetLabel(); } } else { values = Items[SelectedIndex]->GetValue(); menuItems = Items[SelectedIndex]->GetLabel(); } // Measure labels const char* menuItemsCStr = menuItems.ToCStr(); bool havelLabelSelection = FindLineCharRange(menuItemsCStr, highlightIndex, selection); OVR_UNUSED(havelLabelSelection); prender->MeasureText(&DejaVu, menuItemsCStr, textSize, labelsSize, selection, labelSelectionRect); // Measure label-to-value gap const char* valuesCStr = values.ToCStr(); bool haveValueSelection = FindLineCharRange(valuesCStr, highlightIndex, selection); OVR_UNUSED(haveValueSelection); prender->MeasureText(&DejaVu, valuesCStr, textSize, valuesSize, selection, valueSelectionRect); // Measure max value size (absolute size varies, so just use a reasonable max) maxValueWidth = prender->MeasureText(&DejaVu, "Max value width", textSize); maxValueWidth = Alg::Max(maxValueWidth, valuesSize[0]); Vector2f borderSize(4.0f, 4.0f); Vector2f totalDimensions = borderSize * 2 + Vector2f(bufferSize[0], 0) + Vector2f(maxValueWidth, 0) + Vector2f(labelsSize[0], labelsSize[1]); Vector2f fudgeOffset= Vector2f(10.0f, 25.0f); // This offset looks better Vector2f topLeft = (-totalDimensions / 2.0f) + fudgeOffset; Vector2f bottomRight = topLeft + totalDimensions; // If displaying a single item, shift it down. if (DisplayState == Display_SingleItem) { topLeft.y += textSize * 7; bottomRight.y += textSize * 7; } prender->FillRect(topLeft.x, topLeft.y, bottomRight.x, bottomRight.y, Color(40,40,100,210)); Vector2f labelsPos = topLeft + borderSize; Vector2f valuesPos = labelsPos + Vector2f(labelsSize[0], 0) + Vector2f(bufferSize[0], 0); // Highlight selected label Vector2f selectionInset = Vector2f(0.3f, 2.0f); if (DisplayState == Display_Menu) { Vector2f labelSelectionTopLeft = labelsPos + labelSelectionRect[0] - selectionInset; Vector2f labelSelectionBottomRight = labelsPos + labelSelectionRect[1] + selectionInset; prender->FillRect(labelSelectionTopLeft.x, labelSelectionTopLeft.y, labelSelectionBottomRight.x, labelSelectionBottomRight.y, SelectionActive ? pickedColor : focusColor); } // Highlight selected value if active if (SelectionActive) { Vector2f valueSelectionTopLeft = valuesPos + valueSelectionRect[0] - selectionInset; Vector2f valueSelectionBottomRight = valuesPos + valueSelectionRect[1] + selectionInset; prender->FillRect(valueSelectionTopLeft.x, valueSelectionTopLeft.y, valueSelectionBottomRight.x, valueSelectionBottomRight.y, focusColor); } // Measure and draw title if (DisplayState == Display_Menu && title.GetLength() > 0) { Vector2f titleDimensions; prender->MeasureText(&DejaVu, title.ToCStr(), textSize, &titleDimensions.x); Vector2f titleTopLeft = topLeft - Vector2f(0, borderSize.y) * 2 - Vector2f(0, titleDimensions.y); titleDimensions.x = totalDimensions.x; prender->FillRect(titleTopLeft.x, titleTopLeft.y, titleTopLeft.x + totalDimensions.x, titleTopLeft.y + titleDimensions.y + borderSize.y * 2, titleOutlineColor); prender->FillRect(titleTopLeft.x + borderSize.x / 2, titleTopLeft.y + borderSize.y / 2, titleTopLeft.x + totalDimensions.x - borderSize.x / 2, titleTopLeft.y + borderSize.y / 2 + titleDimensions.y, titleColor); prender->RenderText(&DejaVu, title.ToCStr(), titleTopLeft.x + borderSize.x, titleTopLeft.y + borderSize.y, textSize, Color(255,255,0,210)); } prender->RenderText(&DejaVu, menuItemsCStr, labelsPos.x, labelsPos.y, textSize, Color(255,255,0,210)); prender->RenderText(&DejaVu, valuesCStr, valuesPos.x, valuesPos.y, textSize, Color(255,255,0,210)); } void OptionSelectionMenu::renderShortcutChangeMessage(RenderDevice* prender) { if (ovr_GetTimeInSeconds() < PopupMessageTimeout) { DrawTextBox(prender, 0, 120, 22.0f, PopupMessage.ToCStr(), DrawText_Center | (PopupMessageBorder ? DrawText_Border : 0)); } } void OptionSelectionMenu::SetPopupMessage(const char* format, ...) { //Lock::Locker lock(pManager->GetHandlerLock()); char textBuff[2048]; va_list argList; va_start(argList, format); OVR_vsprintf(textBuff, sizeof(textBuff), format, argList); va_end(argList); // Message will time out in 4 seconds. PopupMessage = textBuff; PopupMessageTimeout = ovr_GetTimeInSeconds() + 4.0f; PopupMessageBorder = false; } void OptionSelectionMenu::SetPopupTimeout(double timeoutSeconds, bool border) { PopupMessageTimeout = ovr_GetTimeInSeconds() + timeoutSeconds; PopupMessageBorder = border; } void OptionSelectionMenu::AddItem(OptionMenuItem* menuItem) { String ns = PopNamespaceFrom(menuItem); if (ns.GetLength() == 0) { Items.PushBack(menuItem); } else { // Item is part of a submenu, add it to that instead. GetOrCreateSubmenu(ns)->AddItem(menuItem); } } //virtual void OptionSelectionMenu::Select() { SelectedIndex = 0; SelectionActive = false; DisplayState = Display_Menu; } OptionSelectionMenu* OptionSelectionMenu::GetSubmenu() { if (!SelectionActive || !Items[SelectedIndex]->IsMenu()) return NULL; OptionSelectionMenu* submenu = static_cast<OptionSelectionMenu*>(Items[SelectedIndex]); return submenu; } OptionSelectionMenu* OptionSelectionMenu::GetOrCreateSubmenu(String submenuName) { for (uint32_t i = 0; i < Items.GetSize(); i++) { if (!Items[i]->IsMenu()) continue; OptionSelectionMenu* submenu = static_cast<OptionSelectionMenu*>(Items[i]); if (submenu->Label == submenuName) { return submenu; } } // Submenu doesn't exist, create it. OptionSelectionMenu* newSubmenu = new OptionSelectionMenu(this); newSubmenu->Label = submenuName; Items.PushBack(newSubmenu); return newSubmenu; } void OptionSelectionMenu::HandleUp(bool* pFast) { int numItems = (int)Items.GetSize(); if (SelectionActive) Items[SelectedIndex]->NextValue(pFast); else SelectedIndex = ((SelectedIndex - 1 + numItems) % numItems); } void OptionSelectionMenu::HandleDown(bool* pFast) { if (SelectionActive) Items[SelectedIndex]->PrevValue(pFast); else SelectedIndex = ((SelectedIndex + 1) % Items.GetSize()); } void OptionSelectionMenu::HandleLeft() { if (DisplayState != Display_Menu) return; if (SelectionActive) SelectionActive = false; else if (ParentMenu) { // Escape to parent menu ParentMenu->SelectionActive = false; DisplayState = Display_Menu; } } void OptionSelectionMenu::HandleRight() { if (DisplayState != Display_Menu) return; if (!SelectionActive) { SelectionActive = true; Items[SelectedIndex]->Select(); } } void OptionSelectionMenu::HandleSelect() { if (!SelectionActive) { SelectionActive = true; Items[SelectedIndex]->Select(); } else { Items[SelectedIndex]->NextValue(); } } void OptionSelectionMenu::HandleBack() { if (DisplayState != Display_Menu) return; if (!SelectionActive) DisplayState = Display_None; else SelectionActive = false; } void OptionSelectionMenu::HandleMenuToggle() { // Mark this & parent With correct visibility. OptionSelectionMenu* menu = this; if (DisplayState == Display_Menu) DisplayState = Display_None; else DisplayState = Display_Menu; while (menu) { menu->DisplayState = DisplayState; menu = menu->ParentMenu; } // Hide message PopupMessageTimeout = 0; } void OptionSelectionMenu::HandleSingleItemToggle() { // Mark this & parent With correct visibility. OptionSelectionMenu* menu = this; if (DisplayState == Display_SingleItem) DisplayState = Display_None; else { DisplayState = Display_SingleItem; SelectionActive = true; } while (menu) { menu->DisplayState = DisplayState; menu = menu->ParentMenu; } // Hide message PopupMessageTimeout = 0; } //------------------------------------------------------------------------------------- // **** Text Rendering / Management void DrawTextBox(RenderDevice* prender, float x, float y, float textSize, const char* text, unsigned centerType) { float ssize[2] = {0.0f, 0.0f}; prender->MeasureText(&DejaVu, text, textSize, ssize); // Treat 0 a VCenter. if (centerType & DrawText_HCenter) { x -= ssize[0]/2; } if (centerType & DrawText_VCenter) { y -= ssize[1]/2; } const float borderSize = 4.0f; float linesHeight = 0.0f; if (centerType & DrawText_Border) linesHeight = 10.0f; prender->FillRect(x-borderSize, y-borderSize - linesHeight, x+ssize[0]+borderSize, y+ssize[1]+borderSize + linesHeight, Color(40,40,100,210)); if (centerType & DrawText_Border) { // Add top & bottom lines float topLineY = y-borderSize - linesHeight * 0.5f, bottomLineY = y+ssize[1]+borderSize + linesHeight * 0.5f; prender->FillRect(x-borderSize * 0.5f, topLineY, x+ssize[0]+borderSize * 0.5f, topLineY + 2.0f, Color(255,255,0,210)); prender->FillRect(x-borderSize * 0.5f, bottomLineY, x+ssize[0]+borderSize * 0.5f, bottomLineY + 2.0f, Color(255,255,0,210)); } prender->RenderText(&DejaVu, text, x, y, textSize, Color(255,255,0,210)); } void CleanupDrawTextFont() { if (DejaVu.fill) { DejaVu.fill->Release(); DejaVu.fill = 0; } }
/** * @file PlatformPCH.cpp * @author zopenge (zopenge@126.com) * @brief The precompiled header of platform module. * @version 0.1 * @date 2021-06-26 * * @copyright Copyright (c) 2021 * */ #include "PlatformPCH.h" #pragma region "Global variables implementation" _thread_id EGE::gMainThreadID = 0; PerformanceData EGE::gPerformanceData; CPUData EGE::gCPUData; GPUData EGE::gGPUData; OSData EGE::gOSData; template <> const PointI PointI::cZeroPoint(0, 0); template <> const PointI PointI::cMaxPoint(0x7FFFFFFF, 0x7FFFFFFF); template <> const PointI PointI::cMinPoint(0x80000001, 0x80000001); template <> const PointU PointU::cZeroPoint(0, 0); template <> const PointU PointU::cMaxPoint(0xFFFFFFFF, 0xFFFFFFFF); template <> const PointU PointU::cMinPoint(0x00000001, 0x00000001); template <> const PointF PointF::cZeroPoint(0.0f, 0.0f); template <> const PointF PointF::cMaxPoint(3.402823466e+38f, 3.402823466e+38f); template <> const PointF PointF::cMinPoint(-3.402823466e+38f, -3.402823466e+38f); template <> const RectI RectI::cNull(0, 0, 0, 0); template <> const RectU RectU::cNull(0, 0, 0, 0); template <> const RectF RectF::cNull(0.0f, 0.0f, 0.0f, 0.0f); template <> const RectI RectI::cMax(Math::cMinInt, Math::cMinInt, Math::cMaxInt, Math::cMaxInt); template <> const RectU RectU::cMax(Math::cMinDword, Math::cMinDword, Math::cMaxDword, Math::cMaxDword); template <> const RectF RectF::cMax(Math::cMinFloat, Math::cMinFloat, Math::cMaxFloat, Math::cMaxFloat); template <> const WordRange WordRange::cNull(0, 0); template <> const DwordRange DwordRange::cNull(0, 0); template <> const QwordRange QwordRange::cNull(0, 0); template <> const FloatRange FloatRange::cNull(0.0f, 0.0f); template <> const WordProgression WordProgression::cNull(0, 0); template <> const DwordProgression DwordProgression::cNull(0, 0); template <> const FloatProgression FloatProgression::cNull(0.0f, 0.0f); template <> const DwordDataField DwordDataField::cNull(0, 0); template <> const QwordParams2 QwordParams2::cNull(0, 0); template <> const QwordParams3 QwordParams3::cNull(0, 0, 0); template <> const QwordParams4 QwordParams4::cNull(0, 0, 0, 0); #pragma endregion //---------------------------------------------------------------------------- // External Template Functions Implementation //---------------------------------------------------------------------------- namespace EGE { _int TemplateExternal::CompareString(const _chara* string1, const _chara* string2, _ubool ignorecase) { return Platform::CompareString(string1, string2, ignorecase); } _dword TemplateExternal::StringLength(const _chara* string) { return Platform::StringLength(string); } _chara* TemplateExternal::ConvertLongToString(_int value, _dword radix, _chara* string, _dword length) { return Platform::ConvertLongToString(value, radix, string, length); } _chara* TemplateExternal::ConvertDwordToString(_dword value, _dword radix, _chara* string, _dword length) { return Platform::ConvertDwordToString(value, radix, string, length); } _chara* TemplateExternal::ConvertLargeToString(_large value, _dword radix, _chara* string, _dword length) { return Platform::ConvertLargeToString(value, radix, string, length); } _chara* TemplateExternal::ConvertQwordToString(_qword value, _dword radix, _chara* string, _dword length) { return Platform::ConvertQwordToString(value, radix, string, length); } _chara* TemplateExternal::ConvertFloatToString(_float value, _chara* string, _dword length, _dword precision) { return Platform::ConvertFloatToString(value, string, length, precision); } _chara* TemplateExternal::ConvertDoubleToString(_double value, _chara* string, _dword length, _dword precision) { return Platform::ConvertDoubleToString(value, string, length, precision); } _ubool TemplateExternal::ConvertStringToBool(const _chara* string) { return Platform::ConvertStringToBool(string); } _int TemplateExternal::ConvertStringToLong(const _chara* string, _dword radix) { return Platform::ConvertStringToLong(string, radix); } _dword TemplateExternal::ConvertStringToDword(const _chara* string, _dword radix) { return Platform::ConvertStringToDword(string, radix); } _large TemplateExternal::ConvertStringToLarge(const _chara* string, _dword radix) { return Platform::ConvertStringToLarge(string, radix); } _qword TemplateExternal::ConvertStringToQword(const _chara* string, _dword radix) { return Platform::ConvertStringToQword(string, radix); } _float TemplateExternal::ConvertStringToFloat(const _chara* string) { return Platform::ConvertStringToFloat(string); } _double TemplateExternal::ConvertStringToDouble(const _chara* string) { return Platform::ConvertStringToDouble(string); } _dword TemplateExternal::SearchL2R(const _chara* string, _chara character, _ubool ignorecase) { return Platform::SearchL2R(string, character, ignorecase); } _dword TemplateExternal::SearchL2R(const _chara* string, const _chara* substring, _ubool ignorecase, _dword* endindex) { return Platform::SearchL2R(string, substring, ignorecase, endindex); } _dword TemplateExternal::SearchR2L(const _chara* string, _chara character, _ubool ignorecase) { return Platform::SearchR2L(string, character, ignorecase); } _dword TemplateExternal::SearchR2L(const _chara* string, const _chara* substring, _ubool ignorecase, _dword* startindex) { return Platform::SearchR2L(string, substring, ignorecase, startindex); } _ubool TemplateExternal::CompareWildcard(const _chara* string, const _chara* matchstring, _ubool ignorecase) { return Platform::CompareWildcard(string, matchstring, ignorecase); } _ubool TemplateExternal::IsBlank(const _chara* string) { return Platform::IsBlank(string); } _ubool TemplateExternal::IsFullpath(const _chara* path) { return Platform::IsFullpath(path); } _chara* TemplateExternal::LowercaseString(_chara* string, _dword number) { return Platform::LowercaseString(string, number); } _chara* TemplateExternal::UppercaseString(_chara* string, _dword number) { return Platform::UppercaseString(string, number); } _chara* TemplateExternal::TrimStringLeft(_chara* string, _dword& stringlength, _chara character, _ubool ignorecase) { return Platform::TrimStringLeft(string, stringlength, character, ignorecase); } _chara* TemplateExternal::TrimStringRight(_chara* string, _dword& stringlength, _chara character, _ubool ignorecase) { return Platform::TrimStringRight(string, stringlength, character, ignorecase); } _chara* TemplateExternal::TrimStringBoth(_chara* string, _dword& stringlength, _chara character, _ubool ignorecase) { return Platform::TrimStringBoth(string, stringlength, character, ignorecase); } _chara* TemplateExternal::TrimStringLeft(_chara* string, _dword& stringlength, const _chara* charset, _ubool ignorecase) { return Platform::TrimStringLeft(string, stringlength, charset, ignorecase); } _chara* TemplateExternal::TrimStringRight(_chara* string, _dword& stringlength, const _chara* charset, _ubool ignorecase) { return Platform::TrimStringRight(string, stringlength, charset, ignorecase); } _chara* TemplateExternal::TrimStringBoth(_chara* string, _dword& stringlength, const _chara* charset, _ubool ignorecase) { return Platform::TrimStringBoth(string, stringlength, charset, ignorecase); } _dword TemplateExternal::GetFormatStringLength(const _chara* format, _va_list arguments) { return Platform::GetFormatStringLength(format, arguments); } _chara* TemplateExternal::FormatStringByVAList(_chara* buffer, _dword size, const _chara* format, _va_list arguments) { return Platform::FormatStringByVAList(buffer, size, format, arguments); } _int TemplateExternal::CompareString(const _charw* string1, const _charw* string2, _ubool ignorecase) { return Platform::CompareString(string1, string2, ignorecase); } _dword TemplateExternal::StringLength(const _charw* string) { return Platform::StringLength(string); } _charw* TemplateExternal::ConvertLongToString(_int value, _dword radix, _charw* string, _dword length) { return Platform::ConvertLongToString(value, radix, string, length); } _charw* TemplateExternal::ConvertDwordToString(_dword value, _dword radix, _charw* string, _dword length) { return Platform::ConvertDwordToString(value, radix, string, length); } _charw* TemplateExternal::ConvertLargeToString(_large value, _dword radix, _charw* string, _dword length) { return Platform::ConvertLargeToString(value, radix, string, length); } _charw* TemplateExternal::ConvertQwordToString(_qword value, _dword radix, _charw* string, _dword length) { return Platform::ConvertQwordToString(value, radix, string, length); } _charw* TemplateExternal::ConvertFloatToString(_float value, _charw* string, _dword length, _dword precision) { return Platform::ConvertFloatToString(value, string, length, precision); } _charw* TemplateExternal::ConvertDoubleToString(_double value, _charw* string, _dword length, _dword precision) { return Platform::ConvertDoubleToString(value, string, length, precision); } _ubool TemplateExternal::ConvertStringToBool(const _charw* string) { return Platform::ConvertStringToBool(string); } _int TemplateExternal::ConvertStringToLong(const _charw* string, _dword radix) { return Platform::ConvertStringToLong(string, radix); } _dword TemplateExternal::ConvertStringToDword(const _charw* string, _dword radix) { return Platform::ConvertStringToDword(string, radix); } _large TemplateExternal::ConvertStringToLarge(const _charw* string, _dword radix) { return Platform::ConvertStringToLarge(string, radix); } _qword TemplateExternal::ConvertStringToQword(const _charw* string, _dword radix) { return Platform::ConvertStringToQword(string, radix); } _float TemplateExternal::ConvertStringToFloat(const _charw* string) { return Platform::ConvertStringToFloat(string); } _double TemplateExternal::ConvertStringToDouble(const _charw* string) { return Platform::ConvertStringToDouble(string); } _dword TemplateExternal::SearchL2R(const _charw* string, _charw character, _ubool ignorecase) { return Platform::SearchL2R(string, character, ignorecase); } _dword TemplateExternal::SearchL2R(const _charw* string, const _charw* substring, _ubool ignorecase, _dword* endindex) { return Platform::SearchL2R(string, substring, ignorecase, endindex); } _dword TemplateExternal::SearchR2L(const _charw* string, _charw character, _ubool ignorecase) { return Platform::SearchR2L(string, character, ignorecase); } _dword TemplateExternal::SearchR2L(const _charw* string, const _charw* substring, _ubool ignorecase, _dword* startindex) { return Platform::SearchR2L(string, substring, ignorecase, startindex); } _ubool TemplateExternal::CompareWildcard(const _charw* string, const _charw* matchstring, _ubool ignorecase) { return Platform::CompareWildcard(string, matchstring, ignorecase); } _ubool TemplateExternal::IsBlank(const _charw* string) { return Platform::IsBlank(string); } _ubool TemplateExternal::IsFullpath(const _charw* path) { return Platform::IsFullpath(path); } _charw* TemplateExternal::LowercaseString(_charw* string, _dword number) { return Platform::LowercaseString(string, number); } _charw* TemplateExternal::UppercaseString(_charw* string, _dword number) { return Platform::UppercaseString(string, number); } _charw* TemplateExternal::TrimStringLeft(_charw* string, _dword& stringlength, _charw character, _ubool ignorecase) { return Platform::TrimStringLeft(string, stringlength, character, ignorecase); } _charw* TemplateExternal::TrimStringRight(_charw* string, _dword& stringlength, _charw character, _ubool ignorecase) { return Platform::TrimStringRight(string, stringlength, character, ignorecase); } _charw* TemplateExternal::TrimStringBoth(_charw* string, _dword& stringlength, _charw character, _ubool ignorecase) { return Platform::TrimStringBoth(string, stringlength, character, ignorecase); } _charw* TemplateExternal::TrimStringLeft(_charw* string, _dword& stringlength, const _charw* charset, _ubool ignorecase) { return Platform::TrimStringLeft(string, stringlength, charset, ignorecase); } _charw* TemplateExternal::TrimStringRight(_charw* string, _dword& stringlength, const _charw* charset, _ubool ignorecase) { return Platform::TrimStringRight(string, stringlength, charset, ignorecase); } _charw* TemplateExternal::TrimStringBoth(_charw* string, _dword& stringlength, const _charw* charset, _ubool ignorecase) { return Platform::TrimStringBoth(string, stringlength, charset, ignorecase); } _dword TemplateExternal::GetFormatStringLength(const _charw* format, _va_list arguments) { return Platform::GetFormatStringLength(format, arguments); } _charw* TemplateExternal::FormatStringByVAList(_charw* buffer, _dword size, const _charw* format, _va_list arguments) { return Platform::FormatStringByVAList(buffer, size, format, arguments); } _dword TemplateExternal::AnsiToUtf16(_charw* buffer, _dword size, const _chara* string, _dword number) { return Platform::AnsiToUtf16(buffer, size, string, number); } _dword TemplateExternal::Utf16ToAnsi(_chara* buffer, _dword size, const _charw* string, _dword number) { return Platform::Utf16ToAnsi(buffer, size, string, number); } _dword TemplateExternal::Utf8ToUtf16(_charw* buffer, _dword size, const _chara* string, _dword number) { return Platform::Utf8ToUtf16(buffer, size, string, number); } _dword TemplateExternal::Utf16ToUtf8(_chara* buffer, _dword size, const _charw* string, _dword number) { return Platform::Utf16ToUtf8(buffer, size, string, number); } _dword TemplateExternal::BuildFromString(const _chara* string, _dword oldcrc) { return CRC::BuildFromString(string, oldcrc); } _dword TemplateExternal::BuildFromString(const _charw* string, _dword oldcrc) { return CRC::BuildFromString(string, oldcrc); } } // namespace EGE //---------------------------------------------------------------------------- // Memory Overload Implementation //---------------------------------------------------------------------------- #ifndef _USE_STANDARD_MEM_OPERATOR_ # ifndef _USE_STANDARD_MALLOC_OPERATOR_ void _ege_free(void* pointer, const char* filename, int linenumber) { EGE::Memory::GetInstance().Free(pointer, filename, linenumber); } void* _ege_malloc(size_t size, const char* filename, int linenumber) { return EGE::Memory::GetInstance().Alloc((_dword)size, filename, linenumber); } void* _ege_calloc(size_t number, size_t size, const char* filename, int linenumber) { EGE::_void* buffer = EGE::Memory::GetInstance().Alloc((_dword)(number * size), filename, linenumber); if (buffer != _null) { EGE_MEM_SET(buffer, 0, number * size); } return buffer; } void* _ege_realloc(void* pointer, size_t size, const char* filename, int linenumber) { return EGE::Memory::GetInstance().Realloc(pointer, (_dword)size, filename, linenumber); } # endif # undef new // Overload New And Delete Operations void* operator new(size_t size) { return EGE::Memory::GetInstance().Alloc((EGE::_dword)size, _null, 0); } void* operator new(size_t size, const char* filename, int linenumber) { return EGE::Memory::GetInstance().Alloc((EGE::_dword)size, filename, linenumber); } void* operator new[](size_t size) { return EGE::Memory::GetInstance().Alloc((EGE::_dword)size, _null, 0); } void* operator new[](size_t size, const char* filename, int linenumber) { return EGE::Memory::GetInstance().Alloc((EGE::_dword)size, filename, linenumber); } void operator delete(void* pointer) { return EGE::Memory::GetInstance().Free(pointer, _null, 0); } void operator delete(void* pointer, const char* filename, int linenumber) { return EGE::Memory::GetInstance().Free(pointer, filename, linenumber); } void operator delete[](void* pointer) { return EGE::Memory::GetInstance().Free(pointer, _null, 0); } void operator delete[](void* pointer, const char* filename, int linenumber) { return EGE::Memory::GetInstance().Free(pointer, filename, linenumber); } #endif // _USE_STANDARD_MEM_OPERATOR_
#include <std/ref.h> #include <cstdio> #include <cstdlib> #include <cstring> #include <iostream> #include <sstream> #include <vector> #include <uv.h> #include <atframe/atapp.h> #include <common/file_system.h> #include <time/time_utility.h> #include "atproxy_manager.h" static int app_handle_on_response(atapp::app &app, const atapp::app::message_sender_t &source, const atapp::app::message_t &msg, int32_t error_code) { if (error_code < 0) { FWLOGERROR("send data from {:#x} to {:#x} failed, sequence: {}, code: {}", app.get_id(), source.id, msg.msg_sequence, error_code); } else { FWLOGDEBUG("send data from {:#x} to {:#x} finished, sequence: {}", app.get_id(), source.id, msg.msg_sequence); } return 0; } struct app_handle_on_connected { std::reference_wrapper<atframe::proxy::atproxy_manager> atproxy_mgr_module; app_handle_on_connected(atframe::proxy::atproxy_manager &mod) : atproxy_mgr_module(mod) {} int operator()(atapp::app &app, atbus::endpoint &ep, int status) { WLOGINFO("node 0x%llx connected, status: %d", static_cast<unsigned long long>(ep.get_id()), status); atproxy_mgr_module.get().on_connected(app, ep.get_id()); return 0; } }; struct app_handle_on_disconnected { std::reference_wrapper<atframe::proxy::atproxy_manager> atproxy_mgr_module; app_handle_on_disconnected(atframe::proxy::atproxy_manager &mod) : atproxy_mgr_module(mod) {} int operator()(atapp::app &app, atbus::endpoint &ep, int status) { WLOGINFO("node 0x%llx disconnected, status: %d", static_cast<unsigned long long>(ep.get_id()), status); atproxy_mgr_module.get().on_disconnected(app, ep.get_id()); return 0; } }; int main(int argc, char *argv[]) { atapp::app app; std::shared_ptr<atframe::proxy::atproxy_manager> proxy_mgr_mod = std::make_shared<atframe::proxy::atproxy_manager>(); if (!proxy_mgr_mod) { fprintf(stderr, "create atproxy manager module failed\n"); return -1; } // project directory { std::string proj_dir; util::file_system::dirname(__FILE__, 0, proj_dir, 4); util::log::log_formatter::set_project_directory(proj_dir.c_str(), proj_dir.size()); } // setup module app.add_module(proxy_mgr_mod); // setup message handle app.set_evt_on_forward_response(app_handle_on_response); app.set_evt_on_app_connected(app_handle_on_connected(*proxy_mgr_mod)); app.set_evt_on_app_disconnected(app_handle_on_disconnected(*proxy_mgr_mod)); // run return app.run(uv_default_loop(), argc, (const char **)argv, NULL); }