blob: 9f77261075eca5e8aecea945bae4b7c8d8f1bd18 [file] [log] [blame]
Olli Etuaho853dc1a2014-11-06 17:25:48 +02001//
2// Copyright (c) 2002-2014 The ANGLE Project Authors. All rights reserved.
3// Use of this source code is governed by a BSD-style license that can be
4// found in the LICENSE file.
5//
6
7#include "compiler/translator/EmulatePrecision.h"
8
9namespace
10{
11
12static void writeVectorPrecisionEmulationHelpers(
13 TInfoSinkBase& sink, ShShaderOutput outputLanguage, unsigned int size)
14{
15 std::stringstream vecTypeStrStr;
16 if (outputLanguage == SH_ESSL_OUTPUT)
17 vecTypeStrStr << "highp ";
18 vecTypeStrStr << "vec" << size;
19 std::string vecType = vecTypeStrStr.str();
20
21 sink <<
22 vecType << " angle_frm(in " << vecType << " v) {\n"
23 " v = clamp(v, -65504.0, 65504.0);\n"
24 " " << vecType << " exponent = floor(log2(abs(v) + 1e-30)) - 10.0;\n"
25 " bvec" << size << " isNonZero = greaterThanEqual(exponent, vec" << size << "(-25.0));\n"
26 " v = v * exp2(-exponent);\n"
27 " v = sign(v) * floor(abs(v));\n"
28 " return v * exp2(exponent) * vec" << size << "(isNonZero);\n"
29 "}\n";
30
31 sink <<
32 vecType << " angle_frl(in " << vecType << " v) {\n"
33 " v = clamp(v, -2.0, 2.0);\n"
34 " v = v * 256.0;\n"
35 " v = sign(v) * floor(abs(v));\n"
36 " return v * 0.00390625;\n"
37 "}\n";
38}
39
40static void writeMatrixPrecisionEmulationHelper(
41 TInfoSinkBase& sink, ShShaderOutput outputLanguage, unsigned int size, const char *functionName)
42{
43 std::stringstream matTypeStrStr;
44 if (outputLanguage == SH_ESSL_OUTPUT)
45 matTypeStrStr << "highp ";
46 matTypeStrStr << "mat" << size;
47 std::string matType = matTypeStrStr.str();
48
49 sink << matType << " " << functionName << "(in " << matType << " m) {\n"
50 " " << matType << " rounded;\n";
51
52 for (unsigned int i = 0; i < size; ++i)
53 {
54 sink << " rounded[" << i << "] = " << functionName << "(m[" << i << "]);\n";
55 }
56
57 sink << " return rounded;\n"
58 "}\n";
59}
60
61static void writeCommonPrecisionEmulationHelpers(TInfoSinkBase& sink, ShShaderOutput outputLanguage)
62{
63 // Write the angle_frm functions that round floating point numbers to
64 // half precision, and angle_frl functions that round them to minimum lowp
65 // precision.
66
67 // Unoptimized version of angle_frm for single floats:
68 //
69 // int webgl_maxNormalExponent(in int exponentBits) {
70 // int possibleExponents = int(exp2(float(exponentBits)));
71 // int exponentBias = possibleExponents / 2 - 1;
72 // int allExponentBitsOne = possibleExponents - 1;
73 // return (allExponentBitsOne - 1) - exponentBias;
74 // }
75 //
76 // float angle_frm(in float x) {
77 // int mantissaBits = 10;
78 // int exponentBits = 5;
79 // float possibleMantissas = exp2(float(mantissaBits));
80 // float mantissaMax = 2.0 - 1.0 / possibleMantissas;
81 // int maxNE = webgl_maxNormalExponent(exponentBits);
82 // float max = exp2(float(maxNE)) * mantissaMax;
83 // if (x > max) {
84 // return max;
85 // }
86 // if (x < -max) {
87 // return -max;
88 // }
89 // float exponent = floor(log2(abs(x)));
90 // if (abs(x) == 0.0 || exponent < -float(maxNE)) {
91 // return 0.0 * sign(x)
92 // }
93 // x = x * exp2(-(exponent - float(mantissaBits)));
94 // x = sign(x) * floor(abs(x));
95 // return x * exp2(exponent - float(mantissaBits));
96 // }
97
98 // All numbers with a magnitude less than 2^-15 are subnormal, and are
99 // flushed to zero.
100
101 // Note the constant numbers below:
102 // a) 65504 is the maximum possible mantissa (1.1111111111 in binary) times
103 // 2^15, the maximum normal exponent.
104 // b) 10.0 is the number of mantissa bits.
105 // c) -25.0 is the minimum normal half-float exponent -15.0 minus the number
106 // of mantissa bits.
107 // d) + 1e-30 is to make sure the argument of log2() won't be zero. It can
108 // only affect the result of log2 on x where abs(x) < 1e-22. Since these
109 // numbers will be flushed to zero either way (2^-15 is the smallest
110 // normal positive number), this does not introduce any error.
111
112 std::string floatType = "float";
113 if (outputLanguage == SH_ESSL_OUTPUT)
114 floatType = "highp float";
115
116 sink <<
117 floatType << " angle_frm(in " << floatType << " x) {\n"
118 " x = clamp(x, -65504.0, 65504.0);\n"
119 " " << floatType << " exponent = floor(log2(abs(x) + 1e-30)) - 10.0;\n"
120 " bool isNonZero = (exponent >= -25.0);\n"
121 " x = x * exp2(-exponent);\n"
122 " x = sign(x) * floor(abs(x));\n"
123 " return x * exp2(exponent) * float(isNonZero);\n"
124 "}\n";
125
126 sink <<
127 floatType << " angle_frl(in " << floatType << " x) {\n"
128 " x = clamp(x, -2.0, 2.0);\n"
129 " x = x * 256.0;\n"
130 " x = sign(x) * floor(abs(x));\n"
131 " return x * 0.00390625;\n"
132 "}\n";
133
134 writeVectorPrecisionEmulationHelpers(sink, outputLanguage, 2);
135 writeVectorPrecisionEmulationHelpers(sink, outputLanguage, 3);
136 writeVectorPrecisionEmulationHelpers(sink, outputLanguage, 4);
137 for (unsigned int size = 2; size <= 4; ++size)
138 {
139 writeMatrixPrecisionEmulationHelper(sink, outputLanguage, size, "angle_frm");
140 writeMatrixPrecisionEmulationHelper(sink, outputLanguage, size, "angle_frl");
141 }
142}
143
144static void writeCompoundAssignmentPrecisionEmulation(
145 TInfoSinkBase& sink, ShShaderOutput outputLanguage,
146 const char *lType, const char *rType, const char *opStr, const char *opNameStr)
147{
148 std::string lTypeStr = lType;
149 std::string rTypeStr = rType;
150 if (outputLanguage == SH_ESSL_OUTPUT)
151 {
152 std::stringstream lTypeStrStr;
153 lTypeStrStr << "highp " << lType;
154 lTypeStr = lTypeStrStr.str();
155 std::stringstream rTypeStrStr;
156 rTypeStrStr << "highp " << rType;
157 rTypeStr = rTypeStrStr.str();
158 }
159
160 // Note that y should be passed through angle_frm at the function call site,
161 // but x can't be passed through angle_frm there since it is an inout parameter.
162 // So only pass x and the result through angle_frm here.
163 sink <<
164 lTypeStr << " angle_compound_" << opNameStr << "_frm(inout " << lTypeStr << " x, in " << rTypeStr << " y) {\n"
165 " x = angle_frm(angle_frm(x) " << opStr << " y);\n"
166 " return x;\n"
167 "}\n";
168 sink <<
169 lTypeStr << " angle_compound_" << opNameStr << "_frl(inout " << lTypeStr << " x, in " << rTypeStr << " y) {\n"
170 " x = angle_frl(angle_frm(x) " << opStr << " y);\n"
171 " return x;\n"
172 "}\n";
173}
174
175const char *getFloatTypeStr(const TType& type)
176{
177 switch (type.getNominalSize())
178 {
179 case 1:
180 return "float";
181 case 2:
182 return type.getSecondarySize() > 1 ? "mat2" : "vec2";
183 case 3:
184 return type.getSecondarySize() > 1 ? "mat3" : "vec3";
185 case 4:
186 return type.getSecondarySize() > 1 ? "mat4" : "vec4";
187 default:
188 UNREACHABLE();
189 return NULL;
190 }
191}
192
193bool canRoundFloat(const TType &type)
194{
195 return type.getBasicType() == EbtFloat && !type.isNonSquareMatrix() && !type.isArray() &&
196 (type.getPrecision() == EbpLow || type.getPrecision() == EbpMedium);
197}
198
199TIntermAggregate *createInternalFunctionCallNode(TString name, TIntermNode *child)
200{
201 TIntermAggregate *callNode = new TIntermAggregate();
202 callNode->setOp(EOpInternalFunctionCall);
203 callNode->setName(name);
204 callNode->getSequence()->push_back(child);
205 return callNode;
206}
207
208TIntermAggregate *createRoundingFunctionCallNode(TIntermTyped *roundedChild)
209{
210 TString roundFunctionName;
211 if (roundedChild->getPrecision() == EbpMedium)
212 roundFunctionName = "angle_frm";
213 else
214 roundFunctionName = "angle_frl";
215 return createInternalFunctionCallNode(roundFunctionName, roundedChild);
216}
217
218TIntermAggregate *createCompoundAssignmentFunctionCallNode(TIntermTyped *left, TIntermTyped *right, const char *opNameStr)
219{
220 std::stringstream strstr;
221 if (left->getPrecision() == EbpMedium)
222 strstr << "angle_compound_" << opNameStr << "_frm";
223 else
224 strstr << "angle_compound_" << opNameStr << "_frl";
225 TString functionName = strstr.str().c_str();
226 TIntermAggregate *callNode = createInternalFunctionCallNode(functionName, left);
227 callNode->getSequence()->push_back(right);
228 return callNode;
229}
230
231} // namespace anonymous
232
233EmulatePrecision::EmulatePrecision()
234 : TIntermTraverser(true, true, true),
235 mDeclaringVariables(false),
236 mInLValue(false),
237 mInFunctionCallOutParameter(false)
238{}
239
240void EmulatePrecision::visitSymbol(TIntermSymbol *node)
241{
242 if (canRoundFloat(node->getType()) &&
243 !mDeclaringVariables && !mInLValue && !mInFunctionCallOutParameter)
244 {
245 TIntermNode *parent = getParentNode();
246 TIntermNode *replacement = createRoundingFunctionCallNode(node);
247 mReplacements.push_back(NodeUpdateEntry(parent, node, replacement, true));
248 }
249}
250
251
252bool EmulatePrecision::visitBinary(Visit visit, TIntermBinary *node)
253{
254 bool visitChildren = true;
255
256 if (node->isAssignment())
257 {
258 if (visit == PreVisit)
259 mInLValue = true;
260 else if (visit == InVisit)
261 mInLValue = false;
262 }
263
264 TOperator op = node->getOp();
265
266 // RHS of initialize is not being declared.
267 if (op == EOpInitialize && visit == InVisit)
268 mDeclaringVariables = false;
269
270 if ((op == EOpIndexDirectStruct || op == EOpVectorSwizzle) && visit == InVisit)
271 visitChildren = false;
272
273 if (visit != PreVisit)
274 return visitChildren;
275
276 const TType& type = node->getType();
277 bool roundFloat = canRoundFloat(type);
278
279 if (roundFloat) {
280 switch (op) {
281 // Math operators that can result in a float may need to apply rounding to the return
282 // value. Note that in the case of assignment, the rounding is applied to its return
283 // value here, not the value being assigned.
284 case EOpAssign:
285 case EOpAdd:
286 case EOpSub:
287 case EOpMul:
288 case EOpDiv:
289 case EOpVectorTimesScalar:
290 case EOpVectorTimesMatrix:
291 case EOpMatrixTimesVector:
292 case EOpMatrixTimesScalar:
293 case EOpMatrixTimesMatrix:
294 {
295 TIntermNode *parent = getParentNode();
296 TIntermNode *replacement = createRoundingFunctionCallNode(node);
297 mReplacements.push_back(NodeUpdateEntry(parent, node, replacement, true));
298 break;
299 }
300
301 // Compound assignment cases need to replace the operator with a function call.
302 case EOpAddAssign:
303 {
304 mEmulateCompoundAdd.insert(TypePair(getFloatTypeStr(type), getFloatTypeStr(node->getRight()->getType())));
305 TIntermNode *parent = getParentNode();
306 TIntermNode *replacement = createCompoundAssignmentFunctionCallNode(node->getLeft(), node->getRight(), "add");
307 mReplacements.push_back(NodeUpdateEntry(parent, node, replacement, false));
308 break;
309 }
310 case EOpSubAssign:
311 {
312 mEmulateCompoundSub.insert(TypePair(getFloatTypeStr(type), getFloatTypeStr(node->getRight()->getType())));
313 TIntermNode *parent = getParentNode();
314 TIntermNode *replacement = createCompoundAssignmentFunctionCallNode(node->getLeft(), node->getRight(), "sub");
315 mReplacements.push_back(NodeUpdateEntry(parent, node, replacement, false));
316 break;
317 }
318 case EOpMulAssign:
319 case EOpVectorTimesMatrixAssign:
320 case EOpVectorTimesScalarAssign:
321 case EOpMatrixTimesScalarAssign:
322 case EOpMatrixTimesMatrixAssign:
323 {
324 mEmulateCompoundMul.insert(TypePair(getFloatTypeStr(type), getFloatTypeStr(node->getRight()->getType())));
325 TIntermNode *parent = getParentNode();
326 TIntermNode *replacement = createCompoundAssignmentFunctionCallNode(node->getLeft(), node->getRight(), "mul");
327 mReplacements.push_back(NodeUpdateEntry(parent, node, replacement, false));
328 break;
329 }
330 case EOpDivAssign:
331 {
332 mEmulateCompoundDiv.insert(TypePair(getFloatTypeStr(type), getFloatTypeStr(node->getRight()->getType())));
333 TIntermNode *parent = getParentNode();
334 TIntermNode *replacement = createCompoundAssignmentFunctionCallNode(node->getLeft(), node->getRight(), "div");
335 mReplacements.push_back(NodeUpdateEntry(parent, node, replacement, false));
336 break;
337 }
338 default:
339 // The rest of the binary operations should not need precision emulation.
340 break;
341 }
342 }
343 return visitChildren;
344}
345
346bool EmulatePrecision::visitAggregate(Visit visit, TIntermAggregate *node)
347{
348 bool visitChildren = true;
349 switch (node->getOp())
350 {
351 case EOpSequence:
352 case EOpConstructStruct:
353 // No special handling
354 break;
355 case EOpFunction:
356 if (visit == PreVisit)
357 {
358 const TIntermSequence &sequence = *(node->getSequence());
359 TIntermSequence::const_iterator seqIter = sequence.begin();
360 TIntermAggregate *params = (*seqIter)->getAsAggregate();
361 ASSERT(params != NULL);
362 ASSERT(params->getOp() == EOpParameters);
363 mFunctionMap[node->getName()] = params->getSequence();
364 }
365 break;
366 case EOpPrototype:
367 if (visit == PreVisit)
368 mFunctionMap[node->getName()] = node->getSequence();
369 visitChildren = false;
370 break;
371 case EOpParameters:
372 visitChildren = false;
373 break;
374 case EOpInvariantDeclaration:
375 visitChildren = false;
376 break;
377 case EOpDeclaration:
378 // Variable declaration.
379 if (visit == PreVisit)
380 {
381 mDeclaringVariables = true;
382 }
383 else if (visit == InVisit)
384 {
385 mDeclaringVariables = true;
386 }
387 else
388 {
389 mDeclaringVariables = false;
390 }
391 break;
392 case EOpFunctionCall:
393 {
394 // Function call.
395 bool inFunctionMap = (mFunctionMap.find(node->getName()) != mFunctionMap.end());
396 if (visit == PreVisit)
397 {
398 if (canRoundFloat(node->getType()) && !inFunctionMap) {
399 TIntermNode *parent = getParentNode();
400 TIntermNode *replacement = createRoundingFunctionCallNode(node);
401 mReplacements.push_back(NodeUpdateEntry(parent, node, replacement, true));
402 }
403
404 if (inFunctionMap)
405 {
406 mSeqIterStack.push_back(mFunctionMap[node->getName()]->begin());
407 if (mSeqIterStack.back() != mFunctionMap[node->getName()]->end())
408 {
409 TQualifier qualifier = (*mSeqIterStack.back())->getAsTyped()->getQualifier();
410 mInFunctionCallOutParameter = (qualifier == EvqOut || qualifier == EvqInOut);
411 }
412 }
413 else
414 {
415 // The function is not user-defined - it is likely built-in texture function.
416 // Assume that those do not have out parameters.
417 mInFunctionCallOutParameter = false;
418 }
419 }
420 else if (visit == InVisit)
421 {
422 if (inFunctionMap)
423 {
424 ++mSeqIterStack.back();
425 TQualifier qualifier = (*mSeqIterStack.back())->getAsTyped()->getQualifier();
426 mInFunctionCallOutParameter = (qualifier == EvqOut || qualifier == EvqInOut);
427 }
428 }
429 else
430 {
431 if (inFunctionMap)
432 {
433 mSeqIterStack.pop_back();
434 mInFunctionCallOutParameter = false;
435 }
436 }
437 break;
438 }
439 default:
440 if (canRoundFloat(node->getType()) && visit == PreVisit)
441 {
442 TIntermNode *parent = getParentNode();
443 TIntermNode *replacement = createRoundingFunctionCallNode(node);
444 mReplacements.push_back(NodeUpdateEntry(parent, node, replacement, true));
445 }
446 break;
447 }
448 return visitChildren;
449}
450
451bool EmulatePrecision::visitUnary(Visit visit, TIntermUnary *node)
452{
453 switch (node->getOp())
454 {
455 case EOpNegative:
456 case EOpVectorLogicalNot:
457 case EOpLogicalNot:
458 break;
459 case EOpPostIncrement:
460 case EOpPostDecrement:
461 case EOpPreIncrement:
462 case EOpPreDecrement:
463 if (visit == PreVisit)
464 mInLValue = true;
465 else if (visit == PostVisit)
466 mInLValue = false;
467 break;
468 default:
469 if (canRoundFloat(node->getType()) && visit == PreVisit)
470 {
471 TIntermNode *parent = getParentNode();
472 TIntermNode *replacement = createRoundingFunctionCallNode(node);
473 mReplacements.push_back(NodeUpdateEntry(parent, node, replacement, true));
474 }
475 break;
476 }
477
478 return true;
479}
480
481void EmulatePrecision::writeEmulationHelpers(TInfoSinkBase& sink, ShShaderOutput outputLanguage)
482{
483 // Other languages not yet supported
484 ASSERT(outputLanguage == SH_GLSL_OUTPUT || outputLanguage == SH_ESSL_OUTPUT);
485 writeCommonPrecisionEmulationHelpers(sink, outputLanguage);
486
487 EmulationSet::const_iterator it;
488 for (it = mEmulateCompoundAdd.begin(); it != mEmulateCompoundAdd.end(); it++)
489 writeCompoundAssignmentPrecisionEmulation(sink, outputLanguage, it->lType, it->rType, "+", "add");
490 for (it = mEmulateCompoundSub.begin(); it != mEmulateCompoundSub.end(); it++)
491 writeCompoundAssignmentPrecisionEmulation(sink, outputLanguage, it->lType, it->rType, "-", "sub");
492 for (it = mEmulateCompoundDiv.begin(); it != mEmulateCompoundDiv.end(); it++)
493 writeCompoundAssignmentPrecisionEmulation(sink, outputLanguage, it->lType, it->rType, "/", "div");
494 for (it = mEmulateCompoundMul.begin(); it != mEmulateCompoundMul.end(); it++)
495 writeCompoundAssignmentPrecisionEmulation(sink, outputLanguage, it->lType, it->rType, "*", "mul");
496}
497