text
stringlengths 5
1.04M
|
|---|
#pragma once
#include "Utils.hpp"
#include "Program.hpp"
#include "Shader.hpp"
#include "Uniform.hpp"
#include "VertexArray.hpp"
#include "VertexAttribute.hpp"
#include "VertexBuffer.hpp"
|
#include "catch.hpp"
#include "common/file_system.hpp"
#include "duckdb.hpp"
#include "main/appender.hpp"
#include "test_helpers.hpp"
#include <signal.h>
#include <sys/mman.h>
#include <unistd.h>
using namespace duckdb;
using namespace std;
TEST_CASE("Test transactional integrity when facing process aborts", "[persistence][.]") {
FileSystem fs;
// shared memory to keep track of insertions
size_t *count = (size_t *)mmap(NULL, sizeof(size_t), PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_SHARED, 0, 0);
string db_folder_parent = TestCreatePath("llstorage");
if (fs.DirectoryExists(db_folder_parent)) {
fs.RemoveDirectory(db_folder_parent);
}
fs.CreateDirectory(db_folder_parent);
string db_folder = fs.JoinPath(db_folder_parent, "dbfolder");
{
DuckDB db(db_folder);
Connection con(db);
con.Query("CREATE TABLE a (i INTEGER)");
}
// fork away a child to be mercilessy shot in a bit
pid_t pid = fork();
if (pid == 0) { // child process
DuckDB db(db_folder);
Connection con(db);
while (true) {
con.Query("INSERT INTO a VALUES(42)");
(*count)++;
}
} else if (pid > 0) { // parent process
// wait until child has inserted at least 1000 rows
while (*count < 1000) {
usleep(100);
}
if (kill(pid, SIGKILL) != 0) {
FAIL();
}
unique_ptr<DuckDB> db;
// it may take some time for the OS to reclaim the lock
// loop and wait until the database is successfully started again
for (size_t i = 0; i < 1000; i++) {
usleep(10000);
try {
db = make_unique<DuckDB>(db_folder);
} catch (...) {
}
if (db) {
break;
}
}
Connection con(*db);
auto res = con.Query("SELECT COUNT(*) FROM a");
// there may be an off-by-one if we kill exactly between query and count increment
REQUIRE(abs((int64_t)(res->GetValue(0, 0).GetNumericValue() - *count)) < 2);
} else {
FAIL();
}
}
|
/*
* Copyright (C) 2018 Open Source Robotics Foundation
*
* 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.
*
*/
#ifndef IGNITION_TEST_INTEGRATION_UTILS_HH_
#define IGNITION_TEST_INTEGRATION_UTILS_HH_
#include <dlfcn.h>
/////////////////////////////////////////////////
// The macro RTLD_NOLOAD is not part of the POSIX standard, and is a custom
// addition to glibc-2.2, so the unloading test can only work when we are using
// glibc-2.2 or higher. The unloading tests fundamentally require the use of the
// RTLD_NOLOAD feature, because without it, there is no way to observe that a
// library is not loaded.
#ifdef RTLD_NOLOAD
/////////////////////////////////////////////////
// Note (MXG): According to some online discussions, there is no guarantee
// that a correct number of calls to dlclose(void*) will actually unload the
// shared library. In fact, there is no guarantee that a dynamically loaded
// library from dlopen will ever be unloaded until the program is terminated.
// This may cause dlopen(~, RTLD_NOLOAD) to return a non-null handle even if
// we are managing the handles correctly. If the test for
// EXPECT_EQ(nullptr, dlHandle) is found to fail occasionally, we should
// consider removing it because it may be unreliable. At the very least, if
// it fails very infrequently, then we can safely consider the failures to be
// false negatives and may want to consider relaxing this test.
#define CHECK_FOR_LIBRARY(_path, _isLoaded) \
{ \
void *dlHandle = dlopen(_path.c_str(), \
RTLD_NOLOAD | RTLD_LAZY | RTLD_GLOBAL); \
\
if (_isLoaded) \
EXPECT_NE(nullptr, dlHandle); \
else /* NOLINT */ \
EXPECT_EQ(nullptr, dlHandle); \
\
if (dlHandle) \
dlclose(dlHandle); \
}
#else
#define CHECK_FOR_LIBRARY(_path, _isLoaded)
#endif
#endif
|
// Copyright (c) 2017-2021, University of Tennessee. All rights reserved.
// SPDX-License-Identifier: BSD-3-Clause
// This program is free software: you can redistribute it and/or modify it under
// the terms of the BSD 3-Clause license. See the accompanying LICENSE file.
#ifndef BLAS_DEVICE_NAMES_HH
#define BLAS_DEVICE_NAMES_HH
#include "blas/device.hh"
#include <complex>
namespace blas {
namespace device {
// =============================================================================
// Level 1 BLAS - Device Interfaces
// -----------------------------------------------------------------------------
// swap
void sswap(
blas::Queue& queue,
device_blas_int n,
float *dx, device_blas_int incdx,
float *dy, device_blas_int incdy);
void dswap(
blas::Queue& queue,
device_blas_int n,
double *dx, device_blas_int incdx,
double *dy, device_blas_int incdy);
void cswap(
blas::Queue& queue,
device_blas_int n,
std::complex<float> *dx, device_blas_int incdx,
std::complex<float> *dy, device_blas_int incdy);
void zswap(
blas::Queue& queue,
device_blas_int n,
std::complex<double> *dx, device_blas_int incdx,
std::complex<double> *dy, device_blas_int incdy);
// =============================================================================
// Level 2 BLAS - Device Interfaces
// -----------------------------------------------------------------------------
// =============================================================================
// Level 3 BLAS - Device Interfaces
// -----------------------------------------------------------------------------
// gemm
void sgemm(
blas::Queue& queue,
blas::Op transA, blas::Op transB,
device_blas_int m, device_blas_int n, device_blas_int k,
float alpha,
float const *dA, device_blas_int ldda,
float const *dB, device_blas_int lddb,
float beta,
float *dC, device_blas_int lddc);
void dgemm(
blas::Queue& queue,
blas::Op transA, blas::Op transB,
device_blas_int m, device_blas_int n, device_blas_int k,
double alpha,
double const *dA, device_blas_int ldda,
double const *dB, device_blas_int lddb,
double beta,
double *dC, device_blas_int lddc);
void cgemm(
blas::Queue& queue,
blas::Op transA, blas::Op transB,
device_blas_int m, device_blas_int n, device_blas_int k,
std::complex<float> alpha,
std::complex<float> const *dA, device_blas_int ldda,
std::complex<float> const *dB, device_blas_int lddb,
std::complex<float> beta,
std::complex<float> *dC, device_blas_int lddc);
void zgemm(
blas::Queue& queue,
blas::Op transA, blas::Op transB,
device_blas_int m, device_blas_int n, device_blas_int k,
std::complex<double> alpha,
std::complex<double> const *dA, device_blas_int ldda,
std::complex<double> const *dB, device_blas_int lddb,
std::complex<double> beta,
std::complex<double> *dC, device_blas_int lddc);
// -----------------------------------------------------------------------------
// trsm
void strsm(
blas::Queue& queue,
blas::Side side, blas::Uplo uplo, blas::Op trans, blas::Diag diag,
device_blas_int m, device_blas_int n,
float alpha,
float const *dA, device_blas_int ldda,
float *dB, device_blas_int lddb);
void dtrsm(
blas::Queue& queue,
blas::Side side, blas::Uplo uplo, blas::Op trans, blas::Diag diag,
device_blas_int m, device_blas_int n,
double alpha,
double const *dA, device_blas_int ldda,
double *dB, device_blas_int lddb);
void ctrsm(
blas::Queue& queue,
blas::Side side, blas::Uplo uplo, blas::Op trans, blas::Diag diag,
device_blas_int m, device_blas_int n,
std::complex<float> alpha,
std::complex<float> const *dA, device_blas_int ldda,
std::complex<float> *dB, device_blas_int lddb);
void ztrsm(
blas::Queue& queue,
blas::Side side, blas::Uplo uplo, blas::Op trans, blas::Diag diag,
device_blas_int m, device_blas_int n,
std::complex<double> alpha,
std::complex<double> const *dA, device_blas_int ldda,
std::complex<double> *dB, device_blas_int lddb);
// -----------------------------------------------------------------------------
// trmm
void strmm(
blas::Queue& queue,
blas::Side side, blas::Uplo uplo, blas::Op trans, blas::Diag diag,
device_blas_int m, device_blas_int n,
float alpha,
float const *dA, device_blas_int ldda,
float *dB, device_blas_int lddb);
void dtrmm(
blas::Queue& queue,
blas::Side side, blas::Uplo uplo, blas::Op trans, blas::Diag diag,
device_blas_int m, device_blas_int n,
double alpha,
double const *dA, device_blas_int ldda,
double *dB, device_blas_int lddb);
void ctrmm(
blas::Queue& queue,
blas::Side side, blas::Uplo uplo, blas::Op trans, blas::Diag diag,
device_blas_int m, device_blas_int n,
std::complex<float> alpha,
std::complex<float> const *dA, device_blas_int ldda,
std::complex<float> *dB, device_blas_int lddb);
void ztrmm(
blas::Queue& queue,
blas::Side side, blas::Uplo uplo, blas::Op trans, blas::Diag diag,
device_blas_int m, device_blas_int n,
std::complex<double> alpha,
std::complex<double> const *dA, device_blas_int ldda,
std::complex<double> *dB, device_blas_int lddb);
// -----------------------------------------------------------------------------
// hemm
void chemm(
blas::Queue& queue,
blas::Side side, blas::Uplo uplo,
device_blas_int m, device_blas_int n,
std::complex<float> alpha,
std::complex<float> const *dA, device_blas_int ldda,
std::complex<float> const *dB, device_blas_int lddb,
std::complex<float> beta,
std::complex<float>* dC, device_blas_int lddc);
void zhemm(
blas::Queue& queue,
blas::Side side, blas::Uplo uplo,
device_blas_int m, device_blas_int n,
std::complex<double> alpha,
std::complex<double> const *dA, device_blas_int ldda,
std::complex<double> const *dB, device_blas_int lddb,
std::complex<double> beta,
std::complex<double>* dC, device_blas_int lddc);
// -----------------------------------------------------------------------------
// symm
void ssymm(
blas::Queue& queue,
blas::Side side, blas::Uplo uplo,
device_blas_int m, device_blas_int n,
float alpha,
float const *dA, device_blas_int ldda,
float const *dB, device_blas_int lddb,
float beta,
float* dC, device_blas_int lddc);
void dsymm(
blas::Queue& queue,
blas::Side side, blas::Uplo uplo,
device_blas_int m, device_blas_int n,
double alpha,
double const *dA, device_blas_int ldda,
double const *dB, device_blas_int lddb,
double beta,
double* dC, device_blas_int lddc);
void csymm(
blas::Queue& queue,
blas::Side side, blas::Uplo uplo,
device_blas_int m, device_blas_int n,
std::complex<float> alpha,
std::complex<float> const *dA, device_blas_int ldda,
std::complex<float> const *dB, device_blas_int lddb,
std::complex<float> beta,
std::complex<float>* dC, device_blas_int lddc);
void zsymm(
blas::Queue& queue,
blas::Side side, blas::Uplo uplo,
device_blas_int m, device_blas_int n,
std::complex<double> alpha,
std::complex<double> const *dA, device_blas_int ldda,
std::complex<double> const *dB, device_blas_int lddb,
std::complex<double> beta,
std::complex<double>* dC, device_blas_int lddc);
// -----------------------------------------------------------------------------
// herk
void cherk(
blas::Queue& queue,
blas::Uplo uplo, blas::Op trans,
device_blas_int n, device_blas_int k,
float alpha,
std::complex<float> const *dA, device_blas_int ldda,
float beta,
std::complex<float>* dC, device_blas_int lddc);
void zherk(
blas::Queue& queue,
blas::Uplo uplo, blas::Op trans,
device_blas_int n, device_blas_int k,
double alpha,
std::complex<double> const *dA, device_blas_int ldda,
double beta,
std::complex<double>* dC, device_blas_int lddc);
// -----------------------------------------------------------------------------
// syrk
void ssyrk(
blas::Queue& queue,
blas::Uplo uplo, blas::Op trans,
device_blas_int n, device_blas_int k,
float alpha,
float const *dA, device_blas_int ldda,
float beta,
float* dC, device_blas_int lddc);
void dsyrk(
blas::Queue& queue,
blas::Uplo uplo, blas::Op trans,
device_blas_int n, device_blas_int k,
double alpha,
double const *dA, device_blas_int ldda,
double beta,
double* dC, device_blas_int lddc);
void csyrk(
blas::Queue& queue,
blas::Uplo uplo, blas::Op trans,
device_blas_int n, device_blas_int k,
std::complex<float> alpha,
std::complex<float> const *dA, device_blas_int ldda,
std::complex<float> beta,
std::complex<float>* dC, device_blas_int lddc);
void zsyrk(
blas::Queue& queue,
blas::Uplo uplo, blas::Op trans,
device_blas_int n, device_blas_int k,
std::complex<double> alpha,
std::complex<double> const *dA, device_blas_int ldda,
std::complex<double> beta,
std::complex<double>* dC, device_blas_int lddc);
// -----------------------------------------------------------------------------
// her2k
void cher2k(
blas::Queue& queue,
blas::Uplo uplo, blas::Op trans,
device_blas_int n, device_blas_int k,
std::complex<float> alpha,
std::complex<float> const *dA, device_blas_int ldda,
std::complex<float> const *dB, device_blas_int lddb,
float beta,
std::complex<float>* dC, device_blas_int lddc);
void zher2k(
blas::Queue& queue,
blas::Uplo uplo, blas::Op trans,
device_blas_int n, device_blas_int k,
std::complex<double> alpha,
std::complex<double> const *dA, device_blas_int ldda,
std::complex<double> const *dB, device_blas_int lddb,
double beta,
std::complex<double>* dC, device_blas_int lddc);
// -----------------------------------------------------------------------------
// syr2k
void ssyr2k(
blas::Queue& queue,
blas::Uplo uplo, blas::Op trans,
device_blas_int n, device_blas_int k,
float alpha,
float const *dA, device_blas_int ldda,
float const *dB, device_blas_int lddb,
float beta,
float* dC, device_blas_int lddc);
void dsyr2k(
blas::Queue& queue,
blas::Uplo uplo, blas::Op trans,
device_blas_int n, device_blas_int k,
double alpha,
double const *dA, device_blas_int ldda,
double const *dB, device_blas_int lddb,
double beta,
double* dC, device_blas_int lddc);
void csyr2k(
blas::Queue& queue,
blas::Uplo uplo, blas::Op trans,
device_blas_int n, device_blas_int k,
std::complex<float> alpha,
std::complex<float> const *dA, device_blas_int ldda,
std::complex<float> const *dB, device_blas_int lddb,
std::complex<float> beta,
std::complex<float>* dC, device_blas_int lddc);
void zsyr2k(
blas::Queue& queue,
blas::Uplo uplo, blas::Op trans,
device_blas_int n, device_blas_int k,
std::complex<double> alpha,
std::complex<double> const *dA, device_blas_int ldda,
std::complex<double> const *dB, device_blas_int lddb,
std::complex<double> beta,
std::complex<double>* dC, device_blas_int lddc);
// -----------------------------------------------------------------------------
// batch gemm
void batch_sgemm(
blas::Queue& queue,
blas::Op transA, blas::Op transB,
device_blas_int m, device_blas_int n, device_blas_int k,
float alpha,
float const * const * dAarray, device_blas_int ldda,
float const * const * dBarray, device_blas_int lddb,
float beta,
float** dCarray, device_blas_int lddc,
device_blas_int batch_size);
void batch_dgemm(
blas::Queue& queue,
blas::Op transA, blas::Op transB,
device_blas_int m, device_blas_int n, device_blas_int k,
double alpha,
double const * const * dAarray, device_blas_int ldda,
double const * const * dBarray, device_blas_int lddb,
double beta,
double** dCarray, device_blas_int lddc,
device_blas_int batch_size);
void batch_cgemm(
blas::Queue& queue,
blas::Op transA, blas::Op transB,
device_blas_int m, device_blas_int n, device_blas_int k,
std::complex<float> alpha,
std::complex<float> const * const * dAarray, device_blas_int ldda,
std::complex<float> const * const * dBarray, device_blas_int lddb,
std::complex<float> beta,
std::complex<float>** dCarray, device_blas_int lddc,
device_blas_int batch_size);
void batch_zgemm(
blas::Queue& queue,
blas::Op transA, blas::Op transB,
device_blas_int m, device_blas_int n, device_blas_int k,
std::complex<double> alpha,
std::complex<double> const * const * dAarray, device_blas_int ldda,
std::complex<double> const * const * dBarray, device_blas_int lddb,
std::complex<double> beta,
std::complex<double>** dCarray, device_blas_int lddc,
device_blas_int batch_size);
// -----------------------------------------------------------------------------
// batch trsm
void batch_strsm(
blas::Queue& queue,
blas::Side side, blas::Uplo uplo, blas::Op trans, blas::Diag diag,
device_blas_int m, device_blas_int n,
float alpha,
float const * const * dAarray, device_blas_int ldda,
float const * const * dBarray, device_blas_int lddb,
device_blas_int batch_size);
void batch_dtrsm(
blas::Queue& queue,
blas::Side side, blas::Uplo uplo, blas::Op trans, blas::Diag diag,
device_blas_int m, device_blas_int n,
double alpha,
double const * const * dAarray, device_blas_int ldda,
double const * const * dBarray, device_blas_int lddb,
device_blas_int batch_size);
void batch_ctrsm(
blas::Queue& queue,
blas::Side side, blas::Uplo uplo, blas::Op trans, blas::Diag diag,
device_blas_int m, device_blas_int n,
std::complex<float> alpha,
std::complex<float> const * const * dAarray, device_blas_int ldda,
std::complex<float> const * const * dBarray, device_blas_int lddb,
device_blas_int batch_size);
void batch_ztrsm(
blas::Queue& queue,
blas::Side side, blas::Uplo uplo, blas::Op trans, blas::Diag diag,
device_blas_int m, device_blas_int n,
std::complex<double> alpha,
std::complex<double> const * const * dAarray, device_blas_int ldda,
std::complex<double> const * const * dBarray, device_blas_int lddb,
device_blas_int batch_size);
} // namespace device
} // namespace blas
#endif // #ifndef BLAS_DEVICE_NAMES_HH
|
#include <iostream>
using namespace std;
int main(){
int first_value = 5;
int *pttre;
pttre = &first_value;
*pttre = *pttre + 1;
cout<<*pttre<<endl;
int &reference = first_value;
++reference;
cout<<reference<<endl;
cout<<0xf3f2<<endl;
cout<<0437<<endl;
cout<<'a'<<endl;
}
|
//===--- SILMem2Reg.cpp - Promotes AllocStacks to registers ---------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 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 pass promotes AllocStack instructions into virtual register
// references. It only handles load, store and deallocation
// instructions. The algorithm is based on:
//
// Sreedhar and Gao. A linear time algorithm for placing phi-nodes. POPL '95.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "sil-mem2reg"
#include "swift/AST/DiagnosticsSIL.h"
#include "swift/SIL/Dominance.h"
#include "swift/SIL/Projection.h"
#include "swift/SIL/SILBuilder.h"
#include "swift/SIL/SILFunction.h"
#include "swift/SIL/SILInstruction.h"
#include "swift/SIL/SILModule.h"
#include "swift/SIL/TypeLowering.h"
#include "swift/SIL/SILBitfield.h"
#include "swift/SILOptimizer/Analysis/DominanceAnalysis.h"
#include "swift/SILOptimizer/PassManager/Passes.h"
#include "swift/SILOptimizer/PassManager/Transforms.h"
#include "swift/SILOptimizer/Utils/CFGOptUtils.h"
#include "swift/SILOptimizer/Utils/InstOptUtils.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Support/Debug.h"
#include <algorithm>
#include <queue>
using namespace swift;
STATISTIC(NumAllocStackFound, "Number of AllocStack found");
STATISTIC(NumAllocStackCaptured, "Number of AllocStack captured");
STATISTIC(NumInstRemoved, "Number of Instructions removed");
STATISTIC(NumPhiPlaced, "Number of Phi blocks placed");
namespace {
typedef llvm::DomTreeNodeBase<SILBasicBlock> DomTreeNode;
typedef llvm::DenseMap<DomTreeNode *, unsigned> DomTreeLevelMap;
/// Promotes a single AllocStackInst into registers..
class StackAllocationPromoter {
typedef BasicBlockSetVector<16> BlockSet;
typedef llvm::DenseMap<SILBasicBlock *, SILInstruction *> BlockToInstMap;
// Use a priority queue keyed on dominator tree level so that inserted nodes
// are handled from the bottom of the dom tree upwards.
typedef std::pair<DomTreeNode *, unsigned> DomTreeNodePair;
typedef std::priority_queue<DomTreeNodePair, SmallVector<DomTreeNodePair, 32>,
llvm::less_second> NodePriorityQueue;
/// The AllocStackInst that we are handling.
AllocStackInst *ASI;
/// The deallocation Instruction. This value could be NULL if there are
/// multiple deallocations.
DeallocStackInst *DSI;
/// Dominator info.
DominanceInfo *DT;
/// Map from dominator tree node to tree level.
DomTreeLevelMap &DomTreeLevels;
/// The builder used to create new instructions during register promotion.
SILBuilder &B;
/// Records the last store instruction in each block for a specific
/// AllocStackInst.
BlockToInstMap LastStoreInBlock;
public:
/// C'tor.
StackAllocationPromoter(AllocStackInst *Asi, DominanceInfo *Di,
DomTreeLevelMap &DomTreeLevels, SILBuilder &B)
: ASI(Asi), DSI(nullptr), DT(Di), DomTreeLevels(DomTreeLevels), B(B) {
// Scan the users in search of a deallocation instruction.
for (auto UI = ASI->use_begin(), E = ASI->use_end(); UI != E; ++UI)
if (auto *D = dyn_cast<DeallocStackInst>(UI->getUser())) {
// Don't record multiple dealloc instructions.
if (DSI) {
DSI = nullptr;
break;
}
// Record the deallocation instruction.
DSI = D;
}
}
/// Promote the Allocation.
void run();
private:
/// Promote AllocStacks into SSA.
void promoteAllocationToPhi();
/// Replace the dummy nodes with new block arguments.
void addBlockArguments(BlockSet &PhiBlocks);
/// Fix all of the branch instructions and the uses to use
/// the AllocStack definitions (which include stores and Phis).
void fixBranchesAndUses(BlockSet &Blocks);
/// update the branch instructions with the new Phi argument.
/// The blocks in \p PhiBlocks are blocks that define a value, \p Dest is
/// the branch destination, and \p Pred is the predecessors who's branch we
/// modify.
void fixPhiPredBlock(BlockSet &PhiBlocks, SILBasicBlock *Dest,
SILBasicBlock *Pred);
/// Get the value for this AllocStack variable that is
/// flowing out of StartBB.
SILValue getLiveOutValue(BlockSet &PhiBlocks, SILBasicBlock *StartBB);
/// Get the value for this AllocStack variable that is
/// flowing into BB.
SILValue getLiveInValue(BlockSet &PhiBlocks, SILBasicBlock *BB);
/// Prune AllocStacks usage in the function. Scan the function
/// and remove in-block usage of the AllocStack. Leave only the first
/// load and the last store.
void pruneAllocStackUsage();
/// Promote all of the AllocStacks in a single basic block in one
/// linear scan. This function deletes all of the loads and stores except
/// for the first load and the last store.
/// \returns the last StoreInst found or zero if none found.
StoreInst *promoteAllocationInBlock(SILBasicBlock *BB);
};
} // end of namespace
namespace {
/// Promote memory to registers
class MemoryToRegisters {
/// The function that we are optimizing.
SILFunction &F;
/// Dominators.
DominanceInfo *DT;
/// The builder used to create new instructions during register promotion.
SILBuilder B;
/// Check if the AllocStackInst \p ASI is only written into.
bool isWriteOnlyAllocation(AllocStackInst *ASI);
/// Promote all of the AllocStacks in a single basic block in one
/// linear scan. Note: This function deletes all of the users of the
/// AllocStackInst, including the DeallocStackInst but it does not remove the
/// AllocStackInst itself!
void removeSingleBlockAllocation(AllocStackInst *ASI);
/// Attempt to promote the specified stack allocation, returning true if so
/// or false if not. On success, all uses of the AllocStackInst have been
/// removed, but the ASI itself is still in the program.
bool promoteSingleAllocation(AllocStackInst *ASI,
DomTreeLevelMap &DomTreeLevels);
public:
/// C'tor
MemoryToRegisters(SILFunction &Func, DominanceInfo *Dt) : F(Func), DT(Dt),
B(Func) {}
/// Promote memory to registers. Return True on change.
bool run();
};
} // end anonymous namespace
/// Returns true if \p I is an address of a LoadInst, skipping struct and
/// tuple address projections. Sets \p singleBlock to null if the load (or
/// it's address is not in \p singleBlock.
/// This function looks for these patterns:
/// 1. (load %ASI)
/// 2. (load (struct_element_addr/tuple_element_addr/unchecked_addr_cast %ASI))
static bool isAddressForLoad(SILInstruction *I, SILBasicBlock *&singleBlock,
bool &hasGuaranteedOwnership) {
if (isa<LoadInst>(I)) {
// SILMem2Reg is disabled when we find:
// (load [take] (struct_element_addr/tuple_element_addr %ASI))
// struct_element_addr and tuple_element_addr are lowered into
// struct_extract and tuple_extract and these SIL instructions have a
// guaranteed ownership. For replacing load's users, we need an owned value.
// We will need a new copy and destroy of the running val placed after the
// last use. This is not implemented currently.
if (hasGuaranteedOwnership && cast<LoadInst>(I)->getOwnershipQualifier() ==
LoadOwnershipQualifier::Take) {
return false;
}
return true;
}
if (!isa<UncheckedAddrCastInst>(I) && !isa<StructElementAddrInst>(I) &&
!isa<TupleElementAddrInst>(I))
return false;
if (isa<StructElementAddrInst>(I) || isa<TupleElementAddrInst>(I)) {
hasGuaranteedOwnership = true;
}
// Recursively search for other (non-)loads in the instruction's uses.
for (auto UI : cast<SingleValueInstruction>(I)->getUses()) {
SILInstruction *II = UI->getUser();
if (II->getParent() != singleBlock)
singleBlock = nullptr;
if (!isAddressForLoad(II, singleBlock, hasGuaranteedOwnership))
return false;
}
return true;
}
/// Returns true if \p I is a dead struct_element_addr or tuple_element_addr.
static bool isDeadAddrProjection(SILInstruction *I) {
if (!isa<UncheckedAddrCastInst>(I) && !isa<StructElementAddrInst>(I) &&
!isa<TupleElementAddrInst>(I))
return false;
// Recursively search for uses which are dead themselves.
for (auto UI : cast<SingleValueInstruction>(I)->getUses()) {
SILInstruction *II = UI->getUser();
if (!isDeadAddrProjection(II))
return false;
}
return true;
}
/// Returns true if this AllocStacks is captured.
/// Sets \p inSingleBlock to true if all uses of \p ASI are in a single block.
static bool isCaptured(AllocStackInst *ASI, bool &inSingleBlock) {
SILBasicBlock *singleBlock = ASI->getParent();
// For all users of the AllocStack instruction.
for (auto UI = ASI->use_begin(), E = ASI->use_end(); UI != E; ++UI) {
SILInstruction *II = UI->getUser();
if (II->getParent() != singleBlock)
singleBlock = nullptr;
// Loads are okay.
bool hasGuaranteedOwnership = false;
if (isAddressForLoad(II, singleBlock, hasGuaranteedOwnership))
continue;
// We can store into an AllocStack (but not the pointer).
if (auto *SI = dyn_cast<StoreInst>(II))
if (SI->getDest() == ASI)
continue;
// Deallocation is also okay, as are DebugValueAddr. We will turn
// the latter into DebugValue.
if (isa<DeallocStackInst>(II) || isa<DebugValueAddrInst>(II))
continue;
// Destroys of loadable types can be rewritten as releases, so
// they are fine.
if (auto *DAI = dyn_cast<DestroyAddrInst>(II))
if (DAI->getOperand()->getType().isLoadable(*DAI->getFunction()))
continue;
// Other instructions are assumed to capture the AllocStack.
LLVM_DEBUG(llvm::dbgs() << "*** AllocStack is captured by: " << *II);
return true;
}
// None of the users capture the AllocStack.
inSingleBlock = (singleBlock != nullptr);
return false;
}
/// Returns true if the AllocStack is only stored into.
bool MemoryToRegisters::isWriteOnlyAllocation(AllocStackInst *ASI) {
// For all users of the AllocStack:
for (auto UI = ASI->use_begin(), E = ASI->use_end(); UI != E; ++UI) {
SILInstruction *II = UI->getUser();
// It is okay to store into this AllocStack.
if (auto *SI = dyn_cast<StoreInst>(II))
if (!isa<AllocStackInst>(SI->getSrc()))
continue;
// Deallocation is also okay.
if (isa<DeallocStackInst>(II))
continue;
// If we haven't already promoted the AllocStack, we may see
// DebugValueAddr uses.
if (isa<DebugValueAddrInst>(II))
continue;
if (isDeadAddrProjection(II))
continue;
// Can't do anything else with it.
LLVM_DEBUG(llvm::dbgs() << "*** AllocStack has non-write use: " << *II);
return false;
}
return true;
}
/// Promote a DebugValueAddr to a DebugValue of the given value.
static void
promoteDebugValueAddr(DebugValueAddrInst *DVAI, SILValue Value, SILBuilder &B) {
assert(DVAI->getOperand()->getType().isLoadable(*DVAI->getFunction()) &&
"Unexpected promotion of address-only type!");
assert(Value && "Expected valid value");
// Avoid inserting the same debug_value twice.
for (Operand *Use : Value->getUses())
if (auto *DVI = dyn_cast<DebugValueInst>(Use->getUser()))
if (*DVI->getVarInfo() == *DVAI->getVarInfo()) {
DVAI->eraseFromParent();
return;
}
B.setInsertionPoint(DVAI);
B.setCurrentDebugScope(DVAI->getDebugScope());
B.createDebugValue(DVAI->getLoc(), Value, *DVAI->getVarInfo());
DVAI->eraseFromParent();
}
/// Returns true if \p I is a load which loads from \p ASI.
static bool isLoadFromStack(SILInstruction *I, AllocStackInst *ASI) {
if (!isa<LoadInst>(I))
return false;
// Skip struct and tuple address projections.
ValueBase *op = I->getOperand(0);
while (op != ASI) {
if (!isa<UncheckedAddrCastInst>(op) && !isa<StructElementAddrInst>(op) &&
!isa<TupleElementAddrInst>(op))
return false;
op = cast<SingleValueInstruction>(op)->getOperand(0);
}
return true;
}
/// Collects all load instructions which (transitively) use \p I as address.
static void collectLoads(SILInstruction *I, SmallVectorImpl<LoadInst *> &Loads) {
if (auto *load = dyn_cast<LoadInst>(I)) {
Loads.push_back(load);
return;
}
if (!isa<UncheckedAddrCastInst>(I) && !isa<StructElementAddrInst>(I) &&
!isa<TupleElementAddrInst>(I))
return;
// Recursively search for other loads in the instruction's uses.
for (auto UI : cast<SingleValueInstruction>(I)->getUses()) {
collectLoads(UI->getUser(), Loads);
}
}
static void replaceLoad(LoadInst *LI, SILValue val, AllocStackInst *ASI) {
ProjectionPath projections(val->getType());
SILValue op = LI->getOperand();
SILBuilderWithScope builder(LI);
while (op != ASI) {
assert(isa<UncheckedAddrCastInst>(op) || isa<StructElementAddrInst>(op) ||
isa<TupleElementAddrInst>(op));
auto *Inst = cast<SingleValueInstruction>(op);
projections.push_back(Projection(Inst));
op = Inst->getOperand(0);
}
SmallVector<SILValue, 4> borrowedVals;
for (auto iter = projections.rbegin(); iter != projections.rend(); ++iter) {
const Projection &projection = *iter;
assert(projection.getKind() == ProjectionKind::BitwiseCast ||
projection.getKind() == ProjectionKind::Struct ||
projection.getKind() == ProjectionKind::Tuple);
// struct_extract and tuple_extract expect guaranteed operand ownership
// non-trivial RunningVal is owned. Insert borrow operation to convert
if (projection.getKind() == ProjectionKind::Struct ||
projection.getKind() == ProjectionKind::Tuple) {
SILValue opVal = builder.emitBeginBorrowOperation(LI->getLoc(), val);
if (opVal != val) {
borrowedVals.push_back(opVal);
val = opVal;
}
}
val = projection.createObjectProjection(builder, LI->getLoc(), val).get();
}
op = LI->getOperand();
// Replace users of the loaded value with `val`
// If we have a load [copy], replace the users with copy_value of `val`
if (LI->getOwnershipQualifier() == LoadOwnershipQualifier::Copy) {
LI->replaceAllUsesWith(builder.createCopyValue(LI->getLoc(), val));
} else {
assert(!ASI->getFunction()->hasOwnership() ||
val.getOwnershipKind() != OwnershipKind::Guaranteed);
LI->replaceAllUsesWith(val);
}
for (auto borrowedVal : borrowedVals) {
builder.emitEndBorrowOperation(LI->getLoc(), borrowedVal);
}
// Delete the load
LI->eraseFromParent();
while (op != ASI && op->use_empty()) {
assert(isa<UncheckedAddrCastInst>(op) || isa<StructElementAddrInst>(op) ||
isa<TupleElementAddrInst>(op));
auto *Inst = cast<SingleValueInstruction>(op);
SILValue next = Inst->getOperand(0);
Inst->eraseFromParent();
op = next;
}
}
static void replaceDestroy(DestroyAddrInst *DAI, SILValue NewValue) {
SILFunction *F = DAI->getFunction();
auto Ty = DAI->getOperand()->getType();
assert(Ty.isLoadable(*F) &&
"Unexpected promotion of address-only type!");
assert(NewValue || (Ty.is<TupleType>() && Ty.getAs<TupleType>()->getNumElements() == 0));
SILBuilderWithScope Builder(DAI);
auto &TL = F->getTypeLowering(Ty);
bool expand = shouldExpand(DAI->getModule(),
DAI->getOperand()->getType().getObjectType());
using TypeExpansionKind = Lowering::TypeLowering::TypeExpansionKind;
auto expansionKind = expand ? TypeExpansionKind::MostDerivedDescendents
: TypeExpansionKind::None;
TL.emitLoweredDestroyValue(Builder, DAI->getLoc(), NewValue, expansionKind);
DAI->eraseFromParent();
}
StoreInst *
StackAllocationPromoter::promoteAllocationInBlock(SILBasicBlock *BB) {
LLVM_DEBUG(llvm::dbgs() << "*** Promoting ASI in block: " << *ASI);
// RunningVal is the current value in the stack location.
// We don't know the value of the alloca until we find the first store.
SILValue RunningVal = SILValue();
// Keep track of the last StoreInst that we found.
StoreInst *LastStore = nullptr;
// For all instructions in the block.
for (auto BBI = BB->begin(), E = BB->end(); BBI != E;) {
SILInstruction *Inst = &*BBI;
++BBI;
if (isLoadFromStack(Inst, ASI)) {
auto Load = cast<LoadInst>(Inst);
if (RunningVal) {
// If we are loading from the AllocStackInst and we already know the
// content of the Alloca then use it.
LLVM_DEBUG(llvm::dbgs() << "*** Promoting load: " << *Load);
replaceLoad(Load, RunningVal, ASI);
++NumInstRemoved;
} else if (Load->getOperand() == ASI &&
Load->getOwnershipQualifier() !=
LoadOwnershipQualifier::Copy) {
// If we don't know the content of the AllocStack then the loaded
// value *is* the new value;
// Don't use result of load [copy] as a RunningVal, it necessitates
// additional logic for cleanup of consuming instructions of the result.
// StackAllocationPromoter::fixBranchesAndUses will later handle it.
LLVM_DEBUG(llvm::dbgs() << "*** First load: " << *Load);
RunningVal = Load;
}
continue;
}
// Remove stores and record the value that we are saving as the running
// value.
if (auto *SI = dyn_cast<StoreInst>(Inst)) {
if (SI->getDest() != ASI)
continue;
// If we see a store [assign], always convert it to a store [init]. This
// simplifies further processing.
if (SI->getOwnershipQualifier() == StoreOwnershipQualifier::Assign) {
if (RunningVal) {
SILBuilderWithScope(SI).createDestroyValue(SI->getLoc(), RunningVal);
} else {
SILBuilderWithScope localBuilder(SI);
auto *newLoad = localBuilder.createLoad(SI->getLoc(), ASI,
LoadOwnershipQualifier::Take);
localBuilder.createDestroyValue(SI->getLoc(), newLoad);
}
SI->setOwnershipQualifier(StoreOwnershipQualifier::Init);
}
// If we met a store before this one, delete it.
if (LastStore) {
assert(LastStore->getOwnershipQualifier() !=
StoreOwnershipQualifier::Assign &&
"store [assign] to the stack location should have been "
"transformed to a store [init]");
LLVM_DEBUG(llvm::dbgs()
<< "*** Removing redundant store: " << *LastStore);
++NumInstRemoved;
LastStore->eraseFromParent();
}
// The stored value is the new running value.
RunningVal = SI->getSrc();
// The current store is now the LastStore
LastStore = SI;
continue;
}
// Replace debug_value_addr with debug_value of the promoted value
// if we have a valid value to use at this point. Otherwise we'll
// promote this when we deal with hooking up phis.
if (auto *DVAI = dyn_cast<DebugValueAddrInst>(Inst)) {
if (DVAI->getOperand() == ASI &&
RunningVal)
promoteDebugValueAddr(DVAI, RunningVal, B);
continue;
}
// Replace destroys with a release of the value.
if (auto *DAI = dyn_cast<DestroyAddrInst>(Inst)) {
if (DAI->getOperand() == ASI &&
RunningVal) {
replaceDestroy(DAI, RunningVal);
}
continue;
}
if (auto *DVI = dyn_cast<DestroyValueInst>(Inst)) {
if (DVI->getOperand() == RunningVal) {
// Reset LastStore.
// So that we don't end up passing dead values as phi args in
// StackAllocationPromoter::fixBranchesAndUses
LastStore = nullptr;
}
}
// Stop on deallocation.
if (auto *DSI = dyn_cast<DeallocStackInst>(Inst)) {
if (DSI->getOperand() == ASI)
break;
}
}
if (LastStore) {
assert(LastStore->getOwnershipQualifier() !=
StoreOwnershipQualifier::Assign &&
"store [assign] to the stack location should have been "
"transformed to a store [init]");
LLVM_DEBUG(llvm::dbgs() << "*** Finished promotion. Last store: "
<< *LastStore);
} else {
LLVM_DEBUG(llvm::dbgs() << "*** Finished promotion with no stores.\n");
}
return LastStore;
}
void MemoryToRegisters::removeSingleBlockAllocation(AllocStackInst *ASI) {
LLVM_DEBUG(llvm::dbgs() << "*** Promoting in-block: " << *ASI);
SILBasicBlock *BB = ASI->getParent();
// The default value of the AllocStack is NULL because we don't have
// uninitialized variables in Swift.
SILValue RunningVal = SILValue();
// For all instructions in the block.
for (auto BBI = BB->begin(), E = BB->end(); BBI != E;) {
SILInstruction *Inst = &*BBI;
++BBI;
// Remove instructions that we are loading from. Replace the loaded value
// with our running value.
if (isLoadFromStack(Inst, ASI)) {
if (!RunningVal) {
// Loading without a previous store is only acceptable if the type is
// Void (= empty tuple) or a tuple of Voids.
RunningVal = SILUndef::get(ASI->getElementType(), *ASI->getFunction());
}
replaceLoad(cast<LoadInst>(Inst), RunningVal, ASI);
++NumInstRemoved;
continue;
}
// Remove stores and record the value that we are saving as the running
// value.
if (auto *SI = dyn_cast<StoreInst>(Inst)) {
if (SI->getDest() == ASI) {
if (SI->getOwnershipQualifier() == StoreOwnershipQualifier::Assign) {
assert(RunningVal);
SILBuilderWithScope(SI).createDestroyValue(SI->getLoc(), RunningVal);
}
RunningVal = SI->getSrc();
Inst->eraseFromParent();
++NumInstRemoved;
continue;
}
}
// Replace debug_value_addr with debug_value of the promoted value.
if (auto *DVAI = dyn_cast<DebugValueAddrInst>(Inst)) {
if (DVAI->getOperand() == ASI) {
if (RunningVal) {
promoteDebugValueAddr(DVAI, RunningVal, B);
} else {
// Drop debug_value_addr of uninitialized void values.
assert(ASI->getElementType().isVoid() &&
"Expected initialization of non-void type!");
DVAI->eraseFromParent();
}
}
continue;
}
// Replace destroys with a release of the value.
if (auto *DAI = dyn_cast<DestroyAddrInst>(Inst)) {
if (DAI->getOperand() == ASI) {
replaceDestroy(DAI, RunningVal);
}
continue;
}
// Remove deallocation.
if (auto *DSI = dyn_cast<DeallocStackInst>(Inst)) {
if (DSI->getOperand() == ASI) {
Inst->eraseFromParent();
NumInstRemoved++;
// No need to continue scanning after deallocation.
break;
}
}
// Remove dead address instructions that may be uses of the allocation.
auto *addrInst = dyn_cast<SingleValueInstruction>(Inst);
while (addrInst && addrInst->use_empty() &&
(isa<StructElementAddrInst>(addrInst) ||
isa<TupleElementAddrInst>(addrInst) ||
isa<UncheckedAddrCastInst>(addrInst))) {
SILValue op = addrInst->getOperand(0);
addrInst->eraseFromParent();
++NumInstRemoved;
addrInst = dyn_cast<SingleValueInstruction>(op);
}
}
}
void StackAllocationPromoter::addBlockArguments(BlockSet &PhiBlocks) {
LLVM_DEBUG(llvm::dbgs() << "*** Adding new block arguments.\n");
for (auto *Block : PhiBlocks)
Block->createPhiArgument(ASI->getElementType(), OwnershipKind::Owned);
}
SILValue
StackAllocationPromoter::getLiveOutValue(BlockSet &PhiBlocks,
SILBasicBlock *StartBB) {
LLVM_DEBUG(llvm::dbgs() << "*** Searching for a value definition.\n");
// Walk the Dom tree in search of a defining value:
for (DomTreeNode *Node = DT->getNode(StartBB); Node; Node = Node->getIDom()) {
SILBasicBlock *BB = Node->getBlock();
// If there is a store (that must come after the phi), use its value.
BlockToInstMap::iterator it = LastStoreInBlock.find(BB);
if (it != LastStoreInBlock.end())
if (auto *St = dyn_cast_or_null<StoreInst>(it->second)) {
LLVM_DEBUG(llvm::dbgs() << "*** Found Store def " << *St->getSrc());
return St->getSrc();
}
// If there is a Phi definition in this block:
if (PhiBlocks.contains(BB)) {
// Return the dummy instruction that represents the new value that we will
// add to the basic block.
SILValue Phi = BB->getArgument(BB->getNumArguments() - 1);
LLVM_DEBUG(llvm::dbgs() << "*** Found a dummy Phi def " << *Phi);
return Phi;
}
// Move to the next dominating block.
LLVM_DEBUG(llvm::dbgs() << "*** Walking up the iDOM.\n");
}
LLVM_DEBUG(llvm::dbgs() << "*** Could not find a Def. Using Undef.\n");
return SILUndef::get(ASI->getElementType(), *ASI->getFunction());
}
SILValue
StackAllocationPromoter::getLiveInValue(BlockSet &PhiBlocks,
SILBasicBlock *BB) {
// First, check if there is a Phi value in the current block. We know that
// our loads happen before stores, so we need to first check for Phi nodes
// in the first block, but stores first in all other stores in the idom
// chain.
if (PhiBlocks.contains(BB)) {
LLVM_DEBUG(llvm::dbgs() << "*** Found a local Phi definition.\n");
return BB->getArgument(BB->getNumArguments() - 1);
}
if (BB->pred_empty() || !DT->getNode(BB))
return SILUndef::get(ASI->getElementType(), *ASI->getFunction());
// No phi for this value in this block means that the value flowing
// out of the immediate dominator reaches here.
DomTreeNode *IDom = DT->getNode(BB)->getIDom();
assert(IDom &&
"Attempt to get live-in value for alloc_stack in entry block!");
return getLiveOutValue(PhiBlocks, IDom->getBlock());
}
void StackAllocationPromoter::fixPhiPredBlock(BlockSet &PhiBlocks,
SILBasicBlock *Dest,
SILBasicBlock *Pred) {
TermInst *TI = Pred->getTerminator();
LLVM_DEBUG(llvm::dbgs() << "*** Fixing the terminator " << TI << ".\n");
SILValue Def = getLiveOutValue(PhiBlocks, Pred);
LLVM_DEBUG(llvm::dbgs() << "*** Found the definition: " << *Def);
addArgumentToBranch(Def, Dest, TI);
TI->eraseFromParent();
}
void StackAllocationPromoter::fixBranchesAndUses(BlockSet &PhiBlocks) {
// First update uses of the value.
SmallVector<LoadInst *, 4> collectedLoads;
for (auto UI = ASI->use_begin(), E = ASI->use_end(); UI != E;) {
auto *Inst = UI->getUser();
++UI;
bool removedUser = false;
collectedLoads.clear();
collectLoads(Inst, collectedLoads);
for (LoadInst *LI : collectedLoads) {
SILValue Def;
// If this block has no predecessors then nothing dominates it and
// the instruction is unreachable. If the instruction we're
// examining is a value, replace it with undef. Either way, delete
// the instruction and move on.
SILBasicBlock *BB = LI->getParent();
Def = getLiveInValue(PhiBlocks, BB);
LLVM_DEBUG(llvm::dbgs() << "*** Replacing " << *LI
<< " with Def " << *Def);
// Replace the load with the definition that we found.
replaceLoad(LI, Def, ASI);
removedUser = true;
++NumInstRemoved;
}
if (removedUser)
continue;
// If this block has no predecessors then nothing dominates it and
// the instruction is unreachable. Delete the instruction and move
// on.
SILBasicBlock *BB = Inst->getParent();
if (auto *DVAI = dyn_cast<DebugValueAddrInst>(Inst)) {
// Replace DebugValueAddr with DebugValue.
SILValue Def = getLiveInValue(PhiBlocks, BB);
promoteDebugValueAddr(DVAI, Def, B);
++NumInstRemoved;
continue;
}
// Replace destroys with a release of the value.
if (auto *DAI = dyn_cast<DestroyAddrInst>(Inst)) {
SILValue Def = getLiveInValue(PhiBlocks, BB);
replaceDestroy(DAI, Def);
continue;
}
}
// Now that all of the uses are fixed we can fix the branches that point
// to the blocks with the added arguments.
// For each Block with a new Phi argument:
for (auto Block : PhiBlocks) {
// Fix all predecessors.
for (auto PBBI = Block->getPredecessorBlocks().begin(),
E = Block->getPredecessorBlocks().end();
PBBI != E;) {
auto *PBB = *PBBI;
++PBBI;
assert(PBB && "Invalid block!");
fixPhiPredBlock(PhiBlocks, Block, PBB);
}
}
// If the owned phi arg we added did not have any uses, create end_lifetime to
// end its lifetime. In asserts mode, make sure we have only undef incoming
// values for such phi args.
for (auto Block : PhiBlocks) {
auto *phiArg = cast<SILPhiArgument>(
Block->getArgument(Block->getNumArguments() - 1));
if (phiArg->use_empty()) {
erasePhiArgument(Block, Block->getNumArguments() - 1);
}
}
}
void StackAllocationPromoter::pruneAllocStackUsage() {
LLVM_DEBUG(llvm::dbgs() << "*** Pruning : " << *ASI);
BlockSet Blocks(ASI->getFunction());
// Insert all of the blocks that ASI is live in.
for (auto UI = ASI->use_begin(), E = ASI->use_end(); UI != E; ++UI)
Blocks.insert(UI->getUser()->getParent());
// Clear AllocStack state.
LastStoreInBlock.clear();
for (auto Block : Blocks) {
StoreInst *SI = promoteAllocationInBlock(Block);
LastStoreInBlock[Block] = SI;
}
LLVM_DEBUG(llvm::dbgs() << "*** Finished pruning : " << *ASI);
}
/// Compute the dominator tree levels for DT.
static void computeDomTreeLevels(DominanceInfo *DT,
DomTreeLevelMap &DomTreeLevels) {
// TODO: This should happen once per function.
SmallVector<DomTreeNode *, 32> Worklist;
DomTreeNode *Root = DT->getRootNode();
DomTreeLevels[Root] = 0;
Worklist.push_back(Root);
while (!Worklist.empty()) {
DomTreeNode *Node = Worklist.pop_back_val();
unsigned ChildLevel = DomTreeLevels[Node] + 1;
for (auto CI = Node->begin(), CE = Node->end(); CI != CE; ++CI) {
DomTreeLevels[*CI] = ChildLevel;
Worklist.push_back(*CI);
}
}
}
void StackAllocationPromoter::promoteAllocationToPhi() {
LLVM_DEBUG(llvm::dbgs() << "*** Placing Phis for : " << *ASI);
// A list of blocks that will require new Phi values.
BlockSet PhiBlocks(ASI->getFunction());
// The "piggy-bank" data-structure that we use for processing the dom-tree
// bottom-up.
NodePriorityQueue PQ;
// Collect all of the stores into the AllocStack. We know that at this point
// we have at most one store per block.
for (auto UI = ASI->use_begin(), E = ASI->use_end(); UI != E; ++UI) {
SILInstruction *II = UI->getUser();
// We need to place Phis for this block.
if (isa<StoreInst>(II)) {
// If the block is in the dom tree (dominated by the entry block).
if (DomTreeNode *Node = DT->getNode(II->getParent()))
PQ.push(std::make_pair(Node, DomTreeLevels[Node]));
}
}
LLVM_DEBUG(llvm::dbgs() << "*** Found: " << PQ.size() << " Defs\n");
// A list of nodes for which we already calculated the dominator frontier.
llvm::SmallPtrSet<DomTreeNode *, 32> Visited;
SmallVector<DomTreeNode *, 32> Worklist;
// Scan all of the definitions in the function bottom-up using the priority
// queue.
while (!PQ.empty()) {
DomTreeNodePair RootPair = PQ.top();
PQ.pop();
DomTreeNode *Root = RootPair.first;
unsigned RootLevel = RootPair.second;
// Walk all dom tree children of Root, inspecting their successors. Only
// J-edges, whose target level is at most Root's level are added to the
// dominance frontier.
Worklist.clear();
Worklist.push_back(Root);
while (!Worklist.empty()) {
DomTreeNode *Node = Worklist.pop_back_val();
SILBasicBlock *BB = Node->getBlock();
// For all successors of the node:
for (auto &Succ : BB->getSuccessors()) {
DomTreeNode *SuccNode = DT->getNode(Succ);
// Skip D-edges (edges that are dom-tree edges).
if (SuccNode->getIDom() == Node)
continue;
// Ignore J-edges that point to nodes that are not smaller or equal
// to the root level.
unsigned SuccLevel = DomTreeLevels[SuccNode];
if (SuccLevel > RootLevel)
continue;
// Ignore visited nodes.
if (!Visited.insert(SuccNode).second)
continue;
// If the new PHInode is not dominated by the allocation then it's dead.
if (!DT->dominates(ASI->getParent(), SuccNode->getBlock()))
continue;
// If the new PHInode is properly dominated by the deallocation then it
// is obviously a dead PHInode, so we don't need to insert it.
if (DSI && DT->properlyDominates(DSI->getParent(),
SuccNode->getBlock()))
continue;
// The successor node is a new PHINode. If this is a new PHI node
// then it may require additional definitions, so add it to the PQ.
if (PhiBlocks.insert(Succ))
PQ.push(std::make_pair(SuccNode, SuccLevel));
}
// Add the children in the dom-tree to the worklist.
for (auto CI = Node->begin(), CE = Node->end(); CI != CE; ++CI)
if (!Visited.count(*CI))
Worklist.push_back(*CI);
}
}
LLVM_DEBUG(llvm::dbgs() << "*** Found: " << PhiBlocks.size() <<" new PHIs\n");
NumPhiPlaced += PhiBlocks.size();
// At this point we calculated the locations of all of the new Phi values.
// Next, add the Phi values and promote all of the loads and stores into the
// new locations.
// Replace the dummy values with new block arguments.
addBlockArguments(PhiBlocks);
// Hook up the Phi nodes, loads, and debug_value_addr with incoming values.
fixBranchesAndUses(PhiBlocks);
LLVM_DEBUG(llvm::dbgs() << "*** Finished placing Phis ***\n");
}
void StackAllocationPromoter::run() {
// Reduce the number of load/stores in the function to minimum.
// After this phase we are left with up to one load and store
// per block and the last store is recorded.
pruneAllocStackUsage();
// Replace AllocStacks with Phi-nodes.
promoteAllocationToPhi();
}
/// Attempt to promote the specified stack allocation, returning true if so
/// or false if not. On success, this returns true and usually drops all of the
/// uses of the AllocStackInst, but never deletes the ASI itself. Callers
/// should check to see if the ASI is dead after this and remove it if so.
bool MemoryToRegisters::promoteSingleAllocation(AllocStackInst *alloc,
DomTreeLevelMap &DomTreeLevels){
LLVM_DEBUG(llvm::dbgs() << "*** Memory to register looking at: " << *alloc);
++NumAllocStackFound;
// Don't handle captured AllocStacks.
bool inSingleBlock = false;
if (isCaptured(alloc, inSingleBlock)) {
++NumAllocStackCaptured;
return false;
}
// Remove write-only AllocStacks.
if (isWriteOnlyAllocation(alloc)) {
eraseUsesOfInstruction(alloc);
LLVM_DEBUG(llvm::dbgs() << "*** Deleting store-only AllocStack: "<< *alloc);
return true;
}
// For AllocStacks that are only used within a single basic blocks, use
// the linear sweep to remove the AllocStack.
if (inSingleBlock) {
removeSingleBlockAllocation(alloc);
LLVM_DEBUG(llvm::dbgs() << "*** Deleting single block AllocStackInst: "
<< *alloc);
if (!alloc->use_empty()) {
// Handle a corner case where the ASI still has uses:
// This can come up if the source contains a withUnsafePointer where
// the pointer escapes. It's illegal code but we should not crash.
// Re-insert a dealloc_stack so that the verifier is happy.
B.setInsertionPoint(std::next(alloc->getIterator()));
B.createDeallocStack(alloc->getLoc(), alloc);
}
return true;
}
LLVM_DEBUG(llvm::dbgs() << "*** Need to insert BB arguments for " << *alloc);
// Promote this allocation.
StackAllocationPromoter(alloc, DT, DomTreeLevels, B).run();
// Make sure that all of the allocations were promoted into registers.
assert(isWriteOnlyAllocation(alloc) && "Non-write uses left behind");
// ... and erase the allocation.
eraseUsesOfInstruction(alloc);
return true;
}
bool MemoryToRegisters::run() {
bool Changed = false;
F.verifyCriticalEdges();
// Compute dominator tree node levels for the function.
DomTreeLevelMap DomTreeLevels;
computeDomTreeLevels(DT, DomTreeLevels);
for (auto &BB : F) {
auto I = BB.begin(), E = BB.end();
while (I != E) {
SILInstruction *Inst = &*I;
auto *ASI = dyn_cast<AllocStackInst>(Inst);
if (!ASI) {
++I;
continue;
}
bool promoted = promoteSingleAllocation(ASI, DomTreeLevels);
++I;
if (promoted) {
if (ASI->use_empty())
ASI->eraseFromParent();
++NumInstRemoved;
Changed = true;
}
}
}
return Changed;
}
namespace {
class SILMem2Reg : public SILFunctionTransform {
void run() override {
SILFunction *F = getFunction();
LLVM_DEBUG(llvm::dbgs() << "** Mem2Reg on function: " << F->getName()
<< " **\n");
DominanceAnalysis* DA = PM->getAnalysis<DominanceAnalysis>();
bool Changed = MemoryToRegisters(*F, DA->get(F)).run();
if (Changed)
invalidateAnalysis(SILAnalysis::InvalidationKind::Instructions);
}
};
} // end anonymous namespace
SILTransform *swift::createMem2Reg() {
return new SILMem2Reg();
}
|
#include "Sandbox2D.h"
#include <imgui/imgui.h>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
Sandbox2D::Sandbox2D()
: Layer("Sandbox2D"), m_CameraController(1280.0f / 720.0f), m_SquareColor({ 0.2f, 0.3f, 0.8f, 1.0f })
{
}
void Sandbox2D::OnAttach()
{
HZ_PROFILE_FUNCTION();
m_CheckerboardTexture = Hazel::Texture2D::Create("assets/textures/Checkerboard.png");
}
void Sandbox2D::OnDetach()
{
HZ_PROFILE_FUNCTION();
}
void Sandbox2D::OnUpdate(Hazel::Timestep ts)
{
HZ_PROFILE_FUNCTION();
// Update
m_CameraController.OnUpdate(ts);
// Render
Hazel::Renderer2D::ResetStats();
{
HZ_PROFILE_SCOPE("Renderer Prep");
Hazel::RenderCommand::SetClearColor({ 0.1f, 0.1f, 0.1f, 1 });
Hazel::RenderCommand::Clear();
}
{
static float rotation = 0.0f;
rotation += ts * 50.0f;
HZ_PROFILE_SCOPE("Renderer Draw");
Hazel::Renderer2D::BeginScene(m_CameraController.GetCamera());
Hazel::Renderer2D::DrawRotatedQuad({ 1.0f, 0.0f }, { 0.8f, 0.8f }, -45.0f, { 0.8f, 0.2f, 0.3f, 1.0f });
Hazel::Renderer2D::DrawQuad({ -1.0f, 0.0f }, { 0.8f, 0.8f }, { 0.8f, 0.2f, 0.3f, 1.0f });
Hazel::Renderer2D::DrawQuad({ 0.5f, -0.5f }, { 0.5f, 0.75f }, m_SquareColor);
Hazel::Renderer2D::DrawQuad({ 0.0f, 0.0f, -0.1f }, { 20.0f, 20.0f }, m_CheckerboardTexture, 10.0f);
Hazel::Renderer2D::DrawRotatedQuad({ -2.0f, 0.0f, 0.0f }, { 1.0f, 1.0f }, rotation, m_CheckerboardTexture, 20.0f);
Hazel::Renderer2D::EndScene();
Hazel::Renderer2D::BeginScene(m_CameraController.GetCamera());
for (float y = -5.0f; y < 5.0f; y += 0.5f)
{
for (float x = -5.0f; x < 5.0f; x += 0.5f)
{
glm::vec4 color = { (x + 5.0f) / 10.0f, 0.4f, (y + 5.0f) / 10.0f, 0.7f };
Hazel::Renderer2D::DrawQuad({ x, y }, { 0.45f, 0.45f }, color);
}
}
Hazel::Renderer2D::EndScene();
}
}
void Sandbox2D::OnImGuiRender()
{
HZ_PROFILE_FUNCTION();
ImGui::Begin("Settings");
auto stats = Hazel::Renderer2D::GetStats();
ImGui::Text("Renderer2D Stats:");
ImGui::Text("Draw Calls: %d", stats.DrawCalls);
ImGui::Text("Quads: %d", stats.QuadCount);
ImGui::Text("Vertices: %d", stats.GetTotalVertexCount());
ImGui::Text("Indices: %d", stats.GetTotalIndexCount());
ImGui::ColorEdit4("Square Color", glm::value_ptr(m_SquareColor));
ImGui::End();
}
void Sandbox2D::OnEvent(Hazel::Event& e)
{
m_CameraController.OnEvent(e);
}
|
/*
* Copyright (c) 2018 01 People, s.r.o. (01 CryptoHouse).
*
* The MIT License
*
* 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.
*/
#pragma once
#include <graphene/app/plugin.hpp>
#include <graphene/chain/database.hpp>
#include <graphene/chain/operation_archive_object.hpp>
#include <graphene/account_archive/operation_database.hpp>
#include <fc/thread/future.hpp>
namespace graphene { namespace account_archive {
using namespace chain;
//
// Plugins should #define their SPACE_ID's so plugins with
// conflicting SPACE_ID assignments can be compiled into the
// same binary (by simply re-assigning some of the conflicting #defined
// SPACE_ID's in a build script).
//
// Assignment of SPACE_ID's cannot be done at run-time because
// various template automagic depends on them being known at compile
// time.
//
#ifndef ACCOUNT_ARCHIVE_SPACE_ID
#define ACCOUNT_ARCHIVE_SPACE_ID 7
#endif
namespace detail
{
class account_archive_plugin_impl;
}
class account_archive_plugin : public graphene::app::plugin
{
public:
account_archive_plugin();
~account_archive_plugin();
std::string plugin_name() const override;
void plugin_initialize(const boost::program_options::variables_map& options) override;
void plugin_startup() override;
void plugin_set_program_options(
boost::program_options::options_description& cli,
boost::program_options::options_description& cfg) override;
operation_history_object load(uint32_t index) const;
friend class detail::account_archive_plugin_impl;
std::unique_ptr<detail::account_archive_plugin_impl> impl;
};
} } // graphene::account_archive
|
// Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
#include "extern/beatsaber-hook/shared/utils/byref.hpp"
// Including type: UnityEngine.Behaviour
#include "UnityEngine/Behaviour.hpp"
// Completed includes
// Type namespace: UnityEngine.Rendering
namespace UnityEngine::Rendering {
// Size: 0x18
#pragma pack(push, 1)
// Autogenerated type: UnityEngine.Rendering.SortingGroup
// [TokenAttribute] Offset: FFFFFFFF
// [RequireComponent] Offset: E2C490
// [NativeTypeAttribute] Offset: E2C490
class SortingGroup : public UnityEngine::Behaviour {
public:
// Creating value type constructor for type: SortingGroup
SortingGroup() noexcept {}
}; // UnityEngine.Rendering.SortingGroup
#pragma pack(pop)
}
#include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
DEFINE_IL2CPP_ARG_TYPE(UnityEngine::Rendering::SortingGroup*, "UnityEngine.Rendering", "SortingGroup");
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
|
#include<stdio.h>
char x[] = "programming";
char y[] = "Fortran";
void main()
{
int i = 0l;
while (x[i] != '\0' && y[i] != '\0')
{
if (x[i] == y[i])
{
int c=x[i]; putchar(c); c=getchar();
}
else i++;
}
}
|
// Copyright 2015 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/logger.h"
#include "ppapi/cpp/instance.h"
static pp::Instance* instance_ = nullptr; // non-owning pointer
static LogLevel log_level_ = LOGDISABLED;
void LogInit(pp::Instance* instance, LogLevel level) {
instance_ = instance;
log_level_ = level;
DINF() << "Initializing log system with level: " << level;
}
base::LoggedStream LogPrint(LogLevel level) {
return base::LoggedStream(instance_, log_level_, level);
}
|
/* 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/inference/analysis/pass_manager.h"
#include "paddle/fluid/inference/analysis/fluid_to_data_flow_graph_pass.h"
namespace paddle {
namespace inference {
namespace analysis {
bool PassManager::Initialize(Argument* argument) {
argument_ = argument;
for (auto& pass : data_) {
LOG(WARNING) << "Initializing pass [" << pass->repr() << "]";
if (!pass->Initialize(argument)) {
LOG(ERROR) << "Failed to initialize pass [" << pass->repr() << "]";
return false;
}
}
return true;
}
void DfgPassManager::RunAll() {
PADDLE_ENFORCE(argument_);
LOG(INFO) << "Total " << data_.size() << " Analysys passes";
for (auto& pass : data_) {
LOG(WARNING) << "Running Analysis pass [" << pass->repr() << "]";
pass->Run(argument_->main_dfg.get());
}
}
void NodePassManager::RunAll() {
PADDLE_ENFORCE(argument_);
PADDLE_ENFORCE(argument_->main_dfg.get());
auto trait = GraphTraits<DataFlowGraph>(*argument_->main_dfg).nodes_in_DFS();
for (auto& node : trait) {
for (auto& pass : data_) {
pass->Run(&node);
}
}
}
} // namespace analysis
} // namespace inference
} // namespace paddle
|
#include "Base.h"
#include "Maths/Matrix4.h"
#include "Graphics/Mesh/Mesh.h"
#include "Graphics/Renderer/Renderer.h"
#include "Log/LogManager.h"
#include "Log/LogVerbose.h"
#include "CA_Assert.h"
#include "Game/Game.h"
namespace CasaEngine
{
Texture* Mesh::m_pDefaultTexture = nullptr;
// bgfx::TextureHandle genMissingTexture(uint32_t _width, uint32_t _height, float _lineWidth = 0.02f)
// {
// const bgfx::Memory* mem = bgfx::alloc(_width*_height*4);
// uint32_t* bgra8 = (uint32_t*)mem->data;
//
// const float sx = 0.70710677f;
// const float cx = 0.70710677f;
//
// for (uint32_t yy = 0; yy < _height; ++yy)
// {
// for (uint32_t xx = 0; xx < _width; ++xx)
// {
// float px = xx / float(_width) * 2.0f - 1.0f;
// float py = yy / float(_height) * 2.0f - 1.0f;
//
// float sum = bx::fpulse(px * cx - py * sx, _lineWidth, -_lineWidth)
// + bx::fpulse(px * sx + py * cx, _lineWidth, -_lineWidth)
// ;
// *bgra8++ = sum >= 1.0f ? 0xffff0000 : 0xffffffff;
// }
// }
//
// return bgfx::createTexture2D(uint16_t(_width), uint16_t(_height), 0, bgfx::TextureFormat::BGRA8, 0, mem);
// }
/**
*
*/
Mesh::Mesh(const VertexPositionNormalTexture* Vertices, unsigned long VerticesCount, const unsigned short* Indices, unsigned long IndicesCount) :
m_pMaterial(nullptr)
{
if (m_pDefaultTexture == nullptr)
{
//Todo : create it programmatically
m_pDefaultTexture = Texture::loadTexture(Game::Instance().GetMediaManager().FindMedia("checkboard.dds", true), BGFX_TEXTURE_NONE);
}
CA_ASSERT(Vertices != nullptr, "Mesh::Mesh() : Vertices is nullptr");
CA_ASSERT(Indices != nullptr, "Mesh::Mesh() : Indices is nullptr");
m_VertexBuffer = bgfx::createVertexBuffer(
bgfx::makeRef(Vertices, VerticesCount * sizeof(VertexPositionNormalTexture)),
VertexPositionNormalTexture::ms_layout);
m_IndexBuffer = bgfx::createIndexBuffer(
bgfx::makeRef(Indices, IndicesCount * sizeof(short)));
m_TextureRepetitionUniform = bgfx::createUniform("u_texcoord0rep", bgfx::UniformType::Vec4);
m_TextureUniform = bgfx::createUniform("s_texColor", bgfx::UniformType::Sampler);
const char* materialName = "internal_default_material";
if (nullptr == m_pMaterial
&& !Game::Instance().GetAssetManager().Contains(materialName))
{
m_pMaterial = NEW_AO Material();
m_pMaterial->Texture0(m_pDefaultTexture);
Game::Instance().GetAssetManager().AddAsset(materialName, m_pMaterial);
}
m_pMaterial = Game::Instance().GetAssetManager().GetAsset<Material>(materialName);
}
Mesh::~Mesh()
{
bgfx::destroy(m_IndexBuffer);
bgfx::destroy(m_VertexBuffer);
}
Material* Mesh::GetMaterial() const
{
return m_pMaterial;
}
void Mesh::SetMaterial(Material* val)
{
// if (nullptr != m_pMaterial)
// {
// m_pMaterial->Release();
// }
m_pMaterial = val;
}
void Mesh::Render(bgfx::ProgramHandle handle_, Matrix4& matWorld_) const
{
bgfx::setTransform(matWorld_);
bgfx::setVertexBuffer(0, m_VertexBuffer);
bgfx::setIndexBuffer(m_IndexBuffer);
bgfx::TextureHandle texture = m_pMaterial->Texture0() != nullptr ? m_pMaterial->Texture0()->Handle() : m_pDefaultTexture->Handle();
bgfx::setTexture(0, m_TextureUniform, bgfx::isValid(texture) ? texture : m_pDefaultTexture->Handle());
bgfx::setUniform(m_TextureRepetitionUniform, Vector4F(m_pMaterial->Texture0Repeat().x, m_pMaterial->Texture0Repeat().y, 1.0f, 1.0f));
bgfx::setState(BGFX_STATE_WRITE_RGB
| BGFX_STATE_WRITE_A
| BGFX_STATE_WRITE_Z
| BGFX_STATE_DEPTH_TEST_GREATER
| BGFX_STATE_CULL_CW
| BGFX_STATE_MSAA);
bgfx::submit(0, handle_);
}
}
|
#include "winbd_cipher.h"
using namespace std;
int main()
{
Cipher cp;
string lol = "hello";
char key[5] = { 'A','B','C','D','E' };
string d = cp.xor_data_hex(lol, key);
cout << cp.xor_data(lol, key) << endl;
cout << d << endl;
cout << cp.hex_format_raw(d) << endl;
cout << cp.not_data(lol, key) << endl;
return 0;
}
|
#include "while.h"
//Using a while loop write code for sum_of_squares function that accepts an int and returns
//the sum of all the squares of that number from 1 to the number.
//Example: sum_of_squares(4)
//1*1 + 2 * 2 + 3*3 + 4*4 = 30
//Using a while loop write code for display function that accepts a string and displays
//each character of the string in a line
//Example: display("Hello")
/*
result:
H
e
l
l
0
*/
|
// Copyright 2017 PDFium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com
#include "xfa/fxfa/parser/cxfa_timezoneprovider.h"
#include <time.h>
static bool g_bProviderTimeZoneSet = false;
CXFA_TimeZoneProvider::CXFA_TimeZoneProvider() {
#if _FX_PLATFORM_ == _FX_PLATFORM_WINDOWS_
if (!g_bProviderTimeZoneSet) {
g_bProviderTimeZoneSet = true;
_tzset();
}
m_tz.tzHour = static_cast<int8_t>(_timezone / 3600 * -1);
m_tz.tzMinute = static_cast<int8_t>((abs(_timezone) % 3600) / 60);
#else
if (!g_bProviderTimeZoneSet) {
g_bProviderTimeZoneSet = true;
tzset();
}
m_tz.tzHour = static_cast<int8_t>(timezone / 3600 * -1);
m_tz.tzMinute =
static_cast<int8_t>((abs(static_cast<int>(timezone)) % 3600) / 60);
#endif
}
CXFA_TimeZoneProvider::~CXFA_TimeZoneProvider() {}
|
/*************************************************************************/
/* quick_open.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* http://www.godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */
/* */
/* 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 "quick_open.h"
#include "os/keyboard.h"
void EditorQuickOpen::popup(const StringName &p_base, bool p_enable_multi, bool p_add_dirs, bool p_dontclear) {
add_directories=p_add_dirs;
popup_centered_ratio(0.6);
if (p_dontclear)
search_box->select_all();
else
search_box->clear();
if (p_enable_multi)
search_options->set_select_mode(Tree::SELECT_MULTI);
else
search_options->set_select_mode(Tree::SELECT_SINGLE);
search_box->grab_focus();
base_type=p_base;
_update_search();
}
String EditorQuickOpen::get_selected() const {
TreeItem *ti = search_options->get_selected();
if (!ti)
return String();
return "res://" + ti->get_text(0);
}
Vector<String> EditorQuickOpen::get_selected_files() const {
Vector<String> files;
TreeItem* item = search_options->get_next_selected(search_options->get_root());
while (item) {
files.push_back("res://"+item->get_text(0));
item = search_options->get_next_selected(item);
}
return files;
}
void EditorQuickOpen::_text_changed(const String& p_newtext) {
_update_search();
}
void EditorQuickOpen::_sbox_input(const InputEvent& p_ie) {
if (p_ie.type==InputEvent::KEY) {
switch(p_ie.key.scancode) {
case KEY_UP:
case KEY_DOWN:
case KEY_PAGEUP:
case KEY_PAGEDOWN: {
search_options->call("_gui_input", p_ie);
search_box->accept_event();
TreeItem *root = search_options->get_root();
if (!root->get_children())
break;
TreeItem *current = search_options->get_selected();
TreeItem *item = search_options->get_next_selected(root);
while (item) {
item->deselect(0);
item = search_options->get_next_selected(item);
}
current->select(0);
} break;
}
}
}
float EditorQuickOpen::_path_cmp(String search, String path) const {
if (search == path) {
return 1.2f;
}
if (path.findn(search) != -1) {
return 1.1f;
}
return path.to_lower().similarity(search.to_lower());
}
void EditorQuickOpen::_parse_fs(EditorFileSystemDirectory *efsd, Vector< Pair< String, Ref<Texture> > > &list) {
if (!add_directories) {
for(int i=0;i<efsd->get_subdir_count();i++) {
_parse_fs(efsd->get_subdir(i), list);
}
}
String search_text = search_box->get_text();
if (add_directories) {
String path = efsd->get_path();
if (!path.ends_with("/"))
path+="/";
if (path!="res://") {
path=path.substr(6,path.length());
if (search_text.is_subsequence_ofi(path)) {
Pair< String, Ref<Texture> > pair;
pair.first = path;
pair.second = get_icon("folder", "FileDialog");
if (search_text != String() && list.size() > 0) {
float this_sim = _path_cmp(search_text, path);
float other_sim = _path_cmp(list[0].first, path);
int pos = 1;
while (pos < list.size() && this_sim <= other_sim) {
other_sim = _path_cmp(list[pos++].first, path);
}
pos = this_sim >= other_sim ? pos - 1 : pos;
list.insert(pos, pair);
} else {
list.push_back(pair);
}
}
}
}
for(int i=0;i<efsd->get_file_count();i++) {
String file = efsd->get_file_path(i);
file=file.substr(6,file.length());
if (ClassDB::is_parent_class(efsd->get_file_type(i),base_type) && (search_text.is_subsequence_ofi(file))) {
Pair< String, Ref<Texture> > pair;
pair.first = file;
pair.second = get_icon((has_icon(efsd->get_file_type(i), ei) ? efsd->get_file_type(i) : ot), ei);
if (search_text != String() && list.size() > 0) {
float this_sim = _path_cmp(search_text, file);
float other_sim = _path_cmp(list[0].first, file);
int pos = 1;
while (pos < list.size() && this_sim <= other_sim) {
other_sim = _path_cmp(list[pos++].first, file);
}
pos = this_sim >= other_sim ? pos - 1 : pos;
list.insert(pos, pair);
} else {
list.push_back(pair);
}
}
}
if (add_directories) {
for(int i=0;i<efsd->get_subdir_count();i++) {
_parse_fs(efsd->get_subdir(i), list);
}
}
}
void EditorQuickOpen::_update_search() {
search_options->clear();
TreeItem *root = search_options->create_item();
EditorFileSystemDirectory *efsd = EditorFileSystem::get_singleton()->get_filesystem();
Vector< Pair< String, Ref<Texture> > > list;
_parse_fs(efsd, list);
for (int i = 0; i < list.size(); i++) {
TreeItem *ti = search_options->create_item(root);
ti->set_text(0, list[i].first);
ti->set_icon(0, list[i].second);
}
if (root->get_children()) {
TreeItem *ti = root->get_children();
ti->select(0);
ti->set_as_cursor(0);
}
get_ok()->set_disabled(root->get_children()==NULL);
}
void EditorQuickOpen::_confirmed() {
TreeItem *ti = search_options->get_selected();
if (!ti)
return;
emit_signal("quick_open");
hide();
}
void EditorQuickOpen::_notification(int p_what) {
if (p_what==NOTIFICATION_ENTER_TREE) {
connect("confirmed",this,"_confirmed");
}
}
StringName EditorQuickOpen::get_base_type() const {
return base_type;
}
void EditorQuickOpen::_bind_methods() {
ClassDB::bind_method(_MD("_text_changed"),&EditorQuickOpen::_text_changed);
ClassDB::bind_method(_MD("_confirmed"),&EditorQuickOpen::_confirmed);
ClassDB::bind_method(_MD("_sbox_input"),&EditorQuickOpen::_sbox_input);
ADD_SIGNAL(MethodInfo("quick_open"));
}
EditorQuickOpen::EditorQuickOpen() {
VBoxContainer *vbc = memnew( VBoxContainer );
add_child(vbc);
//set_child_rect(vbc);
search_box = memnew( LineEdit );
vbc->add_margin_child(TTR("Search:"),search_box);
search_box->connect("text_changed",this,"_text_changed");
search_box->connect("gui_input",this,"_sbox_input");
search_options = memnew( Tree );
vbc->add_margin_child(TTR("Matches:"),search_options,true);
get_ok()->set_text(TTR("Open"));
get_ok()->set_disabled(true);
register_text_enter(search_box);
set_hide_on_ok(false);
search_options->connect("item_activated",this,"_confirmed");
search_options->set_hide_root(true);
ei="EditorIcons";
ot="Object";
add_directories=false;
}
|
// Copyright (c) 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 "content/renderer/media/mock_media_stream_registry.h"
#include <string>
#include "base/strings/utf_string_conversions.h"
#include "content/renderer/media/media_stream.h"
#include "content/renderer/media/media_stream_audio_source.h"
#include "content/renderer/media/media_stream_video_track.h"
#include "content/renderer/media/mock_media_stream_video_source.h"
#include "content/renderer/media/video_track_adapter.h"
#include "third_party/WebKit/public/platform/WebMediaStreamSource.h"
#include "third_party/WebKit/public/platform/WebMediaStreamTrack.h"
#include "third_party/WebKit/public/platform/WebString.h"
#include "third_party/WebKit/public/platform/WebVector.h"
namespace content {
namespace {
const char kTestStreamLabel[] = "stream_label";
class MockCDQualityAudioSource : public MediaStreamAudioSource {
public:
MockCDQualityAudioSource() : MediaStreamAudioSource(true) {
MediaStreamAudioSource::SetFormat(media::AudioParameters(
media::AudioParameters::AUDIO_PCM_LOW_LATENCY,
media::CHANNEL_LAYOUT_STEREO,
media::AudioParameters::kAudioCDSampleRate,
16,
media::AudioParameters::kAudioCDSampleRate / 100));
MediaStreamAudioSource::SetDeviceInfo(StreamDeviceInfo(
MEDIA_DEVICE_AUDIO_CAPTURE, "Mock audio device", "mock_audio_device_id",
media::AudioParameters::kAudioCDSampleRate,
media::CHANNEL_LAYOUT_STEREO,
media::AudioParameters::kAudioCDSampleRate / 100));
}
private:
DISALLOW_COPY_AND_ASSIGN(MockCDQualityAudioSource);
};
} // namespace
MockMediaStreamRegistry::MockMediaStreamRegistry() {}
void MockMediaStreamRegistry::Init(const std::string& stream_url) {
stream_url_ = stream_url;
const blink::WebVector<blink::WebMediaStreamTrack> webkit_audio_tracks;
const blink::WebVector<blink::WebMediaStreamTrack> webkit_video_tracks;
const blink::WebString label(kTestStreamLabel);
test_stream_.Initialize(label, webkit_audio_tracks, webkit_video_tracks);
test_stream_.SetExtraData(new MediaStream());
}
void MockMediaStreamRegistry::AddVideoTrack(
const std::string& track_id,
const VideoTrackAdapterSettings& adapter_settings,
const base::Optional<bool>& noise_reduction,
bool is_screencast,
double min_frame_rate) {
blink::WebMediaStreamSource blink_source;
blink_source.Initialize("mock video source id",
blink::WebMediaStreamSource::kTypeVideo,
"mock video source name", false /* remote */);
MockMediaStreamVideoSource* native_source = new MockMediaStreamVideoSource();
blink_source.SetExtraData(native_source);
blink::WebMediaStreamTrack blink_track;
blink_track.Initialize(blink::WebString::FromUTF8(track_id), blink_source);
MediaStreamVideoTrack* native_track = new MediaStreamVideoTrack(
native_source, adapter_settings, noise_reduction, is_screencast,
min_frame_rate, MediaStreamVideoSource::ConstraintsCallback(),
true /* enabled */);
blink_track.SetTrackData(native_track);
test_stream_.AddTrack(blink_track);
}
void MockMediaStreamRegistry::AddVideoTrack(const std::string& track_id) {
AddVideoTrack(track_id, VideoTrackAdapterSettings(), base::Optional<bool>(),
false /* is_screncast */, 0.0 /* min_frame_rate */);
}
void MockMediaStreamRegistry::AddAudioTrack(const std::string& track_id) {
blink::WebMediaStreamSource blink_source;
blink_source.Initialize("mock audio source id",
blink::WebMediaStreamSource::kTypeAudio,
"mock audio source name", false /* remote */);
MediaStreamAudioSource* const source = new MockCDQualityAudioSource();
blink_source.SetExtraData(source); // Takes ownership.
blink::WebMediaStreamTrack blink_track;
blink_track.Initialize(blink_source);
CHECK(source->ConnectToTrack(blink_track));
test_stream_.AddTrack(blink_track);
}
blink::WebMediaStream MockMediaStreamRegistry::GetMediaStream(
const std::string& url) {
return (url != stream_url_) ? blink::WebMediaStream() : test_stream_;
}
} // namespace content
|
/*=========================================================================
Program: ParaView
Module: pqStandardViewFrameActionsImplementation.cxx
Copyright (c) 2005,2006 Sandia Corporation, Kitware Inc.
All rights reserved.
ParaView is a free software; you can redistribute it and/or modify it
under the terms of the ParaView license version 1.2.
See License_v1.2.txt for the full ParaView license.
A copy of this license can be obtained by contacting
Kitware Inc.
28 Corporate Drive
Clifton Park, NY 12065
USA
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 AUTHORS 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 "pqStandardViewFrameActionsImplementation.h"
#include "ui_pqEmptyView.h"
#include "pqActiveObjects.h"
#include "pqApplicationCore.h"
#include "pqCameraUndoRedoReaction.h"
#include "pqChartSelectionReaction.h"
#include "pqColorOverlay.h"
#include "pqContextView.h"
#include "pqCoreUtilities.h"
#include "pqDataQueryReaction.h"
#include "pqEditCameraReaction.h"
#include "pqInterfaceTracker.h"
#include "pqMultiViewWidget.h"
#include "pqObjectBuilder.h"
#include "pqRenameProxyReaction.h"
#include "pqRenderView.h"
#include "pqRenderViewSelectionReaction.h"
#include "pqSaveScreenshotReaction.h"
#include "pqServer.h"
#include "pqSpreadSheetView.h"
#include "pqSpreadSheetViewDecorator.h"
#include "pqToggleInteractionViewMode.h"
#include "pqUndoStack.h"
#include "pqViewFrame.h"
#include "vtkChart.h"
#include "vtkCollection.h"
#include "vtkPVProxyDefinitionIterator.h"
#include "vtkPVXMLElement.h"
#include "vtkSMInteractiveSelectionPipeline.h"
#include "vtkSMProxy.h"
#include "vtkSMProxyDefinitionManager.h"
#include "vtkSMRenderViewProxy.h"
#include "vtkSMSessionProxyManager.h"
#include "vtkSMTooltipSelectionPipeline.h"
#include "vtkSMViewLayoutProxy.h"
#include "vtkSmartPointer.h"
#include <QGuiApplication>
#include <QKeyEvent>
#include <QMenu>
#include <QPropertyAnimation>
#include <QPushButton>
#include <QSet>
#include <QShortcut>
#include <QStyle>
#include <QToolTip>
#include <algorithm>
#include <cassert>
namespace
{
template <typename T>
T findParent(QObject* obj)
{
if (auto view = qobject_cast<T>(obj))
{
return view;
}
else if (obj)
{
return findParent<T>(obj->parent());
}
return nullptr;
}
QAction* findActiveAction(const QString& name)
{
pqView* activeView = pqActiveObjects::instance().activeView();
if (activeView && activeView->widget() && activeView->widget()->parentWidget() &&
activeView->widget()->parentWidget()->parentWidget())
{
return activeView->widget()->parentWidget()->parentWidget()->findChild<QAction*>(name);
}
return nullptr;
}
void triggerAction(const QString& name)
{
QAction* atcn = findActiveAction(name);
if (atcn)
{
atcn->trigger();
}
}
}
//-----------------------------------------------------------------------------
pqStandardViewFrameActionsImplementation::pqStandardViewFrameActionsImplementation(
QObject* parentObject)
: QObject(parentObject)
{
QWidget* mainWindow = pqCoreUtilities::mainWidget();
this->ShortCutSurfaceCells = new QShortcut(QKeySequence(tr("s")), mainWindow);
this->ShortCutSurfacePoints = new QShortcut(QKeySequence(tr("d")), mainWindow);
this->ShortCutFrustumCells = new QShortcut(QKeySequence(tr("f")), mainWindow);
this->ShortCutFrustumPoints = new QShortcut(QKeySequence(tr("g")), mainWindow);
this->ShortCutBlocks = new QShortcut(QKeySequence("b"), mainWindow);
this->ShortCutGrow = new QShortcut(QKeySequence("+"), mainWindow);
this->ShortCutShrink = new QShortcut(QKeySequence("-"), mainWindow);
QObject::connect(
this->ShortCutSurfaceCells, SIGNAL(activated()), this, SLOT(selectSurfaceCellsTriggered()));
QObject::connect(
this->ShortCutSurfacePoints, SIGNAL(activated()), this, SLOT(selectSurfacePointsTriggered()));
QObject::connect(
this->ShortCutFrustumCells, SIGNAL(activated()), this, SLOT(selectFrustumCellsTriggered()));
QObject::connect(
this->ShortCutFrustumPoints, SIGNAL(activated()), this, SLOT(selectFrustumPointsTriggered()));
QObject::connect(this->ShortCutBlocks, SIGNAL(activated()), this, SLOT(selectBlocksTriggered()));
QObject::connect(this->ShortCutGrow.data(), &QShortcut::activated,
[]() { triggerAction("actionGrowSelection"); });
QObject::connect(this->ShortCutShrink.data(), &QShortcut::activated,
[]() { triggerAction("actionShrinkSelection"); });
this->ShortCutEsc = new QShortcut(QKeySequence(Qt::Key_Escape), mainWindow);
this->ShortCutEsc->setEnabled(false);
this->connect(this->ShortCutEsc, SIGNAL(activated()), SLOT(escTriggered()));
}
//-----------------------------------------------------------------------------
pqStandardViewFrameActionsImplementation::~pqStandardViewFrameActionsImplementation()
{
delete this->ShortCutSurfaceCells;
delete this->ShortCutSurfacePoints;
delete this->ShortCutFrustumCells;
delete this->ShortCutFrustumPoints;
delete this->ShortCutBlocks;
}
//-----------------------------------------------------------------------------
void pqStandardViewFrameActionsImplementation::frameConnected(pqViewFrame* frame, pqView* view)
{
assert(frame != nullptr);
if (view == nullptr)
{
// Setup the UI shown when no view is present in the frame.
QWidget* empty_frame = new QWidget(frame);
this->setupEmptyFrame(empty_frame);
frame->setCentralWidget(empty_frame);
}
else
{
// add view-type independent actions.
frame->setTitle(view->getSMName());
this->addGenericActions(frame, view);
if (pqContextView* const chart_view = qobject_cast<pqContextView*>(view))
{
this->addContextViewActions(frame, chart_view);
}
else if (pqRenderView* const render_view = qobject_cast<pqRenderView*>(view))
{
this->addRenderViewActions(frame, render_view);
}
else if (pqSpreadSheetView* const sp_view = qobject_cast<pqSpreadSheetView*>(view))
{
this->addSpreadSheetViewActions(frame, sp_view);
}
}
}
//-----------------------------------------------------------------------------
void pqStandardViewFrameActionsImplementation::addContextViewActions(
pqViewFrame* frame, pqContextView* chart_view)
{
// Adding special selection controls for chart/context view
assert(chart_view);
assert(frame);
QActionGroup* modeGroup = this->addSelectionModifierActions(frame, chart_view);
QActionGroup* group = new QActionGroup(frame);
this->addSeparator(frame, chart_view);
if (this->isButtonVisible("SelectPolygon", chart_view))
{
QAction* chartSelectPolygonAction = frame->addTitleBarAction(
QIcon(":/pqWidgets/Icons/pqSelectChartPolygon.svg"), "Polygon Selection (d)");
chartSelectPolygonAction->setObjectName("actionChartSelectPolygon");
chartSelectPolygonAction->setCheckable(true);
chartSelectPolygonAction->setData(QVariant(vtkChart::SELECT_POLYGON));
this->connect(
chartSelectPolygonAction, SIGNAL(toggled(bool)), SLOT(escapeableActionToggled(bool)));
group->addAction(chartSelectPolygonAction);
new pqChartSelectionReaction(chartSelectPolygonAction, chart_view, modeGroup);
}
if (this->isButtonVisible("SelectRectangle", chart_view))
{
QAction* chartSelectRectangularAction = frame->addTitleBarAction(
QIcon(":/pqWidgets/Icons/pqSelectChart.svg"), "Rectangle Selection (s)");
chartSelectRectangularAction->setObjectName("actionChartSelectRectangle");
chartSelectRectangularAction->setCheckable(true);
chartSelectRectangularAction->setData(QVariant(vtkChart::SELECT_RECTANGLE));
this->connect(
chartSelectRectangularAction, SIGNAL(toggled(bool)), SLOT(escapeableActionToggled(bool)));
new pqChartSelectionReaction(chartSelectRectangularAction, chart_view, modeGroup);
group->addAction(chartSelectRectangularAction);
}
/// If a QAction is added to an exclusive QActionGroup, then a checked action
/// cannot be unchecked by clicking on it. We need that to work. Hence, we
/// manually manage the exclusivity of the action group.
group->setExclusive(false);
this->QObject::connect(
group, SIGNAL(triggered(QAction*)), SLOT(manageGroupExclusivity(QAction*)));
}
//-----------------------------------------------------------------------------
QActionGroup* pqStandardViewFrameActionsImplementation::addSelectionModifierActions(
pqViewFrame* frame, pqView* view)
{
assert(view);
assert(frame);
QAction* toggleAction = nullptr;
QAction* minusAction = nullptr;
QAction* plusAction = nullptr;
this->addSeparator(frame, view);
if (this->isButtonVisible("AddSelection", view))
{
plusAction = frame->addTitleBarAction(
QIcon(":/pqWidgets/Icons/pqSelectPlus.svg"), tr("Add selection (Ctrl)"));
plusAction->setObjectName("actionAddSelection");
plusAction->setCheckable(true);
plusAction->setData(QVariant(pqView::PV_SELECTION_ADDITION));
}
if (this->isButtonVisible("SubtractSelection", view))
{
minusAction = frame->addTitleBarAction(
QIcon(":/pqWidgets/Icons/pqSelectMinus.svg"), tr("Subtract selection (Shift)"));
minusAction->setObjectName("actionSubtractSelection");
minusAction->setCheckable(true);
minusAction->setData(QVariant(pqView::PV_SELECTION_SUBTRACTION));
}
if (this->isButtonVisible("ToggleSelection", view))
{
toggleAction = frame->addTitleBarAction(
QIcon(":/pqWidgets/Icons/pqSelectToggle.svg"), tr("Toggle selection (Ctrl+Shift)"));
toggleAction->setObjectName("actionToggleSelection");
toggleAction->setCheckable(true);
toggleAction->setData(QVariant(pqView::PV_SELECTION_TOGGLE));
}
QActionGroup* modeGroup = new QActionGroup(frame);
if (plusAction)
{
modeGroup->addAction(plusAction);
}
if (minusAction)
{
modeGroup->addAction(minusAction);
}
if (toggleAction)
{
modeGroup->addAction(toggleAction);
}
/// If a QAction is added to an exclusive QActionGroup, then a checked action
/// cannot be unchecked by clicking on it. We need that to work. Hence, we
/// manually manage the exclusivity of the action group.
modeGroup->setExclusive(false);
this->QObject::connect(
modeGroup, SIGNAL(triggered(QAction*)), SLOT(manageGroupExclusivity(QAction*)));
return modeGroup;
}
//-----------------------------------------------------------------------------
void pqStandardViewFrameActionsImplementation::addSeparator(pqViewFrame* frame, pqView* view)
{
if (this->isButtonVisible("Separator", view))
{
frame->addTitleBarSeparator();
}
}
//-----------------------------------------------------------------------------
void pqStandardViewFrameActionsImplementation::addGenericActions(pqViewFrame* frame, pqView* view)
{
assert(frame);
assert(view);
/// Add convert-to menu.
frame->contextMenu()->addSeparator();
QAction* renameAction = frame->contextMenu()->addAction("Rename");
new pqRenameProxyReaction(renameAction, view, view->widget());
QMenu* convertMenu = frame->contextMenu()->addMenu("Convert To ...");
QObject::connect(convertMenu, SIGNAL(aboutToShow()), this, SLOT(aboutToShowConvertMenu()));
if (view->supportsUndo())
{
// Setup undo/redo connections if the view module
// supports interaction undo.
if (this->isButtonVisible("BackButton", view))
{
QAction* backAction =
frame->addTitleBarAction(QIcon(":/pqWidgets/Icons/pqUndoCamera.svg"), "Camera Undo");
backAction->setObjectName("actionBackButton");
new pqCameraUndoRedoReaction(backAction, true, view);
}
if (this->isButtonVisible("ForwardButton", view))
{
QAction* forwardAction =
frame->addTitleBarAction(QIcon(":/pqWidgets/Icons/pqRedoCamera.svg"), "Camera Redo");
forwardAction->setObjectName("actionForwardButton");
new pqCameraUndoRedoReaction(forwardAction, false, view);
}
this->addSeparator(frame, view);
}
if (view->supportsCapture())
{
if (this->isButtonVisible("captureViewAction", view))
{
QAction* captureViewAction = frame->addTitleBarAction(
QIcon(":/pqWidgets/Icons/pqCaptureScreenshot.svg"), "Capture to Clipboard or File");
captureViewAction->setObjectName("actionCaptureView");
captureViewAction->setToolTip("Capture screenshot to a file or to the clipboard if a "
"modifier key (Ctrl, Alt or Shift) is pressed.");
this->connect(captureViewAction, SIGNAL(triggered(bool)), SLOT(captureViewTriggered()));
}
}
}
//-----------------------------------------------------------------------------
void pqStandardViewFrameActionsImplementation::addRenderViewActions(
pqViewFrame* frame, pqRenderView* renderView)
{
assert(renderView);
assert(frame);
this->addSeparator(frame, renderView);
if (this->isButtonVisible("ToggleInteractionMode", renderView))
{
QAction* toggleInteractionModeAction = frame->addTitleBarAction(
QIcon(":/pqWidgets/Icons/pqInteractionMode3D.svg"), "Change Interaction Mode");
toggleInteractionModeAction->setObjectName("actionToggleInteractionMode");
new pqToggleInteractionViewMode(toggleInteractionModeAction, renderView);
}
if (this->isButtonVisible("AdjustCamera", renderView))
{
QAction* adjustCameraAction =
frame->addTitleBarAction(QIcon(":/pqWidgets/Icons/pqEditCamera.svg"), "Adjust Camera");
adjustCameraAction->setObjectName("actionAdjustCamera");
new pqEditCameraReaction(adjustCameraAction, renderView);
}
QActionGroup* modeGroup = this->addSelectionModifierActions(frame, renderView);
this->addSeparator(frame, renderView);
if (this->isButtonVisible("SelectSurfaceCells", renderView))
{
QAction* selectSurfaceCellsAction = frame->addTitleBarAction(
QIcon(":/pqWidgets/Icons/pqSurfaceSelectionCell.svg"), "Select Cells On (s)");
selectSurfaceCellsAction->setObjectName("actionSelectSurfaceCells");
selectSurfaceCellsAction->setCheckable(true);
new pqRenderViewSelectionReaction(selectSurfaceCellsAction, renderView,
pqRenderViewSelectionReaction::SELECT_SURFACE_CELLS, modeGroup);
this->connect(
selectSurfaceCellsAction, SIGNAL(toggled(bool)), SLOT(escapeableActionToggled(bool)));
}
if (this->isButtonVisible("SelectSurfacePoints", renderView))
{
QAction* selectSurfacePointsAction = frame->addTitleBarAction(
QIcon(":/pqWidgets/Icons/pqSurfaceSelectionPoint.svg"), "Select Points On (d)");
selectSurfacePointsAction->setObjectName("actionSelectSurfacePoints");
selectSurfacePointsAction->setCheckable(true);
new pqRenderViewSelectionReaction(selectSurfacePointsAction, renderView,
pqRenderViewSelectionReaction::SELECT_SURFACE_POINTS, modeGroup);
this->connect(
selectSurfacePointsAction, SIGNAL(toggled(bool)), SLOT(escapeableActionToggled(bool)));
}
if (this->isButtonVisible("SelectFrustumCells", renderView))
{
QAction* selectFrustumCellsAction = frame->addTitleBarAction(
QIcon(":/pqWidgets/Icons/pqFrustumSelectionCell.svg"), "Select Cells Through (f)");
selectFrustumCellsAction->setObjectName("actionSelectFrustumCells");
selectFrustumCellsAction->setCheckable(true);
new pqRenderViewSelectionReaction(selectFrustumCellsAction, renderView,
pqRenderViewSelectionReaction::SELECT_FRUSTUM_CELLS, modeGroup);
this->connect(
selectFrustumCellsAction, SIGNAL(toggled(bool)), SLOT(escapeableActionToggled(bool)));
}
if (this->isButtonVisible("SelectFrustumPoints", renderView))
{
QAction* selectFrustumPointsAction = frame->addTitleBarAction(
QIcon(":/pqWidgets/Icons/pqFrustumSelectionPoint.svg"), "Select Points Through (g)");
selectFrustumPointsAction->setObjectName("actionSelectFrustumPoints");
selectFrustumPointsAction->setCheckable(true);
new pqRenderViewSelectionReaction(selectFrustumPointsAction, renderView,
pqRenderViewSelectionReaction::SELECT_FRUSTUM_POINTS, modeGroup);
this->connect(
selectFrustumPointsAction, SIGNAL(toggled(bool)), SLOT(escapeableActionToggled(bool)));
}
if (this->isButtonVisible("SelectPolygonSelectionCells", renderView))
{
QAction* selectionPolygonCellsAction = frame->addTitleBarAction(
QIcon(":/pqWidgets/Icons/pqPolygonSelectSurfaceCell.svg"), "Select Cells With Polygon");
selectionPolygonCellsAction->setObjectName("actionPolygonSelectionCells");
selectionPolygonCellsAction->setCheckable(true);
new pqRenderViewSelectionReaction(selectionPolygonCellsAction, renderView,
pqRenderViewSelectionReaction::SELECT_SURFACE_CELLS_POLYGON, modeGroup);
this->connect(
selectionPolygonCellsAction, SIGNAL(toggled(bool)), SLOT(escapeableActionToggled(bool)));
}
if (this->isButtonVisible("SelectPolygonSelectionPoints", renderView))
{
QAction* selectionPolygonPointsAction = frame->addTitleBarAction(
QIcon(":/pqWidgets/Icons/pqPolygonSelectSurfacePoint.svg"), "Select Points With Polygon");
selectionPolygonPointsAction->setObjectName("actionPolygonSelectionPoints");
selectionPolygonPointsAction->setCheckable(true);
new pqRenderViewSelectionReaction(selectionPolygonPointsAction, renderView,
pqRenderViewSelectionReaction::SELECT_SURFACE_POINTS_POLYGON, modeGroup);
this->connect(
selectionPolygonPointsAction, SIGNAL(toggled(bool)), SLOT(escapeableActionToggled(bool)));
}
if (this->isButtonVisible("SelectBlock", renderView))
{
QAction* selectBlockAction =
frame->addTitleBarAction(QIcon(":/pqWidgets/Icons/pqSelectBlock.svg"), "Select Block (b)");
selectBlockAction->setObjectName("actionSelectBlock");
selectBlockAction->setCheckable(true);
new pqRenderViewSelectionReaction(
selectBlockAction, renderView, pqRenderViewSelectionReaction::SELECT_BLOCKS, modeGroup);
this->connect(selectBlockAction, SIGNAL(toggled(bool)), SLOT(escapeableActionToggled(bool)));
}
if (this->isButtonVisible("InteractiveSelectSurfaceCellData", renderView))
{
QAction* interactiveSelectSurfaceCellDataAction =
frame->addTitleBarAction(QIcon(":/pqWidgets/Icons/pqSurfaceSelectionCellDataInteractive.svg"),
"Interactive Select Cell Data On");
interactiveSelectSurfaceCellDataAction->setObjectName("actionInteractiveSelectSurfaceCellData");
interactiveSelectSurfaceCellDataAction->setCheckable(true);
new pqRenderViewSelectionReaction(interactiveSelectSurfaceCellDataAction, renderView,
pqRenderViewSelectionReaction::SELECT_SURFACE_CELLDATA_INTERACTIVELY, modeGroup);
this->connect(interactiveSelectSurfaceCellDataAction, SIGNAL(toggled(bool)),
SLOT(escapeableActionToggled(bool)));
this->connect(interactiveSelectSurfaceCellDataAction, SIGNAL(toggled(bool)),
SLOT(interactiveSelectionToggled(bool)));
}
if (this->isButtonVisible("InteractiveSelectSurfacePointData", renderView))
{
QAction* interactiveSelectSurfacePointDataAction = frame->addTitleBarAction(
QIcon(":/pqWidgets/Icons/pqSurfaceSelectionPointDataInteractive.svg"),
"Interactive Select Point Data On");
interactiveSelectSurfacePointDataAction->setObjectName(
"actionInteractiveSelectSurfacePointData");
interactiveSelectSurfacePointDataAction->setCheckable(true);
new pqRenderViewSelectionReaction(interactiveSelectSurfacePointDataAction, renderView,
pqRenderViewSelectionReaction::SELECT_SURFACE_POINTDATA_INTERACTIVELY, modeGroup);
this->connect(interactiveSelectSurfacePointDataAction, SIGNAL(toggled(bool)),
SLOT(escapeableActionToggled(bool)));
this->connect(interactiveSelectSurfacePointDataAction, SIGNAL(toggled(bool)),
SLOT(interactiveSelectionToggled(bool)));
}
if (this->isButtonVisible("InteractiveSelectSurfaceCells", renderView))
{
QAction* interactiveSelectSurfaceCellsAction =
frame->addTitleBarAction(QIcon(":/pqWidgets/Icons/pqSurfaceSelectionCellInteractive.svg"),
"Interactive Select Cells On");
interactiveSelectSurfaceCellsAction->setObjectName("actionInteractiveSelectSurfaceCells");
interactiveSelectSurfaceCellsAction->setCheckable(true);
new pqRenderViewSelectionReaction(interactiveSelectSurfaceCellsAction, renderView,
pqRenderViewSelectionReaction::SELECT_SURFACE_CELLS_INTERACTIVELY, modeGroup);
this->connect(interactiveSelectSurfaceCellsAction, SIGNAL(toggled(bool)),
SLOT(escapeableActionToggled(bool)));
this->connect(interactiveSelectSurfaceCellsAction, SIGNAL(toggled(bool)),
SLOT(interactiveSelectionToggled(bool)));
}
if (this->isButtonVisible("InteractiveSelectSurfacePoints", renderView))
{
QAction* interactiveSelectSurfacePointsAction =
frame->addTitleBarAction(QIcon(":/pqWidgets/Icons/pqSurfaceSelectionPointInteractive.svg"),
"Interactive Select Points On");
interactiveSelectSurfacePointsAction->setObjectName("actionInteractiveSelectSurfacePoints");
interactiveSelectSurfacePointsAction->setCheckable(true);
new pqRenderViewSelectionReaction(interactiveSelectSurfacePointsAction, renderView,
pqRenderViewSelectionReaction::SELECT_SURFACE_POINTS_INTERACTIVELY, modeGroup);
this->connect(interactiveSelectSurfacePointsAction, SIGNAL(toggled(bool)),
SLOT(escapeableActionToggled(bool)));
this->connect(interactiveSelectSurfacePointsAction, SIGNAL(toggled(bool)),
SLOT(interactiveSelectionToggled(bool)));
}
if (this->isButtonVisible("HoveringSurfaceCells", renderView))
{
QAction* hoveringSurfaceCellsAction = frame->addTitleBarAction(
QIcon(":/pqWidgets/Icons/pqSurfaceHoveringCell.svg"), "Hover Cells On");
hoveringSurfaceCellsAction->setObjectName("actionHoveringSurfaceCells");
hoveringSurfaceCellsAction->setCheckable(true);
new pqRenderViewSelectionReaction(hoveringSurfaceCellsAction, renderView,
pqRenderViewSelectionReaction::SELECT_SURFACE_CELLS_TOOLTIP);
this->connect(
hoveringSurfaceCellsAction, SIGNAL(toggled(bool)), SLOT(escapeableActionToggled(bool)));
this->connect(
hoveringSurfaceCellsAction, SIGNAL(toggled(bool)), SLOT(interactiveSelectionToggled(bool)));
}
if (this->isButtonVisible("HoveringSurfacePoints", renderView))
{
QAction* hoveringSurfacePointsAction = frame->addTitleBarAction(
QIcon(":/pqWidgets/Icons/pqSurfaceHoveringPoint.svg"), "Hover Points On");
hoveringSurfacePointsAction->setObjectName("actionHoveringSurfacePoints");
hoveringSurfacePointsAction->setCheckable(true);
new pqRenderViewSelectionReaction(hoveringSurfacePointsAction, renderView,
pqRenderViewSelectionReaction::SELECT_SURFACE_POINTS_TOOLTIP);
this->connect(
hoveringSurfacePointsAction, SIGNAL(toggled(bool)), SLOT(escapeableActionToggled(bool)));
this->connect(
hoveringSurfacePointsAction, SIGNAL(toggled(bool)), SLOT(interactiveSelectionToggled(bool)));
}
if (this->isButtonVisible("Grow Selection", renderView))
{
QAction* growAction =
frame->addTitleBarAction(QIcon(":/QtWidgets/Icons/pqPlus.svg"), "Grow selection");
growAction->setObjectName("actionGrowSelection");
new pqRenderViewSelectionReaction(
growAction, renderView, pqRenderViewSelectionReaction::GROW_SELECTION);
}
if (this->isButtonVisible("Shrink Selection", renderView))
{
auto shrinkAction =
frame->addTitleBarAction(QIcon(":/QtWidgets/Icons/pqMinus.svg"), "Shrink selection");
shrinkAction->setObjectName("actionShrinkSelection");
new pqRenderViewSelectionReaction(
shrinkAction, renderView, pqRenderViewSelectionReaction::SHRINK_SELECTION);
}
if (this->isButtonVisible("ClearSelection", renderView))
{
QStyle* style = qApp->style();
QAction* clearAction = frame->addTitleBarAction(
style->standardIcon(QStyle::SP_DialogDiscardButton), "Clear selection");
clearAction->setObjectName("actionClearSelection");
new pqRenderViewSelectionReaction(
clearAction, renderView, pqRenderViewSelectionReaction::CLEAR_SELECTION);
}
}
//-----------------------------------------------------------------------------
void pqStandardViewFrameActionsImplementation::addSpreadSheetViewActions(
pqViewFrame* frame, pqSpreadSheetView* spreadSheet)
{
assert(frame);
assert(spreadSheet);
Q_UNUSED(frame);
new pqSpreadSheetViewDecorator(spreadSheet);
}
//-----------------------------------------------------------------------------
bool pqStandardViewFrameActionsImplementation::isButtonVisible(
const std::string& buttonName, pqView* view)
{
vtkPVXMLElement* hints = view->getHints();
if (!hints)
{
// Default to true
return true;
}
bool isVisible = true;
vtkPVXMLElement* svfa = hints->FindNestedElementByName("StandardViewFrameActions");
if (svfa)
{
// See if we should disable all view frame actions
std::string defaultActions(svfa->GetAttributeOrEmpty("default_actions"));
vtkPVXMLElement* buttonElement = svfa->FindNestedElementByName(buttonName.c_str());
std::string visibility;
if (buttonElement)
{
visibility = std::string(buttonElement->GetAttributeOrEmpty("visibility"));
}
isVisible = visibility != "never";
if (defaultActions == "none")
{
// Turn all actions off *unless* the button has been
// explicitly enabled by listing them as child elements
isVisible = isVisible && buttonElement != nullptr;
}
}
return isVisible;
}
//-----------------------------------------------------------------------------
// Comparator for strings with a twist. It tries to put strings with "Render
// View" at the top of the sorted list.
bool pqStandardViewFrameActionsImplementation::ViewTypeComparator(
const pqStandardViewFrameActionsImplementation::ViewType& one,
const pqStandardViewFrameActionsImplementation::ViewType& two)
{
bool inone = one.Label.contains("Render View", Qt::CaseInsensitive);
bool intwo = two.Label.contains("Render View", Qt::CaseInsensitive);
if ((inone && intwo) || (!inone && !intwo))
{
return one.Label.toLower() < two.Label.toLower();
}
assert(inone || intwo);
// one is less if it has "Render View", else two is less.
return inone;
}
//-----------------------------------------------------------------------------
QList<pqStandardViewFrameActionsImplementation::ViewType>
pqStandardViewFrameActionsImplementation::availableViewTypes()
{
// Iterate over all available "views".
QList<ViewType> views;
pqServer* server = pqActiveObjects::instance().activeServer();
if (!server)
{
return views;
}
vtkSMSessionProxyManager* pxm = server->proxyManager();
vtkSmartPointer<vtkPVProxyDefinitionIterator> iter;
iter.TakeReference(pxm->GetProxyDefinitionManager()->NewSingleGroupIterator("views"));
for (iter->InitTraversal(); !iter->IsDoneWithTraversal(); iter->GoToNextItem())
{
vtkSMProxy* prototype = pxm->GetPrototypeProxy("views", iter->GetProxyName());
if (prototype)
{
ViewType info;
info.Label = prototype->GetXMLLabel();
info.Name = iter->GetProxyName();
views.push_back(info);
}
}
std::sort(
views.begin(), views.end(), pqStandardViewFrameActionsImplementation::ViewTypeComparator);
return views;
}
//-----------------------------------------------------------------------------
void pqStandardViewFrameActionsImplementation::aboutToShowConvertMenu()
{
QMenu* menu = qobject_cast<QMenu*>(this->sender());
if (menu)
{
menu->clear();
auto viewframe = ::findParent<pqViewFrame*>(menu);
assert(viewframe != nullptr);
QList<ViewType> views = this->availableViewTypes();
foreach (const ViewType& type, views)
{
QAction* view_action = new QAction(type.Label, menu);
menu->addAction(view_action);
QObject::connect(view_action, &QAction::triggered, this,
[viewframe, type, this](bool) { this->invoked(viewframe, type, "Convert To"); },
Qt::QueuedConnection);
}
}
}
//-----------------------------------------------------------------------------
void pqStandardViewFrameActionsImplementation::setupEmptyFrame(QWidget* frame)
{
Ui::EmptyView ui;
ui.setupUi(frame);
auto viewframe = ::findParent<pqViewFrame*>(frame);
assert(viewframe != nullptr);
QList<ViewType> views = this->availableViewTypes();
foreach (const ViewType& type, views)
{
QPushButton* button = new QPushButton(type.Label, ui.ConvertActionsFrame);
button->setObjectName(type.Name);
QObject::connect(button, &QPushButton::clicked, this,
[viewframe, type, this]() { this->invoked(viewframe, type, "Create"); },
Qt::QueuedConnection);
ui.ConvertActionsFrame->layout()->addWidget(button);
}
}
//-----------------------------------------------------------------------------
void pqStandardViewFrameActionsImplementation::invoked(pqViewFrame* viewframe,
const pqStandardViewFrameActionsImplementation::ViewType& vtype, const QString& command)
{
if (!viewframe)
{
return;
}
// this implementation is a little hackish.
// pqStandardViewFrameActionsImplementation is ripe for refactoring.
auto pqmvwidget = ::findParent<pqMultiViewWidget*>(viewframe);
assert(pqmvwidget != nullptr);
int frameIndex = viewframe->property("FRAME_INDEX").toInt();
viewframe = nullptr;
// either create a new view, or convert the existing one.
BEGIN_UNDO_SET(QString("%1 %2").arg(command).arg(vtype.Label));
if (auto view = this->handleCreateView(vtype))
{
// note: handleCreateView may destroy the pqViewFrame.
// assign it to layout.
pqmvwidget->layoutManager()->AssignViewToAnyCell(view->getViewProxy(), frameIndex);
}
END_UNDO_SET();
}
//-----------------------------------------------------------------------------
pqView* pqStandardViewFrameActionsImplementation::handleCreateView(
const pqStandardViewFrameActionsImplementation::ViewType& viewType)
{
pqObjectBuilder* builder = pqApplicationCore::instance()->getObjectBuilder();
// destroy active-view, if present (implying convert was called).
if (pqActiveObjects::instance().activeView())
{
builder->destroy(pqActiveObjects::instance().activeView());
}
if (viewType.Name != "None")
{
return builder->createView(viewType.Name, pqActiveObjects::instance().activeServer());
}
return nullptr;
}
//-----------------------------------------------------------------------------
void pqStandardViewFrameActionsImplementation::selectSurfaceCellsTriggered()
{
pqView* activeView = pqActiveObjects::instance().activeView();
pqContextView* chartView = qobject_cast<pqContextView*>(activeView);
if (chartView)
{
// if we are in a chart view then trigger the chart selection
triggerAction("actionChartSelectRectangle");
}
else
{
// else trigger the render view selection
triggerAction("actionSelectSurfaceCells");
}
}
//-----------------------------------------------------------------------------
void pqStandardViewFrameActionsImplementation::selectSurfacePointsTriggered()
{
pqView* activeView = pqActiveObjects::instance().activeView();
pqContextView* chartView = qobject_cast<pqContextView*>(activeView);
if (chartView)
{
// if we are in a chart view then trigger the chart selection
triggerAction("actionChartSelectPolygon");
}
else
{
// else trigger the render view selection
triggerAction("actionSelectSurfacePoints");
}
}
//-----------------------------------------------------------------------------
void pqStandardViewFrameActionsImplementation::selectFrustumCellsTriggered()
{
triggerAction("actionSelectFrustumCells");
}
//-----------------------------------------------------------------------------
void pqStandardViewFrameActionsImplementation::selectFrustumPointsTriggered()
{
triggerAction("actionSelectFrustumPoints");
}
//-----------------------------------------------------------------------------
void pqStandardViewFrameActionsImplementation::selectBlocksTriggered()
{
triggerAction("actionSelectBlock");
}
//-----------------------------------------------------------------------------
void pqStandardViewFrameActionsImplementation::escTriggered()
{
QAction* actn =
qobject_cast<QAction*>(this->ShortCutEsc->property("PV_ACTION").value<QObject*>());
if (actn && actn->isChecked() && actn->isEnabled())
{
actn->trigger();
}
// this is not necessary for the most part, but just to be on the safe side.
this->ShortCutEsc->setEnabled(false);
}
//-----------------------------------------------------------------------------
void pqStandardViewFrameActionsImplementation::manageGroupExclusivity(QAction* curAction)
{
if (!curAction || !curAction->isChecked())
{
return;
}
QActionGroup* group = qobject_cast<QActionGroup*>(this->sender());
foreach (QAction* groupAction, group->actions())
{
if (groupAction != curAction && groupAction->isChecked())
{
groupAction->setChecked(false);
}
}
}
//-----------------------------------------------------------------------------
void pqStandardViewFrameActionsImplementation::escapeableActionToggled(bool checked)
{
// If a "selection mode" begins, we will enable the ShortCutEsc to start monitoring
// the Esc key to end selection.
// If "selection mode" ends (due to one reason or another) and the selection that
// ended was indeed the one which we're monitoring the Esc key for, then we
// disable the Esc shortcut since it is no longer needed. This disabling
// ensure that the shortcut doesn't eat away Esc keys which interferes with
// the Esc key in the Search box, for example.
QAction* actn = qobject_cast<QAction*>(this->sender());
if (!actn || !actn->isEnabled() || !actn->isCheckable())
{
return;
}
if (!checked)
{
if (this->ShortCutEsc->property("PV_ACTION").value<QObject*>() == actn)
{
this->ShortCutEsc->setEnabled(false);
}
return;
}
// User has entered into a selection mode. Let's add a shortcut to "catch" the
// Esc key.
assert(checked && actn->isCheckable());
this->ShortCutEsc->setEnabled(true);
this->ShortCutEsc->setProperty("PV_ACTION", QVariant::fromValue<QObject*>(actn));
}
//-----------------------------------------------------------------------------
void pqStandardViewFrameActionsImplementation::interactiveSelectionToggled(bool checked)
{
if (!checked)
{
vtkSMInteractiveSelectionPipeline::GetInstance()->Hide(
vtkSMRenderViewProxy::SafeDownCast(pqActiveObjects::instance().activeView()->getViewProxy()));
vtkSMTooltipSelectionPipeline::GetInstance()->Hide(
vtkSMRenderViewProxy::SafeDownCast(pqActiveObjects::instance().activeView()->getViewProxy()));
}
}
//-----------------------------------------------------------------------------
void pqStandardViewFrameActionsImplementation::captureViewTriggered()
{
pqView* activeView = pqActiveObjects::instance().activeView();
if (activeView)
{
// If a modifier key is enabled, let's save screenshot to a file, otherwise
// copy the screenshot to the clipboard.
bool clipboardMode = QGuiApplication::queryKeyboardModifiers() != Qt::NoModifier;
bool captured = pqSaveScreenshotReaction::saveScreenshot(clipboardMode);
if (clipboardMode && captured)
{
auto viewWidget = pqActiveObjects::instance().activeView()->widget();
auto overlay = new pqColorOverlay(viewWidget);
overlay->resize(viewWidget->size());
// Light blue
overlay->setRgb(171, 223, 255);
overlay->show();
// Makes the overlay appear then disappear quickly to indicate a screenshot was taken
auto animation = new QPropertyAnimation(overlay, "opacity");
animation->setEasingCurve(QEasingCurve::OutQuad);
animation->setDuration(250);
animation->setKeyValueAt(0, 0);
animation->setKeyValueAt(0.1, 192);
animation->setKeyValueAt(1, 0);
animation->start();
this->connect(animation, &QPropertyAnimation::finished, [=] { overlay->deleteLater(); });
}
}
}
|
// Copyright (c) 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 <assert.h>
#include <stdlib.h>
#include <string.h>
#include "ppapi_main/ppapi_queue.h"
PPAPIQueue::PPAPIQueue()
: read_(0),
write_(0),
freed_(0),
size_(0),
array_(NULL) { }
PPAPIQueue::~PPAPIQueue() {
// Messages may be leaked if the queue is not empty.
assert(read_ == write_);
delete[] array_;
}
bool PPAPIQueue::SetSize(uint32_t queue_size) {
assert(queue_size > 0);
if (array_) return false;
array_ = new void*[queue_size];
size_ = queue_size;
memset(array_, 0, sizeof(void*) * queue_size);
return true;
}
bool PPAPIQueue::AddNewMessage(void* msg) {
// Writting a NULL message is illegal
assert(array_ != NULL);
assert(msg != NULL);
// If the slot not empty, the queue must be full. Calling RemoveStaleMessage
// may create space by freeing messages that have already been read.
if (array_[write_] != NULL) return false;
// Write to the spot
array_[write_] = msg;
// Fence to make sure the payload and payload pointer are visible.
// Since Win32 is x86 which provides ordered writes, we don't need to
// synchronize in that case.
#ifndef WIN32
__sync_synchronize();
#endif
// Increment the write pointer, to signal it's readable.
write_ = (write_ + 1) % size_;
return true;
}
void* PPAPIQueue::RemoveStaleMessage() {
assert(array_ != NULL);
// If freed and read pointer are equal, this hasn't been read yet
if (freed_ == read_) return NULL;
assert(array_[freed_] != NULL);
void* ret = array_[freed_];
array_[freed_] = NULL;
freed_ = (freed_ + 1) % size_;
return ret;
}
void* PPAPIQueue::AcquireTopMessage() {
// Assert that we aren't already reading a message.
assert(last_msg_ == NULL);
// If read and write pointers are equal, the queue is empty.
if (read_ == write_) return NULL;
// Track the last message to look for illegal API use.
last_msg_ = array_[read_];
return last_msg_;
}
void PPAPIQueue::ReleaseTopMessage(void* msg) {
// Verify we currently acquire message.
assert(msg != NULL);
assert(msg == last_msg_);
last_msg_ = NULL;
// Signal that the message can be freed.
read_ = (read_ + 1) % size_;
}
|
// 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 "exec/select-node.h"
#include "codegen/llvm-codegen.h"
#include "exec/exec-node-util.h"
#include "exprs/scalar-expr-evaluator.h"
#include "exprs/scalar-expr.h"
#include "gen-cpp/PlanNodes_types.h"
#include "runtime/fragment-state.h"
#include "runtime/raw-value.h"
#include "runtime/row-batch.h"
#include "runtime/runtime-state.h"
#include "util/runtime-profile-counters.h"
#include "common/names.h"
namespace impala {
Status SelectPlanNode::CreateExecNode(RuntimeState* state, ExecNode** node) const {
ObjectPool* pool = state->obj_pool();
*node = pool->Add(new SelectNode(pool, *this, state->desc_tbl()));
return Status::OK();
}
SelectNode::SelectNode(
ObjectPool* pool, const SelectPlanNode& pnode, const DescriptorTbl& descs)
: ExecNode(pool, pnode, descs),
child_row_batch_(NULL),
child_row_idx_(0),
child_eos_(false),
codegend_copy_rows_fn_(pnode.codegend_copy_rows_fn_) {}
Status SelectNode::Prepare(RuntimeState* state) {
SCOPED_TIMER(runtime_profile_->total_time_counter());
RETURN_IF_ERROR(ExecNode::Prepare(state));
return Status::OK();
}
void SelectPlanNode::Codegen(FragmentState* state) {
DCHECK(state->ShouldCodegen());
PlanNode::Codegen(state);
if (IsNodeCodegenDisabled()) return;
AddCodegenStatus(CodegenCopyRows(state));
}
Status SelectPlanNode::CodegenCopyRows(FragmentState* state) {
LlvmCodeGen* codegen = state->codegen();
DCHECK(codegen != nullptr);
llvm::Function* copy_rows_fn =
codegen->GetFunction(IRFunction::SELECT_NODE_COPY_ROWS, true);
DCHECK(copy_rows_fn != nullptr);
llvm::Function* eval_conjuncts_fn;
RETURN_IF_ERROR(
ExecNode::CodegenEvalConjuncts(codegen, conjuncts_, &eval_conjuncts_fn));
int replaced = codegen->ReplaceCallSites(copy_rows_fn, eval_conjuncts_fn,
"EvalConjuncts");
DCHECK_REPLACE_COUNT(replaced, 1);
copy_rows_fn = codegen->FinalizeFunction(copy_rows_fn);
if (copy_rows_fn == nullptr) return Status("Failed to finalize CopyRows().");
codegen->AddFunctionToJit(copy_rows_fn, &codegend_copy_rows_fn_);
return Status::OK();
}
Status SelectNode::Open(RuntimeState* state) {
SCOPED_TIMER(runtime_profile_->total_time_counter());
ScopedOpenEventAdder ea(this);
RETURN_IF_ERROR(ExecNode::Open(state));
RETURN_IF_ERROR(child(0)->Open(state));
child_row_batch_.reset(
new RowBatch(child(0)->row_desc(), state->batch_size(), mem_tracker()));
return Status::OK();
}
Status SelectNode::GetNext(RuntimeState* state, RowBatch* row_batch, bool* eos) {
SCOPED_TIMER(runtime_profile_->total_time_counter());
ScopedGetNextEventAdder ea(this, eos);
RETURN_IF_ERROR(ExecDebugAction(TExecNodePhase::GETNEXT, state));
// start (or continue) consuming row batches from child
do {
RETURN_IF_CANCELLED(state);
RETURN_IF_ERROR(QueryMaintenance(state));
if (child_row_batch_->num_rows() == 0) {
// Fetch rows from child if either child row batch has been
// consumed completely or it is empty.
RETURN_IF_ERROR(child(0)->GetNext(state, child_row_batch_.get(), &child_eos_));
}
SelectPlanNode::CopyRowsFn copy_rows_fn = codegend_copy_rows_fn_.load();
if (copy_rows_fn != nullptr) {
copy_rows_fn(this, row_batch);
} else {
CopyRows(row_batch);
}
COUNTER_SET(rows_returned_counter_, rows_returned());
*eos = ReachedLimit()
|| (child_row_idx_ == child_row_batch_->num_rows() && child_eos_);
if (*eos || child_row_idx_ == child_row_batch_->num_rows()) {
child_row_idx_ = 0;
child_row_batch_->TransferResourceOwnership(row_batch);
child_row_batch_->Reset();
}
} while (!*eos && !row_batch->AtCapacity());
return Status::OK();
}
Status SelectNode::Reset(RuntimeState* state, RowBatch* row_batch) {
child_row_batch_->TransferResourceOwnership(row_batch);
child_row_idx_ = 0;
child_eos_ = false;
return ExecNode::Reset(state, row_batch);
}
void SelectNode::Close(RuntimeState* state) {
if (is_closed()) return;
child_row_batch_.reset();
ExecNode::Close(state);
}
}
|
#include "../include/ConcurrentPipeline.hpp"
#include <unistd.h>
ConcurrentPipeline::ConcurrentPipeline(ISource &source, InPlaceProcessor &ipp, ReturningProcessor &rp, ITarget &target) :
ConcurrentSink(source, ipp, rp, target)
{
pthread_mutex_init(&Mutex2, NULL);
pthread_cond_init(&Cond2, NULL);
}
ConcurrentPipeline::~ConcurrentPipeline() {}
void ConcurrentPipeline::Start()
{
FrameReadyForOOPP = false;
FrameReadyForTarget = false;
Running = true;
pthread_t downloader, uploader;
pthread_create(&downloader, NULL, Download, this);
pthread_create(&uploader, NULL, Upload, this);
Process();
pthread_join(downloader, NULL);
pthread_join(uploader, NULL);
}
#undef DEBUG
#ifdef DEBUG
#include <stdio.h>
#define operationInfo(number, letter) (printf("%i - %c\n", number, letter))
#define threadEndInfo(name) (printf("%s thread ended\n", name))
#else
#define operationInfo(number, letter) // no-operation
#define threadEndInfo(name) // no-operation
#endif
void ConcurrentPipeline::Process()
{
ReturningProcessor &RP = static_cast<ReturningProcessor&>(OOPP);
while (Running == true)
{
pthread_mutex_lock(&Mutex1);
if (FrameReadyForOOPP == false)
pthread_cond_wait(&Cond1, &Mutex1);
operationInfo(2, 's');
RP.UploadFrame();
operationInfo(2, 'e');
FrameReadyForOOPP = false;
pthread_cond_signal(&Cond1); // jak wyżej
pthread_mutex_unlock(&Mutex1);
operationInfo(3, 's');
RP.ProcessFrame();
operationInfo(3, 'e');
pthread_mutex_lock(&Mutex2);
FrameReadyForTarget = false;
operationInfo(4, 's');
RP.DownloadFrame();
operationInfo(4, 'e');
FrameReadyForTarget = true;
pthread_cond_signal(&Cond2);
pthread_mutex_unlock(&Mutex2);
}
threadEndInfo("Process");
// ustawiamy flagę i sygnalizujemy zmienną warunkową, aby wątek Download się nie zablokował
FrameReadyForOOPP = false;
pthread_cond_signal(&Cond1);
// ustawiamy flagę i sygnalizujemy zmienną warunkową, aby wątek Upload się nie zablokował
FrameReadyForTarget = true;
pthread_cond_signal(&Cond2);
}
void* ConcurrentPipeline::Upload(void* caller)
{
ConcurrentPipeline &mp = *((ConcurrentPipeline*)caller);
while (mp.Running == true)
{
pthread_mutex_lock(&mp.Mutex2);
if (mp.FrameReadyForTarget == false)
pthread_cond_wait(&mp.Cond2, &mp.Mutex2);
operationInfo(5, 's');
mp.Target.UploadFrame();
operationInfo(5, 'e');
mp.FrameReadyForTarget = false;
pthread_mutex_unlock(&mp.Mutex2);
}
threadEndInfo("Upload");
return NULL;
}
|
/**
Copyright (c) 2015-present, Facebook, Inc.
All rights reserved.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree. An additional grant
of patent rights can be found in the PATENTS file in the same directory.
*/
#include <xcdriver/ShowBuildSettingsAction.h>
#include <xcdriver/Options.h>
#include <xcdriver/Action.h>
#include <libutil/Filesystem.h>
#include <process/Context.h>
#include <process/User.h>
using xcdriver::ShowBuildSettingsAction;
using xcdriver::Options;
using libutil::Filesystem;
ShowBuildSettingsAction::
ShowBuildSettingsAction()
{
}
ShowBuildSettingsAction::
~ShowBuildSettingsAction()
{
}
int ShowBuildSettingsAction::
Run(process::User const *user, process::Context const *processContext, Filesystem const *filesystem, Options const &options)
{
if (!Action::VerifyBuildActions(options.actions())) {
return -1;
}
ext::optional<pbxbuild::Build::Environment> buildEnvironment = pbxbuild::Build::Environment::Default(user, processContext, filesystem);
if (!buildEnvironment) {
fprintf(stderr, "error: couldn't create build environment\n");
return -1;
}
std::vector<pbxsetting::Level> overrideLevels = Action::CreateOverrideLevels(processContext, filesystem, buildEnvironment->baseEnvironment(), options, processContext->currentDirectory());
xcexecution::Parameters parameters = Action::CreateParameters(options, overrideLevels);
ext::optional<pbxbuild::WorkspaceContext> workspaceContext = parameters.loadWorkspace(filesystem, user->userName(), *buildEnvironment, processContext->currentDirectory());
if (!workspaceContext) {
return -1;
}
ext::optional<pbxbuild::Build::Context> buildContext = parameters.createBuildContext(*workspaceContext);
if (!buildContext) {
return -1;
}
ext::optional<pbxbuild::DirectedGraph<pbxproj::PBX::Target::shared_ptr>> graph = parameters.resolveDependencies(*buildEnvironment, *buildContext);
if (!graph) {
return -1;
}
ext::optional<std::vector<pbxproj::PBX::Target::shared_ptr>> targets = graph->ordered();
if (!targets) {
fprintf(stderr, "error: cycle detected in target dependencies\n");
return -1;
}
for (pbxproj::PBX::Target::shared_ptr const &target : *targets) {
ext::optional<pbxbuild::Target::Environment> targetEnvironment = buildContext->targetEnvironment(*buildEnvironment, target);
if (!targetEnvironment) {
fprintf(stderr, "error: couldn't create target environment\n");
continue;
}
pbxsetting::Environment const &environment = targetEnvironment->environment();
std::unordered_map<std::string, std::string> values = environment.computeValues(pbxsetting::Condition::Empty());
std::map<std::string, std::string> orderedValues = std::map<std::string, std::string>(values.begin(), values.end());
printf("Build settings for action %s and target %s:\n", buildContext->action().c_str(), target->name().c_str());
for (auto const &value : orderedValues) {
printf(" %s = %s\n", value.first.c_str(), value.second.c_str());
}
printf("\n");
}
return 0;
}
|
#include "hrpcheaders.h"
#include "ImGuiConsole.h"
#include "imgui.h"
#include "examples/imgui_impl_glfw.h"
#include "examples/imgui_impl_opengl3.h"
namespace Hildur {
uint16_t ImGuiConsole::s_MessageBufferCapacity = 200;
uint16_t ImGuiConsole::s_MessageBufferSize = 0;
uint16_t ImGuiConsole::s_MessageBufferBegin = 0;
ImGuiConsole::Message::Level ImGuiConsole::s_MessageBufferRenderFilter = ImGuiConsole::Message::Level::Trace;
std::vector<std::shared_ptr<ImGuiConsole::Message>> ImGuiConsole::s_MessageBuffer(s_MessageBufferCapacity);
bool ImGuiConsole::s_AllowScrollingToBottom = true;
bool ImGuiConsole::s_RequestScrollToBottom = false;
std::shared_ptr<ImGuiConsole> ImGuiConsole::GetConsole()
{
return std::dynamic_pointer_cast<ImGuiConsole>(Log::GetSinks()[1]);
}
void ImGuiConsole::AddMessage(std::shared_ptr<Message> message)
{
if (message->m_Level == Message::Level::Invalid)
return;
*(s_MessageBuffer.begin() + s_MessageBufferBegin) = message;
if (++s_MessageBufferBegin == s_MessageBufferCapacity)
s_MessageBufferBegin = 0;
if (s_MessageBufferSize < s_MessageBufferCapacity)
s_MessageBufferSize++;
if (s_AllowScrollingToBottom)
s_RequestScrollToBottom = true;
}
void ImGuiConsole::OnImGuiRender(bool* show)
{
ImGui::SetNextWindowSize(ImVec2(640, 480), ImGuiCond_FirstUseEver);
ImGui::Begin("Console", show);
{
ImGuiRendering::ImGuiRenderHeader();
ImGui::Separator();
ImGuiRendering::ImGuiRenderMessages();
}
ImGui::End();
}
void ImGuiConsole::ImGuiRendering::ImGuiRenderHeader()
{
ImGuiStyle& style = ImGui::GetStyle();
float spacing = style.ItemInnerSpacing.x;
float button_sz = ImGui::GetFrameHeight();
float width = ImGui::CalcItemWidth() / 2.0f;
// Dropdown with levels
ImGui::PushItemWidth(width - spacing * 2.0f - button_sz * 2.0f);
if (ImGui::BeginCombo(
"##MessageBufferRenderFilter",
Message::GetLevelName(s_MessageBufferRenderFilter),
ImGuiComboFlags_NoArrowButton))
{
for (auto level = Message::s_Levels.begin(); level != Message::s_Levels.end(); level++)
{
bool is_selected = (s_MessageBufferRenderFilter == *level);
if (ImGui::Selectable(Message::GetLevelName(*level), is_selected))
s_MessageBufferRenderFilter = *level;
if (is_selected)
ImGui::SetItemDefaultFocus();
}
ImGui::EndCombo();
}
ImGui::PopItemWidth();
// Buttons to quickly change level
ImGui::SameLine(0.0f, spacing);
if (ImGui::ArrowButton("##MessageBufferRenderFilter_L", ImGuiDir_Left))
{
s_MessageBufferRenderFilter = Message::GetLowerLevel(s_MessageBufferRenderFilter);
}
ImGui::SameLine(0.0f, spacing);
if (ImGui::ArrowButton("##MessageBufferRenderFilter_R", ImGuiDir_Right))
{
s_MessageBufferRenderFilter = Message::GetHigherLevel(s_MessageBufferRenderFilter);
}
// Text change level
ImGui::SameLine(0.0f, spacing);
ImGui::Text("Display level");
// Checkbox for scrolling lock
ImGui::SameLine(0.0f, 5.0f * spacing);
ImGui::Checkbox("Scroll to bottom", &s_AllowScrollingToBottom);
}
void ImGuiConsole::ImGuiRendering::ImGuiRenderMessages()
{
ImGui::BeginChild("ScrollRegion", ImVec2(0, 0), false, ImGuiWindowFlags_HorizontalScrollbar);
{
auto messageStart = s_MessageBuffer.begin() + s_MessageBufferBegin;
if (*messageStart) // If contains old message here
for (auto message = messageStart; message != s_MessageBuffer.end(); message++)
(*message)->OnImGuiRender();
if (s_MessageBufferBegin != 0) // Skipped first messages in vector
for (auto message = s_MessageBuffer.begin(); message != messageStart; message++)
(*message)->OnImGuiRender();
if (s_RequestScrollToBottom && ImGui::GetScrollMaxY() > 0)
{
ImGui::SetScrollY(ImGui::GetScrollMaxY());
s_RequestScrollToBottom = false;
}
}
ImGui::EndChild();
}
std::vector<ImGuiConsole::Message::Level> ImGuiConsole::Message::s_Levels{
ImGuiConsole::Message::Level::Trace,
//ImGuiConsole::Message::Level::Debug,
ImGuiConsole::Message::Level::Info,
ImGuiConsole::Message::Level::Warn,
ImGuiConsole::Message::Level::Error,
ImGuiConsole::Message::Level::Critical,
ImGuiConsole::Message::Level::Off
};
ImGuiConsole::Message::Message(const std::string message, Level level)
: m_Message(message), m_Level(level)
{
}
void ImGuiConsole::Message::OnImGuiRender()
{
if (m_Level != Level::Invalid && m_Level >= ImGuiConsole::s_MessageBufferRenderFilter)
{
Color color = GetRenderColor(m_Level);
ImGui::PushStyleColor(ImGuiCol_Text, { color.r, color.g, color.b, color.a });
ImGui::TextUnformatted(m_Message.c_str());
ImGui::PopStyleColor();
}
}
ImGuiConsole::Message::Level ImGuiConsole::Message::GetLowerLevel(Level level)
{
switch (level)
{
case ImGuiConsole::Message::Level::Off: return ImGuiConsole::Message::Level::Critical;
case ImGuiConsole::Message::Level::Critical: return ImGuiConsole::Message::Level::Error;
case ImGuiConsole::Message::Level::Error: return ImGuiConsole::Message::Level::Warn;
case ImGuiConsole::Message::Level::Warn: //return ImGuiConsole::Message::Level::Debug;
case ImGuiConsole::Message::Level::Debug: return ImGuiConsole::Message::Level::Info;
case ImGuiConsole::Message::Level::Info:
case ImGuiConsole::Message::Level::Trace: return ImGuiConsole::Message::Level::Trace;
}
return ImGuiConsole::Message::Level::Invalid;
}
ImGuiConsole::Message::Level ImGuiConsole::Message::GetHigherLevel(Level level)
{
switch (level)
{
case ImGuiConsole::Message::Level::Trace: return ImGuiConsole::Message::Level::Info;
case ImGuiConsole::Message::Level::Info: //return ImGuiConsole::Message::Level::Debug;
case ImGuiConsole::Message::Level::Debug: return ImGuiConsole::Message::Level::Warn;
case ImGuiConsole::Message::Level::Warn: return ImGuiConsole::Message::Level::Error;
case ImGuiConsole::Message::Level::Error: return ImGuiConsole::Message::Level::Critical;
case ImGuiConsole::Message::Level::Critical:
case ImGuiConsole::Message::Level::Off: return ImGuiConsole::Message::Level::Off;
}
return ImGuiConsole::Message::Level::Invalid;
}
const char* ImGuiConsole::Message::GetLevelName(Level level)
{
switch (level)
{
case ImGuiConsole::Message::Level::Trace: return "Trace";
case ImGuiConsole::Message::Level::Info: return "Info";
case ImGuiConsole::Message::Level::Debug: return "Debug";
case ImGuiConsole::Message::Level::Warn: return "Warning";
case ImGuiConsole::Message::Level::Error: return "Error";
case ImGuiConsole::Message::Level::Critical: return "Critical";
case ImGuiConsole::Message::Level::Off: return "None";
}
return "Unknown name";
}
ImGuiConsole::Message::Color ImGuiConsole::Message::GetRenderColor(Level level)
{
switch (level)
{
case ImGuiConsole::Message::Level::Trace: return { 0.75f, 0.75f, 0.75f, 1.00f }; // White-ish gray
case ImGuiConsole::Message::Level::Info: return { 0.00f, 0.50f, 0.00f, 1.00f }; // Green
case ImGuiConsole::Message::Level::Debug: return { 0.00f, 0.50f, 0.50f, 1.00f }; // Cyan
case ImGuiConsole::Message::Level::Warn: return { 1.00f, 1.00f, 0.00f, 1.00f }; // Yellow
case ImGuiConsole::Message::Level::Error: return { 1.00f, 0.00f, 0.00f, 1.00f }; // Red
case ImGuiConsole::Message::Level::Critical: return { 1.0f, 0.0f, 1.0f, 1.0f }; // White-white
}
return { 1.00f, 1.00f, 1.00f, 1.00f };
}
}
|
// Copyright (c) 2016 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.
// Decodes the packet HandshakeFailureReason from the chromium histogram
// Net.QuicClientHelloRejectReasons
#include <iostream>
#include "quic/core/crypto/crypto_handshake.h"
#include "quic/core/crypto/crypto_utils.h"
#include "quic/platform/api/quic_flags.h"
#include "common/platform/api/quiche_text_utils.h"
using quic::CryptoUtils;
using quic::HandshakeFailureReason;
using quic::MAX_FAILURE_REASON;
int main(int argc, char* argv[]) {
const char* usage = "Usage: quic_reject_reason_decoder <packed_reason>";
std::vector<std::string> args =
quic::QuicParseCommandLineFlags(usage, argc, argv);
if (args.size() != 1) {
std::cerr << usage << std::endl;
return 1;
}
uint32_t packed_error = 0;
if (!quiche::QuicheTextUtils::StringToUint32(args[0], &packed_error)) {
std::cerr << "Unable to parse: " << args[0] << "\n";
return 2;
}
for (int i = 1; i < MAX_FAILURE_REASON; ++i) {
if ((packed_error & (1 << (i - 1))) == 0) {
continue;
}
HandshakeFailureReason reason = static_cast<HandshakeFailureReason>(i);
std::cout << CryptoUtils::HandshakeFailureReasonToString(reason) << "\n";
}
return 0;
}
|
/*
---------------------------------------------------------------------------
Open Asset Import Library (assimp)
---------------------------------------------------------------------------
Copyright (c) 2006-2020, assimp team
All rights reserved.
Redistribution and use of this software 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 the assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
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.
---------------------------------------------------------------------------
*/
#include "assimp_view.h"
namespace AssimpView {
CLogDisplay CLogDisplay::s_cInstance;
//-------------------------------------------------------------------------------
void CLogDisplay::AddEntry(const std::string& szText, const D3DCOLOR clrColor) {
SEntry sNew;
sNew.clrColor = clrColor;
sNew.szText = szText;
sNew.dwStartTicks = (DWORD)GetTickCount();
this->asEntries.push_back(sNew);
}
//-------------------------------------------------------------------------------
void CLogDisplay::ReleaseNativeResource() {
if (this->piFont) {
this->piFont->Release();
this->piFont = nullptr;
}
}
//-------------------------------------------------------------------------------
void CLogDisplay::RecreateNativeResource() {
if (!this->piFont) {
if (FAILED(D3DXCreateFont(g_piDevice,
16, //Font height
0, //Font width
FW_BOLD, //Font Weight
1, //MipLevels
false, //Italic
DEFAULT_CHARSET, //CharSet
OUT_DEFAULT_PRECIS, //OutputPrecision
//CLEARTYPE_QUALITY, //Quality
5, //Quality
DEFAULT_PITCH|FF_DONTCARE, //PitchAndFamily
"Verdana", //pFacename,
&this->piFont))) {
CLogDisplay::Instance().AddEntry("Unable to load font",D3DCOLOR_ARGB(0xFF,0xFF,0,0));
this->piFont = nullptr;
return;
}
}
}
//-------------------------------------------------------------------------------
void CLogDisplay::OnRender() {
DWORD dwTick = (DWORD) GetTickCount();
DWORD dwLimit = dwTick - 8000;
DWORD dwLimit2 = dwLimit + 3000;
unsigned int iCnt = 0;
RECT sRect;
sRect.left = 10;
sRect.top = 10;
RECT sWndRect;
GetWindowRect(GetDlgItem(g_hDlg,IDC_RT),&sWndRect);
sWndRect.right -= sWndRect.left;
sWndRect.bottom -= sWndRect.top;
sWndRect.left = sWndRect.top = 0;
sRect.right = sWndRect.right - 30;
sRect.bottom = sWndRect.bottom;
// if no asset is loaded draw a "no asset loaded" text in the center
if (!g_pcAsset) {
const char* szText = "Nothing to display ... \r\nTry [Viewer | Open asset] to load an asset";
// shadow
RECT sCopy;
sCopy.left = sWndRect.left+1;
sCopy.top = sWndRect.top+1;
sCopy.bottom = sWndRect.bottom+1;
sCopy.right = sWndRect.right+1;
this->piFont->DrawText(NULL,szText ,
-1,&sCopy,DT_CENTER | DT_VCENTER,D3DCOLOR_ARGB(100,0x0,0x0,0x0));
sCopy.left = sWndRect.left+1;
sCopy.top = sWndRect.top+1;
sCopy.bottom = sWndRect.bottom-1;
sCopy.right = sWndRect.right-1;
this->piFont->DrawText(NULL,szText ,
-1,&sCopy,DT_CENTER | DT_VCENTER,D3DCOLOR_ARGB(100,0x0,0x0,0x0));
sCopy.left = sWndRect.left-1;
sCopy.top = sWndRect.top-1;
sCopy.bottom = sWndRect.bottom+1;
sCopy.right = sWndRect.right+1;
this->piFont->DrawText(NULL,szText ,
-1,&sCopy,DT_CENTER | DT_VCENTER,D3DCOLOR_ARGB(100,0x0,0x0,0x0));
sCopy.left = sWndRect.left-1;
sCopy.top = sWndRect.top-1;
sCopy.bottom = sWndRect.bottom-1;
sCopy.right = sWndRect.right-1;
this->piFont->DrawText(NULL,szText ,
-1,&sCopy,DT_CENTER | DT_VCENTER,D3DCOLOR_ARGB(100,0x0,0x0,0x0));
// text
this->piFont->DrawText(NULL,szText ,
-1,&sWndRect,DT_CENTER | DT_VCENTER,D3DCOLOR_ARGB(0xFF,0xFF,0xFF,0xFF));
}
// update all elements in the queue and render them
for (std::list<SEntry>::iterator
i = this->asEntries.begin();
i != this->asEntries.end();++i,++iCnt) {
if ((*i).dwStartTicks < dwLimit) {
i = this->asEntries.erase(i);
if (i == this->asEntries.end()) {
break;
}
} else if (nullptr != this->piFont) {
float fAlpha = 1.0f;
if ((*i).dwStartTicks <= dwLimit2) {
// linearly interpolate to create the fade out effect
fAlpha = 1.0f - (float)(dwLimit2 - (*i).dwStartTicks) / 3000.0f;
}
D3DCOLOR& clrColor = (*i).clrColor;
clrColor &= ~(0xFFu << 24);
clrColor |= (((unsigned char)(fAlpha * 255.0f)) & 0xFFu) << 24;
const char* szText = (*i).szText.c_str();
if (sRect.top + 30 > sWndRect.bottom) {
// end of window. send a special message
szText = "... too many errors";
clrColor = D3DCOLOR_ARGB(0xFF,0xFF,100,0x0);
}
// draw the black shadow
RECT sCopy;
sCopy.left = sRect.left+1;
sCopy.top = sRect.top+1;
sCopy.bottom = sRect.bottom+1;
sCopy.right = sRect.right+1;
this->piFont->DrawText(NULL,szText,
-1,&sCopy,DT_RIGHT | DT_TOP,D3DCOLOR_ARGB(
(unsigned char)(fAlpha * 100.0f),0x0,0x0,0x0));
sCopy.left = sRect.left-1;
sCopy.top = sRect.top-1;
sCopy.bottom = sRect.bottom-1;
sCopy.right = sRect.right-1;
this->piFont->DrawText(NULL,szText,
-1,&sCopy,DT_RIGHT | DT_TOP,D3DCOLOR_ARGB(
(unsigned char)(fAlpha * 100.0f),0x0,0x0,0x0));
sCopy.left = sRect.left-1;
sCopy.top = sRect.top-1;
sCopy.bottom = sRect.bottom+1;
sCopy.right = sRect.right+1;
this->piFont->DrawText(NULL,szText,
-1,&sCopy,DT_RIGHT | DT_TOP,D3DCOLOR_ARGB(
(unsigned char)(fAlpha * 100.0f),0x0,0x0,0x0));
sCopy.left = sRect.left+1;
sCopy.top = sRect.top+1;
sCopy.bottom = sRect.bottom-1;
sCopy.right = sRect.right-1;
this->piFont->DrawText(NULL,szText,
-1,&sCopy,DT_RIGHT | DT_TOP,D3DCOLOR_ARGB(
(unsigned char)(fAlpha * 100.0f),0x0,0x0,0x0));
// draw the text itself
int iPX = this->piFont->DrawText(NULL,szText,
-1,&sRect,DT_RIGHT | DT_TOP,clrColor);
sRect.top += iPX;
sRect.bottom += iPX;
if (szText != (*i).szText.c_str()) {
break;
}
}
}
}
}
|
/*
* Copyright (c) 2015 Cryptonomex, Inc., and contributors.
*
* The MIT License
*
* 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.
*/
#pragma once
#include <graphene/chain/protocol/operations.hpp>
#include <graphene/chain/evaluator.hpp>
#include <graphene/chain/database.hpp>
namespace graphene { namespace chain {
class asset_create_evaluator : public evaluator<asset_create_evaluator>
{
public:
typedef asset_create_operation operation_type;
void_result do_evaluate( const asset_create_operation& o );
object_id_type do_apply( const asset_create_operation& o );
};
class asset_issue_evaluator : public evaluator<asset_issue_evaluator>
{
public:
typedef asset_issue_operation operation_type;
void_result do_evaluate( const asset_issue_operation& o );
void_result do_apply( const asset_issue_operation& o );
const asset_dynamic_data_object* asset_dyn_data = nullptr;
const account_object* to_account = nullptr;
};
class asset_reserve_evaluator : public evaluator<asset_reserve_evaluator>
{
public:
typedef asset_reserve_operation operation_type;
void_result do_evaluate( const asset_reserve_operation& o );
void_result do_apply( const asset_reserve_operation& o );
const asset_dynamic_data_object* asset_dyn_data = nullptr;
const account_object* from_account = nullptr;
};
class asset_update_evaluator : public evaluator<asset_update_evaluator>
{
public:
typedef asset_update_operation operation_type;
void_result do_evaluate( const asset_update_operation& o );
void_result do_apply( const asset_update_operation& o );
const asset_object* asset_to_update = nullptr;
};
class asset_update_bitasset_evaluator : public evaluator<asset_update_bitasset_evaluator>
{
public:
typedef asset_update_bitasset_operation operation_type;
void_result do_evaluate( const asset_update_bitasset_operation& o );
void_result do_apply( const asset_update_bitasset_operation& o );
const asset_bitasset_data_object* bitasset_to_update = nullptr;
};
class asset_update_feed_producers_evaluator : public evaluator<asset_update_feed_producers_evaluator>
{
public:
typedef asset_update_feed_producers_operation operation_type;
void_result do_evaluate( const operation_type& o );
void_result do_apply( const operation_type& o );
const asset_bitasset_data_object* bitasset_to_update = nullptr;
};
class asset_fund_fee_pool_evaluator : public evaluator<asset_fund_fee_pool_evaluator>
{
public:
typedef asset_fund_fee_pool_operation operation_type;
void_result do_evaluate(const asset_fund_fee_pool_operation& op);
void_result do_apply(const asset_fund_fee_pool_operation& op);
const asset_dynamic_data_object* asset_dyn_data = nullptr;
};
class asset_global_settle_evaluator : public evaluator<asset_global_settle_evaluator>
{
public:
typedef asset_global_settle_operation operation_type;
void_result do_evaluate(const operation_type& op);
void_result do_apply(const operation_type& op);
const asset_object* asset_to_settle = nullptr;
};
class asset_settle_evaluator : public evaluator<asset_settle_evaluator>
{
public:
typedef asset_settle_operation operation_type;
void_result do_evaluate(const operation_type& op);
operation_result do_apply(const operation_type& op);
const asset_object* asset_to_settle = nullptr;
};
class asset_publish_feeds_evaluator : public evaluator<asset_publish_feeds_evaluator>
{
public:
typedef asset_publish_feed_operation operation_type;
void_result do_evaluate( const asset_publish_feed_operation& o );
void_result do_apply( const asset_publish_feed_operation& o );
std::map<std::pair<asset_id_type,asset_id_type>,price_feed> median_feed_values;
};
class normal_asset_publish_feeds_evaluator : public evaluator<normal_asset_publish_feeds_evaluator>
{
public:
typedef normal_asset_publish_feed_operation operation_type;
void_result do_evaluate(const normal_asset_publish_feed_operation& o);
void_result do_apply(const normal_asset_publish_feed_operation& o);
bool if_evluate();
std::map<std::pair<asset_id_type, asset_id_type>, price_feed> median_feed_values;
};
class asset_claim_fees_evaluator : public evaluator<asset_claim_fees_evaluator>
{
public:
typedef asset_claim_fees_operation operation_type;
void_result do_evaluate( const asset_claim_fees_operation& o );
void_result do_apply( const asset_claim_fees_operation& o );
};
class asset_real_create_evaluator : public evaluator<asset_real_create_evaluator>
{
public:
typedef asset_real_create_operation operation_type;
void_result do_evaluate(const asset_real_create_operation& o);
void_result do_apply(const asset_real_create_operation& o);
};
class asset_eth_create_evaluator :public evaluator<asset_eth_create_evaluator> {
public:
typedef asset_eth_create_operation operation_type;
void_result do_evaluate(const asset_eth_create_operation& o);
void_result do_apply(const asset_eth_create_operation& o);
};
class gurantee_create_evaluator :public evaluator<gurantee_create_evaluator>
{
public:
typedef gurantee_create_operation operation_type;
void_result do_evaluate(const gurantee_create_operation& o);
void_result do_apply(const gurantee_create_operation& o);
};
class gurantee_cancel_evaluator :public evaluator<gurantee_cancel_evaluator>
{
public:
typedef gurantee_cancel_operation operation_type;
void_result do_evaluate(const gurantee_cancel_operation& o);
void_result do_apply(const gurantee_cancel_operation& o);
};
class publisher_appointed_evaluator : public evaluator <publisher_appointed_evaluator>
{
public:
typedef publisher_appointed_operation operation_type;
void_result do_evaluate(const publisher_appointed_operation& o);
void_result do_apply(const publisher_appointed_operation& o);
};
class publisher_canceled_evaluator : public evaluator <publisher_canceled_evaluator>
{
public:
typedef publisher_canceled_operation operation_type;
void_result do_evaluate(const publisher_canceled_operation& o);
void_result do_apply(const publisher_canceled_operation& o);
};
class asset_fee_modification_evaluator: public evaluator <asset_fee_modification_evaluator>
{
public:
typedef asset_fee_modification_operation operation_type;
void_result do_evaluate(const asset_fee_modification_operation& o);
void_result do_apply(const asset_fee_modification_operation& o);
};
class withdraw_limit_modify_evaluator :public evaluator<withdraw_limit_modify_evaluator>
{
public:
typedef withdraw_limit_modify_operation operation_type;
void_result do_evaluate(const withdraw_limit_modify_operation& o);
void_result do_apply(const withdraw_limit_modify_operation& o);
};
class guard_lock_balance_set_evaluator :public evaluator<guard_lock_balance_set_evaluator>
{
public:
typedef set_guard_lockbalance_operation operation_type;
void_result do_evaluate(const set_guard_lockbalance_operation& o);
void_result do_apply(const set_guard_lockbalance_operation& o);
};
class senator_determine_withdraw_deposit_evaluator : public evaluator<senator_determine_withdraw_deposit_evaluator>
{
public:
typedef senator_determine_withdraw_deposit_operation operation_type;
void_result do_evaluate(const senator_determine_withdraw_deposit_operation& o);
void_result do_apply(const senator_determine_withdraw_deposit_operation& o);
};
class senator_determine_block_payment_evaluator : public evaluator<senator_determine_block_payment_evaluator>
{
public:
typedef senator_determine_block_payment_operation operation_type;
void_result do_evaluate(const senator_determine_block_payment_operation& o);
void_result do_apply(const senator_determine_block_payment_operation& o);
};
class senator_change_eth_gas_price_evaluator :public evaluator<senator_change_eth_gas_price_evaluator> {
public:
typedef senator_change_eth_gas_price_operation operation_type;
void_result do_evaluate(const senator_change_eth_gas_price_operation& o);
void_result do_apply(const senator_change_eth_gas_price_operation& o);
};
} } // graphene::chain
|
#include <hk_physics/physics.h>
#include <hk_physics/simunit/psi_info.h>
#include <hk_physics/core/vm_query_builder/vm_query_builder.h>
#include <hk_physics/constraint/pulley/pulley_bp.h>
#include <hk_physics/constraint/pulley/pulley_constraint.h>
#ifdef HK_ARCH_PPC
#include <stddef.h> // for size_t
#endif
class hk_Pulley_Work {
public:
#ifdef HK_ARCH_PPC
static inline void *operator new (size_t size, void *addr){
return addr;
}
#else
static inline void *operator new(size_t size, void *addr) {
return addr;
}
static inline void operator delete(void *, void *) { ; }
#endif
hk_VM_Query_Builder<hk_VMQ_Storage<1> > query_engine;
hk_real current_length;
};
void hk_Pulley_Constraint::init_constraint(const void *vbp) {
const hk_Pulley_BP *bp = static_cast<const hk_Pulley_BP *>(vbp);
this->init_pulley_constraint(bp);
}
void hk_Pulley_Constraint::init_pulley_constraint(const hk_Pulley_BP *bp) {
m_tau = bp->m_tau;
m_strength = bp->m_strength;
m_length = bp->m_length;
m_gearing = bp->m_gearing;
m_translation_os_ks[0] = bp->m_translation_os_ks[0];
m_translation_os_ks[1] = bp->m_translation_os_ks[1];
m_worldspace_point[0] = bp->m_worldspace_point[0];
m_worldspace_point[1] = bp->m_worldspace_point[1];
m_is_rigid = bp->m_is_rigid;
}
void hk_Pulley_Constraint::write_to_blueprint(hk_Pulley_BP *bp) {
bp->m_tau = m_tau;
bp->m_strength = m_strength;
bp->m_length = m_length;
bp->m_gearing = m_gearing;
bp->m_translation_os_ks[0] = m_translation_os_ks[0];
bp->m_translation_os_ks[1] = m_translation_os_ks[1];
bp->m_worldspace_point[0] = m_worldspace_point[0];
bp->m_worldspace_point[1] = m_worldspace_point[1];
bp->m_is_rigid = m_is_rigid;
}
hk_Pulley_Constraint::hk_Pulley_Constraint(
hk_Environment *env,
const hk_Pulley_BP *bp,
hk_Rigid_Body *a,
hk_Rigid_Body *b)
: hk_Constraint(env, a, b, HK_PRIORITY_LOCAL_CONSTRAINT) {
init_pulley_constraint(bp);
}
hk_Pulley_Constraint::hk_Pulley_Constraint(
hk_Local_Constraint_System *constraint_system,
const hk_Pulley_BP *bp,
hk_Rigid_Body *a,
hk_Rigid_Body *b)
: hk_Constraint(constraint_system, a, b, HK_PRIORITY_LOCAL_CONSTRAINT,
HK_NEXT_MULTIPLE_OF(16, sizeof(hk_Pulley_Work))) {
init_pulley_constraint(bp);
}
void hk_Pulley_Constraint::set_length(hk_real length) {
m_length = length;
}
void hk_Pulley_Constraint::set_gearing(hk_real gearing) {
m_gearing = gearing;
}
void hk_Pulley_Constraint::set_worldspace_point(int index, const hk_Vector3 &ws_point) {
m_worldspace_point[index] = ws_point;
}
int hk_Pulley_Constraint::get_vmq_storage_size() {
return HK_NEXT_MULTIPLE_OF(16, sizeof(hk_Pulley_Work));
}
int
hk_Pulley_Constraint::setup_and_step_constraint(hk_PSI_Info &pi, void *mem, hk_real tau_factor, hk_real damp_factor) {
hk_Pulley_Work &work = *new(mem) hk_Pulley_Work;
hk_VM_Query_Builder<hk_VMQ_Storage<1> > &query_engine = work.query_engine;
hk_Rigid_Body *b0 = get_rigid_body(0);
hk_Rigid_Body *b1 = get_rigid_body(1);
hk_Vector3 translation_ws_ks[2];
translation_ws_ks[0]._set_transformed_pos(b0->get_cached_transform(), m_translation_os_ks[0]);
translation_ws_ks[1]._set_transformed_pos(b1->get_cached_transform(), m_translation_os_ks[1]);
hk_Vector3 dir[2];
dir[0].set_sub(m_worldspace_point[0], translation_ws_ks[0]);
dir[1].set_sub(m_worldspace_point[1], translation_ws_ks[1]);
dir[1] *= m_gearing;
work.current_length = dir[0].normalize_with_length() + dir[1].normalize_with_length() - m_length;
query_engine.begin(1);
{
query_engine.begin_entries(1);
{
query_engine.add_linear(0, HK_BODY_A, b0, translation_ws_ks[0], dir[0], 1.0f);
query_engine.add_linear(0, HK_BODY_B, b1, translation_ws_ks[1], dir[1], 1.0f);
}
query_engine.commit_entries(1);
}
query_engine.commit(HK_BODY_A, b0);
query_engine.commit(HK_BODY_B, b1);
hk_Dense_Matrix &mass_matrix = query_engine.get_vmq_storage().get_dense_matrix();
mass_matrix(0, 0) = 1.0f / mass_matrix(0, 0); // invert in place
{ // step
if (m_is_rigid || work.current_length >= 0) {
hk_real *approaching_velocity = query_engine.get_vmq_storage().get_velocities();
hk_real delta_dist = tau_factor * m_tau * pi.get_inv_delta_time() * work.current_length -
damp_factor * m_strength * approaching_velocity[0];
hk_Vector3 impulses;
impulses(0) = delta_dist * mass_matrix(0, 0);
query_engine.apply_impulses(HK_BODY_A, b0, (hk_real *) &impulses(0));
query_engine.apply_impulses(HK_BODY_B, b1, (hk_real *) &impulses(0));
}
}
return HK_NEXT_MULTIPLE_OF(16, sizeof(hk_Pulley_Work));
}
void hk_Pulley_Constraint::step_constraint(hk_PSI_Info &pi, void *mem, hk_real tau_factor, hk_real damp_factor) {
hk_Pulley_Work &work = *(hk_Pulley_Work *) mem;
hk_VM_Query_Builder<hk_VMQ_Storage<1> > &query_engine = work.query_engine;
hk_real *approaching_velocity = query_engine.get_vmq_storage().get_velocities();
approaching_velocity[0] = 0.0f;
hk_Rigid_Body *b0 = get_rigid_body(0);
hk_Rigid_Body *b1 = get_rigid_body(1);
query_engine.update_velocities(HK_BODY_A, b0);
query_engine.update_velocities(HK_BODY_B, b1);
if (m_is_rigid || work.current_length >= 0) {
hk_real delta_dist = tau_factor * m_tau * pi.get_inv_delta_time() * work.current_length -
damp_factor * m_strength * approaching_velocity[0];
hk_Vector3 impulses;
hk_Dense_Matrix &mass_matrix = query_engine.get_vmq_storage().get_dense_matrix();
impulses(0) = delta_dist * mass_matrix(0, 0);
query_engine.apply_impulses(HK_BODY_A, b0, (hk_real *) &impulses(0));
query_engine.apply_impulses(HK_BODY_B, b1, (hk_real *) &impulses(0));
}
}
void hk_Pulley_Constraint::apply_effector_PSI(hk_PSI_Info &pi, hk_Array<hk_Entity *> *) {
hk_Pulley_Work work_mem;
hk_Pulley_Constraint::setup_and_step_constraint(pi, (void *) &work_mem, 1.0f, 1.0f);
}
// HAVOK DO NOT EDIT
|
/**
* @file lz4_compressor.cc
*
* @section LICENSE
*
* The MIT License
*
* @copyright Copyright (c) 2017-2020 TileDB, Inc.
*
* 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.
*
* @section DESCRIPTION
*
* This file implements the lz4 compressor class.
*/
#include "tiledb/sm/compressors/lz4_compressor.h"
#include "tiledb/sm/buffer/buffer.h"
#include "tiledb/sm/buffer/const_buffer.h"
#include "tiledb/sm/buffer/preallocated_buffer.h"
#include "tiledb/sm/misc/logger.h"
#include "tiledb/sm/misc/stats.h"
#include <lz4.h>
#include <limits>
namespace tiledb {
namespace sm {
Status LZ4::compress(
int level, ConstBuffer* input_buffer, Buffer* output_buffer) {
STATS_FUNC_IN(compressor_lz4_compress);
// Sanity check
if (input_buffer->data() == nullptr || output_buffer->data() == nullptr)
return LOG_STATUS(Status::CompressionError(
"Failed compressing with LZ4; invalid buffer format"));
// TODO: level is ignored using the simple api interface
(void)level;
// Compress
#if LZ4_VERSION_NUMBER >= 10705
int ret = LZ4_compress_default(
(char*)input_buffer->data(),
(char*)output_buffer->cur_data(),
(int)input_buffer->size(),
(int)output_buffer->free_space());
#else
// deprecated lz4 api
int ret = LZ4_compress(
(char*)input_buffer->data(),
(char*)output_buffer->cur_data(),
(int)input_buffer->size());
#endif
// Check error
if (ret < 0)
return Status::CompressionError("LZ4 compression failed");
// Set size of compressed data
output_buffer->advance_size(static_cast<uint64_t>(ret));
output_buffer->advance_offset(static_cast<uint64_t>(ret));
return Status::Ok();
STATS_FUNC_OUT(compressor_lz4_compress);
}
Status LZ4::decompress(
ConstBuffer* input_buffer, PreallocatedBuffer* output_buffer) {
STATS_FUNC_IN(compressor_lz4_decompress);
// Sanity check
if (input_buffer->data() == nullptr || output_buffer->data() == nullptr)
return LOG_STATUS(Status::CompressionError(
"Failed decompressing with LZ4; invalid buffer format"));
// Decompress
int ret = LZ4_decompress_safe(
(char*)input_buffer->data(),
(char*)output_buffer->cur_data(),
(int)input_buffer->size(),
(int)output_buffer->free_space());
// Check error
if (ret < 0)
return Status::CompressionError("LZ4 decompression failed");
// Set size of decompressed data
output_buffer->advance_offset(static_cast<uint64_t>(ret));
return Status::Ok();
STATS_FUNC_OUT(compressor_lz4_decompress);
}
uint64_t LZ4::overhead(uint64_t nbytes) {
// So that we avoid overflow
auto half_bound =
static_cast<uint64_t>(LZ4_compressBound((int)ceil(nbytes / 2.0)));
return 2 * half_bound - nbytes;
}
} // namespace sm
} // namespace tiledb
|
#ifndef CONTEXT_HPP
#define CONTEXT_HPP
#include <SFML/Graphics.hpp>
#include "resourceIdentifiers.hpp"
class ResourceManager;
class MusicPlayer;
class SoundPlayer;
class Engine;
class SwapContext;
struct Context
{
Context(sf::RenderWindow& window,
ResourceManager& resourceManager,
MusicPlayer& mPlayer,
SoundPlayer& sPlayer,
Engine& ecEngine,
bool& isQuitting,
sf::Color& clearColor,
SwapContext& swapContext);
sf::RenderWindow* window;
ResourceManager* resourceManager;
MusicPlayer* mPlayer;
SoundPlayer* sPlayer;
Engine* ecEngine;
bool* isQuitting;
sf::Color* clearColor;
SwapContext* swapContext;
};
#endif
|
#include "core/uri.h"
#include <regex>
class UriPrivate {
public:
string mUri;
smatch mResult;
};
/*!
\class Uri
\brief Uri class provides an interface for working with URI's.
\since Next 1.0
\inmodule Core
*/
Uri::Uri(const string &uri) :
p_ptr(new UriPrivate) {
PROFILE_FUNCTION();
p_ptr->mUri = uri;
replace(p_ptr->mUri.begin(), p_ptr->mUri.end(), '\\', '/');
regex_match(p_ptr->mUri, p_ptr->mResult, regex("^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?"));
}
Uri::~Uri() {
delete p_ptr;
}
/*!
Returns the scheme of the URI. If an empty string is returned, this means the scheme is undefined and the URI is then relative.
*/
string Uri::scheme() const {
PROFILE_FUNCTION();
return p_ptr->mResult[2].str();
}
/*!
Returns the host of the URI if it is defined; otherwise an empty string is returned.
*/
string Uri::host() const {
PROFILE_FUNCTION();
return p_ptr->mResult[4];
}
/*!
Returns the path of the URI.
*/
string Uri::path() const {
PROFILE_FUNCTION();
return p_ptr->mResult[5];
}
/*!
Returns the query string of the URI if there's a query string, or an empty result if not.
*/
string Uri::query() const {
PROFILE_FUNCTION();
return p_ptr->mResult[7];
}
/*!
Returns the fragment of the URI.
*/
string Uri::fragment() const {
PROFILE_FUNCTION();
return p_ptr->mResult[9];
}
/*!
Returns a directory of URI path.
*/
string Uri::dir() const {
PROFILE_FUNCTION();
string str = path();
size_t found = str.rfind('/');
if(found != string::npos) {
str.replace(found, str.length(), "");
}
return str;
}
/*!
Returns a file name in the URI path.
*/
string Uri::name() const {
PROFILE_FUNCTION();
string str = path();
size_t found = str.rfind('/');
if(found != string::npos) {
str.replace(0, found + 1, "");
}
return str;
}
/*!
Returns a base name of file in the URI path.
*/
string Uri::baseName() const {
PROFILE_FUNCTION();
string str = name();
size_t found = str.find('.');
if(found != string::npos) {
str.replace(found, str.length(), "");
}
return str;
}
/*!
Returns a file suffix in the URI path.
*/
string Uri::suffix() const {
PROFILE_FUNCTION();
string str = name();
size_t found = str.find('.');
if(found != string::npos) {
str.replace(0, found + 1, "");
}
return str;
}
|
#include "../test/gtest.h"
#include <vector>
#include <arbor/morph/embed_pwlin.hpp>
#include <arbor/morph/locset.hpp>
#include <arbor/morph/morphexcept.hpp>
#include <arbor/morph/morphology.hpp>
#include <arbor/morph/mprovider.hpp>
#include <arbor/morph/primitives.hpp>
#include <arbor/morph/region.hpp>
#include <arbor/morph/sample_tree.hpp>
#include "util/span.hpp"
#include "util/strprintf.hpp"
#include "morph_pred.hpp"
using namespace arb;
using embedding = embed_pwlin;
using testing::region_eq;
using testing::cablelist_eq;
using testing::mlocationlist_eq;
TEST(region, expr_repn) {
using util::to_string;
auto c1 = reg::cable(1, 0, 1);
auto c2 = reg::cable(4, 0.125, 0.5);
auto c3 = join(reg::cable(4, 0.125, 0.5), reg::cable(3, 0, 1));
auto b1 = reg::branch(1);
auto t1 = reg::tagged(1);
auto t2 = reg::tagged(2);
auto t3 = reg::tagged(3);
auto all = reg::all();
EXPECT_EQ(to_string(c1), "(cable 1 0 1)");
EXPECT_EQ(to_string(c2), "(cable 4 0.125 0.5)");
EXPECT_EQ(to_string(c3), "(join (cable 4 0.125 0.5) (cable 3 0 1))");
EXPECT_EQ(to_string(b1), "(cable 1 0 1)");
EXPECT_EQ(to_string(t1), "(tag 1)");
EXPECT_EQ(to_string(t2), "(tag 2)");
EXPECT_EQ(to_string(intersect(c1, t2)), "(intersect (cable 1 0 1) (tag 2))");
EXPECT_EQ(to_string(join(c1, t2)), "(join (cable 1 0 1) (tag 2))");
EXPECT_EQ(to_string(join(t1, t2, t3)), "(join (join (tag 1) (tag 2)) (tag 3))");
EXPECT_EQ(to_string(intersect(t1, t2, t3)), "(intersect (intersect (tag 1) (tag 2)) (tag 3))");
EXPECT_EQ(to_string(intersect(join(c1, t2), c2)), "(intersect (join (cable 1 0 1) (tag 2)) (cable 4 0.125 0.5))");
EXPECT_EQ(to_string(all), "(all)");
}
TEST(region, invalid_mcable) {
EXPECT_NO_THROW(reg::cable(123, 0.5, 0.8));
EXPECT_THROW(reg::cable(1, 0, 1.1), invalid_mcable);
EXPECT_THROW(reg::branch(-1), invalid_mcable);
}
TEST(locset, expr_repn) {
using util::to_string;
auto root = ls::root();
auto term = ls::terminal();
auto samp = ls::sample(42);
auto loc = ls::location(2, 0.5);
EXPECT_EQ(to_string(root), "(root)");
EXPECT_EQ(to_string(term), "(terminal)");
EXPECT_EQ(to_string(sum(root, term)), "(sum (root) (terminal))");
EXPECT_EQ(to_string(sum(root, term, samp)), "(sum (sum (root) (terminal)) (sample 42))");
EXPECT_EQ(to_string(sum(root, term, samp, loc)), "(sum (sum (sum (root) (terminal)) (sample 42)) (location 2 0.5))");
EXPECT_EQ(to_string(samp), "(sample 42)");
EXPECT_EQ(to_string(loc), "(location 2 0.5)");
}
TEST(locset, invalid_mlocation) {
// Location positions have to be in the range [0,1].
EXPECT_NO_THROW(ls::location(123, 0.0));
EXPECT_NO_THROW(ls::location(123, 0.02));
EXPECT_NO_THROW(ls::location(123, 1.0));
EXPECT_THROW(ls::location(0, 1.5), invalid_mlocation);
EXPECT_THROW(ls::location(unsigned(-1), 0.), invalid_mlocation);
}
// Name evaluation (thingify) tests:
TEST(locset, thingify_named) {
using pvec = std::vector<msize_t>;
using svec = std::vector<msample>;
locset banana = ls::root();
locset cake = ls::terminal();
sample_tree sm(svec{ {{0,0,0,1},1}, {{10,0,0,1},1} }, pvec{mnpos, 0});
{
label_dict dict;
dict.set("banana", banana);
dict.set("cake", cake);
mprovider mp(morphology(sm, false), dict);
EXPECT_EQ(thingify(locset("cake"), mp), thingify(cake, mp));
EXPECT_EQ(thingify(locset("banana"), mp), thingify(banana, mp));
EXPECT_THROW(thingify(locset("durian"), mp), unbound_name);
}
{
label_dict dict;
dict.set("banana", banana);
dict.set("cake", cake);
dict.set("topping", locset("fruit"));
dict.set("fruit", locset("strawberry"));
EXPECT_THROW(mprovider(morphology(sm, false), dict), unbound_name);
}
{
label_dict dict;
dict.set("banana", banana);
dict.set("cake", cake);
dict.set("topping", locset("fruit"));
dict.set("fruit", sum(locset("banana"), locset("topping")));
EXPECT_THROW(mprovider(morphology(sm, false), dict), circular_definition);
}
}
TEST(region, thingify_named) {
using pvec = std::vector<msize_t>;
using svec = std::vector<msample>;
region banana = reg::branch(0);
region cake = reg::cable(0, 0.2, 0.3);
// copy-paste ftw
sample_tree sm(svec{ {{0,0,0,1},1}, {{10,0,0,1},1} }, pvec{mnpos, 0});
{
label_dict dict;
dict.set("banana", banana);
dict.set("cake", cake);
mprovider mp(morphology(sm, false), dict);
EXPECT_EQ(thingify(region("cake"), mp), thingify(cake, mp));
EXPECT_EQ(thingify(region("banana"), mp), thingify(banana, mp));
EXPECT_THROW(thingify(region("durian"), mp), unbound_name);
}
{
label_dict dict;
dict.set("banana", banana);
dict.set("cake", cake);
dict.set("topping", region("fruit"));
dict.set("fruit", region("strawberry"));
EXPECT_THROW(mprovider(morphology(sm, false), dict), unbound_name);
}
{
label_dict dict;
dict.set("banana", banana);
dict.set("cake", cake);
dict.set("topping", region("fruit"));
dict.set("fruit", join(region("cake"), region("topping")));
EXPECT_THROW(mprovider(morphology(sm, false), dict), circular_definition);
}
}
// Embedded evaluation (thingify) tests:
TEST(locset, thingify) {
using pvec = std::vector<msize_t>;
using svec = std::vector<msample>;
using ll = mlocation_list;
auto root = ls::root();
auto term = ls::terminal();
auto samp = ls::sample(4);
auto midb2 = ls::location(2, 0.5);
auto midb1 = ls::location(1, 0.5);
auto begb0 = ls::location(0, 0);
auto begb1 = ls::location(1, 0);
auto begb2 = ls::location(2, 0);
auto begb3 = ls::location(3, 0);
auto begb4 = ls::location(4, 0);
auto multi = sum(begb3, midb2, midb1, midb2);
// Eight samples
//
// 0
// 1 3
// 2 4
// 5 6
// 7
pvec parents = {mnpos, 0, 1, 0, 3, 4, 4, 6};
svec samples = {
{{ 0, 0, 0, 2}, 3},
{{ 10, 0, 0, 2}, 3},
{{100, 0, 0, 2}, 3},
{{ 0, 10, 0, 2}, 3},
{{ 0,100, 0, 2}, 3},
{{100,100, 0, 2}, 3},
{{ 0,200, 0, 2}, 3},
{{ 0,300, 0, 2}, 3},
};
sample_tree sm(samples, parents);
{
mprovider mp(morphology(sm, true));
EXPECT_EQ(thingify(root, mp), (ll{{0,0}}));
EXPECT_EQ(thingify(term, mp), (ll{{1,1},{3,1},{4,1}}));
EXPECT_EQ(thingify(samp, mp), (ll{{2,1}}));
EXPECT_EQ(thingify(midb2, mp), (ll{{2,0.5}}));
EXPECT_EQ(thingify(midb1, mp), (ll{{1,0.5}}));
EXPECT_EQ(thingify(begb0, mp), (ll{{0,0}}));
EXPECT_EQ(thingify(begb1, mp), (ll{{1,0}}));
EXPECT_EQ(thingify(begb2, mp), (ll{{2,0}}));
EXPECT_EQ(thingify(begb3, mp), (ll{{3,0}}));
EXPECT_EQ(thingify(begb4, mp), (ll{{4,0}}));
// Check round-trip of implicit locset conversions.
// (Use a locset which is non-trivially a multiset in order to
// test the fold in the constructor.)
EXPECT_EQ(thingify(multi, mp), thingify(locset(thingify(multi, mp)), mp));
}
{
mprovider mp(morphology(sm, false));
EXPECT_EQ(thingify(root, mp), (ll{{0,0}}));
EXPECT_EQ(thingify(term, mp), (ll{{0,1},{2,1},{3,1}}));
EXPECT_EQ(thingify(samp, mp), (ll{{1,1}}));
EXPECT_EQ(thingify(midb2, mp), (ll{{2,0.5}}));
EXPECT_EQ(thingify(midb1, mp), (ll{{1,0.5}}));
EXPECT_EQ(thingify(begb0, mp), (ll{{0,0}}));
EXPECT_EQ(thingify(begb1, mp), (ll{{1,0}}));
EXPECT_EQ(thingify(begb2, mp), (ll{{2,0}}));
EXPECT_EQ(thingify(begb3, mp), (ll{{3,0}}));
// In the absence of a spherical root, there is no branch 4.
EXPECT_THROW(thingify(begb4, mp), no_such_branch);
}
{
mprovider mp(morphology(sm, false));
auto all = reg::all();
auto ls0 = thingify(ls::uniform(all, 0, 9, 12), mp);
auto ls1 = thingify(ls::uniform(all, 0, 9, 12), mp);
auto ls2 = thingify(ls::uniform(all, 10, 19, 12), mp);
auto ls3 = thingify(ls::uniform(all, 0, 9, 13), mp);
auto ls4 = thingify(ls::uniform(all, 5, 6, 12), mp);
auto ls5 = thingify(ls::uniform(all, 2, 5, 12), mp);
auto ls6 = thingify(ls::uniform(all, 5, 11, 12), mp);
EXPECT_EQ(ls0, ls1);
bool found_none = true;
for (auto l: ls2) {
auto it = std::find(ls0.begin(), ls0.end(), l);
if (it != ls0.end()) {
found_none = false;
}
}
EXPECT_TRUE(found_none);
found_none = true;
for (auto l: ls3) {
auto it = std::find(ls0.begin(), ls0.end(), l);
if (it != ls0.end()) {
found_none = false;
}
}
EXPECT_TRUE(found_none);
bool found_all = true;
for (auto l: ls4) {
auto it = std::find(ls0.begin(), ls0.end(), l);
if (it == ls0.end()) {
found_all = false;
}
}
EXPECT_TRUE(found_all);
int found = 0;
for (auto l: ls5) {
auto it = std::find(ls4.begin(), ls4.end(), l);
if (it != ls4.end()) found++;
}
EXPECT_TRUE(found == 1);
found = 0;
for (auto l: ls6) {
auto it = std::find(ls4.begin(), ls4.end(), l);
if (it != ls4.end()) found++;
}
EXPECT_TRUE(found == 2);
}
{
mprovider mp(morphology(sm, false));
auto sub_reg = join(reg::cable(0, 0.2, 0.7), reg::cable(1, 0.1, 1), reg::cable(3, 0.5, 0.6));
auto ls0 = thingify(ls::uniform(sub_reg, 0, 10000, 72), mp);
for (auto l: ls0) {
switch(l.branch) {
case 0: {
if (l.pos < 0.2 || l.pos > 0.7) FAIL();
break;
}
case 1: {
if (l.pos < 0.1 || l.pos > 1) FAIL();
break;
}
case 3: {
if (l.pos < 0.5 || l.pos > 0.6) FAIL();
break;
}
default: {
FAIL();
break;
}
}
SUCCEED();
}
}
}
TEST(region, thingify_simple_morphologies) {
using pvec = std::vector<msize_t>;
using svec = std::vector<msample>;
using cl = mcable_list;
// A single unbranched cable with 5 sample points.
// The cable has length 10 μm, with samples located at
// 0 μm, 1 μm, 3 μm, 7 μm and 10 μm.
{
pvec parents = {mnpos, 0, 1, 2, 3};
svec samples = {
{{ 0, 0, 0, 2}, 1},
{{ 1, 0, 0, 2}, 1},
{{ 3, 0, 0, 2}, 2},
{{ 7, 0, 0, 2}, 1},
{{ 10, 0, 0, 2}, 2},
};
sample_tree sm(samples, parents);
mprovider mp(morphology(sm, false));
auto h1 = reg::cable(0, 0, 0.5);
auto h2 = reg::cable(0, 0.5, 1);
auto t1 = reg::tagged(1);
auto t2 = reg::tagged(2);
auto all = reg::all();
// Concrete cable lists
cl h1_{{0, 0.0, 0.5}};
cl h2_{{0, 0.5, 1.0}};
cl t1_{{0, 0.0, 0.1}, {0, 0.3, 0.7}};
cl t2_{{0, 0.1, 0.3}, {0, 0.7, 1.0}};
cl all_{{0, 0, 1}};
cl empty_{};
EXPECT_TRUE(region_eq(mp, join(h1, h2), all_));
EXPECT_TRUE(region_eq(mp, intersect(h1, h2), cl{{0, 0.5, 0.5}}));
EXPECT_TRUE(region_eq(mp, t1, t1_));
EXPECT_TRUE(region_eq(mp, t2, t2_));
EXPECT_TRUE(region_eq(mp, intersect(h1, h1), h1_));
EXPECT_TRUE(region_eq(mp, intersect(t1, t1), t1_));
EXPECT_TRUE(region_eq(mp, join(t1, t2), all_));
EXPECT_TRUE(region_eq(mp, intersect(all, t1), t1_));
EXPECT_TRUE(region_eq(mp, intersect(all, t2), t2_));
EXPECT_TRUE(region_eq(mp, join(all, t1), all_));
EXPECT_TRUE(region_eq(mp, join(all, t2), all_));
EXPECT_TRUE(region_eq(mp, join(h1, t1), cl{{0, 0, 0.7}}));
EXPECT_TRUE(region_eq(mp, join(h1, t2), cl{{0, 0, 0.5}, {0, 0.7, 1}}));
EXPECT_TRUE(region_eq(mp, intersect(h2, t1), cl{{0, 0.5, 0.7}}));
// Check round-trip of implicit region conversions.
// (No fork points in cables, so extent should not including anyhing extra).
EXPECT_EQ((mcable_list{{0, 0.3, 0.6}}), thingify(region(mcable{0, 0.3, 0.6}), mp).cables());
EXPECT_TRUE(cablelist_eq(t2_, thingify(region(t2_), mp).cables()));
}
// Test handling of spherical soma on multi-branch morphologies
//
// sample ids:
// 0 |
// 1 3 |
// 2 4 |
// tags:
// 1 |
// 3 2 |
// 3 2 |
{
pvec parents = {mnpos, 0, 1, 0, 3};
svec samples = {
{{ 0, 0, 0, 2}, 1},
{{ 10, 0, 0, 2}, 3},
{{100, 0, 0, 2}, 3},
{{ 0, 10, 0, 2}, 2},
{{ 0,100, 0, 2}, 2},
};
// with a spherical root
sample_tree sm(samples, parents);
mprovider mp(morphology(sm, true));
using ls::location;
using reg::tagged;
using reg::distal_interval;
using reg::proximal_interval;
using reg::branch;
using reg::cable;
using reg::all;
locset mid0_ = location(0,0.5);
locset start1_ = location(1,0);
locset end1_ = location(1,1);
auto reg0_ = distal_interval(start1_, 45);
auto reg1_ = distal_interval(mid0_, 74);
auto reg2_ = proximal_interval(end1_, 45);
auto reg3_ = proximal_interval(end1_, 91);
auto reg4_ = distal_interval(end1_, 0);
auto reg5_ = distal_interval(start1_, 0);
auto reg6_ = proximal_interval(start1_, 0);
EXPECT_TRUE(region_eq(mp, tagged(1), mcable_list{{0,0,1}}));
EXPECT_TRUE(region_eq(mp, tagged(2), mcable_list{{2,0,1}}));
EXPECT_TRUE(region_eq(mp, tagged(3), mcable_list{{1,0,1}}));
EXPECT_TRUE(region_eq(mp, join(tagged(1), tagged(2), tagged(3)), mcable_list{{0,0,1}, {1,0,1}, {2,0,1}}));
EXPECT_TRUE(region_eq(mp, join(tagged(1), tagged(2), tagged(3)), all()));
EXPECT_TRUE(region_eq(mp, reg0_, mcable_list{{1,0,0.5}}));
EXPECT_TRUE(region_eq(mp, reg1_, mcable_list{{0,0.5,1}, {1,0,0.8}, {2,0,0.8}}));
EXPECT_TRUE(region_eq(mp, reg2_, mcable_list{{1,0.5,1}}));
EXPECT_TRUE(region_eq(mp, reg3_, mcable_list{{0, 0.75, 1}, {1,0,1}}));
EXPECT_TRUE(region_eq(mp, reg4_, mcable_list{{1,1,1}}));
EXPECT_TRUE(region_eq(mp, reg5_, mcable_list{{0,1,1}}));
EXPECT_TRUE(region_eq(mp, reg6_, mcable_list{{0,1,1}}));
}
}
TEST(region, thingify_moderate_morphologies) {
using pvec = std::vector<msize_t>;
using svec = std::vector<msample>;
using cl = mcable_list;
// Test multi-level morphologies.
//
// Eight samples
//
// sample ids:
// 0
// 1 3
// 2 4
// 5 6
// 7
// tags:
// 1
// 3 2
// 3 2
// 4 3
// 3
{
pvec parents = {mnpos, 0, 1, 0, 3, 4, 4, 6};
svec samples = {
{{ 0, 0, 0, 1}, 1},
{{ 10, 0, 0, 1}, 3},
{{100, 0, 0, 3}, 3},
{{ 0, 10, 0, 1}, 2},
{{ 0,100, 0, 5}, 2},
{{100,100, 0, 2}, 4},
{{ 0,200, 0, 1}, 3},
{{ 0,300, 0, 3}, 3},
};
sample_tree sm(samples, parents);
// Without spherical root
mprovider mp(morphology(sm, false));
using ls::location;
using reg::tagged;
using reg::distal_interval;
using reg::proximal_interval;
using reg::radius_lt;
using reg::radius_le;
using reg::radius_gt;
using reg::radius_ge;
using reg::branch;
using reg::all;
using reg::cable;
auto soma = tagged(1);
auto axon = tagged(2);
auto dend = tagged(3);
auto apic = tagged(4);
auto b1 = branch(1);
auto b3 = branch(3);
auto b13 = join(b1, b3);
cl empty_{};
cl soma_ = empty_;
// Whole branches:
mcable b0_{0,0,1};
mcable b1_{1,0,1};
mcable b2_{2,0,1};
mcable b3_{3,0,1};
cl all_ = {b0_,b1_,b2_,b3_};
mcable c_end1_{1,1,1};
mcable c_root_{0,0,0};
EXPECT_TRUE(region_eq(mp, all(), all_));
EXPECT_TRUE(region_eq(mp, axon, cl{b1_}));
EXPECT_TRUE(region_eq(mp, dend, cl{b0_,b3_}));
EXPECT_TRUE(region_eq(mp, apic, cl{b2_}));
EXPECT_TRUE(region_eq(mp, join(dend, apic), cl{b0_,b2_,b3_}));
EXPECT_TRUE(region_eq(mp, join(axon, join(dend, apic)), all_));
// Test that intersection correctly generates zero-length cables at
// parent-child interfaces.
EXPECT_TRUE(region_eq(mp, intersect(apic, dend), cl{c_end1_}));
EXPECT_TRUE(region_eq(mp, intersect(apic, axon), cl{c_end1_}));
EXPECT_TRUE(region_eq(mp, intersect(axon, dend), cl{c_root_, c_end1_}));
// Test distal and proximal interavls
auto start0_ = location(0, 0 );
auto quar_1_ = location(1, 0.25);
auto mid1_ = location(1, 0.5 );
auto end1_ = location(1, 1 );
auto mid2_ = location(2, 0.5 );
auto end2_ = location(2, 1 );
auto mid3_ = location(3, 0.5 );
auto loc_3_0_ = location(3, 0.4 );
auto loc_3_1_ = location(3, 0.65);
auto mid_3_ = location(3, 0.5 );
auto reg_a_ = join(cable(0,0.1,0.4), cable(2,0,1), cable(3,0.1,0.4));
auto reg_b_ = join(cable(0,0.1,0.4), cable(2,0,1), cable(3,0.1,0.3));
auto reg_c_ = join(cable(0,0,0.7), cable(2,0,0.5), cable(3,0.1,0.4), cable(3,0.9,1));
auto reg_d_ = join(cable(0,0,0.7), cable(2,0,0.5), cable(3,0.1,0.9));
// Distal from point and/or interval
EXPECT_TRUE(region_eq(mp, distal_interval(start0_, 1000), mcable_list{{0,0,1}}));
EXPECT_TRUE(region_eq(mp, distal_interval(quar_1_, 150), mcable_list{{1,0.25,1}, {2,0,0.75}, {3,0,0.375}}));
EXPECT_TRUE(region_eq(mp, distal_interval(mid1_, 1000), mcable_list{{1,0.5,1}, {2,0,1}, {3,0,1}}));
EXPECT_TRUE(region_eq(mp, distal_interval(mid1_, 150), mcable_list{{1,0.5,1}, {2,0,1}, {3,0,0.5}}));
EXPECT_TRUE(region_eq(mp, distal_interval(end1_, 100), mcable_list{{2,0,1},{3,0,0.5}}));
EXPECT_TRUE(region_eq(mp, distal_interval(join(quar_1_, mid1_), 150), mcable_list{{1,0.25,1}, {2,0,1}, {3,0,0.5}}));
EXPECT_TRUE(region_eq(mp, distal_interval(join(quar_1_, loc_3_1_), 150), mcable_list{{1,0.25,1}, {2,0,0.75}, {3,0,0.375}, {3,0.65,1}}));
EXPECT_TRUE(region_eq(mp, distal_interval(join(quar_1_, loc_3_1_), 150), mcable_list{{1,0.25,1}, {2,0,0.75}, {3,0,0.375}, {3,0.65,1}}));
// Proximal from point and/or interval
EXPECT_TRUE(region_eq(mp, proximal_interval(mid3_, 100), mcable_list{{3,0,0.5}}));
EXPECT_TRUE(region_eq(mp, proximal_interval(mid3_, 150), mcable_list{{1,0.5,1}, {3,0,0.5}}));
EXPECT_TRUE(region_eq(mp, proximal_interval(end2_, 150), mcable_list{{1,0.5,1}, {2,0,1}}));
EXPECT_TRUE(region_eq(mp, proximal_interval(end2_, 500), mcable_list{{1,0,1}, {2,0,1}}));
EXPECT_TRUE(region_eq(mp, proximal_interval(loc_3_0_, 100), mcable_list{{1,0.8,1}, {3,0,0.4}}));
EXPECT_TRUE(region_eq(mp, proximal_interval(join(loc_3_0_, mid2_), 120), mcable_list{{1,0.3,1}, {2,0,0.5}, {3, 0, 0.4}}));
// Test radius_lt and radius_gt
EXPECT_TRUE(region_eq(mp, radius_lt(all(), 2), mcable_list{{0,0,0.55}, {1,0,0.325}, {3,0.375,0.75}}));
EXPECT_TRUE(region_eq(mp, radius_lt(all(), 3), mcable_list{{0,0,1}, {1,0,0.55}, {2,6.0/9.0,1}, {3,0.25,1}}));
EXPECT_TRUE(region_eq(mp, radius_gt(all(), 2), mcable_list{{0,0.55,1}, {1,0.325,1}, {2,0,1}, {3,0,0.375}, {3,0.75,1}}));
EXPECT_TRUE(region_eq(mp, radius_gt(all(), 3), mcable_list{{1,0.55,1}, {2,0,6.0/9.0}, {3,0,0.25}}));
EXPECT_TRUE(region_eq(mp, radius_le(all(), 2), mcable_list{{0,0,0.55}, {1,0,0.325}, {2,1,1}, {3,0.375,0.75}}));
EXPECT_TRUE(region_eq(mp, radius_le(all(), 3), mcable_list{{0,0,1}, {1,0,0.55}, {2,6.0/9.0,1}, {3,0.25,1}}));
EXPECT_TRUE(region_eq(mp, radius_ge(all(), 2), mcable_list{{0,0.55,1}, {1,0.325,1}, {2,0,1}, {3,0,0.375}, {3,0.75,1}}));
EXPECT_TRUE(region_eq(mp, radius_ge(all(), 3), mcable_list{{1,0.55,1}, {2,0,6.0/9.0}, {3,0,0.25}}));
EXPECT_TRUE(region_eq(mp, radius_lt(reg_a_, 2), mcable_list{{0,0.1,0.4},{3,0.375,0.4}}));
EXPECT_TRUE(region_eq(mp, radius_gt(reg_a_, 2), mcable_list{{2,0,1},{3,0.1,0.375}}));
EXPECT_TRUE(region_eq(mp, radius_lt(reg_b_, 2), mcable_list{{0,0.1,0.4}}));
EXPECT_TRUE(region_eq(mp, radius_gt(reg_c_, 2), mcable_list{{0,0.55,0.7},{2,0,0.5},{3,0.1,0.375},{3,0.9,1}}));
EXPECT_TRUE(region_eq(mp, radius_gt(reg_d_, 2), mcable_list{{0,0.55,0.7},{2,0,0.5},{3,0.1,0.375},{3,0.75,0.9}}));
// Test some more interesting intersections and unions.
// 123456789 123456789
// |---------|---------| lhs
// | ----- | --- | rhs
// | xxxxx | xxx | rand
// |xxxxxxxxx|xxxxxxxxx| ror
auto lhs = b13;
auto rhs = join(cable(1,.2,.7), cable(3,.3,.6));
auto rand = cl{{1,.2,.7}, {3,.3,.6}};
auto ror = cl{{1,.0,1.}, {3,.0,1.}};
EXPECT_TRUE(region_eq(mp, intersect(lhs, rhs), rand));
EXPECT_TRUE(region_eq(mp, join(lhs, rhs), ror));
// Assert communtativity
std::swap(lhs, rhs);
EXPECT_TRUE(region_eq(mp, intersect(lhs, rhs), rand));
EXPECT_TRUE(region_eq(mp, join(lhs, rhs), ror));
// 123456789 123456789
// | ----- | ---- | lhs
// | ----- | --- | rhs
// | xxxx | xx | rand
// | xxxxxx | xxxxx | ror
lhs = join(cable(1,.3,.8), cable(3,.1,.5));
rhs = join(cable(1,.2,.7), cable(3,.3,.6));
rand = cl{ {1,.3,.7}, {3,.3,.5}};
ror = cl{ {1,.2,.8}, {3,.1,.6}};
EXPECT_TRUE(region_eq(mp, intersect(lhs, rhs), rand));
EXPECT_TRUE(region_eq(mp, join(lhs, rhs), ror));
// Assert communtativity
std::swap(lhs, rhs);
EXPECT_TRUE(region_eq(mp, intersect(lhs, rhs), rand));
EXPECT_TRUE(region_eq(mp, join(lhs, rhs), ror));
// 123456789 123456789
// | -- - | --- --- | lhs
// | ----- | --- | rhs
// | x x | x x | rand
// | xxxxxx | xxxxxxx | ror
lhs = join(cable(1,.1,.3), cable(1,.4,.5), cable(3,.1,.4), cable(3,.5,.9));
rhs = join(cable(1,.2,.7), cable(3,.3,.6));
rand = cl{ {1,.2,.3}, {1,.4,.5}, {3,.3,.4}, {3,.5,.6}};
ror = cl{ {1,.1,.7}, {3,.1,.9}};
EXPECT_TRUE(region_eq(mp, intersect(lhs, rhs), rand));
EXPECT_TRUE(region_eq(mp, join(lhs, rhs), ror));
// Assert communtativity
std::swap(lhs, rhs);
EXPECT_TRUE(region_eq(mp, intersect(lhs, rhs), rand));
EXPECT_TRUE(region_eq(mp, join(lhs, rhs), ror));
// b1
// 123456789
// |----- | lhs
// |----- | rhs
// |xxxxx | rand
// |xxxxx | ror
lhs = cable(1,0,.5);
rhs = cable(1,0,.5);
rand = cl{{1,0,.5}};
ror = cl{{1,0,.5}};
EXPECT_TRUE(region_eq(mp, intersect(lhs, rhs), rand));
EXPECT_TRUE(region_eq(mp, join(lhs, rhs), ror));
// b3
// 123456789
// |----- | lhs
// |----- | rhs
// |xxxxx | rand
// |xxxxx | ror
lhs = cable(3,0,.5);
rhs = cable(3,0,.5);
rand = cl{{3,0,.5}};
ror = cl{{3,0,.5}};
EXPECT_TRUE(region_eq(mp, intersect(lhs, rhs), rand));
EXPECT_TRUE(region_eq(mp, join(lhs, rhs), ror));
// b0 b1
// 123456789 123456789
// |xxxxx | | lhs
// | |xxxxx | rhs
// x | | rand
// |xxxxx |xxxxx | ror
lhs = cable(0,0,.5);
rhs = cable(1,0,.5);
rand = cl{{0,0,0}};
ror = cl{{0,0,.5},{1,0,.5}};
EXPECT_TRUE(region_eq(mp, intersect(lhs, rhs), rand));
EXPECT_TRUE(region_eq(mp, join(lhs, rhs), ror));
// Assert communtativity
std::swap(lhs, rhs);
EXPECT_TRUE(region_eq(mp, intersect(lhs, rhs), rand));
EXPECT_TRUE(region_eq(mp, join(lhs, rhs), ror));
// b2 b3
// 123456789 123456789
// |xxxxx | | lhs
// | |xxxxx | rhs
// x | | rand
// |xxxxx |xxxxx | ror
lhs = cable(2,0,.5);
rhs = cable(3,0,.5);
rand = cl{{1,1,1}};
ror = cl{{2,0,.5},{3,0,.5}};
EXPECT_TRUE(region_eq(mp, intersect(lhs, rhs), rand));
EXPECT_TRUE(region_eq(mp, join(lhs, rhs), ror));
// Assert communtativity
std::swap(lhs, rhs);
EXPECT_TRUE(region_eq(mp, intersect(lhs, rhs), rand));
EXPECT_TRUE(region_eq(mp, join(lhs, rhs), ror));
// b0 b3
// 123456789 123456789
// |xxxxx |xxxxx | lhs
// |xxxxxxx |xxx | rhs
// |xxxxx |xxx | rand
// |xxxxxxx |xxxxx | ror
lhs = join(cable(0,0,.5), cable(3,0,.5));
rhs = join(cable(0,0,.7), cable(3,0,.3));
rand = cl{{0,0,.5},{3,0,.3}};
ror = cl{{0,0,.7},{3,0,.5}};
EXPECT_TRUE(region_eq(mp, intersect(lhs, rhs), rand));
EXPECT_TRUE(region_eq(mp, join(lhs, rhs), ror));
// Assert communtativity
std::swap(lhs, rhs);
EXPECT_TRUE(region_eq(mp, intersect(lhs, rhs), rand));
EXPECT_TRUE(region_eq(mp, join(lhs, rhs), ror));
}
}
TEST(region, thingify_complex_morphologies) {
using pvec = std::vector<msize_t>;
using svec = std::vector<msample>;
{
pvec parents = {mnpos, 0, 1, 0, 3, 4, 5, 5, 7, 7, 4, 10};
svec samples = {
{{ 0, 0, 0, 2}, 3}, //0
{{ 10, 0, 0, 2}, 3}, //1
{{100, 0, 0, 2}, 3}, //2
{{ 0, 10, 0, 2}, 3}, //3
{{ 0,100, 0, 2}, 3}, //4
{{100,100, 0, 2}, 3}, //5
{{200,100, 0, 2}, 3}, //6
{{100,200, 0, 2}, 3}, //7
{{200,200, 0, 2}, 3}, //8
{{100,300, 0, 2}, 3}, //9
{{ 0,200, 0, 2}, 3}, //10
{{ 0,300, 0, 2}, 3}, //11
};
sample_tree sm(samples, parents);
auto m = morphology(sm, false);
{
mprovider mp(m);
using reg::cable;
using ls::most_distal;
using ls::most_proximal;
auto reg_a_ = join(cable(0,0.1,0.4), cable(0,0,0.9), cable(1,0.1,0.4));
auto reg_b_ = join(cable(0,0.1,0.4), cable(0,0,0.9), cable(1,0.1,0.4), cable(1,0.2,0.5));
auto reg_c_ = join(cable(0,0.1,0.4), cable(0,0,0.9), cable(1,0.1,0.4), cable(2,0.2,0.5));
auto reg_d_ = join(cable(2,0,0.9), cable(3,0.1,0.1), cable(4,0.1,0.6));
auto reg_e_ = join(cable(2,0,0.9), cable(4,0.1,0.1), cable(5,0.1,0.6));
auto reg_f_ = join(cable(7,0,1), cable(2,0,0.9), cable(4,0.1,0.1), cable(5,0.1,0.6));
EXPECT_TRUE(mlocationlist_eq(thingify(most_distal(reg_a_), mp), mlocation_list{{0,0.9},{1,0.4}}));
EXPECT_TRUE(mlocationlist_eq(thingify(most_distal(reg_b_), mp), mlocation_list{{0,0.9},{1,0.5}}));
EXPECT_TRUE(mlocationlist_eq(thingify(most_distal(reg_c_), mp), mlocation_list{{0,0.9},{2,0.5}}));
EXPECT_TRUE(mlocationlist_eq(thingify(most_distal(reg_d_), mp), mlocation_list{{3,0.1},{4,0.6}}));
EXPECT_TRUE(mlocationlist_eq(thingify(most_distal(reg_e_), mp), mlocation_list{{5,0.6}}));
EXPECT_TRUE(mlocationlist_eq(thingify(most_distal(reg_f_), mp), mlocation_list{{5,0.6},{7,1}}));
EXPECT_TRUE(mlocationlist_eq(thingify(most_proximal(reg_a_), mp), mlocation_list{{0,0}}));
EXPECT_TRUE(mlocationlist_eq(thingify(most_proximal(reg_b_), mp), mlocation_list{{0,0}}));
EXPECT_TRUE(mlocationlist_eq(thingify(most_proximal(reg_c_), mp), mlocation_list{{0,0}}));
EXPECT_TRUE(mlocationlist_eq(thingify(most_proximal(reg_d_), mp), mlocation_list{{1,1}}));
EXPECT_TRUE(mlocationlist_eq(thingify(most_proximal(reg_e_), mp), mlocation_list{{1,1}}));
EXPECT_TRUE(mlocationlist_eq(thingify(most_proximal(reg_f_), mp), mlocation_list{{1,1}}));
}
}
{
pvec parents = {mnpos, 0, 1, 1, 2, 3, 0, 6, 7, 8, 7};
svec samples = {
{{ 0, 10, 10, 1}, 1},
{{ 0, 30, 30, 1}, 2},
{{ 0, 60,-20, 1}, 2},
{{ 0, 90, 70, 1}, 2},
{{ 0, 80,-10, 1}, 2},
{{ 0,100,-40, 1}, 2},
{{ 0,-50,-50, 1}, 2},
{{ 0, 20,-30, 2}, 2},
{{ 0, 40,-80, 2}, 2},
{{ 0,-30,-80, 3}, 2},
{{ 0, 90,-70, 5}, 2}
};
sample_tree sm(samples, parents);
// Without spherical root
mprovider mp(morphology(sm, false));
using reg::all;
using reg::nil;
using reg::z_dist_from_root_lt;
using reg::z_dist_from_root_le;
using reg::z_dist_from_root_gt;
using reg::z_dist_from_root_ge;
using reg::cable;
// Test projection
EXPECT_TRUE(region_eq(mp, z_dist_from_root_lt(0), nil()));
EXPECT_TRUE(region_eq(mp, z_dist_from_root_gt(0), all()));
EXPECT_TRUE(region_eq(mp, z_dist_from_root_le(100), all()));
EXPECT_TRUE(region_eq(mp, z_dist_from_root_gt(100), nil()));
EXPECT_TRUE(region_eq(mp, z_dist_from_root_le(90), all()));
EXPECT_TRUE(region_eq(mp, z_dist_from_root_gt(90), nil()));
EXPECT_TRUE(region_eq(mp, z_dist_from_root_lt(20),
mcable_list{{0,0,1},
{1,0,0.578250901781922829},
{2,0.61499300915417734997,0.8349970039232188642},
{3,0,0.179407353580315756}}));
EXPECT_TRUE(region_eq(mp, z_dist_from_root_ge(20),
mcable_list{{0,1,1},
{1,0.578250901781922829,1},
{2,0,0.61499300915417734997},
{2,0.8349970039232188642,1},
{3,0.179407353580315756,1},
{4,0,1},
{5,0,1}}));
EXPECT_TRUE(region_eq(mp, join(z_dist_from_root_lt(20), z_dist_from_root_ge(20)), all()));
EXPECT_TRUE(region_eq(mp, z_dist_from_root_le(50),
mcable_list{{0,0,1},
{1,0,1},
{2,0,0.2962417607888518767},
{2,0.4499900130773962142,1},
{3,0,0.4485183839507893905},
{3,0.7691110303704736343,1},
{4,0,0.0869615364994152821},
{5,0,0.25}}));
EXPECT_TRUE(region_eq(mp, z_dist_from_root_gt(50),
mcable_list{{2,0.2962417607888518767,0.4499900130773962142},
{3,0.4485183839507893905,0.7691110303704736343},
{4,0.0869615364994152821,1},
{5,0.25,1}}));
EXPECT_TRUE(region_eq(mp, join(z_dist_from_root_le(50), z_dist_from_root_gt(50)), all()));
}
}
|
/*=========================================================================
Program: Visualization Toolkit
Module: vtkRectilinearSynchronizedTemplates.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkRectilinearSynchronizedTemplates.h"
#include "vtkCellArray.h"
#include "vtkCellData.h"
#include "vtkCharArray.h"
#include "vtkDoubleArray.h"
#include "vtkFloatArray.h"
#include "vtkIdListCollection.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkIntArray.h"
#include "vtkLongArray.h"
#include "vtkMath.h"
#include "vtkObjectFactory.h"
#include "vtkPointData.h"
#include "vtkPolyData.h"
#include "vtkRectilinearGrid.h"
#include "vtkShortArray.h"
#include "vtkStreamingDemandDrivenPipeline.h"
#include "vtkStructuredPoints.h"
#include "vtkSynchronizedTemplates3D.h"
#include "vtkUnsignedCharArray.h"
#include "vtkUnsignedIntArray.h"
#include "vtkUnsignedLongArray.h"
#include "vtkUnsignedShortArray.h"
#include "vtkPolygonBuilder.h"
#include "vtkSmartPointer.h"
#include <cmath>
vtkStandardNewMacro(vtkRectilinearSynchronizedTemplates);
//----------------------------------------------------------------------------
// Description:
// Construct object with initial scalar range (0,1) and single contour value
// of 0.0. The ImageRange are set to extract the first k-plane.
vtkRectilinearSynchronizedTemplates::vtkRectilinearSynchronizedTemplates()
{
this->ContourValues = vtkContourValues::New();
this->ComputeNormals = 1;
this->ComputeGradients = 0;
this->ComputeScalars = 1;
this->GenerateTriangles = 1;
this->ArrayComponent = 0;
// by default process active point scalars
this->SetInputArrayToProcess(0,0,0,vtkDataObject::FIELD_ASSOCIATION_POINTS,
vtkDataSetAttributes::SCALARS);
}
//----------------------------------------------------------------------------
vtkRectilinearSynchronizedTemplates::~vtkRectilinearSynchronizedTemplates()
{
this->ContourValues->Delete();
}
//----------------------------------------------------------------------------
// Overload standard modified time function. If contour values are modified,
// then this object is modified as well.
vtkMTimeType vtkRectilinearSynchronizedTemplates::GetMTime()
{
vtkMTimeType mTime=this->Superclass::GetMTime();
vtkMTimeType mTime2=this->ContourValues->GetMTime();
mTime = ( mTime2 > mTime ? mTime2 : mTime );
return mTime;
}
//----------------------------------------------------------------------------
static void vtkRectilinearSynchronizedTemplatesInitializeOutput(
int *ext, vtkRectilinearGrid *input, vtkPolyData *o, vtkFloatArray *scalars,
vtkFloatArray *normals, vtkFloatArray *gradients, vtkDataArray *inScalars)
{
vtkPoints *newPts;
vtkCellArray *newPolys;
long estimatedSize;
estimatedSize = (int) pow ((double)
((ext[1]-ext[0]+1)*(ext[3]-ext[2]+1)*(ext[5]-ext[4]+1)), .75);
if (estimatedSize < 1024)
{
estimatedSize = 1024;
}
newPts = vtkPoints::New();
newPts->Allocate(estimatedSize,estimatedSize);
newPolys = vtkCellArray::New();
newPolys->Allocate(newPolys->EstimateSize(estimatedSize,3));
o->GetPointData()->CopyAllOn();
// It is more efficient to just create the scalar array
// rather than redundantly interpolate the scalars.
if (input->GetPointData()->GetScalars() == inScalars)
{
o->GetPointData()->CopyScalarsOff();
}
else
{
o->GetPointData()->CopyFieldOff(inScalars->GetName());
}
if (normals)
{
normals->SetNumberOfComponents(3);
normals->Allocate(3*estimatedSize,3*estimatedSize/2);
normals->SetName("Normals");
}
if (gradients)
{
gradients->SetNumberOfComponents(3);
gradients->Allocate(3*estimatedSize,3*estimatedSize/2);
gradients->SetName("Gradients");
}
if (scalars)
{
// A temporary name.
scalars->SetName("Scalars");
}
o->GetPointData()->InterpolateAllocate(input->GetPointData(),
estimatedSize,estimatedSize/2);
o->GetCellData()->CopyAllocate(input->GetCellData(),
estimatedSize,estimatedSize/2);
o->SetPoints(newPts);
newPts->Delete();
o->SetPolys(newPolys);
newPolys->Delete();
}
//----------------------------------------------------------------------------
// Calculate the gradient using central difference.
template <class T>
void vtkRSTComputePointGradient(int i, int j, int k, T *s, int *inExt,
int xInc, int yInc, int zInc,
double *spacing, double n[3])
{
double sp, sm;
// x-direction
if ( i == inExt[0] )
{
sp = *(s+xInc);
sm = *s;
n[0] = (sp - sm) / spacing[1];
}
else if ( i == inExt[1] )
{
sp = *s;
sm = *(s-xInc);
n[0] = (sp - sm) / spacing[0];
}
else
{
sp = *(s+xInc);
sm = *(s-xInc);
n[0] = (sp - sm) / (spacing[0]+spacing[1]);
}
// y-direction
if ( j == inExt[2] )
{
sp = *(s+yInc);
sm = *s;
n[1] = (sp - sm) / spacing[3];
}
else if ( j == inExt[3] )
{
sp = *s;
sm = *(s-yInc);
n[1] = (sp - sm) / spacing[2];
}
else
{
sp = *(s+yInc);
sm = *(s-yInc);
n[1] = (sp - sm) / (spacing[2]+spacing[3]);
}
// z-direction
if ( k == inExt[4] )
{
sp = *(s+zInc);
sm = *s;
n[2] = (sp - sm) / spacing[5];
}
else if ( k == inExt[5] )
{
sp = *s;
sm = *(s-zInc);
n[2] = (sp - sm) / spacing[4];
}
else
{
sp = *(s+zInc);
sm = *(s-zInc);
n[2] = (sp - sm) / (spacing[4]+spacing[5]);
}
}
//----------------------------------------------------------------------------
#define VTK_RECT_CSP3PA(i2,j2,k2,s) \
if (NeedGradients) \
{ \
if (!g0) \
{ \
self->ComputeSpacing(data, i, j, k, exExt, spacing); \
vtkRSTComputePointGradient(i, j, k, s0, inExt, xInc, yInc, zInc, spacing, n0); \
g0 = 1; \
} \
self->ComputeSpacing(data, i2, j2, k2, exExt, spacing); \
vtkRSTComputePointGradient(i2, j2, k2, s, inExt, xInc, yInc, zInc, spacing, n1); \
for (jj=0; jj<3; jj++) \
{ \
n[jj] = n0[jj] + t * (n1[jj] - n0[jj]); \
} \
if (ComputeGradients) \
{ \
newGradients->InsertNextTuple(n); \
} \
if (ComputeNormals) \
{ \
vtkMath::Normalize(n); \
n[0] = -n[0]; n[1] = -n[1]; n[2] = -n[2]; \
newNormals->InsertNextTuple(n); \
} \
} \
if (ComputeScalars) \
{ \
newScalars->InsertNextTuple(&value); \
}
//----------------------------------------------------------------------------
//
// Contouring filter specialized for images
//
template <class T>
void ContourRectilinearGrid(vtkRectilinearSynchronizedTemplates *self, int *exExt,
vtkRectilinearGrid *data, vtkPolyData *output, T *ptr,
vtkDataArray *inScalars, bool outputTriangles)
{
int *inExt = data->GetExtent();
int xdim = exExt[1] - exExt[0] + 1;
int ydim = exExt[3] - exExt[2] + 1;
double *values = self->GetValues();
int numContours = self->GetNumberOfContours();
T *inPtrX, *inPtrY, *inPtrZ;
T *s0, *s1, *s2, *s3;
int xMin, xMax, yMin, yMax, zMin, zMax;
int xInc, yInc, zInc;
int *isect1Ptr, *isect2Ptr;
double y, z, t;
int i, j, k;
int zstep, yisectstep;
int offsets[12];
int ComputeNormals = self->GetComputeNormals();
int ComputeGradients = self->GetComputeGradients();
int ComputeScalars = self->GetComputeScalars();
int NeedGradients = ComputeGradients || ComputeNormals;
double n[3], n0[3], n1[3];
int jj, g0;
int *tablePtr;
int idx, vidx;
double x[3], xz[3];
int v0, v1, v2, v3;
vtkIdType ptIds[3];
double value;
// We need to know the edgePointId's for interpolating attributes.
int edgePtId, inCellId, outCellId;
vtkPointData *inPD = data->GetPointData();
vtkCellData *inCD = data->GetCellData();
vtkPointData *outPD = output->GetPointData();
vtkCellData *outCD = output->GetCellData();
// Use to be arguments
vtkFloatArray *newScalars = NULL;
vtkFloatArray *newNormals = NULL;
vtkFloatArray *newGradients = NULL;
vtkPoints *newPts;
vtkCellArray *newPolys;
ptr += self->GetArrayComponent();
vtkDataArray *xCoords = data->GetXCoordinates();
vtkDataArray *yCoords = data->GetYCoordinates();
vtkDataArray *zCoords = data->GetZCoordinates();
double x1, x2, y2, z2;
double spacing[6];
vtkPolygonBuilder polyBuilder;
vtkSmartPointer<vtkIdListCollection> polys =
vtkSmartPointer<vtkIdListCollection>::New();
if (ComputeScalars)
{
newScalars = vtkFloatArray::New();
}
if (ComputeNormals)
{
newNormals = vtkFloatArray::New();
}
if (ComputeGradients)
{
newGradients = vtkFloatArray::New();
}
vtkRectilinearSynchronizedTemplatesInitializeOutput(exExt, data, output,
newScalars, newNormals, newGradients, inScalars);
newPts = output->GetPoints();
newPolys = output->GetPolys();
// this is an exploded execute extent.
xMin = exExt[0];
xMax = exExt[1];
yMin = exExt[2];
yMax = exExt[3];
zMin = exExt[4];
zMax = exExt[5];
// increments to move through scalars Compute these ourself because
// we may be contouring an array other than scalars.
xInc = inScalars->GetNumberOfComponents();
yInc = xInc*(inExt[1]-inExt[0]+1);
zInc = yInc*(inExt[3]-inExt[2]+1);
// Kens increments, probably to do with edge array
zstep = xdim*ydim;
yisectstep = xdim*3;
// compute offsets probably how to get to the edges in the edge array.
offsets[0] = -xdim*3;
offsets[1] = -xdim*3 + 1;
offsets[2] = -xdim*3 + 2;
offsets[3] = -xdim*3 + 4;
offsets[4] = -xdim*3 + 5;
offsets[5] = 0;
offsets[6] = 2;
offsets[7] = 5;
offsets[8] = (zstep - xdim)*3;
offsets[9] = (zstep - xdim)*3 + 1;
offsets[10] = (zstep - xdim)*3 + 4;
offsets[11] = zstep*3;
// allocate storage array
int *isect1 = new int [xdim*ydim*3*2];
// set impossible edges to -1
for (i = 0; i < ydim; i++)
{
isect1[(i+1)*xdim*3-3] = -1;
isect1[(i+1)*xdim*3*2-3] = -1;
}
for (i = 0; i < xdim; i++)
{
isect1[((ydim-1)*xdim + i)*3 + 1] = -1;
isect1[((ydim-1)*xdim + i)*3*2 + 1] = -1;
}
// for each contour
for (vidx = 0; vidx < numContours; vidx++)
{
value = values[vidx];
inPtrZ = ptr;
s2 = inPtrZ;
//==================================================================
for (k = zMin; k <= zMax; k++)
{
self->UpdateProgress((double)vidx/numContours +
(k-zMin)/((zMax - zMin+1.0)*numContours));
z = zCoords->GetComponent(k-inExt[4], 0);
x[2] = z;
// swap the buffers
if (k%2)
{
offsets[8] = (zstep - xdim)*3;
offsets[9] = (zstep - xdim)*3 + 1;
offsets[10] = (zstep - xdim)*3 + 4;
offsets[11] = zstep*3;
isect1Ptr = isect1;
isect2Ptr = isect1 + xdim*ydim*3;
}
else
{
offsets[8] = (-zstep - xdim)*3;
offsets[9] = (-zstep - xdim)*3 + 1;
offsets[10] = (-zstep - xdim)*3 + 4;
offsets[11] = -zstep*3;
isect1Ptr = isect1 + xdim*ydim*3;
isect2Ptr = isect1;
}
inPtrY = inPtrZ;
for (j = yMin; j <= yMax; j++)
{
// Should not impact performance here/
edgePtId = (j-inExt[2])*yInc + (k-inExt[4])*zInc;
// Increments are different for cells.
// Since the cells are not contoured until the second row of templates,
// subtract 1 from i,j,and k. Note: first cube is formed when i=0, j=1, and k=1.
inCellId = (xMin-inExt[0]) + (inExt[1]-inExt[0])*( (j-inExt[2]-1) + (k-inExt[4]-1)*(inExt[3]-inExt[2]) );
y = yCoords->GetComponent(j-inExt[2], 0);
xz[1] = y;
s1 = inPtrY;
v1 = (*s1 < value ? 0 : 1);
inPtrX = inPtrY;
for (i = xMin; i <= xMax; i++)
{
s0 = s1;
v0 = v1;
// this flag keeps up from computing gradient for grid point 0 twice.
g0 = 0;
*isect2Ptr = -1;
*(isect2Ptr + 1) = -1;
*(isect2Ptr + 2) = -1;
if (i < xMax)
{
s1 = (inPtrX + xInc);
v1 = (*s1 < value ? 0 : 1);
if (v0 ^ v1)
{
// watch for degenerate points
if (*s0 == value)
{
if (i > xMin && *(isect2Ptr-3) > -1)
{
*isect2Ptr = *(isect2Ptr-3);
}
else if (j > yMin && *(isect2Ptr - yisectstep + 1) > -1)
{
*isect2Ptr = *(isect2Ptr - yisectstep + 1);
}
else if (k > zMin && *(isect1Ptr+2) > -1)
{
*isect2Ptr = *(isect1Ptr+2);
}
}
else if (*s1 == value)
{
if (j > yMin && *(isect2Ptr - yisectstep +4) > -1)
{
*isect2Ptr = *(isect2Ptr - yisectstep + 4);
}
else if (k > zMin && i < xMax && *(isect1Ptr + 5) > -1)
{
*isect2Ptr = *(isect1Ptr + 5);
}
}
// if the edge has not been set yet then it is a new point
if (*isect2Ptr == -1)
{
t = (value - (double)(*s0)) / ((double)(*s1) - (double)(*s0));
x1 = xCoords->GetComponent(i-inExt[0], 0);
x2 = xCoords->GetComponent(i-inExt[0]+1, 0);
x[0] = x1 + t*(x2-x1);
x[1] = y;
*isect2Ptr = newPts->InsertNextPoint(x);
VTK_RECT_CSP3PA(i+1,j,k,s1);
outPD->InterpolateEdge(inPD, *isect2Ptr, edgePtId, edgePtId+1, t);
}
}
}
if (j < yMax)
{
s2 = (inPtrX + yInc);
v2 = (*s2 < value ? 0 : 1);
if (v0 ^ v2)
{
// watch for degen points
if (*s0 == value)
{
if (*isect2Ptr > -1)
{
*(isect2Ptr + 1) = *isect2Ptr;
}
else if (i > xMin && *(isect2Ptr-3) > -1)
{
*(isect2Ptr + 1) = *(isect2Ptr-3);
}
else if (j > yMin && *(isect2Ptr - yisectstep + 1) > -1)
{
*(isect2Ptr + 1) = *(isect2Ptr - yisectstep + 1);
}
else if (k > zMin && *(isect1Ptr+2) > -1)
{
*(isect2Ptr + 1) = *(isect1Ptr+2);
}
}
else if (*s2 == value && k > zMin && *(isect1Ptr + yisectstep + 2) > -1)
{
*(isect2Ptr+1) = *(isect1Ptr + yisectstep + 2);
}
// if the edge has not been set yet then it is a new point
if (*(isect2Ptr + 1) == -1)
{
t = (value - (double)(*s0)) / ((double)(*s2) - (double)(*s0));
x[0] = xCoords->GetComponent(i-inExt[0], 0);
y2 = yCoords->GetComponent(j-inExt[2]+1, 0);
x[1] = y + t*(y2-y);
*(isect2Ptr + 1) = newPts->InsertNextPoint(x);
VTK_RECT_CSP3PA(i,j+1,k,s2);
outPD->InterpolateEdge(inPD, *(isect2Ptr+1), edgePtId, edgePtId+yInc, t);
}
}
}
if (k < zMax)
{
s3 = (inPtrX + zInc);
v3 = (*s3 < value ? 0 : 1);
if (v0 ^ v3)
{
// watch for degen points
if (*s0 == value)
{
if (*isect2Ptr > -1)
{
*(isect2Ptr + 2) = *isect2Ptr;
}
else if (*(isect2Ptr+1) > -1)
{
*(isect2Ptr + 2) = *(isect2Ptr+1);
}
else if (i > xMin && *(isect2Ptr-3) > -1)
{
*(isect2Ptr + 2) = *(isect2Ptr-3);
}
else if (j > yMin && *(isect2Ptr - yisectstep + 1) > -1)
{
*(isect2Ptr + 2) = *(isect2Ptr - yisectstep + 1);
}
else if (k > zMin && *(isect1Ptr+2) > -1)
{
*(isect2Ptr + 2) = *(isect1Ptr+2);
}
}
if (*(isect2Ptr + 2) == -1)
{
t = (value - (double)(*s0)) / ((double)(*s3) - (double)(*s0));
xz[0] = xCoords->GetComponent(i-inExt[0], 0);
z2 = zCoords->GetComponent(k-inExt[4]+1, 0);
xz[2] = z + t*(z2-z);
*(isect2Ptr + 2) = newPts->InsertNextPoint(xz);
VTK_RECT_CSP3PA(i,j,k+1,s3);
outPD->InterpolateEdge(inPD, *(isect2Ptr+2), edgePtId, edgePtId+zInc, t);
}
}
}
// To keep track of ids for interpolating attributes.
++edgePtId;
// now add any polys that need to be added
// basically look at the isect values,
// form an index and lookup the polys
if (j > yMin && i < xMax && k > zMin)
{
idx = (v0 ? 4096 : 0);
idx = idx + (*(isect1Ptr - yisectstep) > -1 ? 2048 : 0);
idx = idx + (*(isect1Ptr -yisectstep +1) > -1 ? 1024 : 0);
idx = idx + (*(isect1Ptr -yisectstep +2) > -1 ? 512 : 0);
idx = idx + (*(isect1Ptr -yisectstep +4) > -1 ? 256 : 0);
idx = idx + (*(isect1Ptr -yisectstep +5) > -1 ? 128 : 0);
idx = idx + (*(isect1Ptr) > -1 ? 64 : 0);
idx = idx + (*(isect1Ptr + 2) > -1 ? 32 : 0);
idx = idx + (*(isect1Ptr + 5) > -1 ? 16 : 0);
idx = idx + (*(isect2Ptr -yisectstep) > -1 ? 8 : 0);
idx = idx + (*(isect2Ptr -yisectstep +1) > -1 ? 4 : 0);
idx = idx + (*(isect2Ptr -yisectstep +4) > -1 ? 2 : 0);
idx = idx + (*(isect2Ptr) > -1 ? 1 : 0);
tablePtr = VTK_SYNCHRONIZED_TEMPLATES_3D_TABLE_2
+ VTK_SYNCHRONIZED_TEMPLATES_3D_TABLE_1[idx];
if (!outputTriangles)
{
polyBuilder.Reset();
}
while (*tablePtr != -1)
{
ptIds[0] = *(isect1Ptr + offsets[*tablePtr]);
tablePtr++;
ptIds[1] = *(isect1Ptr + offsets[*tablePtr]);
tablePtr++;
ptIds[2] = *(isect1Ptr + offsets[*tablePtr]);
tablePtr++;
if (ptIds[0] != ptIds[1] &&
ptIds[0] != ptIds[2] &&
ptIds[1] != ptIds[2])
{
if(outputTriangles)
{
outCellId = newPolys->InsertNextCell(3,ptIds);
outCD->CopyData(inCD, inCellId, outCellId);
}
else
{
polyBuilder.InsertTriangle(ptIds);
}
}
}
if(!outputTriangles)
{
polyBuilder.GetPolygons(polys);
int nPolys = polys->GetNumberOfItems();
for (int polyId = 0; polyId < nPolys; ++polyId)
{
vtkIdList* poly = polys->GetItem(polyId);
if(poly->GetNumberOfIds()!=0)
{
outCellId = newPolys->InsertNextCell(poly);
outCD->CopyData(inCD, inCellId, outCellId);
}
poly->Delete();
}
polys->RemoveAllItems();
}
}
inPtrX += xInc;
isect2Ptr += 3;
isect1Ptr += 3;
// To keep track of ids for copying cell attributes.
++inCellId;
}
inPtrY += yInc;
}
inPtrZ += zInc;
}
}
delete [] isect1;
if (newScalars)
{
// Lets set the name of the scalars here.
if (inScalars)
{
newScalars->SetName(inScalars->GetName());
}
idx = output->GetPointData()->AddArray(newScalars);
output->GetPointData()->SetActiveAttribute(idx, vtkDataSetAttributes::SCALARS);
newScalars->Delete();
newScalars = NULL;
}
if (newGradients)
{
output->GetPointData()->SetVectors(newGradients);
newGradients->Delete();
newGradients = NULL;
}
if (newNormals)
{
output->GetPointData()->SetNormals(newNormals);
newNormals->Delete();
newNormals = NULL;
}
}
//----------------------------------------------------------------------------
//
// Contouring filter specialized for images (or slices from images)
//
int vtkRectilinearSynchronizedTemplates::RequestData(
vtkInformation *vtkNotUsed(request),
vtkInformationVector **inputVector,
vtkInformationVector *outputVector)
{
// get the info objects
vtkInformation *inInfo = inputVector[0]->GetInformationObject(0);
vtkInformation *outInfo = outputVector->GetInformationObject(0);
// get the input and output
vtkRectilinearGrid *data = vtkRectilinearGrid::SafeDownCast(
inInfo->Get(vtkDataObject::DATA_OBJECT()));
vtkPolyData *output = vtkPolyData::SafeDownCast(
outInfo->Get(vtkDataObject::DATA_OBJECT()));
void *ptr;
vtkDataArray *inScalars;
vtkDebugMacro(<< "Executing 3D structured contour");
//
// Check data type and execute appropriate function
//
inScalars = this->GetInputArrayToProcess(0,inputVector);
if (inScalars == NULL)
{
vtkErrorMacro("No scalars for contouring.");
return 1;
}
int numComps = inScalars->GetNumberOfComponents();
if (this->ArrayComponent >= numComps)
{
vtkErrorMacro("Scalars have " << numComps << " components. "
"ArrayComponent must be smaller than " << numComps);
return 1;
}
int* inExt = data->GetExtent();
ptr = this->GetScalarsForExtent(inScalars, inExt, data);
int exExt[6];
inInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_EXTENT(), exExt);
for (int i=0; i<3; i++)
{
if (inExt[2*i] > exExt[2*i])
{
exExt[2*i] = inExt[2*i];
}
if (inExt[2*i+1] < exExt[2*i+1])
{
exExt[2*i+1] = inExt[2*i+1];
}
}
switch (inScalars->GetDataType())
{
vtkTemplateMacro(
ContourRectilinearGrid(this, exExt, data,
output, (VTK_TT *)ptr, inScalars,this->GenerateTriangles!=0));
}
return 1;
}
//----------------------------------------------------------------------------
int vtkRectilinearSynchronizedTemplates::RequestUpdateExtent(
vtkInformation *vtkNotUsed(request),
vtkInformationVector **inputVector,
vtkInformationVector *outputVector)
{
// These require extra ghost levels
if (this->ComputeGradients || this->ComputeNormals)
{
vtkInformation *inInfo = inputVector[0]->GetInformationObject(0);
vtkInformation *outInfo = outputVector->GetInformationObject(0);
int ghostLevels;
ghostLevels =
outInfo->Get(
vtkStreamingDemandDrivenPipeline::UPDATE_NUMBER_OF_GHOST_LEVELS());
inInfo->Set(vtkStreamingDemandDrivenPipeline::UPDATE_NUMBER_OF_GHOST_LEVELS(),
ghostLevels + 1);
}
return 1;
}
//----------------------------------------------------------------------------
void* vtkRectilinearSynchronizedTemplates::GetScalarsForExtent(
vtkDataArray *array, int extent[6], vtkRectilinearGrid *input)
{
if ( ! array )
{
return NULL;
}
int increments[3], iExt[6], idx;
input->GetExtent(iExt);
for (idx = 0; idx < 3; idx++)
{
if (extent[idx*2] < iExt[idx*2] ||
extent[idx*2] > iExt[idx*2+1])
{
vtkErrorMacro("requested extent not in input's extent");
return NULL;
}
}
increments[0] = array->GetNumberOfComponents();
increments[1] = increments[0] * (iExt[1]-iExt[0]+1);
increments[2] = increments[1] * (iExt[3]-iExt[2]+1);
idx = (extent[0] - iExt[0]) * increments[0] +
(extent[2] - iExt[2]) * increments[1] +
(extent[4] - iExt[4]) * increments[2];
if (idx < 0 || idx > array->GetMaxId())
{
vtkErrorMacro("computed coordinate outside of array bounds");
return NULL;
}
return array->GetVoidPointer(idx);
}
//----------------------------------------------------------------------------
void vtkRectilinearSynchronizedTemplates::ComputeSpacing(
vtkRectilinearGrid *data, int i, int j, int k, int extent[6],
double spacing[6])
{
vtkDataArray *xCoords = data->GetXCoordinates();
vtkDataArray *yCoords = data->GetYCoordinates();
vtkDataArray *zCoords = data->GetZCoordinates();
spacing[0] = 0;
spacing[1] = 0;
spacing[2] = 0;
spacing[3] = 0;
spacing[4] = 0;
spacing[5] = 0;
if (i > extent[0])
{
spacing[0] = xCoords->GetComponent(i-extent[0], 0) -
xCoords->GetComponent(i-extent[0]-1, 0);
}
if (i < extent[1])
{
spacing[1] = xCoords->GetComponent(i-extent[0]+1, 0) -
xCoords->GetComponent(i-extent[0], 0);
}
if (j > extent[2])
{
spacing[2] = yCoords->GetComponent(j-extent[2], 0) -
yCoords->GetComponent(j-extent[2]-1, 0);
}
if (j < extent[3])
{
spacing[3] = yCoords->GetComponent(j-extent[2]+1, 0) -
yCoords->GetComponent(j-extent[2], 0);
}
if (k > extent[4])
{
spacing[4] = zCoords->GetComponent(k-extent[4], 0) -
zCoords->GetComponent(k-extent[4]-1, 0);
}
if (k < extent[5])
{
spacing[5] = zCoords->GetComponent(k-extent[4]+1, 0) -
zCoords->GetComponent(k-extent[4], 0);
}
}
//----------------------------------------------------------------------------
int vtkRectilinearSynchronizedTemplates::FillInputPortInformation(
int, vtkInformation *info)
{
info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkRectilinearGrid");
return 1;
}
//----------------------------------------------------------------------------
void vtkRectilinearSynchronizedTemplates::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
this->ContourValues->PrintSelf(os,indent.GetNextIndent());
os << indent << "Compute Normals: " << (this->ComputeNormals ? "On\n" : "Off\n");
os << indent << "Compute Gradients: " << (this->ComputeGradients ? "On\n" : "Off\n");
os << indent << "Compute Scalars: " << (this->ComputeScalars ? "On\n" : "Off\n");
os << indent << "ArrayComponent: " << this->ArrayComponent << endl;
}
|
/*
* Copyright (c) 2015 Oleg Morozenkov
*
* 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 "tgbot/TgTypeParser.h"
using namespace std;
using namespace boost::property_tree;
namespace TgBot {
Chat::Ptr TgTypeParser::parseJsonAndGetChat(const ptree& data) const {
auto result(make_shared<Chat>());
result->id = data.get<int64_t>("id");
string type = data.get<string>("type");
if (type == "private") {
result->type = Chat::Type::Private;
} else if (type == "group") {
result->type = Chat::Type::Group;
} else if (type == "supergroup") {
result->type = Chat::Type::Supergroup;
} else if (type == "channel") {
result->type = Chat::Type::Channel;
}
result->title = data.get("title", "");
result->username = data.get("username", "");
result->firstName = data.get("first_name", "");
result->lastName = data.get("last_name", "");
result->allMembersAreAdministrators = data.get<bool>("all_members_are_administrators", false);
result->photo = tryParseJson<ChatPhoto>(&TgTypeParser::parseJsonAndGetChatPhoto, data, "photo");
result->description = data.get("description", "");
result->inviteLink = data.get("invite_link", "");
result->pinnedMessage = tryParseJson<Message>(&TgTypeParser::parseJsonAndGetMessage, data, "pinned_message");
result->stickerSetName = data.get("sticker_set_name", "");
result->canSetStickerSet = data.get<bool>("can_set_sticker_set", false);
return result;
}
string TgTypeParser::parseChat(const Chat::Ptr& object) const {
if (!object) {
return "";
}
string result;
result += '{';
appendToJson(result, "id", object->id);
if (object->type == Chat::Type::Private) {
appendToJson(result, "type", "private");
} else if (object->type == Chat::Type::Group) {
appendToJson(result, "type", "group");
} else if (object->type == Chat::Type::Supergroup) {
appendToJson(result, "type", "supergroup");
} else if (object->type == Chat::Type::Channel) {
appendToJson(result, "type", "channel");
}
appendToJson(result, "title", object->title);
appendToJson(result, "username", object->username);
appendToJson(result, "first_name", object->firstName);
appendToJson(result, "last_name", object->lastName);
removeLastComma(result);
result += '}';
return result;
}
User::Ptr TgTypeParser::parseJsonAndGetUser(const ptree& data) const {
auto result(make_shared<User>());
result->id = data.get<int32_t>("id");
result->isBot = data.get<bool>("is_bot", false);
result->firstName = data.get<string>("first_name");
result->lastName = data.get("last_name", "");
result->username = data.get("username", "");
result->languageCode = data.get("language_code", "");
return result;
}
string TgTypeParser::parseUser(const User::Ptr& object) const {
if (!object) {
return "";
}
string result;
result += '{';
appendToJson(result, "id", object->id);
appendToJson(result, "is_bot", object->isBot);
appendToJson(result, "first_name", object->firstName);
appendToJson(result, "last_name", object->lastName);
appendToJson(result, "username", object->username);
appendToJson(result, "language_code", object->languageCode);
removeLastComma(result);
result += '}';
return result;
}
MessageEntity::Ptr TgTypeParser::parseJsonAndGetMessageEntity(const ptree& data) const{
auto result(make_shared<MessageEntity>());
result->type = data.get<string>("type");
result->offset = data.get<int32_t>("offset");
result->length = data.get<int32_t>("length");
result->url = data.get<string>("url", "");
result->user = tryParseJson<User>(&TgTypeParser::parseJsonAndGetUser, data, "user");
return result;
}
string TgTypeParser::parseMessageEntity(const MessageEntity::Ptr& object) const {
if (!object) {
return "";
}
string result;
result += '{';
appendToJson(result, "type", object->type);
appendToJson(result, "offset", object->offset);
appendToJson(result, "length", object->length);
appendToJson(result, "url", object->url);
appendToJson(result, "user", parseUser(object->user));
removeLastComma(result);
result += '}';
return result;
}
Message::Ptr TgTypeParser::parseJsonAndGetMessage(const ptree& data) const {
auto result(make_shared<Message>());
result->messageId = data.get<int32_t>("message_id");
result->from = tryParseJson<User>(&TgTypeParser::parseJsonAndGetUser, data, "from");
result->date = data.get<int32_t>("date");
result->chat = parseJsonAndGetChat(data.find("chat")->second);
result->forwardFrom = tryParseJson<User>(&TgTypeParser::parseJsonAndGetUser, data, "forward_from");
result->forwardFromChat = tryParseJson<Chat>(&TgTypeParser::parseJsonAndGetChat, data, "forward_from_chat");
result->forwardFromMessageId = data.get<int32_t>("forward_from_message_id", 0);
result->forwardSignature = data.get("forward_signature", "");
result->forwardDate = data.get("forward_date", 0);
result->replyToMessage = tryParseJson<Message>(&TgTypeParser::parseJsonAndGetMessage, data, "reply_to_message");
result->editDate = data.get<int32_t>("edit_date", 0);
result->authorSignature = data.get("author_signature", "");
result->text = data.get("text", "");
result->entities = parseJsonAndGetArray<MessageEntity>(&TgTypeParser::parseJsonAndGetMessageEntity, data, "entities");
result->captionEntities = parseJsonAndGetArray<MessageEntity>(&TgTypeParser::parseJsonAndGetMessageEntity, data, "caption_entities");
result->audio = tryParseJson<Audio>(&TgTypeParser::parseJsonAndGetAudio, data, "audio");
result->document = tryParseJson<Document>(&TgTypeParser::parseJsonAndGetDocument, data, "document");
result->animation = tryParseJson<Animation>(&TgTypeParser::parseJsonAndGetAnimation, data, "animation");
result->game = tryParseJson<Game>(&TgTypeParser::parseJsonAndGetGame, data, "game");
result->photo = parseJsonAndGetArray<PhotoSize>(&TgTypeParser::parseJsonAndGetPhotoSize, data, "photo");
result->sticker = tryParseJson<Sticker>(&TgTypeParser::parseJsonAndGetSticker, data, "sticker");
result->video = tryParseJson<Video>(&TgTypeParser::parseJsonAndGetVideo, data, "video");
result->contact = tryParseJson<Contact>(&TgTypeParser::parseJsonAndGetContact, data, "contact");
result->location = tryParseJson<Location>(&TgTypeParser::parseJsonAndGetLocation, data, "location");
result->newChatMember = tryParseJson<User>(&TgTypeParser::parseJsonAndGetUser, data, "new_chat_participant");
result->newChatMembers = parseJsonAndGetArray<User>(&TgTypeParser::parseJsonAndGetUser, data, "new_chat_members");
result->leftChatMember = tryParseJson<User>(&TgTypeParser::parseJsonAndGetUser, data, "left_chat_participant");
result->newChatTitle = data.get("new_chat_title", "");
result->newChatPhoto = parseJsonAndGetArray<PhotoSize>(&TgTypeParser::parseJsonAndGetPhotoSize, data, "new_chat_photo");
result->deleteChatPhoto = data.get("delete_chat_photo", false);
result->groupChatCreated = data.get("group_chat_created", false);
result->caption = data.get("caption", "");
result->supergroupChatCreated = data.get("supergroup_chat_created", false);
result->channelChatCreated = data.get("channel_chat_created", false);
result->migrateToChatId = data.get<int64_t>("migrate_to_chat_id", 0);
result->migrateFromChatId = data.get<int64_t>("migrate_from_chat_id", 0);
result->pinnedMessage = tryParseJson<Message>(&TgTypeParser::parseJsonAndGetMessage, data, "pinned_message");
result->invoice = tryParseJson<Invoice>(&TgTypeParser::parseJsonAndGetInvoice, data, "invoice");
result->successfulPayment = tryParseJson<SuccessfulPayment>(&TgTypeParser::parseJsonAndGetSuccessfulPayment, data, "successful_payment");
result->connectedWebsite = data.get("connected_website", "");
return result;
}
string TgTypeParser::parseMessage(const Message::Ptr& object) const {
if (!object) {
return "";
}
string result;
result += '{';
appendToJson(result, "message_id", object->messageId);
appendToJson(result, "from", parseUser(object->from));
appendToJson(result, "date", object->date);
appendToJson(result, "chat", parseChat(object->chat));
appendToJson(result, "forward_from", parseUser(object->forwardFrom));
appendToJson(result, "forward_from_chat", parseChat(object->forwardFromChat));
appendToJson(result, "forward_from_message_id", object->forwardFromMessageId);
appendToJson(result, "forward_signature", object->forwardSignature);
appendToJson(result, "forward_date", object->forwardDate);
appendToJson(result, "reply_to_message", parseMessage(object->replyToMessage));
appendToJson(result, "edit_date", object->editDate);
appendToJson(result, "author_signature", object->authorSignature);
appendToJson(result, "text", object->text);
appendToJson(result, "audio", parseAudio(object->audio));
appendToJson(result, "document", parseDocument(object->document));
appendToJson(result, "animation", parseAnimation(object->animation));
appendToJson(result, "photo", parseArray(&TgTypeParser::parsePhotoSize, object->photo));
appendToJson(result, "sticker", parseSticker(object->sticker));
appendToJson(result, "video", parseVideo(object->video));
appendToJson(result, "contact", parseContact(object->contact));
appendToJson(result, "location", parseLocation(object->location));
appendToJson(result, "new_chat_member", parseUser(object->newChatMember));
appendToJson(result, "new_chat_members", parseArray(&TgTypeParser::parseUser, object->newChatMembers));
appendToJson(result, "left_chat_member", parseUser(object->leftChatMember));
appendToJson(result, "new_chat_title", object->newChatTitle);
appendToJson(result, "new_chat_photo", parseArray(&TgTypeParser::parsePhotoSize, object->newChatPhoto));
appendToJson(result, "delete_chat_photo", object->deleteChatPhoto);
appendToJson(result, "group_chat_created", object->groupChatCreated);
appendToJson(result, "caption", object->caption);
appendToJson(result, "supergroup_chat_created", object->supergroupChatCreated);
appendToJson(result, "channel_chat_created", object->channelChatCreated);
appendToJson(result, "migrate_to_chat_id", object->migrateToChatId);
appendToJson(result, "migrate_from_chat_id", object->migrateFromChatId);
appendToJson(result, "pinned_message", parseMessage(object->pinnedMessage));
appendToJson(result, "connected_website", object->connectedWebsite);
appendToJson(result, "invoice", parseInvoice(object->invoice));
appendToJson(result, "successful_payment", parseSuccessfulPayment(object->successfulPayment));
removeLastComma(result);
result += '}';
return result;
}
PhotoSize::Ptr TgTypeParser::parseJsonAndGetPhotoSize(const ptree& data) const {
auto result(make_shared<PhotoSize>());
result->fileId = data.get<string>("file_id");
result->width = data.get<int32_t>("width");
result->height = data.get<int32_t>("height");
result->fileSize = data.get("file_size", 0);
return result;
}
string TgTypeParser::parsePhotoSize(const PhotoSize::Ptr& object) const {
if (!object) {
return "";
}
string result;
result += '{';
appendToJson(result, "file_id", object->fileId);
appendToJson(result, "width", object->width);
appendToJson(result, "height", object->height);
appendToJson(result, "file_size", object->fileSize);
removeLastComma(result);
result += '}';
return result;
}
Audio::Ptr TgTypeParser::parseJsonAndGetAudio(const ptree& data) const {
auto result(make_shared<Audio>());
result->fileId = data.get<string>("file_id");
result->duration = data.get<int32_t>("duration");
result->performer = data.get<string>("performer", "");
result->title = data.get<string>("title", "");
result->mimeType = data.get("mime_type", "");
result->fileSize = data.get("file_size", 0);
result->thumb = tryParseJson<PhotoSize>(&TgTypeParser::parseJsonAndGetPhotoSize, data, "thumb");
return result;
}
string TgTypeParser::parseAudio(const Audio::Ptr& object) const {
if (!object) {
return "";
}
string result;
result += '{';
appendToJson(result, "file_id", object->fileId);
appendToJson(result, "duration", object->duration);
appendToJson(result, "mime_type", object->mimeType);
appendToJson(result, "file_size", object->fileSize);
appendToJson(result, "thumb", parsePhotoSize(object->thumb));
removeLastComma(result);
result += '}';
return result;
}
Document::Ptr TgTypeParser::parseJsonAndGetDocument(const ptree& data) const {
auto result(make_shared<Document>());
result->fileId = data.get<string>("file_id");
result->thumb = tryParseJson<PhotoSize>(&TgTypeParser::parseJsonAndGetPhotoSize, data, "thumb");
result->fileName = data.get("file_name", "");
result->mimeType = data.get("mime_type", "");
result->fileSize = data.get("file_size", 0);
return result;
}
string TgTypeParser::parseDocument(const Document::Ptr& object) const {
if (!object) {
return "";
}
string result;
result += '{';
appendToJson(result, "file_id", object->fileId);
appendToJson(result, "thumb", parsePhotoSize(object->thumb));
appendToJson(result, "file_name", object->fileName);
appendToJson(result, "mime_type", object->mimeType);
appendToJson(result, "file_size", object->fileSize);
removeLastComma(result);
result += '}';
return result;
}
Sticker::Ptr TgTypeParser::parseJsonAndGetSticker(const ptree& data) const {
auto result(make_shared<Sticker>());
result->fileId = data.get<string>("file_id");
result->width = data.get<int32_t>("width");
result->height = data.get<int32_t>("height");
result->thumb = tryParseJson<PhotoSize>(&TgTypeParser::parseJsonAndGetPhotoSize, data, "thumb");
result->emoji = data.get("emoji", "");
result->setName = data.get("set_name", "");
result->maskPosition = tryParseJson<MaskPosition>(&TgTypeParser::parseJsonAndGetMaskPosition, data, "mask_position");
result->fileSize = data.get("file_size", 0);
return result;
}
string TgTypeParser::parseSticker(const Sticker::Ptr& object) const {
if (!object) {
return "";
}
string result;
result += '{';
appendToJson(result, "file_id", object->fileId);
appendToJson(result, "width", object->width);
appendToJson(result, "height", object->height);
appendToJson(result, "thumb", parsePhotoSize(object->thumb));
appendToJson(result, "emoji", object->emoji);
appendToJson(result, "file_size", object->fileSize);
removeLastComma(result);
result += '}';
return result;
}
StickerSet::Ptr TgTypeParser::parseJsonAndGetStickerSet(const ptree& data) const {
auto result(make_shared<StickerSet>());
result->name = data.get("name", "");
result->title = data.get("title", "");
result->containsMasks = data.get<bool>("contains_masks", false);
result->stickers = parseJsonAndGetArray<Sticker>(&TgTypeParser::parseJsonAndGetSticker, data, "stickers");
return result;
}
string TgTypeParser::parseStickerSet(const StickerSet::Ptr& object) const {
if (!object) {
return "";
}
string result;
result += '{';
appendToJson(result, "name", object->name);
appendToJson(result, "title", object->title);
appendToJson(result, "contains_masks", object->containsMasks);
appendToJson(result, "stickers", parseArray(&TgTypeParser::parseSticker, object->stickers));
removeLastComma(result);
result += '}';
return result;
}
MaskPosition::Ptr TgTypeParser::parseJsonAndGetMaskPosition(const ptree& data) const {
auto result(make_shared<MaskPosition>());
result->point = data.get("point", "");
result->xShift = data.get<float>("x_shift", 0);
result->yShift = data.get<float>("y_shift", 0);
result->scale = data.get<float>("scale", 0);
return result;
}
string TgTypeParser::parseMaskPosition(const MaskPosition::Ptr& object) const {
if (!object) {
return "";
}
string result;
result += '{';
appendToJson(result, "point", object->point);
appendToJson(result, "x_shift", object->xShift);
appendToJson(result, "y_shift", object->yShift);
appendToJson(result, "scale", object->scale);
removeLastComma(result);
result += '}';
return result;
}
Video::Ptr TgTypeParser::parseJsonAndGetVideo(const ptree& data) const {
auto result(make_shared<Video>());
result->fileId = data.get<string>("file_id");
result->width = data.get<int32_t>("width");
result->height = data.get<int32_t>("height");
result->duration = data.get<int32_t>("duration");
result->thumb = tryParseJson<PhotoSize>(&TgTypeParser::parseJsonAndGetPhotoSize, data, "thumb");
result->mimeType = data.get("mime_type", "");
result->fileSize = data.get("file_size", 0);
return result;
}
string TgTypeParser::parseVideo(const Video::Ptr& object) const {
if (!object) {
return "";
}
string result;
result += '{';
appendToJson(result, "file_id", object->fileId);
appendToJson(result, "width", object->width);
appendToJson(result, "height", object->height);
appendToJson(result, "duration", object->duration);
appendToJson(result, "thumb", parsePhotoSize(object->thumb));
appendToJson(result, "mime_type", object->mimeType);
appendToJson(result, "file_size", object->fileSize);
removeLastComma(result);
result += '}';
return result;
}
VideoNote::Ptr TgTypeParser::parseJsonAndGetVideoNote(const ptree& data) const {
auto result(make_shared<VideoNote>());
result->fileId = data.get<string>("file_id");
result->length = data.get<int32_t>("length");
result->duration = data.get<int32_t>("duration");
result->thumb = tryParseJson<PhotoSize>(&TgTypeParser::parseJsonAndGetPhotoSize, data, "thumb");
result->fileSize = data.get("file_size", 0);
return result;
}
string TgTypeParser::parseVideoNote(const VideoNote::Ptr& object) const {
if (!object) {
return "";
}
string result;
result += '{';
appendToJson(result, "file_id", object->fileId);
appendToJson(result, "length", object->length);
appendToJson(result, "duration", object->duration);
appendToJson(result, "thumb", parsePhotoSize(object->thumb));
appendToJson(result, "file_size", object->fileSize);
result += '}';
result.erase();
return result;
}
Game::Ptr TgTypeParser::parseJsonAndGetGame(const ptree& data) const {
auto result(make_shared<Game>());
result->title = data.get("title", "");
result->description = data.get("description", "");
result->photo = parseJsonAndGetArray<PhotoSize>(&TgTypeParser::parseJsonAndGetPhotoSize, data, "photo");
result->text = data.get("text", "");
result->textEntities = parseJsonAndGetArray<MessageEntity>(&TgTypeParser::parseJsonAndGetMessageEntity, data, "text_entities");
result->animation = tryParseJson<Animation>(&TgTypeParser::parseJsonAndGetAnimation, data, "animation");
return result;
}
string TgTypeParser::parseGame(const Game::Ptr& object) const {
if (!object) {
return "";
}
string result;
result += '{';
appendToJson(result, "title", object->title);
appendToJson(result, "description", object->description);
appendToJson(result, "photo", parseArray(&TgTypeParser::parsePhotoSize, object->photo));
appendToJson(result, "text", object->text);
appendToJson(result, "text_entities", parseArray(&TgTypeParser::parseMessageEntity, object->textEntities));
appendToJson(result, "animation", parseAnimation(object->animation));
removeLastComma(result);
result += '}';
return result;
}
GameHighScore::Ptr TgTypeParser::parseJsonAndGetGameHighScore(const ptree& data) const {
auto result(make_shared<GameHighScore>());
result->position = data.get("position", "");
result->user = tryParseJson<User>(&TgTypeParser::parseJsonAndGetUser, data, "user");
result->score = data.get<int32_t>("score", 0);
return result;
}
string TgTypeParser::parseGameHighScore(const GameHighScore::Ptr& object) const {
if (!object) {
return "";
}
string result;
result += '{';
appendToJson(result, "position", object->position);
appendToJson(result, "user", parseUser(object->user));
appendToJson(result, "score", object->score);
removeLastComma(result);
result += '}';
return result;
}
Animation::Ptr TgTypeParser::parseJsonAndGetAnimation(const ptree& data) const {
auto result(make_shared<Animation>());
result->fileId = data.get("file_id", "");
result->thumb = tryParseJson<PhotoSize>(&TgTypeParser::parseJsonAndGetPhotoSize, data, "thumb");
result->fileName = data.get("file_name", "");
result->mimeType = data.get("mime_type", "");
result->fileSize = data.get<int32_t>("file_size", 0);
return result;
}
string TgTypeParser::parseAnimation(const Animation::Ptr& object) const {
if (!object) {
return "";
}
string result;
result += '{';
appendToJson(result, "file_id", object->fileId);
appendToJson(result, "thumb", parsePhotoSize(object->thumb));
appendToJson(result, "file_name", object->fileName);
appendToJson(result, "mime_type", object->mimeType);
appendToJson(result, "file_size", object->fileSize);
removeLastComma(result);
result += '}';
return result;
}
Contact::Ptr TgTypeParser::parseJsonAndGetContact(const ptree& data) const {
auto result(make_shared<Contact>());
result->phoneNumber = data.get<string>("phone_number");
result->firstName = data.get<string>("first_name");
result->lastName = data.get("last_name", "");
result->userId = data.get("user_id", "");
result->vcard = data.get("vcard", "");
return result;
}
string TgTypeParser::parseContact(const Contact::Ptr& object) const {
if (!object) {
return "";
}
string result;
result += '{';
appendToJson(result, "phone_number", object->phoneNumber);
appendToJson(result, "first_name", object->firstName);
appendToJson(result, "last_name", object->lastName);
appendToJson(result, "user_id", object->userId);
appendToJson(result, "vcard", object->vcard);
removeLastComma(result);
result += '}';
return result;
}
Location::Ptr TgTypeParser::parseJsonAndGetLocation(const ptree& data) const {
auto result(make_shared<Location>());
result->longitude = data.get<float>("longitude", 0);
result->latitude = data.get<float>("latitude", 0);
return result;
}
string TgTypeParser::parseLocation(const Location::Ptr& object) const {
if (!object) {
return "";
}
string result;
result += '{';
appendToJson(result, "longitude", object->longitude);
appendToJson(result, "latitude", object->latitude);
removeLastComma(result);
result += '}';
return result;
}
Update::Ptr TgTypeParser::parseJsonAndGetUpdate(const ptree& data) const {
auto result(make_shared<Update>());
result->updateId = data.get<int32_t>("update_id");
result->message = tryParseJson<Message>(&TgTypeParser::parseJsonAndGetMessage, data, "message");
result->editedMessage = tryParseJson<Message>(&TgTypeParser::parseJsonAndGetMessage, data, "edited_message");
result->channelPost = tryParseJson<Message>(&TgTypeParser::parseJsonAndGetMessage, data, "channel_post");
result->editedChannelPost = tryParseJson<Message>(&TgTypeParser::parseJsonAndGetMessage, data, "edited_channel_post");
result->inlineQuery = tryParseJson<InlineQuery>(&TgTypeParser::parseJsonAndGetInlineQuery, data, "inline_query");
result->chosenInlineResult = tryParseJson<ChosenInlineResult>(&TgTypeParser::parseJsonAndGetChosenInlineResult, data, "chosen_inline_result");
result->callbackQuery = tryParseJson<CallbackQuery>(&TgTypeParser::parseJsonAndGetCallbackQuery, data, "callback_query");
result->shippingQuery = tryParseJson<ShippingQuery>(&TgTypeParser::parseJsonAndGetShippingQuery, data, "shipping_query");
result->preCheckoutQuery = tryParseJson<PreCheckoutQuery>(&TgTypeParser::parseJsonAndGetPreCheckoutQuery, data, "pre_checkout_query");
return result;
}
string TgTypeParser::parseUpdate(const Update::Ptr& object) const {
if (!object) {
return "";
}
string result;
result += '{';
appendToJson(result, "update_id", object->updateId);
appendToJson(result, "message", parseMessage(object->message));
appendToJson(result, "edited_message", parseMessage(object->editedMessage));
appendToJson(result, "channel_post", parseMessage(object->channelPost));
appendToJson(result, "edited_channel_post", parseMessage(object->editedChannelPost));
appendToJson(result, "inline_query", parseInlineQuery(object->inlineQuery));
appendToJson(result, "chosen_inline_result", parseChosenInlineResult(object->chosenInlineResult));
appendToJson(result, "callback_query", parseCallbackQuery(object->callbackQuery));
appendToJson(result, "shipping_query", parseShippingQuery(object->shippingQuery));
appendToJson(result, "pre_checkout_query", parsePreCheckoutQuery(object->preCheckoutQuery));
removeLastComma(result);
result += '}';
return result;
}
UserProfilePhotos::Ptr TgTypeParser::parseJsonAndGetUserProfilePhotos(const ptree& data) const {
auto result(make_shared<UserProfilePhotos>());
result->totalCount = data.get<int32_t>("total_count");
result->photos = parseJsonAndGet2DArray<PhotoSize>(&TgTypeParser::parseJsonAndGetPhotoSize, data, "photos");
return result;
}
string TgTypeParser::parseUserProfilePhotos(const UserProfilePhotos::Ptr& object) const {
if (!object) {
return "";
}
string result;
result += '{';
appendToJson(result, "total_count", object->totalCount);
appendToJson(result, "photos", parse2DArray(&TgTypeParser::parsePhotoSize, object->photos));
removeLastComma(result);
result += '}';
return result;
}
InputMedia::Ptr TgTypeParser::parseJsonAndGetInputMedia(const ptree& data) const {
string type = data.get("type", "");
if (type == "photo") {
auto result(make_shared<InputMediaPhoto>());
result->media = data.get("media", "");
result->caption = data.get("caption", "");
result->parseMode = data.get("parse_mode", "");
result->thumb = data.get("thumb", "");
return result;
}
else if (type == "video") {
auto result(make_shared<InputMediaVideo>());
result->media = data.get("media", "");
result->caption = data.get("caption", "");
result->parseMode = data.get("parse_mode", "");
result->thumb = data.get("thumb", "");
result->width = data.get<int32_t>("width", 0);
result->height = data.get<int32_t>("height", 0);
result->duration = data.get<int32_t>("duration", 0);
result->supportsStreaming = data.get<bool>("supports_streaming", false);
return result;
}
else if (type == "animation") {
auto result(make_shared<InputMediaAnimation>());
result->media = data.get("media", "");
result->caption = data.get("caption", "");
result->parseMode = data.get("parse_mode", "");
result->thumb = data.get("thumb", "");
result->width = data.get<int32_t>("width", 0);
result->height = data.get<int32_t>("height", 0);
result->duration = data.get<int32_t>("duration", 0);
return result;
} else if (type == "document") {
auto result(make_shared<InputMediaDocument>());
result->media = data.get("media", "");
result->caption = data.get("caption", "");
result->parseMode = data.get("parse_mode", "");
result->thumb = data.get("thumb", "");
return result;
} else if (type == "audio") {
auto result(make_shared<InputMediaAudio>());
result->media = data.get("media", "");
result->caption = data.get("caption", "");
result->parseMode = data.get("parse_mode", "");
result->thumb = data.get("thumb", "");
result->duration = data.get<int32_t>("duration", 0);
result->title = data.get<int32_t>("title", 0);
result->performer = data.get<int32_t>("performer", 0);
return result;
}
else {
return nullptr;
}
}
string TgTypeParser::parseInputMedia(const InputMedia::Ptr& object) const {
if (!object) {
return "";
}
string result;
result += '{';
switch(object->type) {
case InputMedia::TYPE::PHOTO:
appendToJson(result, "type", "\"photo\"");
break;
case InputMedia::TYPE::VIDEO:
appendToJson(result, "type", "\"video\"");
break;
case InputMedia::TYPE::ANIMATION:
appendToJson(result, "type", "\"animation\"");
break;
case InputMedia::TYPE::DOCUMENT:
appendToJson(result, "type", "\"document\"");
break;
case InputMedia::TYPE::AUDIO:
appendToJson(result, "type", "\"audio\"");
break;
}
appendToJson(result, "media", object->media);
appendToJson(result, "caption", object->caption);
appendToJson(result, "parse_mode", object->parseMode);
if (object->width) {
appendToJson(result, "width", object->width);
}
if (object->height) {
appendToJson(result, "height", object->height);
}
if (object->duration) {
appendToJson(result, "duration", object->duration);
}
if (object->performer) {
appendToJson(result, "performer", object->performer);
}
if (object->supportsStreaming) {
appendToJson(result, "supports_streaming", object->supportsStreaming);
}
removeLastComma(result);
result += '}';
return result;
}
File::Ptr TgTypeParser::parseJsonAndGetFile(const boost::property_tree::ptree& data) const {
auto result(make_shared<File>());
result->fileId = data.get<string>("file_id");
result->fileSize = data.get<int32_t>("file_size", 0);
result->filePath = data.get<string>("file_path", "");
return result;
}
string TgTypeParser::parseFile(const File::Ptr& object) const {
if (!object) {
return "";
}
string result;
result += '{';
appendToJson(result, "file_id", object->fileId);
appendToJson(result, "file_size", object->fileSize);
appendToJson(result, "file_path", object->filePath);
removeLastComma(result);
result += '}';
return result;
}
ReplyKeyboardMarkup::Ptr TgTypeParser::parseJsonAndGetReplyKeyboardMarkup(const boost::property_tree::ptree& data) const {
auto result(make_shared<ReplyKeyboardMarkup>());
for (const auto& item : data.find("keyboard")->second){
result->keyboard.push_back(parseJsonAndGetArray<KeyboardButton>(&TgTypeParser::parseJsonAndGetKeyboardButton, item.second));
}
result->resizeKeyboard = data.get<bool>("resize_keyboard", false);
result->oneTimeKeyboard = data.get<bool>("one_time_keyboard", false);
result->selective = data.get<bool>("selective", false);
return result;
}
std::string TgTypeParser::parseReplyKeyboardMarkup(const ReplyKeyboardMarkup::Ptr& object) const {
if (!object) {
return "";
}
string result;
result += '{';
result += R"("keyboard":[)";
for (const auto& item : object->keyboard) {
result += '[';
for (const auto& innerItem : item) {
result += parseKeyboardButton(innerItem);
result += ',';
}
removeLastComma(result);
result += "],";
}
if (!object->keyboard.empty())
removeLastComma(result);
result += "],";
appendToJson(result, "resize_keyboard", object->resizeKeyboard);
appendToJson(result, "one_time_keyboard", object->oneTimeKeyboard);
appendToJson(result, "selective", object->selective);
removeLastComma(result);
result += '}';
return result;
}
KeyboardButton::Ptr TgTypeParser::parseJsonAndGetKeyboardButton(const boost::property_tree::ptree& data) const {
auto result(make_shared<KeyboardButton>());
result->text = data.get<string>("text");
result->requestContact = data.get<bool>("request_contact", false);
result->requestLocation = data.get<bool>("request_location", false);
return result;
}
std::string TgTypeParser::parseKeyboardButton(const KeyboardButton::Ptr& object) const {
if (!object) {
return "";
}
string result;
result += '{';
appendToJson(result, "text", object->text);
appendToJson(result, "request_contact", object->requestContact);
appendToJson(result, "request_location", object->requestLocation);
removeLastComma(result);
result += '}';
return result;
}
ReplyKeyboardRemove::Ptr TgTypeParser::parseJsonAndGetReplyKeyboardRemove(const boost::property_tree::ptree& data) const {
auto result(make_shared<ReplyKeyboardRemove>());
result->selective = data.get<bool>("selective", false);
return result;
}
std::string TgTypeParser::parseReplyKeyboardRemove(const ReplyKeyboardRemove::Ptr& object) const {
if (!object) {
return "";
}
string result;
result += '{';
appendToJson(result, "remove_keyboard", object->removeKeyboard);
appendToJson(result, "selective", object->selective);
removeLastComma(result);
result += '}';
return result;
}
ForceReply::Ptr TgTypeParser::parseJsonAndGetForceReply(const boost::property_tree::ptree& data) const {
auto result(make_shared<ForceReply>());
result->selective = data.get<bool>("selective");
return result;
}
std::string TgTypeParser::parseForceReply(const ForceReply::Ptr& object) const {
if (!object) {
return "";
}
string result;
result += '{';
appendToJson(result, "force_reply", object->forceReply);
appendToJson(result, "selective", object->selective);
removeLastComma(result);
result += '}';
return result;
}
ChatMember::Ptr TgTypeParser::parseJsonAndGetChatMember(const boost::property_tree::ptree& data) const {
auto result(make_shared<ChatMember>());
result->user = tryParseJson<User>(&TgTypeParser::parseJsonAndGetUser, data, "user");
result->status = data.get("status", "");
result->untilDate = data.get<uint64_t>("until_date", 0);
result->canBeEdited = data.get<bool>("can_be_edited", false);
result->canChangeInfo = data.get<bool>("can_change_info", false);
result->canPostMessages = data.get<bool>("can_post_messages", false);
result->canEditMessages = data.get<bool>("can_edit_messages", false);
result->canDeleteMessages = data.get<bool>("can_delete_messages", false);
result->canInviteUsers = data.get<bool>("can_invite_users", false);
result->canRestrictMembers = data.get<bool>("can_restrict_members", false);
result->canPinMessages = data.get<bool>("can_pin_messages", false);
result->canPromoteMembers = data.get<bool>("can_promote_messages", false);
result->canSendMessages = data.get<bool>("can_send_messages", false);
result->canSendMediaMessages = data.get<bool>("can_send_media_messages", false);
result->canSendOtherMessages = data.get<bool>("can_send_other_messages", false);
result->canAddWebPagePreviews = data.get<bool>("can_add_web_page_previews", false);
return result;
}
std::string TgTypeParser::parseChatMember(const ChatMember::Ptr& object) const {
if (!object) {
return "";
}
string result;
result += '{';
appendToJson(result, "user", parseUser(object->user));
appendToJson(result, "status", object->status);
removeLastComma(result);
result += '}';
return result;
}
ChatPhoto::Ptr TgTypeParser::parseJsonAndGetChatPhoto(const boost::property_tree::ptree& data) const {
auto result(make_shared<ChatPhoto>());
result->smallFileId = data.get("small_file_id", "");
result->bigFileId = data.get("big_file_id", "");
return result;
}
std::string TgTypeParser::parseChatPhoto(const ChatPhoto::Ptr& object) const {
if (!object) {
return "";
}
string result;
result += '{';
appendToJson(result, "small_file_id", object->smallFileId);
appendToJson(result, "big_file_id", object->bigFileId);
removeLastComma(result);
result += '}';
return result;
}
ResponseParameters::Ptr TgTypeParser::parseJsonAndGetResponseParameters(const boost::property_tree::ptree& data) const {
auto result(make_shared<ResponseParameters>());
result->migrateToChatId = data.get<int32_t>("migrate_to_chat_id", 0);
result->retryAfter = data.get<int32_t>("retry_after", 0);
return result;
}
std::string TgTypeParser::parseResponseParameters(const ResponseParameters::Ptr& object) const {
if (!object) {
return "";
}
string result;
result += '{';
appendToJson(result, "migrate_to_chat_id", object->migrateToChatId);
appendToJson(result, "retry_after", object->retryAfter);
removeLastComma(result);
result += '}';
return result;
}
GenericReply::Ptr TgTypeParser::parseJsonAndGetGenericReply(const boost::property_tree::ptree& data) const {
if (data.find("force_reply") != data.not_found()) {
return static_pointer_cast<GenericReply>(parseJsonAndGetForceReply(data));
} else if (data.find("remove_keyboard") != data.not_found()) {
return static_pointer_cast<GenericReply>(parseJsonAndGetReplyKeyboardRemove(data));
} else if (data.find("keyboard") != data.not_found()) {
return static_pointer_cast<GenericReply>(parseJsonAndGetReplyKeyboardMarkup(data));
} else if (data.find("inline_keyboard") != data.not_found()) {
return static_pointer_cast<GenericReply>(parseJsonAndGetInlineKeyboardMarkup(data));
}
return make_shared<GenericReply>();
}
std::string TgTypeParser::parseGenericReply(const GenericReply::Ptr& object) const {
if (!object) {
return "";
}
if (dynamic_pointer_cast<ForceReply>(object) != nullptr) {
return parseForceReply(static_pointer_cast<ForceReply>(object));
} else if (dynamic_pointer_cast<ReplyKeyboardRemove>(object) != nullptr) {
return parseReplyKeyboardRemove(static_pointer_cast<ReplyKeyboardRemove>(object));
} else if (dynamic_pointer_cast<ReplyKeyboardMarkup>(object) != nullptr){
return parseReplyKeyboardMarkup(static_pointer_cast<ReplyKeyboardMarkup>(object));
} else if (dynamic_pointer_cast<InlineKeyboardMarkup>(object) != nullptr){
return parseInlineKeyboardMarkup(static_pointer_cast<InlineKeyboardMarkup>(object));
}
return "";
}
InlineQuery::Ptr TgTypeParser::parseJsonAndGetInlineQuery(const boost::property_tree::ptree& data) const {
auto result(make_shared<InlineQuery>());
result->id = data.get<string>("id");
result->from = tryParseJson<User>(&TgTypeParser::parseJsonAndGetUser, data, "from");
result->location = tryParseJson<Location>(&TgTypeParser::parseJsonAndGetLocation, data, "location");
result->query = data.get<string>("query");
result->offset = data.get<string>("offset");
return result;
}
std::string TgTypeParser::parseInlineQuery(const InlineQuery::Ptr& object) const{
if (!object) {
return "";
}
string result;
result += '{';
appendToJson(result, "id", object->id);
appendToJson(result, "from", parseUser(object->from));
appendToJson(result, "location", parseLocation(object->location));
appendToJson(result, "query", object->query);
appendToJson(result, "offset", object->offset);
removeLastComma(result);
result += '}';
return result;
}
InlineQueryResult::Ptr TgTypeParser::parseJsonAndGetInlineQueryResult(const boost::property_tree::ptree& data) const {
string type = data.get<string>("type");
InlineQueryResult::Ptr result;
if (type == InlineQueryResultCachedAudio::TYPE) {
result = static_pointer_cast<InlineQueryResult>(parseJsonAndGetInlineQueryResultCachedAudio(data));
} else if (type == InlineQueryResultCachedDocument::TYPE) {
result = static_pointer_cast<InlineQueryResult>(parseJsonAndGetInlineQueryResultCachedDocument(data));
} else if (type == InlineQueryResultCachedGif::TYPE) {
result = static_pointer_cast<InlineQueryResult>(parseJsonAndGetInlineQueryResultCachedGif(data));
} else if (type == InlineQueryResultCachedMpeg4Gif::TYPE) {
result = static_pointer_cast<InlineQueryResult>(parseJsonAndGetInlineQueryResultCachedMpeg4Gif(data));
} else if (type == InlineQueryResultCachedPhoto::TYPE) {
result = static_pointer_cast<InlineQueryResult>(parseJsonAndGetInlineQueryResultCachedPhoto(data));
} else if (type == InlineQueryResultCachedSticker::TYPE) {
result = static_pointer_cast<InlineQueryResult>(parseJsonAndGetInlineQueryResultCachedSticker(data));
} else if (type == InlineQueryResultCachedVideo::TYPE) {
result = static_pointer_cast<InlineQueryResult>(parseJsonAndGetInlineQueryResultCachedVideo(data));
} else if (type == InlineQueryResultCachedVoice::TYPE) {
result = static_pointer_cast<InlineQueryResult>(parseJsonAndGetInlineQueryResultCachedVoice(data));
} else if (type == InlineQueryResultArticle::TYPE) {
result = static_pointer_cast<InlineQueryResult>(parseJsonAndGetInlineQueryResultArticle(data));
} else if (type == InlineQueryResultAudio::TYPE) {
result = static_pointer_cast<InlineQueryResult>(parseJsonAndGetInlineQueryResultAudio(data));
} else if (type == InlineQueryResultContact::TYPE) {
result = static_pointer_cast<InlineQueryResult>(parseJsonAndGetInlineQueryResultContact(data));
} else if (type == InlineQueryResultGame::TYPE) {
result = static_pointer_cast<InlineQueryResult>(parseJsonAndGetInlineQueryResultGame(data));
} else if (type == InlineQueryResultDocument::TYPE) {
result = static_pointer_cast<InlineQueryResult>(parseJsonAndGetInlineQueryResultDocument(data));
} else if (type == InlineQueryResultLocation::TYPE) {
result = static_pointer_cast<InlineQueryResult>(parseJsonAndGetInlineQueryResultLocation(data));
} else if (type == InlineQueryResultVenue::TYPE) {
result = static_pointer_cast<InlineQueryResult>(parseJsonAndGetInlineQueryResultVenue(data));
} else if (type == InlineQueryResultVoice::TYPE) {
result = static_pointer_cast<InlineQueryResult>(parseJsonAndGetInlineQueryResultVoice(data));
} else if (type == InlineQueryResultPhoto::TYPE) {
result = static_pointer_cast<InlineQueryResult>(parseJsonAndGetInlineQueryResultPhoto(data));
} else if (type == InlineQueryResultGif::TYPE) {
result = static_pointer_cast<InlineQueryResult>(parseJsonAndGetInlineQueryResultGif(data));
} else if (type == InlineQueryResultMpeg4Gif::TYPE) {
result = static_pointer_cast<InlineQueryResult>(parseJsonAndGetInlineQueryResultMpeg4Gif(data));
} else if (type == InlineQueryResultVideo::TYPE) {
result = static_pointer_cast<InlineQueryResult>(parseJsonAndGetInlineQueryResultVideo(data));
} else {
result = make_shared<InlineQueryResult>();
}
result->id = data.get<string>("id");
result->title = data.get<string>("title", "");
result->caption = data.get<string>("caption", "");
result->replyMarkup = tryParseJson<InlineKeyboardMarkup>(&TgTypeParser::parseJsonAndGetInlineKeyboardMarkup, data, "reply_markup");
result->inputMessageContent = tryParseJson<InputMessageContent>(&TgTypeParser::parseJsonAndGetInputMessageContent, data, "input_message_content");
return result;
}
std::string TgTypeParser::parseInlineQueryResult(const InlineQueryResult::Ptr& object) const {
if (!object){
return "";
}
string result;
result += '{';
appendToJson(result, "id", object->id);
appendToJson(result, "type", object->type);
appendToJson(result, "title", object->title);
appendToJson(result, "caption", object->caption);
appendToJson(result, "reply_markup", parseInlineKeyboardMarkup(object->replyMarkup));
appendToJson(result, "input_message_content", parseInputMessageContent(object->inputMessageContent));
if (object->type == InlineQueryResultCachedAudio::TYPE) {
result += parseInlineQueryResultCachedAudio(static_pointer_cast<InlineQueryResultCachedAudio>(object));
}
else if (object->type == InlineQueryResultCachedDocument::TYPE) {
result += parseInlineQueryResultCachedDocument(static_pointer_cast<InlineQueryResultCachedDocument>(object));
}
else if (object->type == InlineQueryResultCachedGif::TYPE) {
result += parseInlineQueryResultCachedGif(static_pointer_cast<InlineQueryResultCachedGif>(object));
}
else if (object->type == InlineQueryResultCachedMpeg4Gif::TYPE) {
result += parseInlineQueryResultCachedMpeg4Gif(static_pointer_cast<InlineQueryResultCachedMpeg4Gif>(object));
}
else if (object->type == InlineQueryResultCachedPhoto::TYPE) {
result += parseInlineQueryResultCachedPhoto(static_pointer_cast<InlineQueryResultCachedPhoto>(object));
}
else if (object->type == InlineQueryResultCachedSticker::TYPE) {
result += parseInlineQueryResultCachedSticker(static_pointer_cast<InlineQueryResultCachedSticker>(object));
}
else if (object->type == InlineQueryResultCachedVideo::TYPE) {
result += parseInlineQueryResultCachedVideo(static_pointer_cast<InlineQueryResultCachedVideo>(object));
}
else if (object->type == InlineQueryResultCachedVoice::TYPE) {
result += parseInlineQueryResultCachedVoice(static_pointer_cast<InlineQueryResultCachedVoice>(object));
}
else if (object->type == InlineQueryResultArticle::TYPE) {
result += parseInlineQueryResultArticle(static_pointer_cast<InlineQueryResultArticle>(object));
}
else if (object->type == InlineQueryResultAudio::TYPE) {
result += parseInlineQueryResultAudio(static_pointer_cast<InlineQueryResultAudio>(object));
}
else if (object->type == InlineQueryResultContact::TYPE) {
result += parseInlineQueryResultContact(static_pointer_cast<InlineQueryResultContact>(object));
}
else if (object->type == InlineQueryResultGame::TYPE) {
result += parseInlineQueryResultGame(static_pointer_cast<InlineQueryResultGame>(object));
}
else if (object->type == InlineQueryResultDocument::TYPE) {
result += parseInlineQueryResultDocument(static_pointer_cast<InlineQueryResultDocument>(object));
}
else if (object->type == InlineQueryResultLocation::TYPE) {
result += parseInlineQueryResultLocation(static_pointer_cast<InlineQueryResultLocation>(object));
}
else if (object->type == InlineQueryResultVenue::TYPE) {
result += parseInlineQueryResultVenue(static_pointer_cast<InlineQueryResultVenue>(object));
}
else if (object->type == InlineQueryResultVoice::TYPE) {
result += parseInlineQueryResultVoice(static_pointer_cast<InlineQueryResultVoice>(object));
}
else if (object->type == InlineQueryResultPhoto::TYPE) {
result += parseInlineQueryResultPhoto(static_pointer_cast<InlineQueryResultPhoto>(object));
}
else if (object->type == InlineQueryResultGif::TYPE) {
result += parseInlineQueryResultGif(static_pointer_cast<InlineQueryResultGif>(object));
}
else if (object->type == InlineQueryResultMpeg4Gif::TYPE) {
result += parseInlineQueryResultMpeg4Gif(static_pointer_cast<InlineQueryResultMpeg4Gif>(object));
}
else if (object->type == InlineQueryResultVideo::TYPE) {
result += parseInlineQueryResultVideo(static_pointer_cast<InlineQueryResultVideo>(object));
}
removeLastComma(result);
result += '}';
return result;
}
InlineQueryResultCachedAudio::Ptr TgTypeParser::parseJsonAndGetInlineQueryResultCachedAudio(const boost::property_tree::ptree& data) const {
// NOTE: This function will be called by parseJsonAndGgetInlineQueryResult().
auto result(make_shared<InlineQueryResultCachedAudio>());
result->audioFileId = data.get<string>("audio_file_id");
return result;
}
std::string TgTypeParser::parseInlineQueryResultCachedAudio(const InlineQueryResultCachedAudio::Ptr& object) const {
if (!object){
return "";
}
// This function will be called by parseInlineQueryResult(), so I don't add
// curly brackets to the result string.
string result;
appendToJson(result, "audio_file_id", object->audioFileId);
// The last comma will be erased by parseInlineQueryResult().
return result;
}
InlineQueryResultCachedDocument::Ptr TgTypeParser::parseJsonAndGetInlineQueryResultCachedDocument(const boost::property_tree::ptree& data) const {
// NOTE: This function will be called by parseJsonAndGgetInlineQueryResult().
auto result(make_shared<InlineQueryResultCachedDocument>());
result->documentFileId = data.get<string>("document_file_id");
result->description = data.get<string>("description", "");
return result;
}
std::string TgTypeParser::parseInlineQueryResultCachedDocument(const InlineQueryResultCachedDocument::Ptr& object) const {
if (!object){
return "";
}
// This function will be called by parseInlineQueryResult(), so I don't add
// curly brackets to the result string.
string result;
appendToJson(result, "document_file_id", object->documentFileId);
appendToJson(result, "description", object->description);
// The last comma will be erased by parseInlineQueryResult().
return result;
}
InlineQueryResultCachedGif::Ptr TgTypeParser::parseJsonAndGetInlineQueryResultCachedGif(const boost::property_tree::ptree& data) const {
// NOTE: This function will be called by parseJsonAndGgetInlineQueryResult().
auto result(make_shared<InlineQueryResultCachedGif>());
result->gifFileId = data.get<string>("gif_file_id");
return result;
}
std::string TgTypeParser::parseInlineQueryResultCachedGif(const InlineQueryResultCachedGif::Ptr& object) const {
if (!object){
return "";
}
// This function will be called by parseInlineQueryResult(), so I don't add
// curly brackets to the result string.
string result;
appendToJson(result, "gif_file_id", object->gifFileId);
// The last comma will be erased by parseInlineQueryResult().
return result;
}
InlineQueryResultCachedMpeg4Gif::Ptr TgTypeParser::parseJsonAndGetInlineQueryResultCachedMpeg4Gif(const boost::property_tree::ptree& data) const {
// NOTE: This function will be called by parseJsonAndGgetInlineQueryResult().
auto result(make_shared<InlineQueryResultCachedMpeg4Gif>());
result->mpeg4FileId = data.get<string>("mpeg4_file_id");
return result;
}
std::string TgTypeParser::parseInlineQueryResultCachedMpeg4Gif(const InlineQueryResultCachedMpeg4Gif::Ptr& object) const {
if (!object){
return "";
}
// This function will be called by parseInlineQueryResult(), so I don't add
// curly brackets to the result string.
string result;
appendToJson(result, "mpeg4_file_id", object->mpeg4FileId);
// The last comma will be erased by parseInlineQueryResult().
return result;
}
InlineQueryResultCachedPhoto::Ptr TgTypeParser::parseJsonAndGetInlineQueryResultCachedPhoto(const boost::property_tree::ptree& data) const {
// NOTE: This function will be called by parseJsonAndGgetInlineQueryResult().
auto result(make_shared<InlineQueryResultCachedPhoto>());
result->photoFileId = data.get<string>("photo_file_id");
result->description = data.get<string>("description", "");
return result;
}
std::string TgTypeParser::parseInlineQueryResultCachedPhoto(const InlineQueryResultCachedPhoto::Ptr& object) const {
if (!object){
return "";
}
// This function will be called by parseInlineQueryResult(), so I don't add
// curly brackets to the result string.
string result;
appendToJson(result, "photo_file_id", object->photoFileId);
appendToJson(result, "description", object->description);
// The last comma will be erased by parseInlineQueryResult().
return result;
}
InlineQueryResultCachedSticker::Ptr TgTypeParser::parseJsonAndGetInlineQueryResultCachedSticker(const boost::property_tree::ptree& data) const {
// NOTE: This function will be called by parseJsonAndGgetInlineQueryResult().
auto result(make_shared<InlineQueryResultCachedSticker>());
result->stickerFileId = data.get<string>("sticker_file_id");
return result;
}
std::string TgTypeParser::parseInlineQueryResultCachedSticker(const InlineQueryResultCachedSticker::Ptr& object) const {
if (!object){
return "";
}
// This function will be called by parseInlineQueryResult(), so I don't add
// curly brackets to the result string.
string result;
appendToJson(result, "sticker_file_id", object->stickerFileId);
// The last comma will be erased by parseInlineQueryResult().
return result;
}
InlineQueryResultCachedVideo::Ptr TgTypeParser::parseJsonAndGetInlineQueryResultCachedVideo(const boost::property_tree::ptree& data) const {
// NOTE: This function will be called by parseJsonAndGgetInlineQueryResult().
auto result(make_shared<InlineQueryResultCachedVideo>());
result->videoFileId = data.get<string>("video_file_id");
result->description = data.get<string>("description", "");
return result;
}
std::string TgTypeParser::parseInlineQueryResultCachedVideo(const InlineQueryResultCachedVideo::Ptr& object) const {
if (!object){
return "";
}
// This function will be called by parseInlineQueryResult(), so I don't add
// curly brackets to the result string.
string result;
appendToJson(result, "video_file_id", object->videoFileId);
appendToJson(result, "description", object->description);
// The last comma will be erased by parseInlineQueryResult().
return result;
}
InlineQueryResultCachedVoice::Ptr TgTypeParser::parseJsonAndGetInlineQueryResultCachedVoice(const boost::property_tree::ptree& data) const {
// NOTE: This function will be called by parseJsonAndGgetInlineQueryResult().
auto result(make_shared<InlineQueryResultCachedVoice>());
result->voiceFileId = data.get<string>("voice_file_id");
return result;
}
std::string TgTypeParser::parseInlineQueryResultCachedVoice(const InlineQueryResultCachedVoice::Ptr& object) const {
if (!object){
return "";
}
// This function will be called by parseInlineQueryResult(), so I don't add
// curly brackets to the result string.
string result;
appendToJson(result, "voice_file_id", object->voiceFileId);
// The last comma will be erased by parseInlineQueryResult().
return result;
}
InlineQueryResultArticle::Ptr TgTypeParser::parseJsonAndGetInlineQueryResultArticle(const boost::property_tree::ptree& data) const {
// NOTE: This function will be called by parseJsonAndGgetInlineQueryResult().
auto result(make_shared<InlineQueryResultArticle>());
result->url = data.get<string>("url", "");
result->hideUrl = data.get("hide_url", false);
result->description = data.get<string>("description", "");
result->thumbUrl = data.get<string>("thumb_url", "");
result->thumbWidth = data.get("thumb_width", 0);
result->thumbHeight = data.get("thumb_height", 0);
return result;
}
std::string TgTypeParser::parseInlineQueryResultArticle(const InlineQueryResultArticle::Ptr& object) const {
if (!object){
return "";
}
// This function will be called by parseInlineQueryResult(), so I don't add
// curly brackets to the result string.
string result;
appendToJson(result, "url", object->url);
appendToJson(result, "hide_url", object->hideUrl);
appendToJson(result, "description", object->description);
appendToJson(result, "thumb_url", object->thumbUrl);
appendToJson(result, "thumb_width", object->thumbWidth);
appendToJson(result, "thumb_height", object->thumbHeight);
// The last comma will be erased by parseInlineQueryResult().
return result;
}
InlineQueryResultAudio::Ptr TgTypeParser::parseJsonAndGetInlineQueryResultAudio(const boost::property_tree::ptree& data) const {
// NOTE: This function will be called by parseJsonAndGgetInlineQueryResult().
auto result(make_shared<InlineQueryResultAudio>());
result->audioUrl = data.get<string>("audio_url");
result->performer = data.get<string>("performer", "");
result->audioDuration = data.get<int32_t>("audio_duration", 0);
return result;
}
std::string TgTypeParser::parseInlineQueryResultAudio(const InlineQueryResultAudio::Ptr& object) const {
if (!object){
return "";
}
// This function will be called by parseInlineQueryResult(), so I don't add
// curly brackets to the result string.
string result;
appendToJson(result, "audio_url", object->audioUrl);
appendToJson(result, "performer", object->performer);
appendToJson(result, "audio_duration", object->audioDuration);
// The last comma will be erased by parseInlineQueryResult().
return result;
}
InlineQueryResultContact::Ptr TgTypeParser::parseJsonAndGetInlineQueryResultContact(const boost::property_tree::ptree& data) const {
// NOTE: This function will be called by parseJsonAndGgetInlineQueryResult().
auto result(make_shared<InlineQueryResultContact>());
result->phoneNumber = data.get<string>("phone_number");
result->firstName = data.get<string>("first_name");
result->lastName = data.get<string>("last_name", "");
result->vcard = data.get<string>("vcard", "");
result->thumbUrl = data.get<string>("thumb_url", "");
result->thumbWidth = data.get<int32_t>("thumb_width", 0);
result->thumbHeight = data.get<int32_t>("thumb_height", 0);
return result;
}
std::string TgTypeParser::parseInlineQueryResultContact(const InlineQueryResultContact::Ptr& object) const {
if (!object){
return "";
}
// This function will be called by parseInlineQueryResult(), so I don't add
// curly brackets to the result string.
string result;
appendToJson(result, "phone_number", object->phoneNumber);
appendToJson(result, "first_name", object->firstName);
appendToJson(result, "last_name", object->lastName);
appendToJson(result, "vcard", object->vcard);
appendToJson(result, "thumb_url", object->thumbUrl);
appendToJson(result, "thumb_width", object->thumbWidth);
appendToJson(result, "thumb_height", object->thumbHeight);
// The last comma will be erased by parseInlineQueryResult().
return result;
}
InlineQueryResultGame::Ptr TgTypeParser::parseJsonAndGetInlineQueryResultGame(const boost::property_tree::ptree& data) const {
// NOTE: This function will be called by parseJsonAndGgetInlineQueryResult().
auto result(make_shared<InlineQueryResultGame>());
result->gameShortName = data.get<string>("game_short_name");
return result;
}
std::string TgTypeParser::parseInlineQueryResultGame(const InlineQueryResultGame::Ptr& object) const {
if (!object){
return "";
}
// This function will be called by parseInlineQueryResult(), so I don't add
// curly brackets to the result string.
string result;
appendToJson(result, "game_short_name", object->gameShortName);
// The last comma will be erased by parseInlineQueryResult().
return result;
}
InlineQueryResultDocument::Ptr TgTypeParser::parseJsonAndGetInlineQueryResultDocument(const boost::property_tree::ptree& data) const {
// NOTE: This function will be called by parseJsonAndGgetInlineQueryResult().
auto result(make_shared<InlineQueryResultDocument>());
result->documentUrl = data.get<string>("document_url");
result->mimeType = data.get<string>("mime_type");
result->description = data.get<string>("description", "");
result->thumbUrl = data.get<string>("thumb_url", "");
result->thumbWidth = data.get<int32_t>("thumb_width", 0);
result->thumbHeight = data.get<int32_t>("thumb_height", 0);
return result;
}
std::string TgTypeParser::parseInlineQueryResultDocument(const InlineQueryResultDocument::Ptr& object) const {
if (!object){
return "";
}
// This function will be called by parseInlineQueryResult(), so I don't add
// curly brackets to the result string.
string result;
appendToJson(result, "document_url", object->documentUrl);
appendToJson(result, "mime_type", object->mimeType);
appendToJson(result, "description", object->description);
appendToJson(result, "thumb_url", object->thumbUrl);
appendToJson(result, "thumb_width", object->thumbWidth);
appendToJson(result, "thumb_height", object->thumbHeight);
// The last comma will be erased by parseInlineQueryResult().
return result;
}
InlineQueryResultLocation::Ptr TgTypeParser::parseJsonAndGetInlineQueryResultLocation(const boost::property_tree::ptree& data) const {
// NOTE: This function will be called by parseJsonAndGgetInlineQueryResult().
auto result(make_shared<InlineQueryResultLocation>());
result->latitude = data.get<float>("latitude");
result->longitude = data.get<float>("longitude");
result->thumbUrl = data.get<string>("thumb_url", "");
result->thumbWidth = data.get<int32_t>("thumb_width", 0);
result->thumbHeight = data.get<int32_t>("thumb_height", 0);
return result;
}
std::string TgTypeParser::parseInlineQueryResultLocation(const InlineQueryResultLocation::Ptr& object) const {
if (!object){
return "";
}
// This function will be called by parseInlineQueryResult(), so I don't add
// curly brackets to the result string.
string result;
appendToJson(result, "latitude", object->latitude);
appendToJson(result, "longitude", object->longitude);
appendToJson(result, "thumb_url", object->thumbUrl);
appendToJson(result, "thumb_width", object->thumbWidth);
appendToJson(result, "thumb_height", object->thumbHeight);
// The last comma will be erased by parseInlineQueryResult().
return result;
}
InlineQueryResultVenue::Ptr TgTypeParser::parseJsonAndGetInlineQueryResultVenue(const boost::property_tree::ptree& data) const {
// NOTE: This function will be called by parseJsonAndGgetInlineQueryResult().
auto result(make_shared<InlineQueryResultVenue>());
result->latitude = data.get<float>("latitude");
result->longitude = data.get<float>("longitude");
result->address = data.get<string>("address");
result->foursquareId = data.get<string>("foursquare_id", "");
result->foursquareType = data.get<string>("foursquare_type", "");
result->thumbUrl = data.get<string>("thumb_url", "");
result->thumbWidth = data.get<int32_t>("thumb_width", 0);
result->thumbHeight = data.get<int32_t>("thumb_height", 0);
return result;
}
std::string TgTypeParser::parseInlineQueryResultVenue(const InlineQueryResultVenue::Ptr& object) const {
if (!object){
return "";
}
// This function will be called by parseInlineQueryResult(), so I don't add
// curly brackets to the result string.
string result;
appendToJson(result, "latitude", object->latitude);
appendToJson(result, "longitude", object->longitude);
appendToJson(result, "address", object->address);
appendToJson(result, "foursquare_id", object->foursquareId);
appendToJson(result, "foursquare_type", object->foursquareType);
appendToJson(result, "thumb_url", object->thumbUrl);
appendToJson(result, "thumb_width", object->thumbWidth);
appendToJson(result, "thumb_height", object->thumbHeight);
// The last comma will be erased by parseInlineQueryResult().
return result;
}
InlineQueryResultVoice::Ptr TgTypeParser::parseJsonAndGetInlineQueryResultVoice(const boost::property_tree::ptree& data) const {
// NOTE: This function will be called by parseJsonAndGgetInlineQueryResult().
auto result(make_shared<InlineQueryResultVoice>());
result->voiceUrl = data.get<string>("voice_url");
result->voiceDuration = data.get<int32_t>("voice_duration", 0);
return result;
}
std::string TgTypeParser::parseInlineQueryResultVoice(const InlineQueryResultVoice::Ptr& object) const {
if (!object){
return "";
}
// This function will be called by parseInlineQueryResult(), so I don't add
// curly brackets to the result string.
string result;
appendToJson(result, "voice_url", object->voiceUrl);
appendToJson(result, "voice_duration", object->voiceDuration);
// The last comma will be erased by parseInlineQueryResult().
return result;
}
InlineQueryResultPhoto::Ptr TgTypeParser::parseJsonAndGetInlineQueryResultPhoto(const boost::property_tree::ptree& data) const {
// NOTE: This function will be called by parseJsonAndGgetInlineQueryResult().
auto result(make_shared<InlineQueryResultPhoto>());
result->photoUrl = data.get<string>("photo_url", "");
result->thumbUrl = data.get<string>("thumb_url");
result->photoWidth = data.get("photo_width", 0);
result->photoHeight = data.get("photo_height", 0);
result->description = data.get<string>("description", "");
return result;
}
std::string TgTypeParser::parseInlineQueryResultPhoto(const InlineQueryResultPhoto::Ptr& object) const{
if (!object){
return "";
}
// This function will be called by parseInlineQueryResult(), so I don't add
// curly brackets to the result string.
string result;
appendToJson(result, "photo_url", object->photoUrl);
appendToJson(result, "thumb_url", object->thumbUrl);
appendToJson(result, "photo_width", object->photoWidth);
appendToJson(result, "photo_height", object->photoHeight);
appendToJson(result, "description", object->description);
// The last comma will be erased by parseInlineQueryResult().
return result;
}
InlineQueryResultGif::Ptr TgTypeParser::parseJsonAndGetInlineQueryResultGif(const boost::property_tree::ptree& data) const {
// NOTE: This function will be called by parseJsonAndGgetInlineQueryResult().
auto result(make_shared<InlineQueryResultGif>());
result->gifUrl = data.get<string>("gif_url", "");
result->gifWidth = data.get("gif_width", 0);
result->gifHeight = data.get("gif_height", 0);
result->gifDuration = data.get("gif_duration", 0);
result->thumbUrl = data.get<string>("thumb_url");
return result;
}
std::string TgTypeParser::parseInlineQueryResultGif(const InlineQueryResultGif::Ptr& object) const {
if (!object){
return "";
}
// This function will be called by parseInlineQueryResult(), so I don't add
// curly brackets to the result string.
string result;
appendToJson(result, "gif_url", object->gifUrl);
appendToJson(result, "gif_width", object->gifWidth);
appendToJson(result, "gif_height", object->gifHeight);
appendToJson(result, "gif_duration", object->gifDuration);
appendToJson(result, "thumb_url", object->thumbUrl);
// The last comma will be erased by parseInlineQueryResult().
return result;
}
InlineQueryResultMpeg4Gif::Ptr TgTypeParser::parseJsonAndGetInlineQueryResultMpeg4Gif(const boost::property_tree::ptree& data) const {
// NOTE: This function will be called by parseJsonAndGgetInlineQueryResult().
auto result(make_shared<InlineQueryResultMpeg4Gif>());
result->mpeg4Url = data.get<string>("mpeg4_url");
result->mpeg4Width = data.get("mpeg4_width", 0);
result->mpeg4Height = data.get("mpeg4_height", 0);
result->mpeg4Duration = data.get("mpeg4_duration", 0);
result->thumbUrl = data.get<string>("thumb_url");
return result;
}
std::string TgTypeParser::parseInlineQueryResultMpeg4Gif(const InlineQueryResultMpeg4Gif::Ptr& object) const {
if (!object){
return "";
}
// This function will be called by parseInlineQueryResult(), so I don't add
// curly brackets to the result string.
string result;
appendToJson(result, "mpeg4_url", object->mpeg4Url);
appendToJson(result, "mpeg4_width", object->mpeg4Width);
appendToJson(result, "mpeg4_height", object->mpeg4Height);
appendToJson(result, "mpeg4_duration", object->mpeg4Duration);
appendToJson(result, "thumb_url", object->thumbUrl);
// The last comma will be erased by parseInlineQueryResult().
return result;
}
InlineQueryResultVideo::Ptr TgTypeParser::parseJsonAndGetInlineQueryResultVideo(const boost::property_tree::ptree& data) const {
// NOTE: This function will be called by parseJsonAndGgetInlineQueryResult().
auto result(make_shared<InlineQueryResultVideo>());
result->videoUrl = data.get<string>("video_url");
result->mimeType = data.get<string>("mime_type");
result->thumbUrl = data.get<string>("thumb_url");
result->videoWidth = data.get("video_width", 0);
result->videoHeight = data.get("video_height", 0);
result->videoDuration = data.get("video_duration", 0);
result->description = data.get<string>("description", "");
return result;
}
std::string TgTypeParser::parseInlineQueryResultVideo(const InlineQueryResultVideo::Ptr& object) const {
if (!object){
return "";
}
// This function will be called by parseInlineQueryResult(), so I don't add
// curly brackets to the result string.
string result;
appendToJson(result, "video_url", object->videoUrl);
appendToJson(result, "mime_type", object->mimeType);
appendToJson(result, "thumb_url", object->thumbUrl);
appendToJson(result, "video_width", object->videoWidth);
appendToJson(result, "video_height", object->videoHeight);
appendToJson(result, "video_duration", object->videoDuration);
appendToJson(result, "description", object->description);
// The last comma will be erased by parseInlineQueryResult().
return result;
}
ChosenInlineResult::Ptr TgTypeParser::parseJsonAndGetChosenInlineResult(const boost::property_tree::ptree& data) const {
auto result(make_shared<ChosenInlineResult>());
result->resultId = data.get<string>("result_id");
result->from = tryParseJson<User>(&TgTypeParser::parseJsonAndGetUser, data, "from");
result->location = tryParseJson<Location>(&TgTypeParser::parseJsonAndGetLocation, data, "location");
result->inlineMessageId = data.get<string>("inline_message_id", "");
result->query = data.get<string>("query");
return result;
}
std::string TgTypeParser::parseChosenInlineResult(const ChosenInlineResult::Ptr& object) const {
if (!object){
return "";
}
string result;
result += '{';
appendToJson(result, "result_id", object->resultId);
appendToJson(result, "from", parseUser(object->from));
appendToJson(result, "query", object->query);
removeLastComma(result);
result += '}';
return result;
}
CallbackQuery::Ptr TgTypeParser::parseJsonAndGetCallbackQuery(const boost::property_tree::ptree& data) const {
auto result(make_shared<CallbackQuery>());
result->id = data.get<string>("id");
result->from = tryParseJson<User>(&TgTypeParser::parseJsonAndGetUser, data, "from");
result->message = tryParseJson<Message>(&TgTypeParser::parseJsonAndGetMessage, data, "message");
result->inlineMessageId = data.get<string>("inline_message_id", "");
result->chatInstance = data.get<string>("chat_instance");
result->gameShortName = data.get<string>("game_short_name", "");
result->data = data.get<string>("data", "");
return result;
}
std::string TgTypeParser::parseCallbackQuery(const CallbackQuery::Ptr& object) const {
if (!object){
return "";
}
string result;
result += '{';
appendToJson(result, "id", object->id);
appendToJson(result, "from", parseUser(object->from));
appendToJson(result, "message", parseMessage(object->message));
appendToJson(result, "inline_message_id", object->inlineMessageId);
appendToJson(result, "chat_instance", object->chatInstance);
appendToJson(result, "game_short_name", object->gameShortName);
appendToJson(result, "data", object->data);
removeLastComma(result);
result += '}';
return result;
}
InlineKeyboardMarkup::Ptr TgTypeParser::parseJsonAndGetInlineKeyboardMarkup(const boost::property_tree::ptree& data) const {
auto result(make_shared<InlineKeyboardMarkup>());
for (const auto& item : data.find("inline_keyboard")->second){
result->inlineKeyboard.push_back(parseJsonAndGetArray<InlineKeyboardButton>(&TgTypeParser::parseJsonAndGetInlineKeyboardButton, item.second));
}
return result;
}
std::string TgTypeParser::parseInlineKeyboardMarkup(const InlineKeyboardMarkup::Ptr& object) const {
if (!object){
return "";
}
string result;
result += '{';
result += R"("inline_keyboard":[)";
for (const auto& item : object->inlineKeyboard){
result += '[';
for (const auto& innerItem : item){
result += parseInlineKeyboardButton(innerItem);
result += ',';
}
removeLastComma(result);
result += "],";
}
if (!object->inlineKeyboard.empty())
removeLastComma(result);
result += "]}";
return result;
}
InlineKeyboardButton::Ptr TgTypeParser::parseJsonAndGetInlineKeyboardButton(const boost::property_tree::ptree& data) const {
auto result(make_shared<InlineKeyboardButton>());
result->text = data.get<string>("text");
result->url = data.get<string>("url", "");
result->callbackData = data.get<string>("callback_data", "");
result->switchInlineQuery = data.get<string>("switch_inline_query", "");
result->switchInlineQueryCurrentChat = data.get<string>("switch_inline_query_current_chat", "");
result->callbackGame = make_shared<CallbackGame>();
result->pay = data.get<bool>("pay", false);
return result;
}
std::string TgTypeParser::parseInlineKeyboardButton(const InlineKeyboardButton::Ptr& object) const {
if (!object){
return "";
}
string result;
result += '{';
appendToJson(result, "text", object->text);
appendToJson(result, "url", object->url);
appendToJson(result, "callback_data", object->callbackData);
appendToJson(result, "switch_inline_query", object->switchInlineQuery);
appendToJson(result, "switch_inline_query_current_chat", object->switchInlineQueryCurrentChat);
appendToJson(result, "pay", object->pay);
removeLastComma(result);
result += '}';
return result;
}
WebhookInfo::Ptr TgTypeParser::parseJsonAndGetWebhookInfo(const boost::property_tree::ptree& data) const {
auto result(make_shared<WebhookInfo>());
result->url = data.get<string>("url");
result->hasCustomCertificate = data.get<bool>("has_custom_certificate");
result->pendingUpdateCount = data.get<int32_t>("pending_update_count");
result->lastErrorDate = data.get<int32_t>("last_error_date", 0);
result->lastErrorMessage = data.get<string>("last_error_message", "");
result->maxConnections = data.get<int32_t>("max_connections", 0);
result->allowedUpdates = parseJsonAndGetArray<std::string>(
[](const boost::property_tree::ptree& innerData)->std::string {
return innerData.get<std::string>("");
}
, data, "allowed_updates");
return result;
}
std::string TgTypeParser::parseWebhookInfo(const WebhookInfo::Ptr& object) const {
if (!object) {
return "";
}
string result;
result += '{';
appendToJson(result, "url", object->url);
appendToJson(result, "has_custom_certificate", object->hasCustomCertificate);
appendToJson(result, "pending_update_count", object->pendingUpdateCount);
appendToJson(result, "last_error_date", object->lastErrorDate);
appendToJson(result, "last_error_message", object->lastErrorMessage);
appendToJson(result, "max_connections", object->maxConnections);
appendToJson(result, "allowed_updates",
parseArray<std::string>([](const std::string &s)->std::string {
return s;
}
, object->allowedUpdates));
removeLastComma(result);
result += '}';
return result;
}
InputMessageContent::Ptr TgTypeParser::parseJsonAndGetInputMessageContent(const boost::property_tree::ptree& data) const {
InputMessageContent::Ptr result;
// define InputMessageContent type
string tMessageText = data.get<string>("message_text", "");
float tLatitude = data.get<float>("latitude", 1000); // latitude belong (-90,90)
string tTitle = data.get<string>("title", "");
string tPnoneNumber = data.get<string>("phone_number", "");
if (!tMessageText.empty()) {
result = static_pointer_cast<InputMessageContent>(parseJsonAndGetInputTextMessageContent(data));
} else if (!tTitle.empty()) {
result = static_pointer_cast<InputMessageContent>(parseJsonAndGetInputVenueMessageContent(data));
} else if (tLatitude != 1000) {
result = static_pointer_cast<InputMessageContent>(parseJsonAndGetInputLocationMessageContent(data));
} else if (!tPnoneNumber.empty()) {
result = static_pointer_cast<InputMessageContent>(parseJsonAndGetInputContactMessageContent(data));
}
return result;
}
std::string TgTypeParser::parseInputMessageContent(const InputMessageContent::Ptr& object) const {
if (!object){
return "";
}
string result;
result += '{';
if (object->type == std::string("InputTextMessageContent")) {
result += parseInputTextMessageContent(static_pointer_cast<InputTextMessageContent>(object));
}
else if (object->type == std::string("InputLocationMessageContent")) {
result += parseInputLocationMessageContent(static_pointer_cast<InputLocationMessageContent>(object));
}
else if (object->type == std::string("InputVenueMessageContent")) {
result += parseInputVenueMessageContent(static_pointer_cast<InputVenueMessageContent>(object));
}
else if (object->type == std::string("InputContactMessageContent")) {
result += parseInputContactMessageContent(static_pointer_cast<InputContactMessageContent>(object));
}
removeLastComma(result);
result += '}';
return result;
}
InputTextMessageContent::Ptr TgTypeParser::parseJsonAndGetInputTextMessageContent(const boost::property_tree::ptree& data) const {
// NOTE: This function will be called by parseJsonAndGetInputMessageContent().
auto result(make_shared<InputTextMessageContent>());
result->messageText = data.get<string>("message_text");
result->parseMode = data.get<string>("parse_mode", "");
result->disableWebPagePreview = data.get<bool>("disable_web_page_preview", false);
return result;
}
std::string TgTypeParser::parseInputTextMessageContent(const InputTextMessageContent::Ptr& object) const {
if (!object){
return "";
}
// This function will be called by parseInputMessageContent()
string result;
appendToJson(result, "message_text", object->messageText);
appendToJson(result, "parse_mode", object->parseMode);
appendToJson(result, "disable_web_page_preview", object->disableWebPagePreview);
// The last comma will be erased by parseInputMessageContent().
return result;
}
InputLocationMessageContent::Ptr TgTypeParser::parseJsonAndGetInputLocationMessageContent(const boost::property_tree::ptree& data) const {
// NOTE: This function will be called by parseJsonAndGetInputMessageContent().
auto result(make_shared<InputLocationMessageContent>());
result->latitude = data.get<float>("latitude");
result->longitude = data.get<float>("longitude");
return result;
}
std::string TgTypeParser::parseInputLocationMessageContent(const InputLocationMessageContent::Ptr& object) const {
if (!object){
return "";
}
// This function will be called by parseInputMessageContent()
string result;
appendToJson(result, "latitude", object->latitude);
appendToJson(result, "longitude", object->longitude);
// The last comma will be erased by parseInputMessageContent().
return result;
}
InputVenueMessageContent::Ptr TgTypeParser::parseJsonAndGetInputVenueMessageContent(const boost::property_tree::ptree& data) const {
// NOTE: This function will be called by parseJsonAndGetInputMessageContent().
auto result(make_shared<InputVenueMessageContent>());
result->latitude = data.get<float>("latitude");
result->longitude = data.get<float>("longitude");
result->title = data.get<string>("title");
result->address = data.get<string>("address");
result->foursquareId = data.get<string>("foursquare_id", "");
result->foursquareType = data.get<string>("foursquare_type", "");
return result;
}
std::string TgTypeParser::parseInputVenueMessageContent(const InputVenueMessageContent::Ptr& object) const {
if (!object){
return "";
}
// This function will be called by parseInputMessageContent()
string result;
appendToJson(result, "latitude", object->latitude);
appendToJson(result, "longitude", object->longitude);
appendToJson(result, "title", object->title);
appendToJson(result, "address", object->address);
appendToJson(result, "foursquare_id", object->foursquareId);
// The last comma will be erased by parseInputMessageContent().
return result;
}
InputContactMessageContent::Ptr TgTypeParser::parseJsonAndGetInputContactMessageContent(const boost::property_tree::ptree& data) const {
// NOTE: This function will be called by parseJsonAndGetInputMessageContent().
auto result(make_shared<InputContactMessageContent>());
result->phoneNumber = data.get<string>("phone_number");
result->firstName = data.get<string>("first_name");
result->lastName = data.get<string>("last_name", "");
result->vcard = data.get<string>("vcard", "");
return result;
}
std::string TgTypeParser::parseInputContactMessageContent(const InputContactMessageContent::Ptr& object) const {
if (!object){
return "";
}
// This function will be called by parseInputMessageContent()
string result;
appendToJson(result, "phone_number", object->phoneNumber);
appendToJson(result, "first_name", object->firstName);
appendToJson(result, "last_name", object->lastName);
appendToJson(result, "vcard", object->vcard);
// The last comma will be erased by parseInputMessageContent().
return result;
}
Invoice::Ptr TgTypeParser::parseJsonAndGetInvoice(const boost::property_tree::ptree& data) const {
auto result(make_shared<Invoice>());
result->title = data.get<string>("title");
result->description = data.get<string>("description");
result->startParameter = data.get<string>("start_parameter");
result->currency = data.get<string>("currency");
result->totalAmount = data.get<int32_t>("total_amount");
return result;
}
std::string TgTypeParser::parseInvoice(const Invoice::Ptr& object) const {
if (!object) {
return "";
}
string result;
result += '{';
appendToJson(result, "title", object->title);
appendToJson(result, "description", object->description);
appendToJson(result, "start_parameter", object->startParameter);
appendToJson(result, "currency", object->currency);
appendToJson(result, "total_amount", object->totalAmount);
removeLastComma(result);
result += '}';
return result;
}
LabeledPrice::Ptr TgTypeParser::parseJsonAndGetLabeledPrice(const boost::property_tree::ptree& data) const {
auto result(make_shared<LabeledPrice>());
result->label = data.get<string>("label");
result->amount = data.get<int32_t>("amount");
return result;
}
string TgTypeParser::parseLabeledPrice(const LabeledPrice::Ptr& object) const {
std::string result;
result += '{';
appendToJson(result, "label", object->label);
appendToJson(result, "amount", object->amount);
removeLastComma(result);
result += '}';
return result;
}
OrderInfo::Ptr TgTypeParser::parseJsonAndGetOrderInfo(const boost::property_tree::ptree& data) const {
auto result(make_shared<OrderInfo>());
result->name = data.get<string>("name", "");
result->phoneNumber = data.get<string>("phone_number", "");
result->email = data.get<string>("email", "");
result->shippingAddress = tryParseJson(&TgTypeParser::parseJsonAndGetShippingAddress, data, "shipping_address");
return result;
}
string TgTypeParser::parseOrderInfo(const OrderInfo::Ptr& object) const {
if (!object) {
return "";
}
std::string result;
result += '{';
if (!object->name.empty()) {
appendToJson(result, "name", object->name);
}
if (!object->phoneNumber.empty()) {
appendToJson(result, "phone_number", object->phoneNumber);
}
if (!object->email.empty()) {
appendToJson(result, "email", object->email);
}
if (!object->shippingAddress) {
result += R"("shipping_address":)";
result += parseShippingAddress(object->shippingAddress);
result += ",";
}
removeLastComma(result);
result += '}';
return result;
}
PreCheckoutQuery::Ptr TgTypeParser::parseJsonAndGetPreCheckoutQuery(const boost::property_tree::ptree& data) const {
auto result(make_shared<PreCheckoutQuery>());
result->id = data.get<string>("id");
result->from = tryParseJson(&TgTypeParser::parseJsonAndGetUser, data, "user");
result->currency = data.get<string>("currency");
result->totalAmount = data.get<int32_t>("total_amount");
return result;
}
string TgTypeParser::parsePreCheckoutQuery(const PreCheckoutQuery::Ptr& object) const {
std::string result;
result += '{';
appendToJson(result, "id", object->id);
result += R"("user":)";
result += parseUser(object->from);
result += ",";
appendToJson(result, "currency", object->currency);
appendToJson(result, "total_amount", object->totalAmount);
removeLastComma(result);
result += '}';
return result;
}
ShippingAddress::Ptr TgTypeParser::parseJsonAndGetShippingAddress(const boost::property_tree::ptree& data) const {
ShippingAddress::Ptr result;
result->countryCode = data.get<string>("country_code");
result->state = data.get<string>("state", "");
result->city = data.get<string>("city");
result->streetLine1 = data.get<string>("street_line1");
result->streetLine2 = data.get<string>("street_line2");
result->postCode = data.get<string>("post_code");
return result;
}
string TgTypeParser::parseShippingAddress(const ShippingAddress::Ptr& object) const {
std::string result;
result += '{';
appendToJson(result, "country_code", object->countryCode);
if (!object->state.empty()) {
appendToJson(result, "state", object->state);
}
appendToJson(result, "city", object->city);
appendToJson(result, "street_line1", object->streetLine1);
appendToJson(result, "street_line2", object->streetLine2);
appendToJson(result, "post_code", object->postCode);
removeLastComma(result);
result += '}';
return result;
}
ShippingOption::Ptr TgTypeParser::parseJsonAndGetShippingOption(const boost::property_tree::ptree& data) const {
auto result(make_shared<ShippingOption>());
result->id = data.get<string>("id");
result->title = data.get<string>("title");
result->prices = parseJsonAndGetArray<LabeledPrice>(&TgTypeParser::parseJsonAndGetLabeledPrice, data, "prices");
return result;
}
string TgTypeParser::parseShippingOption(const ShippingOption::Ptr& object) const {
std::string result;
result += '{';
appendToJson(result, "id", object->id);
appendToJson(result, "title", object->title);
removeLastComma(result);
result += R"("prices":)";
result += parseArray(&TgTypeParser::parseLabeledPrice, object->prices);
result += '}';
return result;
}
ShippingQuery::Ptr TgTypeParser::parseJsonAndGetShippingQuery(const boost::property_tree::ptree& data) const {
auto result(make_shared<ShippingQuery>());
result->id = data.get<string>("id");
result->from = tryParseJson(&TgTypeParser::parseJsonAndGetUser, data, "from");
result->invoicePayload = data.get<string>("invoice_payload");
result->shippingAddress = tryParseJson(&TgTypeParser::parseJsonAndGetShippingAddress, data, "shipping_address");
return result;
}
string TgTypeParser::parseShippingQuery(const ShippingQuery::Ptr& object) const {
string result;
result += '{';
appendToJson(result, "id", object->id);
result += R"("from":)";
result += parseUser(object->from);
result += ",";
appendToJson(result, "invoice_payload", object->invoicePayload);
result += R"("shipping_address":)";
result += parseShippingAddress(object->shippingAddress);
result += ",";
removeLastComma(result);
result += '}';
return result;
}
SuccessfulPayment::Ptr TgTypeParser::parseJsonAndGetSuccessfulPayment(const boost::property_tree::ptree& data) const {
auto result(make_shared<SuccessfulPayment>());
result->currency = data.get<string>("currency");
result->totalAmount = data.get<int32_t>("total_amount");
result->invoicePayload = data.get<string>("invoice_payload");
result->shippingOptionId = data.get<string>("shipping_option_id");
result->orderInfo = tryParseJson(&TgTypeParser::parseJsonAndGetOrderInfo, data, "order_info");
return result;
}
std::string TgTypeParser::parseSuccessfulPayment(const SuccessfulPayment::Ptr& object) const {
string result;
result += '{';
appendToJson(result, "currency", object->currency);
appendToJson(result, "total_amount", object->totalAmount);
appendToJson(result, "invoice_payload", object->invoicePayload);
appendToJson(result, "shipping_option_id", object->shippingOptionId);
result += R"("order_info":)";
result += parseOrderInfo(object->orderInfo);
result += ",";
removeLastComma(result);
result += '}';
return result;
}
void TgTypeParser::appendToJson(string& json, const string& varName, const string& value) const {
if (value.empty()) {
return;
}
json += '"';
json += varName;
json += R"(":)";
if (value.front() != '{') {
json += '"';
}
json += value;
if (value.back() != '}') {
json += '"';
}
json += ',';
}
}
|
//===- BlockExtractor.cpp - Extracts blocks into their own functions ------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This pass extracts the specified basic blocks from the module into their
// own functions.
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Module.h"
#include "llvm/Pass.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Transforms/IPO.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
#include "llvm/Transforms/Utils/CodeExtractor.h"
using namespace llvm;
#define DEBUG_TYPE "block-extractor"
STATISTIC(NumExtracted, "Number of basic blocks extracted");
static cl::opt<std::string> BlockExtractorFile(
"extract-blocks-file", cl::value_desc("filename"),
cl::desc("A file containing list of basic blocks to extract"), cl::Hidden);
cl::opt<bool> BlockExtractorEraseFuncs("extract-blocks-erase-funcs",
cl::desc("Erase the existing functions"),
cl::Hidden);
namespace {
class BlockExtractor : public ModulePass {
SmallVector<BasicBlock *, 16> Blocks;
bool EraseFunctions;
SmallVector<std::pair<std::string, std::string>, 32> BlocksByName;
public:
static char ID;
BlockExtractor(const SmallVectorImpl<BasicBlock *> &BlocksToExtract,
bool EraseFunctions)
: ModulePass(ID), Blocks(BlocksToExtract.begin(), BlocksToExtract.end()),
EraseFunctions(EraseFunctions) {
if (!BlockExtractorFile.empty())
loadFile();
}
BlockExtractor() : BlockExtractor(SmallVector<BasicBlock *, 0>(), false) {}
bool runOnModule(Module &M) override;
private:
void loadFile();
void splitLandingPadPreds(Function &F);
};
} // end anonymous namespace
char BlockExtractor::ID = 0;
INITIALIZE_PASS(BlockExtractor, "extract-blocks",
"Extract basic blocks from module", false, false)
ModulePass *llvm::createBlockExtractorPass() { return new BlockExtractor(); }
ModulePass *llvm::createBlockExtractorPass(
const SmallVectorImpl<BasicBlock *> &BlocksToExtract, bool EraseFunctions) {
return new BlockExtractor(BlocksToExtract, EraseFunctions);
}
/// Gets all of the blocks specified in the input file.
void BlockExtractor::loadFile() {
auto ErrOrBuf = MemoryBuffer::getFile(BlockExtractorFile);
if (ErrOrBuf.getError())
report_fatal_error("BlockExtractor couldn't load the file.");
// Read the file.
auto &Buf = *ErrOrBuf;
SmallVector<StringRef, 16> Lines;
Buf->getBuffer().split(Lines, '\n', /*MaxSplit=*/-1,
/*KeepEmpty=*/false);
for (const auto &Line : Lines) {
auto FBPair = Line.split(' ');
BlocksByName.push_back({FBPair.first, FBPair.second});
}
}
/// Extracts the landing pads to make sure all of them have only one
/// predecessor.
void BlockExtractor::splitLandingPadPreds(Function &F) {
for (BasicBlock &BB : F) {
for (Instruction &I : BB) {
if (!isa<InvokeInst>(&I))
continue;
InvokeInst *II = cast<InvokeInst>(&I);
BasicBlock *Parent = II->getParent();
BasicBlock *LPad = II->getUnwindDest();
// Look through the landing pad's predecessors. If one of them ends in an
// 'invoke', then we want to split the landing pad.
bool Split = false;
for (auto PredBB : predecessors(LPad)) {
if (PredBB->isLandingPad() && PredBB != Parent &&
isa<InvokeInst>(Parent->getTerminator())) {
Split = true;
break;
}
}
if (!Split)
continue;
SmallVector<BasicBlock *, 2> NewBBs;
SplitLandingPadPredecessors(LPad, Parent, ".1", ".2", NewBBs);
}
}
}
bool BlockExtractor::runOnModule(Module &M) {
bool Changed = false;
// Get all the functions.
SmallVector<Function *, 4> Functions;
for (Function &F : M) {
splitLandingPadPreds(F);
Functions.push_back(&F);
}
// Get all the blocks specified in the input file.
for (const auto &BInfo : BlocksByName) {
Function *F = M.getFunction(BInfo.first);
if (!F)
report_fatal_error("Invalid function name specified in the input file");
auto Res = llvm::find_if(*F, [&](const BasicBlock &BB) {
return BB.getName().equals(BInfo.second);
});
if (Res == F->end())
report_fatal_error("Invalid block name specified in the input file");
Blocks.push_back(&*Res);
}
// Extract basic blocks.
for (BasicBlock *BB : Blocks) {
// Check if the module contains BB.
if (BB->getParent()->getParent() != &M)
report_fatal_error("Invalid basic block");
LLVM_DEBUG(dbgs() << "BlockExtractor: Extracting "
<< BB->getParent()->getName() << ":" << BB->getName()
<< "\n");
SmallVector<BasicBlock *, 2> BlocksToExtractVec;
BlocksToExtractVec.push_back(BB);
if (const InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator()))
BlocksToExtractVec.push_back(II->getUnwindDest());
CodeExtractor(BlocksToExtractVec).extractCodeRegion();
++NumExtracted;
Changed = true;
}
// Erase the functions.
if (EraseFunctions || BlockExtractorEraseFuncs) {
for (Function *F : Functions) {
LLVM_DEBUG(dbgs() << "BlockExtractor: Trying to delete " << F->getName()
<< "\n");
F->deleteBody();
}
// Set linkage as ExternalLinkage to avoid erasing unreachable functions.
for (Function &F : M)
F.setLinkage(GlobalValue::ExternalLinkage);
Changed = true;
}
return Changed;
}
|
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2013 - Raw Material Software Ltd.
Permission is granted to use this software under the terms of either:
a) the GPL v2 (or any later version)
b) the Affero GPL v3
Details of these licenses can be found at: www.gnu.org/licenses
JUCE 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.
------------------------------------------------------------------------------
To release a closed-source product which uses JUCE, commercial licenses are
available: visit www.juce.com for more information.
==============================================================================
*/
#if JUCE_USE_OPENGL_SHADERS
OpenGLShaderProgram::OpenGLShaderProgram (const OpenGLContext& c) noexcept
: context (c)
{
// This object can only be created and used when the current thread has an active OpenGL context.
jassert (OpenGLHelpers::isContextActive());
programID = context.extensions.glCreateProgram();
}
OpenGLShaderProgram::~OpenGLShaderProgram() noexcept
{
context.extensions.glDeleteProgram (programID);
}
double OpenGLShaderProgram::getLanguageVersion()
{
#if JUCE_OPENGL_ES
// GLES doesn't support this version number, but that shouldn't matter since
// on GLES you probably won't need to check it.
jassertfalse;
return 0;
#else
return String ((const char*) glGetString (GL_SHADING_LANGUAGE_VERSION))
.upToFirstOccurrenceOf (" ", false, false).getDoubleValue();
#endif
}
bool OpenGLShaderProgram::addShader (StringRef code, GLenum type)
{
GLuint shaderID = context.extensions.glCreateShader (type);
#if JUCE_STRING_UTF_TYPE == 8
const GLchar* c = code.text;
#else
String codeString (code.text);
const GLchar* c = codeString.toRawUTF8();
#endif
context.extensions.glShaderSource (shaderID, 1, &c, nullptr);
context.extensions.glCompileShader (shaderID);
GLint status = GL_FALSE;
context.extensions.glGetShaderiv (shaderID, GL_COMPILE_STATUS, &status);
if (status == GL_FALSE)
{
GLchar infoLog [16384];
GLsizei infoLogLength = 0;
context.extensions.glGetShaderInfoLog (shaderID, sizeof (infoLog), &infoLogLength, infoLog);
errorLog = String (infoLog, (size_t) infoLogLength);
#if JUCE_DEBUG && ! JUCE_DONT_ASSERT_ON_GLSL_COMPILE_ERROR
// Your GLSL code contained compile errors!
// Hopefully this compile log should help to explain what went wrong.
DBG (errorLog);
jassertfalse;
#endif
return false;
}
context.extensions.glAttachShader (programID, shaderID);
context.extensions.glDeleteShader (shaderID);
JUCE_CHECK_OPENGL_ERROR
return true;
}
bool OpenGLShaderProgram::addVertexShader (StringRef code) { return addShader (code, GL_VERTEX_SHADER); }
bool OpenGLShaderProgram::addFragmentShader (StringRef code) { return addShader (code, GL_FRAGMENT_SHADER); }
bool OpenGLShaderProgram::link() noexcept
{
context.extensions.glLinkProgram (programID);
GLint status = GL_FALSE;
context.extensions.glGetProgramiv (programID, GL_LINK_STATUS, &status);
if (status == GL_FALSE)
{
GLchar infoLog [16384];
GLsizei infoLogLength = 0;
context.extensions.glGetProgramInfoLog (programID, sizeof (infoLog), &infoLogLength, infoLog);
errorLog = String (infoLog, (size_t) infoLogLength);
#if JUCE_DEBUG && ! JUCE_DONT_ASSERT_ON_GLSL_COMPILE_ERROR
// Your GLSL code contained link errors!
// Hopefully this compile log should help to explain what went wrong.
DBG (errorLog);
jassertfalse;
#endif
}
JUCE_CHECK_OPENGL_ERROR
return status != GL_FALSE;
}
void OpenGLShaderProgram::use() const noexcept
{
context.extensions.glUseProgram (programID);
}
OpenGLShaderProgram::Uniform::Uniform (const OpenGLShaderProgram& program, const char* const name)
: uniformID (program.context.extensions.glGetUniformLocation (program.programID, name)), context (program.context)
{
jassert (uniformID >= 0);
}
OpenGLShaderProgram::Attribute::Attribute (const OpenGLShaderProgram& program, const char* name)
: attributeID (program.context.extensions.glGetAttribLocation (program.programID, name))
{
jassert (attributeID >= 0);
}
void OpenGLShaderProgram::Uniform::set (GLfloat n1) const noexcept { context.extensions.glUniform1f (uniformID, n1); }
void OpenGLShaderProgram::Uniform::set (GLint n1) const noexcept { context.extensions.glUniform1i (uniformID, n1); }
void OpenGLShaderProgram::Uniform::set (GLfloat n1, GLfloat n2) const noexcept { context.extensions.glUniform2f (uniformID, n1, n2); }
void OpenGLShaderProgram::Uniform::set (GLfloat n1, GLfloat n2, GLfloat n3) const noexcept { context.extensions.glUniform3f (uniformID, n1, n2, n3); }
void OpenGLShaderProgram::Uniform::set (GLfloat n1, GLfloat n2, GLfloat n3, float n4) const noexcept { context.extensions.glUniform4f (uniformID, n1, n2, n3, n4); }
void OpenGLShaderProgram::Uniform::set (GLint n1, GLint n2, GLint n3, GLint n4) const noexcept { context.extensions.glUniform4i (uniformID, n1, n2, n3, n4); }
void OpenGLShaderProgram::Uniform::set (const GLfloat* values, GLsizei numValues) const noexcept { context.extensions.glUniform1fv (uniformID, numValues, values); }
void OpenGLShaderProgram::Uniform::setMatrix2 (const GLfloat* v, GLint num, GLboolean trns) const noexcept { context.extensions.glUniformMatrix2fv (uniformID, num, trns, v); }
void OpenGLShaderProgram::Uniform::setMatrix3 (const GLfloat* v, GLint num, GLboolean trns) const noexcept { context.extensions.glUniformMatrix3fv (uniformID, num, trns, v); }
void OpenGLShaderProgram::Uniform::setMatrix4 (const GLfloat* v, GLint num, GLboolean trns) const noexcept { context.extensions.glUniformMatrix4fv (uniformID, num, trns, v); }
#endif
|
//*******************************************************************************************************
// APath.cpp
// Christopher Wagner 9/5/2018
//
// Contains methods to assist in pathfinding given a vector<vector<>> of nodes with walkable and
// parent variables.
//*******************************************************************************************************
#pragma once
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <stdlib.h>
#include "Node.h"
#include "Vector2.h"
#include "Grid.h"
#include <algorithm>
#include "APath.h"
using namespace std;
Grid tempGrid;
int tempDistance = 0;
bool pathIncomplete = false;
void APath::Start(Grid gridd)
{
tempGrid = gridd; //Set the classes internal grid
}
vector<Node*> APath::findPath(Vector2 start, Vector2 end)
{
vector<Node*> open; //vector to record open nodes to still be checked
vector<Node*> closed; //vector to record closed nodes that have already been checked
Node* startNode = new Node; //Pointer to the starting node
startNode->position.x = start.x;
startNode->position.y = start.y;
Node* targetNode = new Node; //Pointer to the ending node
targetNode->position.x = end.x;
targetNode->position.y = end.y;
Node* current = startNode; //Pointer to the current node being looked at
tempDistance = getDistance(startNode, targetNode); //Finds the distance between the start and end nodes
current->DistanceFrom = tempDistance;
current->MoveCost = 1;
open.push_back(current); //Add the starting node to the open list to be checked
pathIncomplete = false;
//Continues until there are either no nodes left to be checked on the grid or the path has been found
while (open.size() > 0)
{
current = open[0]; //Setting current to the next Node in line to be checked
int toBeErased = 0; //Integer to keep track of which Node to remove from open
//Finds the Node inside of open that is closest to the target node and sets it to current
for (int i = 1; i < open.size(); i++)
{
if (open[i]->TotalScore() < current->TotalScore() || (open[i]->TotalScore() == current->TotalScore() && open[i]->DistanceFrom < current->DistanceFrom))
{
current = open[i];
toBeErased = i;
}
}
open.erase(open.begin() + toBeErased); //remove the selected Node from open
closed.push_back(current); //Place the current node into closed
//Checks to see if the target node has been reached
if (current->position.x == targetNode->position.x && current->position.y ==targetNode->position.y)
{
return retracePath(startNode, current); //Finds the path from the start to the target
}
vector<Node*> neighbor = tempGrid.GetNeighbors(current); //Stores neighbors of the current node to be checked
for (int g = 0; g < neighbor.size(); g++)
{
if (containsNode(neighbor[g], closed)) //Makes sure the node being checked hasnt already been checked
{
}
else
{
int newMovementCostToNeighbor = current->MoveCost + getDistance(current, neighbor[g]); //Record distance between node being checked and target node
//Checks to see if the new node needs to be added to Open
if (newMovementCostToNeighbor < neighbor[g]->MoveCost || !(containsNode(neighbor[g], open)))
{
//Sets the nodes variables before adding it to Open
neighbor[g]->setParent(current);
neighbor[g]->MoveCost = newMovementCostToNeighbor;
neighbor[g]->DistanceFrom = getDistance(neighbor[g], targetNode);
if (!containsNode(neighbor[g], open))
{
open.push_back(neighbor[g]);
}
}
}
}
}
pathIncomplete = true; //Registers that the correct path was not found
if (tempPath.size() == 0 || tempPath.size() == 1)
{
return tempPath;
}
else
{
return tempPath;
}
}
int APath::getDistance(Node* start, Node* end)
{
return (abs(start->position.x - end->position.x) + (abs(start->position.y - end->position.y)) * 10);
}
bool APath::containsNode(Node* check, vector<Node*> target)
{
for (int i = 0; i < target.size(); i++)
{
if (target[i]->position.x == check->position.x && target[i]->position.y == check->position.y)
{
return true;
}
}
return false;
}
vector<Node*> APath::retracePath(Node* start, Node* target)
{
vector<Node*> path;
Node* curren = target;
//Runs until the path from start to target has been fully retraced
while (curren->position.x != start->position.x && curren->position.x != start->position.y)
{
path.push_back(curren);
if (!curren->getParent()) //Something has gone wrong and the linked list is broken
{
return tempPath;
}
curren = curren->getParent(); //Moves down the line of nodes by one
}
reverse(path.begin(), path.end()); //Reverses the list of Nodes so it starts from the start node and ends at the target
return path;
}
|
/*
* Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License, version 2.0, as
* published by the Free Software Foundation.
*
* This program is also distributed with certain software (including
* but not limited to OpenSSL) that is licensed under separate terms,
* as designated in a particular file or component or in included license
* documentation. The authors of MySQL hereby grant you an
* additional permission to link the program and your derivative works
* with the separately licensed software that they have included with
* MySQL.
*
* Without limiting anything contained in the foregoing, this file,
* which is part of MySQL Connector/C++, is also subject to the
* Universal FOSS Exception, version 1.0, a copy of which can be found at
* http://oss.oracle.com/licenses/universal-foss-exception.
*
* This program 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, version 2.0, for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
/*
Implementation of error handling infrastructure
*/
#include <mysql/cdk/foundation/error.h>
PUSH_SYS_WARNINGS
#include <stdexcept>
#include <sstream>
POP_SYS_WARNINGS
namespace cdk {
namespace foundation {
/*
Default prefix added to error description in the string returned by
what().
*/
const string Error::m_default_prefix = L"CDK Error: ";
void Error::description_materialize() const
{
if (m_what)
return;
std::ostringstream buf;
describe(buf);
Error *self= const_cast<Error*>(this);
self->m_what= new std::string(m_what_prefix);
self->m_what->append(buf.str());
}
/*
Generic error category
----------------------
Error codes in this category map to CDK error conditions with the
same numeric value. Error code description is the same as description
of the corresponding error condition.
*/
class error_category_generic : public error_category_base
{
error_category_generic() {}
public:
const char* name() const NOEXCEPT { return "cdk"; }
std::string message(int) const;
error_condition do_default_error_condition(int code) const NOEXCEPT
{
return error_condition(code, generic_error_category());
}
bool do_equivalent(int code, const error_condition &ec) const
{
return ec == default_error_condition(code);
}
friend const error_category& generic_error_category();
};
const error_category& generic_error_category()
{
static const error_category_generic instance;
return instance;
}
// Messages for generic errors
#define ERROR_CONDITION_CASE(C,N,D) \
case cdkerrc::C: return std::string(D);
std::string error_category_generic::message(int code) const
{
switch (code)
{
case 0: return "No error";
ERROR_CONDITION_LIST(ERROR_CONDITION_CASE)
default: return "Unknown error condition";
}
}
/*
System error category
---------------------
*/
const error_category& system_error_category()
{
return std::system_category();
}
/*
Standard/POSIX error category
-----------------------------
*/
const error_category& std_error_category()
{
return std::generic_category();
}
const error_category& posix_error_category()
{
return std::generic_category();
}
bool error_code::operator== (errc::code code) const
{
return category() == std_error_category() && value() == code;
}
bool error_code::operator== (cdkerrc::code code) const
{
return category() == generic_error_category() && value() == code;
}
/*
Wrapping external exceptions as CDK errors
------------------------------------------
*/
// Error class that wraps standard exception
class Std_exception : public Error
{
public:
Std_exception(const std::exception &e)
: Error(cdkerrc::standard_exception, e.what())
{}
};
// Error class for unknown exceptions
class Unknown_exception : public Error
{
public:
Unknown_exception() : Error(cdkerrc::unknown_exception)
{}
};
void rethrow_error()
{
try {
throw;
}
catch (const Error&)
{
// CDK errors do not need any wrapping
throw;
}
catch (const std::system_error &e)
{
throw Error(e);
}
catch (const std::exception &e)
{
throw Std_exception(e);
}
catch (...)
{
throw Unknown_exception();
}
}
// Throwing POSIX and system errors
void throw_posix_error()
{
if (errno)
throw_error(errno, posix_error_category());
}
void throw_system_error()
{
#ifdef _WIN32
int error= static_cast<int>(GetLastError());
#else
int error= errno;
#endif
if (error)
throw_error(error, system_error_category());
}
}} // sdk::foundation
|
////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2014-2021, Lawrence Livermore National Security, LLC.
// Produced at the Lawrence Livermore National Laboratory.
// Written by the LBANN Research Team (B. Van Essen, et al.) listed in
// the CONTRIBUTORS file. <lbann-dev@llnl.gov>
//
// LLNL-CODE-697807.
// All rights reserved.
//
// This file is part of LBANN: Livermore Big Artificial Neural Network
// Toolkit. For details, see http://software.llnl.gov/LBANN or
// https://github.com/LLNL/LBANN.
//
// Licensed under the Apache License, Version 2.0 (the "Licensee"); 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 "lbann/execution_algorithms/ltfb.hpp"
#include "lbann/base.hpp"
#include "lbann/execution_algorithms/factory.hpp"
#include "lbann/execution_algorithms/ltfb/meta_learning_strategy.hpp"
#include "lbann/execution_algorithms/ltfb/termination_criteria.hpp"
#include "lbann/models/model.hpp"
#include "training_algorithm.pb.h"
// FIXME (trb 04/14/21): This code is copied with only minimal
// modification from the LTFB callback implementation. It should be
// reviewed for any potential simplification and/or optimization.
namespace lbann {
void LTFB::apply(execution_context& context,
model& m,
data_coordinator& dc,
execution_mode /*mode*/)
{
auto const& ltfb_term = m_termination_criteria;
auto& ltfb_ctxt = dynamic_cast<ExeContextType&>(context);
// Sync trainers (Assumption: all trainers in this lbann_comm are
// participating in this training algorithm)
m.get_comm()->intertrainer_barrier();
// LTFB likely has different stopping criteria than SGD (e.g., K
// tournament rounds; some specified relative or absolute
// reduction in objective function value; etc.), or its stopping
// criteria might be defined in terms of the SGD stopping criteria
// (e.g., N total sgd batches). That complexity lives in the
// ltfb::TerminationCriteria class.
while (!ltfb_term(ltfb_ctxt)) {
m_local_algo->apply(m, dc);
m_meta_learning_strategy->select_next(m, ltfb_ctxt, dc);
ltfb_ctxt.inc_step();
}
// Final sweep of local training.
m_local_algo->apply(m, dc);
// TODO: How do we support aggregate outputs? What does "output"
// mean here? Do we communicate among all trainers and just write
// some interesting subset to disk? Top-k best models, e.g.
//
// maybe:
//
// intertrainer_postprocess(m);
}
} // namespace lbann
// build_abstract impl for metalearning strategies
template <>
std::unique_ptr<lbann::LTFB>
lbann::make<lbann::LTFB>(google::protobuf::Message const& msg_in)
{
auto const& msg = dynamic_cast<lbann_data::TrainingAlgorithm const&>(msg_in);
// Extract the solver parameters.
lbann_data::LTFB params;
LBANN_ASSERT(msg.parameters().UnpackTo(¶ms));
auto const& stopping = params.stopping_criteria();
return make_unique<LTFB>(
msg.name(),
make_abstract<training_algorithm>(params.local_training_algorithm()),
make_abstract<ltfb::MetaLearningStrategy>(params.meta_learning_strategy()),
ltfb::TerminationCriteria{stopping.max_tournaments()});
}
|
/*
* Copyright (C) 2012 Apple Inc. 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.
*
* 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"
#if WK_HAVE_C_SPI
#include "PlatformUtilities.h"
#include "Test.h"
namespace TestWebKitAPI {
static bool done;
// Callback for WKContextGetStatistics.
static void wkContextGetStatisticsCallback(WKDictionaryRef statistics, WKErrorRef error, void* functionContext)
{
EXPECT_NOT_NULL(error);
done = true;
}
TEST(WebKit2, WebCoreStatisticsWithNoWebProcess)
{
WKRetainPtr<WKContextRef> context = adoptWK(WKContextCreate());
WKContextGetStatistics(context.get(), 0, wkContextGetStatisticsCallback);
Util::run(&done);
}
} // namespace TestWebKitAPI
#endif
|
//////////////////////////////////////////////////////////////////////////////
/// Copyright 2003 and onward LASMEA UMR 6602 CNRS/U.B.P Clermont-Ferrand
/// Copyright 2009 and onward 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 NT2_TOOLBOX_GSL_SPECFUN_FUNCTION_SIMD_SSE_SSE4A_GSL_SF_DILOG_HPP_INCLUDED
#define NT2_TOOLBOX_GSL_SPECFUN_FUNCTION_SIMD_SSE_SSE4A_GSL_SF_DILOG_HPP_INCLUDED
#include <nt2/toolbox/gsl_specfun/function/simd/sse/ssse3/gsl_sf_dilog.hpp>
#endif
|
#include "app_options.hpp"
#include "file_saver.hpp"
//#include "save_image_tga.hpp"
#include "string_helpers.hpp"
#include "save_image_unix.hpp"
//#include "DirectXTex.h"
#include <exception>
#include <string_view>
#include <string>
using namespace std::literals;
namespace {
/*
bool image_needs_converting(const DirectX::ScratchImage& image) noexcept
{
const auto format = image.GetMetadata().format;
switch (format) {
case DXGI_FORMAT_R8G8B8A8_UNORM:
case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB:
case DXGI_FORMAT_B8G8R8A8_UNORM:
case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB:
case DXGI_FORMAT_B8G8R8X8_UNORM:
case DXGI_FORMAT_B8G8R8X8_UNORM_SRGB:
return false;
default:
return true;
}
}
void ensure_basic_format(DirectX::ScratchImage& image)
{
DirectX::ScratchImage conv_image;
if (DirectX::IsCompressed(image.GetMetadata().format)) {
DirectX::Decompress(*image.GetImage(0, 0, 0), DXGI_FORMAT_R8G8B8A8_UNORM,
conv_image);
image = std::move(conv_image);
}
else if (image_needs_converting(image)) {
DirectX::Convert(*image.GetImage(0, 0, 0), DXGI_FORMAT_R8G8B8A8_UNORM,
DirectX::TEX_FILTER_DEFAULT, DirectX::TEX_THRESHOLD_DEFAULT,
conv_image);
image = std::move(conv_image);
}
}
*/
auto image_extension(const Image_format format) noexcept -> std::string_view
{
switch (format) {
case Image_format::tga:
return ".tga"sv;
case Image_format::png:
return ".png"sv;
case Image_format::dds:
return ".dds"sv;
default:
std::terminate();
}
}
}
void save_image(std::string_view name, cv::Mat image,
File_saver& file_saver, Image_format save_format,
Model_format model_format)
{
// Windows' 3D Viewer doesn't handle relative texture paths, so we have to put the
// textures in the same folder as the glTF files if we want them to be previewable in
// it.
const auto dir = model_format == Model_format::gltf2 ? "models"sv : "textures"sv;
// glTF doesn't support .tga files.
//save_format = model_format == Model_format::gltf2 ? Image_format::png : save_format;
save_format = Image_format::png;
const auto path = file_saver.build_file_path(dir, name, image_extension(save_format));
file_saver.create_dir(dir);
/*
if (save_format == Image_format::tga) {
ensure_basic_format(image);
save_image_tga(path, *image.GetImage(0, 0, 0));
}
else if (save_format == Image_format::png) {
ensure_basic_format(image);
DirectX::SaveToWICFile(*image.GetImage(0, 0, 0), DirectX::WIC_FLAGS_NONE,
DirectX::GetWICCodec(DirectX::WIC_CODEC_PNG), path.c_str());
}
else if (save_format == Image_format::dds) {
DirectX::SaveToDDSFile(image.GetImages(), image.GetImageCount(),
image.GetMetadata(), DirectX::DDS_FLAGS_NONE, path.c_str());
}
*/
cv::imwrite(path.string(), image);
}
|
// Copyright Carl Philipp Reh 2009 - 2021.
// 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)
#ifndef FCPPT_PARSE_FAIL_FWD_HPP_INCLUDED
#define FCPPT_PARSE_FAIL_FWD_HPP_INCLUDED
namespace fcppt::parse
{
template <typename Result>
class fail;
}
#endif
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// SPDX-License-Identifier: MIT
#pragma once
#include <chrono>
#include <memory>
#include <string>
#include <type_traits>
#include <vector>
#include <azure/core/context.hpp>
#include <azure/core/datetime.hpp>
#include <azure/core/etag.hpp>
#include <azure/core/http/http.hpp>
#include <azure/core/internal/http/pipeline.hpp>
#include <azure/core/nullable.hpp>
#include <azure/core/response.hpp>
#include <azure/storage/common/crypt.hpp>
#include <azure/storage/common/internal/xml_wrapper.hpp>
#include <azure/storage/common/storage_common.hpp>
#include <azure/storage/common/storage_exception.hpp>
#include "azure/storage/blobs/dll_import_export.hpp"
/* cspell:ignore xmsblobsequencenumber */
namespace Azure { namespace Storage { namespace Blobs {
namespace Models {
/**
* @brief Extensible enum that used to identify the account kind.
*/
class AccountKind final {
public:
AccountKind() = default;
explicit AccountKind(std::string value) : m_value(std::move(value)) {}
bool operator==(const AccountKind& other) const { return m_value == other.m_value; }
bool operator!=(const AccountKind& other) const { return !(*this == other); }
const std::string& ToString() const { return m_value; }
/**
* General-purpose v1 account.
*/
AZ_STORAGE_BLOBS_DLLEXPORT const static AccountKind Storage;
/**
* Blob Storage account.
*/
AZ_STORAGE_BLOBS_DLLEXPORT const static AccountKind BlobStorage;
/**
* General-purpose v2 account.
*/
AZ_STORAGE_BLOBS_DLLEXPORT const static AccountKind StorageV2;
/**
* File Storage account.
*/
AZ_STORAGE_BLOBS_DLLEXPORT const static AccountKind FileStorage;
/**
* Block Blob Storage account.
*/
AZ_STORAGE_BLOBS_DLLEXPORT const static AccountKind BlockBlobStorage;
private:
std::string m_value;
}; // extensible enum AccountKind
/**
* @brief Describes a single block in block blob.
*/
struct BlobBlock final
{
/**
* Base64 encoded block ID.
*/
std::string Name;
/**
* Block size in bytes.
*/
int64_t Size = 0;
}; // struct BlobBlock
/**
* @brief Extensible enum used to identify copy status of a copy operation.
*/
class CopyStatus final {
public:
CopyStatus() = default;
explicit CopyStatus(std::string value) : m_value(std::move(value)) {}
bool operator==(const CopyStatus& other) const { return m_value == other.m_value; }
bool operator!=(const CopyStatus& other) const { return !(*this == other); }
const std::string& ToString() const { return m_value; }
/**
* Successful.
*/
AZ_STORAGE_BLOBS_DLLEXPORT const static CopyStatus Success;
/**
* Pending.
*/
AZ_STORAGE_BLOBS_DLLEXPORT const static CopyStatus Pending;
private:
std::string m_value;
}; // extensible enum CopyStatus
/**
* @brief Extensible enum used to identify the status of secondary storage endpoint.
*/
class GeoReplicationStatus final {
public:
GeoReplicationStatus() = default;
explicit GeoReplicationStatus(std::string value) : m_value(std::move(value)) {}
bool operator==(const GeoReplicationStatus& other) const { return m_value == other.m_value; }
bool operator!=(const GeoReplicationStatus& other) const { return !(*this == other); }
const std::string& ToString() const { return m_value; }
/**
* The secondary location is active and operational.
*/
AZ_STORAGE_BLOBS_DLLEXPORT const static GeoReplicationStatus Live;
/**
* Initial synchronization from the primary location to the secondary location is in progress.
*/
AZ_STORAGE_BLOBS_DLLEXPORT const static GeoReplicationStatus Bootstrap;
/**
* The secondary location is temporarily unavailable.
*/
AZ_STORAGE_BLOBS_DLLEXPORT const static GeoReplicationStatus Unavailable;
private:
std::string m_value;
}; // extensible enum GeoReplicationStatus
/**
* @brief Extensible enum used to identify the lease is of inifinite or fixed duration.
*/
class LeaseDurationType final {
public:
LeaseDurationType() = default;
explicit LeaseDurationType(std::string value) : m_value(std::move(value)) {}
bool operator==(const LeaseDurationType& other) const { return m_value == other.m_value; }
bool operator!=(const LeaseDurationType& other) const { return !(*this == other); }
const std::string& ToString() const { return m_value; }
/**
* Infinite duration.
*/
AZ_STORAGE_BLOBS_DLLEXPORT const static LeaseDurationType Infinite;
/**
* Fixed duration.
*/
AZ_STORAGE_BLOBS_DLLEXPORT const static LeaseDurationType Fixed;
private:
std::string m_value;
}; // extensible enum LeaseDurationType
/**
* @brief Extensible enum used to identify the state of lease.
*/
class LeaseState final {
public:
LeaseState() = default;
explicit LeaseState(std::string value) : m_value(std::move(value)) {}
bool operator==(const LeaseState& other) const { return m_value == other.m_value; }
bool operator!=(const LeaseState& other) const { return !(*this == other); }
const std::string& ToString() const { return m_value; }
/**
* The lease is unlocked and can be acquired.
*/
AZ_STORAGE_BLOBS_DLLEXPORT const static LeaseState Available;
/**
* The lease is locked.
*/
AZ_STORAGE_BLOBS_DLLEXPORT const static LeaseState Leased;
/**
* The lease duration has expired.
*/
AZ_STORAGE_BLOBS_DLLEXPORT const static LeaseState Expired;
/**
* The lease has been broken, but the lease will continue to be locked until the break period
* has expired.
*/
AZ_STORAGE_BLOBS_DLLEXPORT const static LeaseState Breaking;
/**
* The lease has been broken, and the break period has expired.
*/
AZ_STORAGE_BLOBS_DLLEXPORT const static LeaseState Broken;
private:
std::string m_value;
}; // extensible enum LeaseState
/**
* @brief Extensible enum used to identify the status of lease.
*/
class LeaseStatus final {
public:
LeaseStatus() = default;
explicit LeaseStatus(std::string value) : m_value(std::move(value)) {}
bool operator==(const LeaseStatus& other) const { return m_value == other.m_value; }
bool operator!=(const LeaseStatus& other) const { return !(*this == other); }
const std::string& ToString() const { return m_value; }
/**
* The lease is locked.
*/
AZ_STORAGE_BLOBS_DLLEXPORT const static LeaseStatus Locked;
/**
* The lease is unlocked.
*/
AZ_STORAGE_BLOBS_DLLEXPORT const static LeaseStatus Unlocked;
private:
std::string m_value;
}; // extensible enum LeaseStatus
/**
* @brief Extensible enum used to identify object replication status.
*/
class ObjectReplicationStatus final {
public:
ObjectReplicationStatus() = default;
explicit ObjectReplicationStatus(std::string value) : m_value(std::move(value)) {}
bool operator==(const ObjectReplicationStatus& other) const
{
return m_value == other.m_value;
}
bool operator!=(const ObjectReplicationStatus& other) const { return !(*this == other); }
const std::string& ToString() const { return m_value; }
/**
* Object replication to the destination container completed.
*/
AZ_STORAGE_BLOBS_DLLEXPORT const static ObjectReplicationStatus Complete;
/**
* Object replication to the destination container failed.
*/
AZ_STORAGE_BLOBS_DLLEXPORT const static ObjectReplicationStatus Failed;
private:
std::string m_value;
}; // extensible enum ObjectReplicationStatus
/**
* @brief Extensible enum used to indicates whether data in the container may be accessed
* publicly and the level of access.
*/
class PublicAccessType final {
public:
PublicAccessType() = default;
explicit PublicAccessType(std::string value) : m_value(std::move(value)) {}
bool operator==(const PublicAccessType& other) const { return m_value == other.m_value; }
bool operator!=(const PublicAccessType& other) const { return !(*this == other); }
const std::string& ToString() const { return m_value; }
/**
* Indicates full public read access for container and blob data. Clients can enumerate blobs
* within the container via anonymous request, but cannot enumerate containers within the
* storage account.
*/
AZ_STORAGE_BLOBS_DLLEXPORT const static PublicAccessType BlobContainer;
/**
* Indicates public read access for blobs. Blob data within this container can be read via
* anonymous request, but container data is not available. Clients cannot enumerate blobs
* within the container via anonymous request.
*/
AZ_STORAGE_BLOBS_DLLEXPORT const static PublicAccessType Blob;
/**
* Indicates the container is private to the account owner.
*/
AZ_STORAGE_BLOBS_DLLEXPORT const static PublicAccessType None;
private:
std::string m_value;
}; // extensible enum PublicAccessType
/**
* @brief Determines how long the associated data should persist.
*/
struct RetentionPolicy final
{
/**
* Indicates whether this retention policy is enabled.
*/
bool IsEnabled = false;
/**
* Indicates the number of days that metrics or logging or soft-deleted data should be
* retained.
*/
Azure::Nullable<int32_t> Days;
}; // struct RetentionPolicy
/**
* @brief Describes how you reference an ACL in a blob container.
*/
struct SignedIdentifier final
{
/**
* A unique ID for this signed identifier.
*/
std::string Id;
/**
* Date and time since when this policy is active.
*/
Azure::Nullable<Azure::DateTime> StartsOn;
/**
* Date and time the policy expires.
*/
Azure::Nullable<Azure::DateTime> ExpiresOn;
/**
* The permissions for this ACL policy.
*/
std::string Permissions;
}; // struct SignedIdentifier
/**
* @brief Extensible enum that used to identify the sku of a storage account.
*/
class SkuName final {
public:
SkuName() = default;
explicit SkuName(std::string value) : m_value(std::move(value)) {}
bool operator==(const SkuName& other) const { return m_value == other.m_value; }
bool operator!=(const SkuName& other) const { return !(*this == other); }
const std::string& ToString() const { return m_value; }
/**
* Standard Locally Redundant Storage
*/
AZ_STORAGE_BLOBS_DLLEXPORT const static SkuName StandardLrs;
/**
* Standard Geo Replicated Storage
*/
AZ_STORAGE_BLOBS_DLLEXPORT const static SkuName StandardGrs;
/**
* Standard Read-access Geo Replicated Storage
*/
AZ_STORAGE_BLOBS_DLLEXPORT const static SkuName StandardRagrs;
/**
* Standard Zone Redundant Storage
*/
AZ_STORAGE_BLOBS_DLLEXPORT const static SkuName StandardZrs;
/**
* Provisioned IO Locally Redundant Storage
*/
AZ_STORAGE_BLOBS_DLLEXPORT const static SkuName PremiumLrs;
/**
* Provisioned IO Zone Redundant Storage
*/
AZ_STORAGE_BLOBS_DLLEXPORT const static SkuName PremiumZrs;
/**
* Standard Geo-zone-redundant Storage
*/
AZ_STORAGE_BLOBS_DLLEXPORT const static SkuName StandardGzrs;
/**
* Standard Read-access Geo-zone-redundant Storage
*/
AZ_STORAGE_BLOBS_DLLEXPORT const static SkuName StandardRagzrs;
private:
std::string m_value;
}; // extensible enum SkuName
/**
* @brief Blob information from the result of
* #Azure::Storage::Blobs::BlobServiceClient::FindBlobsByTags.
*/
struct TaggedBlobItem final
{
/**
* Blob name.
*/
std::string BlobName;
/**
* Blob container name.
*/
std::string BlobContainerName;
}; // struct TaggedBlobItem
/**
* @brief Azure analytics logging settings.
*/
struct AnalyticsLogging final
{
/**
* The version of storage analytics to configure.
*/
std::string Version;
/**
* Whether all delete requests should be logged.
*/
bool Delete = false;
/**
* Whether all read requests should be logged.
*/
bool Read = false;
/**
* Whether all write requests should be logged.
*/
bool Write = false;
/**
* Determines how long the data should be persist.
*/
Models::RetentionPolicy RetentionPolicy;
}; // struct AnalyticsLogging
/**
* @brief Detailed information of a blob container.
*/
struct BlobContainerItemDetails final
{
/**
* The ETag contains a value that you can use to perform operations conditionally.
*/
Azure::ETag ETag;
/**
* The date and time the container was last modified. Any operation that modifies the blob,
* including an update of the metadata or properties, changes the last-modified time of the
* blob.
*/
Azure::DateTime LastModified;
/**
* A set of name-value pairs associated with this blob as user-defined metadata.
*/
Storage::Metadata Metadata;
/**
* Indicates whether data in the container may be accessed publicly and the level of access.
*/
PublicAccessType AccessType = PublicAccessType::None;
/**
* Indicates whether the container has an immutability policy set on it.
*/
bool HasImmutabilityPolicy = false;
/**
* Indicates whether the container has a legal hold.
*/
bool HasLegalHold = false;
/**
* Indicates whether the lease is of infinite or fixed duration when the blob or container is
* leased. This value is null if the blob or container is not leased.
*/
Azure::Nullable<LeaseDurationType> LeaseDuration;
/**
* Lease state of the blob.
*/
Models::LeaseState LeaseState = Models::LeaseState::Available;
/**
* The current lease status of the blob.
*/
Models::LeaseStatus LeaseStatus = Models::LeaseStatus::Unlocked;
/**
* The default encryption scope for the container.
*/
std::string DefaultEncryptionScope = "$account-encryption-key";
/**
* Indicates whether the container's default encryption scope can be overridden.
*/
bool PreventEncryptionScopeOverride = false;
/**
* Remaining days before this container will be permanantely deleted. Only valid when this
* container was deleted.
*/
Azure::Nullable<int32_t> RemainingRetentionDays;
/**
* Data and time at which this container was deleted. Only valid when this container was
* deleted.
*/
Azure::Nullable<Azure::DateTime> DeletedOn;
}; // struct BlobContainerItemDetails
/**
* @brief Settings for a CORS rule.
*/
struct CorsRule final
{
/**
* A comma-separated list of origin domains that are allowed via CORS, or "*" if all domains
* are allowed.
*/
std::string AllowedOrigins;
/**
* A comma-separated list of HTTP methods that are allowed to be executed by the origin. For
* Azure Storage, permitted methods are DELETE, GET, HEAD, MERGE, POST, OPTIONS or PUT.
*/
std::string AllowedMethods;
/**
* A comma-separated list of headers allowed to be part of the cross-origin request.
*/
std::string AllowedHeaders;
/**
* A comma-separated list of response headers to expose to CORS clients.
*/
std::string ExposedHeaders;
/**
* The number of seconds that the client/browser should cache a preflight response.
*/
int32_t MaxAgeInSeconds = 0;
}; // struct CorsRule
/**
* @brief Geo-replication information for the secondary storage endpoint.
*/
struct GeoReplication final
{
/**
* Status of the secondary storage endpoint.
*/
GeoReplicationStatus Status;
/**
* All primary writes preceding this value are guaranteed to be available for read operations
* at the secondary. Primary writes after this point in time may or may not be available for
* reads. This value may be null if replication status is bootstrap or unavailable.
*/
Azure::Nullable<Azure::DateTime> LastSyncedOn;
}; // struct GeoReplication
/**
* @brief Summary of request statistics grouped by API in hour or minute aggregates for blobs.
*/
struct Metrics final
{
/**
* The version of storage analytics to configure.
*/
std::string Version;
/**
* Indicates whether metrics are enabled for blob service.
*/
bool IsEnabled = false;
/**
* Determines how long the metrics data should persist.
*/
Models::RetentionPolicy RetentionPolicy;
/**
* Indicates whether metrics should generate summary statistics for called API operations.
*/
Azure::Nullable<bool> IncludeApis;
}; // struct Metrics
/**
* @brief Contains the object replication rule ID and replication status of a blob.
*/
struct ObjectReplicationRule final
{
/**
* Rule ID.
*/
std::string RuleId;
/**
* Replication status.
*/
ObjectReplicationStatus ReplicationStatus;
}; // struct ObjectReplicationRule
/**
* @brief The properties that enable a storage account to host a static website.
*/
struct StaticWebsite final
{
/**
* Indicates whether this storage account is hosting a static website.
*/
bool IsEnabled = false;
/**
* The default name of the index page under each directory.
*/
Azure::Nullable<std::string> IndexDocument;
/**
* Absolute path of the default index page.
*/
Azure::Nullable<std::string> DefaultIndexDocumentPath;
/**
* The absolute path of the custom 404 page.
*/
Azure::Nullable<std::string> ErrorDocument404Path;
}; // struct StaticWebsite
/**
* @brief Extensible enum used to identify access tier of a blob.
*/
class AccessTier final {
public:
AccessTier() = default;
explicit AccessTier(std::string value) : m_value(std::move(value)) {}
bool operator==(const AccessTier& other) const { return m_value == other.m_value; }
bool operator!=(const AccessTier& other) const { return !(*this == other); }
const std::string& ToString() const { return m_value; }
/**
* P1 tier for page blob in a premium storage account.
*/
AZ_STORAGE_BLOBS_DLLEXPORT const static AccessTier P1;
/**
* P2 tier for page blob in a premium storage account.
*/
AZ_STORAGE_BLOBS_DLLEXPORT const static AccessTier P2;
/**
* P3 tier for page blob in a premium storage account.
*/
AZ_STORAGE_BLOBS_DLLEXPORT const static AccessTier P3;
/**
* P4 tier for page blob in a premium storage account.
*/
AZ_STORAGE_BLOBS_DLLEXPORT const static AccessTier P4;
/**
* P6 tier for page blob in a premium storage account.
*/
AZ_STORAGE_BLOBS_DLLEXPORT const static AccessTier P6;
/**
* P10 tier for page blob in a premium storage account.
*/
AZ_STORAGE_BLOBS_DLLEXPORT const static AccessTier P10;
/**
* P15 tier for page blob in a premium storage account.
*/
AZ_STORAGE_BLOBS_DLLEXPORT const static AccessTier P15;
/**
* P20 tier for page blob in a premium storage account.
*/
AZ_STORAGE_BLOBS_DLLEXPORT const static AccessTier P20;
/**
* P30 tier for page blob in a premium storage account.
*/
AZ_STORAGE_BLOBS_DLLEXPORT const static AccessTier P30;
/**
* P40 tier for page blob in a premium storage account.
*/
AZ_STORAGE_BLOBS_DLLEXPORT const static AccessTier P40;
/**
* P50 tier for page blob in a premium storage account.
*/
AZ_STORAGE_BLOBS_DLLEXPORT const static AccessTier P50;
/**
* P60 tier for page blob in a premium storage account.
*/
AZ_STORAGE_BLOBS_DLLEXPORT const static AccessTier P60;
/**
* P70 tier for page blob in a premium storage account.
*/
AZ_STORAGE_BLOBS_DLLEXPORT const static AccessTier P70;
/**
* P80 tier for page blob in a premium storage account.
*/
AZ_STORAGE_BLOBS_DLLEXPORT const static AccessTier P80;
/**
* Optimized for storing data that is accessed frequently.
*/
AZ_STORAGE_BLOBS_DLLEXPORT const static AccessTier Hot;
/**
* Optimized for storing data that is infrequently accessed and stored for at least 30 days.
*/
AZ_STORAGE_BLOBS_DLLEXPORT const static AccessTier Cool;
/**
* Optimized for storing data that is rarely accessed and stored for at least 180 days with
* flexible latency requirements, on the order of hours.
*/
AZ_STORAGE_BLOBS_DLLEXPORT const static AccessTier Archive;
private:
std::string m_value;
}; // extensible enum AccessTier
/**
* @brief Extensible enum used to identify the destination tier when a blob is being rehydrated
* and is not complete.
*/
class ArchiveStatus final {
public:
ArchiveStatus() = default;
explicit ArchiveStatus(std::string value) : m_value(std::move(value)) {}
bool operator==(const ArchiveStatus& other) const { return m_value == other.m_value; }
bool operator!=(const ArchiveStatus& other) const { return !(*this == other); }
const std::string& ToString() const { return m_value; }
/**
* The blob is being rehydrated to hot tier.
*/
AZ_STORAGE_BLOBS_DLLEXPORT const static ArchiveStatus RehydratePendingToHot;
/**
* The blob is being rehydrated to cool tier.
*/
AZ_STORAGE_BLOBS_DLLEXPORT const static ArchiveStatus RehydratePendingToCool;
private:
std::string m_value;
}; // extensible enum ArchiveStatus
/**
* @brief A container item from the result of
* #Azure::Storage::Blobs::BlobServiceClient::ListBlobContainers.
*/
struct BlobContainerItem final
{
/**
* Blob container name.
*/
std::string Name;
/**
* Indicates whether this container was deleted.
*/
bool IsDeleted = false;
/**
* Version ID of a deleted container. This is null if a container is not deleted.
*/
Azure::Nullable<std::string> VersionId;
/**
* Detailed information of this container item.
*/
BlobContainerItemDetails Details;
}; // struct BlobContainerItem
/**
* @brief Standard HTTP properties supported by containers and blobs.
*/
struct BlobHttpHeaders final
{
/**
* MIME content type of the blob.
*/
std::string ContentType;
/**
* Specifies which content encodings have been applied to the blob.
*/
std::string ContentEncoding;
/**
* Specifies the natural languages used by this blob.
*/
std::string ContentLanguage;
/**
* A hash of the blob content.
*/
Storage::ContentHash ContentHash;
/**
* Specifies directives for caching mechanisms.
*/
std::string CacheControl;
/**
* Conveys additional information about how to process the resource payload, and also can be
* used to attach additional metadata.
*/
std::string ContentDisposition;
}; // struct BlobHttpHeaders
/**
* @brief Extensible enum used to identify blob type.
*/
class BlobType final {
public:
BlobType() = default;
explicit BlobType(std::string value) : m_value(std::move(value)) {}
bool operator==(const BlobType& other) const { return m_value == other.m_value; }
bool operator!=(const BlobType& other) const { return !(*this == other); }
const std::string& ToString() const { return m_value; }
/**
* Block blob.
*/
AZ_STORAGE_BLOBS_DLLEXPORT const static BlobType BlockBlob;
/**
* Page blob.
*/
AZ_STORAGE_BLOBS_DLLEXPORT const static BlobType PageBlob;
/**
* Append blob.
*/
AZ_STORAGE_BLOBS_DLLEXPORT const static BlobType AppendBlob;
private:
std::string m_value;
}; // extensible enum BlobType
/**
* @brief Contains object replication policy ID and the respective list of
* #ObjectReplicationRule s. This is used when retrieving the object replication properties on
* the source blob. The policy id for the destination blob is set in
* ObjectReplicationDestinationPolicyId of the respective method responses.
*/
struct ObjectReplicationPolicy final
{
/**
* The policy ID.
*/
std::string PolicyId;
/**
* The Rule IDs and respective replication status that are under the policy ID.
*/
std::vector<ObjectReplicationRule> Rules;
}; // struct ObjectReplicationPolicy
/**
* @brief Extensible enum used to identify rehydrate priority.
*/
class RehydratePriority final {
public:
RehydratePriority() = default;
explicit RehydratePriority(std::string value) : m_value(std::move(value)) {}
bool operator==(const RehydratePriority& other) const { return m_value == other.m_value; }
bool operator!=(const RehydratePriority& other) const { return !(*this == other); }
const std::string& ToString() const { return m_value; }
/**
* High priority.
*/
AZ_STORAGE_BLOBS_DLLEXPORT const static RehydratePriority High;
/**
* Standard priority.
*/
AZ_STORAGE_BLOBS_DLLEXPORT const static RehydratePriority Standard;
private:
std::string m_value;
}; // extensible enum RehydratePriority
/**
* @brief Detailed information of a blob.
*/
struct BlobItemDetails final
{
/**
* System properties of the blob.
*/
BlobHttpHeaders HttpHeaders;
/**
* A set of name-value pairs associated with this blob as user-defined metadata.
*/
Storage::Metadata Metadata;
/**
* The date and time at which the blob was created.
*/
Azure::DateTime CreatedOn;
/**
* The time this blob will expire.
*/
Azure::Nullable<Azure::DateTime> ExpiresOn;
/**
* The date and time at which the blob was last read or written to.
*/
Azure::Nullable<Azure::DateTime> LastAccessedOn;
/**
* The date and time the container was last modified. Any operation that modifies the blob,
* including an update of the metadata or properties, changes the last-modified time of the
* blob.
*/
Azure::DateTime LastModified;
/**
* The ETag contains a value that you can use to perform operations conditionally.
*/
Azure::ETag ETag;
/**
* The tier of page blob or block blob.
*/
Azure::Nullable<Models::AccessTier> AccessTier;
/**
* True if the access tier is not explicitly set on the blob.
*/
Azure::Nullable<bool> IsAccessTierInferred;
/**
* The date and time the tier was changed on the object.
*/
Azure::Nullable<Azure::DateTime> AccessTierChangedOn;
/**
* Indicates if the blob is being rehydrated.
*/
Azure::Nullable<Models::ArchiveStatus> ArchiveStatus;
/**
* Priority of rehydrate if the blob is being rehydrated.
*/
Azure::Nullable<Models::RehydratePriority> RehydratePriority;
/**
* The current lease status of the blob.
*/
Models::LeaseStatus LeaseStatus = Models::LeaseStatus::Unlocked;
/**
* Lease state of the blob.
*/
Models::LeaseState LeaseState = Models::LeaseState::Available;
/**
* Indicates whether the lease is of infinite or fixed duration when the blob or container is
* leased. This value is null if the blob or container is not leased.
*/
Azure::Nullable<LeaseDurationType> LeaseDuration;
/**
* True if the blob data and metadata are completely encrypted using the specified algorithm.
* Otherwise, the value is set to false (when the blob is unencrypted, or if only parts of the
* blob/application metadata are encrypted).
*/
bool IsServerEncrypted = false;
/**
* The SHA-256 hash of the encryption key used to encrypt the blob data and metadata.
*/
Azure::Nullable<std::vector<uint8_t>> EncryptionKeySha256;
/**
* Name of the encryption scope used to encrypt the blob data and metadata.
*/
Azure::Nullable<std::string> EncryptionScope;
/**
* The current sequence number for a page blob. This value is null for block blobs or append
* blobs.
*/
Azure::Nullable<int64_t> SequenceNumber;
/**
* If the blob has been sealed. This value is null for block blobs or page blobs.
*/
Azure::Nullable<bool> IsSealed;
/**
* Only valid when Object Replication is enabled and current blob is the source.
*/
std::vector<ObjectReplicationPolicy> ObjectReplicationSourceProperties;
/**
* String identifier for the last attempted Copy Blob operation where this blob was the
* destination. This value is null if this blob has never been the destination of a copy
* operation, or if this blob has been modified after a concluded copy operation.
*/
Azure::Nullable<std::string> CopyId;
/**
* URL that specifies the source blob or file used in the last attempted copy operation where
* this blob was the destination blob. This value is null if this blob has never been the
* destination of a copy operation, or if this blob has been modified after a concluded copy
* operation.
*/
Azure::Nullable<std::string> CopySource;
/**
* State of the copy operation identified by the copy ID. Possible values include success,
* pending, aborted, failed etc. This value is null if this blob has never been the
* destination of a copy operation, or if this blob has been modified after a concluded copy
* operation.
*/
Azure::Nullable<Models::CopyStatus> CopyStatus;
/**
* Describes the cause of the last fatal or non-fatal copy operation failure. This is not null
* only when copy status is failed or pending.
*/
Azure::Nullable<std::string> CopyStatusDescription;
/**
* True if the copy operation is incremental copy.
*/
Azure::Nullable<bool> IsIncrementalCopy;
/**
* Snapshot time of the last successful incremental copy snapshot for this blob.
*/
Azure::Nullable<std::string> IncrementalCopyDestinationSnapshot;
/**
* Contains the number of bytes copied and the total bytes in the source in the last attempted
* copy operation where this blob was the destination blob.
*/
Azure::Nullable<std::string> CopyProgress;
/**
* Conclusion time of the last attempted copy operation where this blob was the destination
* blob.
*/
Azure::Nullable<Azure::DateTime> CopyCompletedOn;
/**
* User-defined tags for this blob.
*/
std::map<std::string, std::string> Tags;
/**
* Data and time at which this blob was deleted. Only valid when this blob was deleted.
*/
Azure::Nullable<Azure::DateTime> DeletedOn;
/**
* Remaining days before this blob will be permanantely deleted. Only valid when this blob was
* deleted.
*/
Azure::Nullable<int32_t> RemainingRetentionDays;
}; // struct BlobItemDetails
/**
* @brief Detailed information of a downloaded blob.
*/
struct DownloadBlobDetails final
{
/**
* The ETag contains a value that you can use to perform operations conditionally.
*/
Azure::ETag ETag;
/**
* The date and time the container was last modified. Any operation that modifies the blob,
* including an update of the metadata or properties, changes the last-modified time of the
* blob.
*/
Azure::DateTime LastModified;
/**
* The date and time at which the blob was created.
*/
Azure::DateTime CreatedOn;
/**
* The time this blob will expire.
*/
Azure::Nullable<Azure::DateTime> ExpiresOn;
/**
* The date and time at which the blob was last read or written to.
*/
Azure::Nullable<Azure::DateTime> LastAccessedOn;
/**
* System properties of the blob.
*/
BlobHttpHeaders HttpHeaders;
/**
* A set of name-value pairs associated with this blob as user-defined metadata.
*/
Storage::Metadata Metadata;
/**
* The current sequence number for a page blob. This value is null for block blobs or append
* blobs.
*/
Azure::Nullable<int64_t> SequenceNumber;
/**
* The number of committed blocks present in the blob. This value is null for block blobs or
* page blobs.
*/
Azure::Nullable<int32_t> CommittedBlockCount;
/**
* If the blob has been sealed. This value is null for block blobs or page blobs.
*/
Azure::Nullable<bool> IsSealed;
/**
* Indicates whether the lease is of infinite or fixed duration when the blob or container is
* leased. This value is null if the blob or container is not leased.
*/
Azure::Nullable<LeaseDurationType> LeaseDuration;
/**
* Lease state of the blob.
*/
Azure::Nullable<Models::LeaseState> LeaseState;
/**
* The current lease status of the blob.
*/
Azure::Nullable<Models::LeaseStatus> LeaseStatus;
/**
* True if the blob data and metadata are completely encrypted using the specified algorithm.
* Otherwise, the value is set to false (when the blob is unencrypted, or if only parts of the
* blob/application metadata are encrypted).
*/
bool IsServerEncrypted = false;
/**
* The SHA-256 hash of the encryption key used to encrypt the blob data and metadata.
*/
Azure::Nullable<std::vector<uint8_t>> EncryptionKeySha256;
/**
* Name of the encryption scope used to encrypt the blob data and metadata.
*/
Azure::Nullable<std::string> EncryptionScope;
/**
* Only valid when Object Replication is enabled and current blob is the destination.
*/
Azure::Nullable<std::string> ObjectReplicationDestinationPolicyId;
/**
* Only valid when Object Replication is enabled and current blob is the source.
*/
std::vector<ObjectReplicationPolicy> ObjectReplicationSourceProperties;
/**
* the number of tags stored on the blob.
*/
Azure::Nullable<int32_t> TagCount;
/**
* String identifier for the last attempted Copy Blob operation where this blob was the
* destination. This value is null if this blob has never been the destination of a copy
* operation, or if this blob has been modified after a concluded copy operation.
*/
Azure::Nullable<std::string> CopyId;
/**
* URL that specifies the source blob or file used in the last attempted copy operation where
* this blob was the destination blob. This value is null if this blob has never been the
* destination of a copy operation, or if this blob has been modified after a concluded copy
* operation.
*/
Azure::Nullable<std::string> CopySource;
/**
* State of the copy operation identified by the copy ID. Possible values include success,
* pending, aborted, failed etc. This value is null if this blob has never been the
* destination of a copy operation, or if this blob has been modified after a concluded copy
* operation.
*/
Azure::Nullable<Models::CopyStatus> CopyStatus;
/**
* Describes the cause of the last fatal or non-fatal copy operation failure. This is not null
* only when copy status is failed or pending.
*/
Azure::Nullable<std::string> CopyStatusDescription;
/**
* Contains the number of bytes copied and the total bytes in the source in the last attempted
* copy operation where this blob was the destination blob.
*/
Azure::Nullable<std::string> CopyProgress;
/**
* Conclusion time of the last attempted copy operation where this blob was the destination
* blob.
*/
Azure::Nullable<Azure::DateTime> CopyCompletedOn;
/**
* A string value that uniquely identifies the blob. This value is null if Blob Versioning is
* not enabled.
*/
Azure::Nullable<std::string> VersionId;
/**
* Indicates if this is the current version of the blob. This value is null if Blob Versioning
* is not enabled.
*/
Azure::Nullable<bool> IsCurrentVersion;
}; // struct DownloadBlobDetails
/**
* @brief A blob item from the result of #Azure::Storage::Blobs::BlobContainerClient::ListBlobs.
*/
struct BlobItem final
{
std::string Name;
/**
* Size of the blob.
*/
int64_t BlobSize = 0;
/**
* The blob's type.
*/
Models::BlobType BlobType;
/**
* Indicates whether this blob was deleted.
*/
bool IsDeleted = false;
/**
* A string value that uniquely identifies a blob snapshot.
*/
std::string Snapshot;
/**
* A string value that uniquely identifies the blob. This value is null if Blob Versioning is
* not enabled.
*/
Azure::Nullable<std::string> VersionId;
/**
* Indicates if this is the current version of the blob. This value is null if Blob Versioning
* is not enabled.
*/
Azure::Nullable<bool> IsCurrentVersion;
/**
* Detailed information of the downloaded blob.
*/
BlobItemDetails Details;
}; // struct BlobItem
/**
* @brief Response type for #Azure::Storage::Blobs::BlobClient::AbortCopy.
*/
struct AbortBlobCopyFromUriResult final
{
}; // struct AbortBlobCopyFromUriResult
/**
* @brief Storage account information.
*/
struct AccountInfo final
{
/**
* The SKU name of the storage account. See
* https://docs.microsoft.com/rest/api/storagerp/srp_sku_types for more information.
*/
Models::SkuName SkuName;
/**
* The account kind of the storage account. See
* https://docs.microsoft.com/rest/api/storagerp/srp_sku_types for more information.
*/
Models::AccountKind AccountKind;
/**
* Indicates if the account has a hierarchical namespace enabled.
*/
bool IsHierarchicalNamespaceEnabled = false;
}; // struct AccountInfo
/**
* @brief Response type for #Azure::Storage::Blobs::AppendBlobClient::AppendBlockFromUri.
*/
struct AppendBlockFromUriResult final
{
/**
* The ETag contains a value that you can use to perform operations conditionally.
*/
Azure::ETag ETag;
/**
* The date and time the container was last modified. Any operation that modifies the blob,
* including an update of the metadata or properties, changes the last-modified time of the
* blob.
*/
Azure::DateTime LastModified;
/**
* The request may return a CRC64 or MD5 hash for the downloaded range of data.
*/
Azure::Nullable<ContentHash> TransactionalContentHash;
/**
* The offset at which the block was committed.
*/
int64_t AppendOffset = 0;
/**
* The number of committed blocks present in the blob. This value is null for block blobs or
* page blobs.
*/
int32_t CommittedBlockCount = 0;
/**
* True if the blob data and metadata are completely encrypted using the specified algorithm.
* Otherwise, the value is set to false (when the blob is unencrypted, or if only parts of the
* blob/application metadata are encrypted).
*/
bool IsServerEncrypted = false;
/**
* The SHA-256 hash of the encryption key used to encrypt the blob data and metadata.
*/
Azure::Nullable<std::vector<uint8_t>> EncryptionKeySha256;
/**
* Name of the encryption scope used to encrypt the blob data and metadata.
*/
Azure::Nullable<std::string> EncryptionScope;
}; // struct AppendBlockFromUriResult
/**
* @brief Response type for #Azure::Storage::Blobs::AppendBlobClient::AppendBlock.
*/
struct AppendBlockResult final
{
/**
* The ETag contains a value that you can use to perform operations conditionally.
*/
Azure::ETag ETag;
/**
* The date and time the container was last modified. Any operation that modifies the blob,
* including an update of the metadata or properties, changes the last-modified time of the
* blob.
*/
Azure::DateTime LastModified;
/**
* The request may return a CRC64 or MD5 hash for the downloaded range of data.
*/
Azure::Nullable<ContentHash> TransactionalContentHash;
/**
* The offset at which the block was committed.
*/
int64_t AppendOffset = 0;
/**
* The number of committed blocks present in the blob. This value is null for block blobs or
* page blobs.
*/
int32_t CommittedBlockCount = 0;
/**
* True if the blob data and metadata are completely encrypted using the specified algorithm.
* Otherwise, the value is set to false (when the blob is unencrypted, or if only parts of the
* blob/application metadata are encrypted).
*/
bool IsServerEncrypted = false;
/**
* The SHA-256 hash of the encryption key used to encrypt the blob data and metadata.
*/
Azure::Nullable<std::vector<uint8_t>> EncryptionKeySha256;
/**
* Name of the encryption scope used to encrypt the blob data and metadata.
*/
Azure::Nullable<std::string> EncryptionScope;
}; // struct AppendBlockResult
/**
* @brief Access policy for a blob container.
*/
struct BlobContainerAccessPolicy final
{
/**
* Indicates whether data in the container may be accessed publicly and the level of access.
*/
PublicAccessType AccessType = PublicAccessType::None;
/**
* A collection of signed identifiers.
*/
std::vector<SignedIdentifier> SignedIdentifiers;
}; // struct BlobContainerAccessPolicy
/**
* @brief Properties of a blob container.
*/
struct BlobContainerProperties final
{
/**
* The ETag contains a value that you can use to perform operations conditionally.
*/
Azure::ETag ETag;
/**
* The date and time the container was last modified. Any operation that modifies the blob,
* including an update of the metadata or properties, changes the last-modified time of the
* blob.
*/
Azure::DateTime LastModified;
/**
* A set of name-value pairs associated with this blob as user-defined metadata.
*/
Storage::Metadata Metadata;
/**
* Indicates whether data in the container may be accessed publicly and the level of access.
*/
PublicAccessType AccessType = PublicAccessType::None;
/**
* Indicates whether the container has an immutability policy set on it.
*/
bool HasImmutabilityPolicy = false;
/**
* Indicates whether the container has a legal hold.
*/
bool HasLegalHold = false;
/**
* Indicates whether the lease is of infinite or fixed duration when the blob or container is
* leased. This value is null if the blob or container is not leased.
*/
Azure::Nullable<LeaseDurationType> LeaseDuration;
/**
* Lease state of the blob.
*/
Models::LeaseState LeaseState = Models::LeaseState::Available;
/**
* The current lease status of the blob.
*/
Models::LeaseStatus LeaseStatus = Models::LeaseStatus::Unlocked;
/**
* The default encryption scope for the container.
*/
std::string DefaultEncryptionScope = "$account-encryption-key";
/**
* Indicates whether the container's default encryption scope can be overridden.
*/
bool PreventEncryptionScopeOverride = false;
}; // struct BlobContainerProperties
/**
* @brief Properties of a blob.
*/
struct BlobProperties final
{
/**
* The ETag contains a value that you can use to perform operations conditionally.
*/
Azure::ETag ETag;
/**
* The date and time the container was last modified. Any operation that modifies the blob,
* including an update of the metadata or properties, changes the last-modified time of the
* blob.
*/
Azure::DateTime LastModified;
/**
* The date and time at which the blob was created.
*/
Azure::DateTime CreatedOn;
/**
* The time this blob will expire.
*/
Azure::Nullable<Azure::DateTime> ExpiresOn;
/**
* The date and time at which the blob was last read or written to.
*/
Azure::Nullable<Azure::DateTime> LastAccessedOn;
/**
* A set of name-value pairs associated with this blob as user-defined metadata.
*/
Storage::Metadata Metadata;
/**
* The blob's type.
*/
Models::BlobType BlobType;
/**
* Indicates whether the lease is of infinite or fixed duration when the blob or container is
* leased. This value is null if the blob or container is not leased.
*/
Azure::Nullable<LeaseDurationType> LeaseDuration;
/**
* Lease state of the blob.
*/
Azure::Nullable<Models::LeaseState> LeaseState;
/**
* The current lease status of the blob.
*/
Azure::Nullable<Models::LeaseStatus> LeaseStatus;
/**
* Size of the blob.
*/
int64_t BlobSize = 0;
/**
* System properties of the blob.
*/
BlobHttpHeaders HttpHeaders;
/**
* The current sequence number for a page blob. This value is null for block blobs or append
* blobs.
*/
Azure::Nullable<int64_t> SequenceNumber;
/**
* The number of committed blocks present in the blob. This value is null for block blobs or
* page blobs.
*/
Azure::Nullable<int32_t> CommittedBlockCount;
/**
* If the blob has been sealed. This value is null for block blobs or page blobs.
*/
Azure::Nullable<bool> IsSealed;
/**
* True if the blob data and metadata are completely encrypted using the specified algorithm.
* Otherwise, the value is set to false (when the blob is unencrypted, or if only parts of the
* blob/application metadata are encrypted).
*/
bool IsServerEncrypted = false;
/**
* The SHA-256 hash of the encryption key used to encrypt the blob data and metadata.
*/
Azure::Nullable<std::vector<uint8_t>> EncryptionKeySha256;
/**
* Name of the encryption scope used to encrypt the blob data and metadata.
*/
Azure::Nullable<std::string> EncryptionScope;
/**
* The tier of page blob or block blob.
*/
Azure::Nullable<Models::AccessTier> AccessTier;
/**
* True if the access tier is not explicitly set on the blob.
*/
Azure::Nullable<bool> IsAccessTierInferred;
/**
* Indicates if the blob is being rehydrated.
*/
Azure::Nullable<Models::ArchiveStatus> ArchiveStatus;
/**
* Priority of rehydrate if the blob is being rehydrated.
*/
Azure::Nullable<Models::RehydratePriority> RehydratePriority;
/**
* The date and time the tier was changed on the object.
*/
Azure::Nullable<Azure::DateTime> AccessTierChangedOn;
/**
* String identifier for the last attempted Copy Blob operation where this blob was the
* destination. This value is null if this blob has never been the destination of a copy
* operation, or if this blob has been modified after a concluded copy operation.
*/
Azure::Nullable<std::string> CopyId;
/**
* URL that specifies the source blob or file used in the last attempted copy operation where
* this blob was the destination blob. This value is null if this blob has never been the
* destination of a copy operation, or if this blob has been modified after a concluded copy
* operation.
*/
Azure::Nullable<std::string> CopySource;
/**
* State of the copy operation identified by the copy ID. Possible values include success,
* pending, aborted, failed etc. This value is null if this blob has never been the
* destination of a copy operation, or if this blob has been modified after a concluded copy
* operation.
*/
Azure::Nullable<Models::CopyStatus> CopyStatus;
/**
* Describes the cause of the last fatal or non-fatal copy operation failure. This is not null
* only when copy status is failed or pending.
*/
Azure::Nullable<std::string> CopyStatusDescription;
/**
* True if the copy operation is incremental copy.
*/
Azure::Nullable<bool> IsIncrementalCopy;
/**
* Snapshot time of the last successful incremental copy snapshot for this blob.
*/
Azure::Nullable<std::string> IncrementalCopyDestinationSnapshot;
/**
* Contains the number of bytes copied and the total bytes in the source in the last attempted
* copy operation where this blob was the destination blob.
*/
Azure::Nullable<std::string> CopyProgress;
/**
* Conclusion time of the last attempted copy operation where this blob was the destination
* blob.
*/
Azure::Nullable<Azure::DateTime> CopyCompletedOn;
/**
* Only valid when Object Replication is enabled and current blob is the destination.
*/
Azure::Nullable<std::string> ObjectReplicationDestinationPolicyId;
/**
* Only valid when Object Replication is enabled and current blob is the source.
*/
std::vector<ObjectReplicationPolicy> ObjectReplicationSourceProperties;
/**
* the number of tags stored on the blob.
*/
Azure::Nullable<int32_t> TagCount;
/**
* A string value that uniquely identifies the blob. This value is null if Blob Versioning is
* not enabled.
*/
Azure::Nullable<std::string> VersionId;
/**
* Indicates if this is the current version of the blob. This value is null if Blob Versioning
* is not enabled.
*/
Azure::Nullable<bool> IsCurrentVersion;
}; // struct BlobProperties
/**
* @brief Properties of blob service.
*/
struct BlobServiceProperties final
{
/**
* Azure analytics logging settings.
*/
AnalyticsLogging Logging;
/**
* Summary of request statistics grouped by API in hour aggregates for blobs.
*/
Metrics HourMetrics;
/**
* Summary of request statistics grouped by API in minute aggregates for blobs.
*/
Metrics MinuteMetrics;
/**
* CORS rules set.
*/
std::vector<CorsRule> Cors;
/**
* The default API version used to handle blob service requests if API version is not
* specified in the request header.
*/
Azure::Nullable<std::string> DefaultServiceVersion;
/**
* Retention policy that determines how long the associated data should persist.
*/
RetentionPolicy DeleteRetentionPolicy;
/**
* The properties that enable an storage account to host a static website.
*/
Models::StaticWebsite StaticWebsite;
}; // struct BlobServiceProperties
/**
* @brief Extensible enum used to specify blocks to list.
*/
class BlockListType final {
public:
BlockListType() = default;
explicit BlockListType(std::string value) : m_value(std::move(value)) {}
bool operator==(const BlockListType& other) const { return m_value == other.m_value; }
bool operator!=(const BlockListType& other) const { return !(*this == other); }
const std::string& ToString() const { return m_value; }
/**
* Only list committed blocks.
*/
AZ_STORAGE_BLOBS_DLLEXPORT const static BlockListType Committed;
/**
* Only list uncommitted blocks.
*/
AZ_STORAGE_BLOBS_DLLEXPORT const static BlockListType Uncommitted;
/**
* List both committed and uncommitted blocks.
*/
AZ_STORAGE_BLOBS_DLLEXPORT const static BlockListType All;
private:
std::string m_value;
}; // extensible enum BlockListType
/**
* @brief Extensible enum used to specify how the service should look for a block ID.
*/
class BlockType final {
public:
BlockType() = default;
explicit BlockType(std::string value) : m_value(std::move(value)) {}
bool operator==(const BlockType& other) const { return m_value == other.m_value; }
bool operator!=(const BlockType& other) const { return !(*this == other); }
const std::string& ToString() const { return m_value; }
/**
* Look for a block ID in the committed block list.
*/
AZ_STORAGE_BLOBS_DLLEXPORT const static BlockType Committed;
/**
* Look for a block ID in the uncommitted block list.
*/
AZ_STORAGE_BLOBS_DLLEXPORT const static BlockType Uncommitted;
/**
* Look for a block ID in the uncommitted block list first and then in the committed block
* list.
*/
AZ_STORAGE_BLOBS_DLLEXPORT const static BlockType Latest;
private:
std::string m_value;
}; // extensible enum BlockType
/**
* @brief Response type for #Azure::Storage::Blobs::PageBlobClient::ClearPages.
*/
struct ClearPagesResult final
{
/**
* The ETag contains a value that you can use to perform operations conditionally.
*/
Azure::ETag ETag;
/**
* The date and time the container was last modified. Any operation that modifies the blob,
* including an update of the metadata or properties, changes the last-modified time of the
* blob.
*/
Azure::DateTime LastModified;
/**
* The current sequence number for a page blob. This value is null for block blobs or append
* blobs.
*/
int64_t SequenceNumber = 0;
}; // struct ClearPagesResult
/**
* @brief Response type for #Azure::Storage::Blobs::BlockBlobClient::CommitBlockList.
*/
struct CommitBlockListResult final
{
/**
* The ETag contains a value that you can use to perform operations conditionally.
*/
Azure::ETag ETag;
/**
* The date and time the container was last modified. Any operation that modifies the blob,
* including an update of the metadata or properties, changes the last-modified time of the
* blob.
*/
Azure::DateTime LastModified;
/**
* A string value that uniquely identifies the blob. This value is null if Blob Versioning is
* not enabled.
*/
Azure::Nullable<std::string> VersionId;
/**
* True if the blob data and metadata are completely encrypted using the specified algorithm.
* Otherwise, the value is set to false (when the blob is unencrypted, or if only parts of the
* blob/application metadata are encrypted).
*/
bool IsServerEncrypted = false;
/**
* The SHA-256 hash of the encryption key used to encrypt the blob data and metadata.
*/
Azure::Nullable<std::vector<uint8_t>> EncryptionKeySha256;
/**
* Name of the encryption scope used to encrypt the blob data and metadata.
*/
Azure::Nullable<std::string> EncryptionScope;
/**
* The request may return a CRC64 or MD5 hash for the downloaded range of data.
*/
Azure::Nullable<ContentHash> TransactionalContentHash;
}; // struct CommitBlockListResult
/**
* @brief Response type for #Azure::Storage::Blobs::AppendBlobClient::Create.
*/
struct CreateAppendBlobResult final
{
/**
* Indicates if the append blob was successfully created in this operation.
*/
bool Created = true;
/**
* The ETag contains a value that you can use to perform operations conditionally.
*/
Azure::ETag ETag;
/**
* The date and time the container was last modified. Any operation that modifies the blob,
* including an update of the metadata or properties, changes the last-modified time of the
* blob.
*/
Azure::DateTime LastModified;
/**
* A string value that uniquely identifies the blob. This value is null if Blob Versioning is
* not enabled.
*/
Azure::Nullable<std::string> VersionId;
/**
* True if the blob data and metadata are completely encrypted using the specified algorithm.
* Otherwise, the value is set to false (when the blob is unencrypted, or if only parts of the
* blob/application metadata are encrypted).
*/
bool IsServerEncrypted = false;
/**
* The SHA-256 hash of the encryption key used to encrypt the blob data and metadata.
*/
Azure::Nullable<std::vector<uint8_t>> EncryptionKeySha256;
/**
* Name of the encryption scope used to encrypt the blob data and metadata.
*/
Azure::Nullable<std::string> EncryptionScope;
}; // struct CreateAppendBlobResult
/**
* @brief Response type for #Azure::Storage::Blobs::BlobContainerClient::Create.
*/
struct CreateBlobContainerResult final
{
/**
* Indicates if the container was successfully created in this operation.
*/
bool Created = true;
/**
* The ETag contains a value that you can use to perform operations conditionally.
*/
Azure::ETag ETag;
/**
* The date and time the container was last modified. Any operation that modifies the blob,
* including an update of the metadata or properties, changes the last-modified time of the
* blob.
*/
Azure::DateTime LastModified;
}; // struct CreateBlobContainerResult
/**
* @brief Response type for #Azure::Storage::Blobs::BlobClient::CreateSnapshot.
*/
struct CreateBlobSnapshotResult final
{
std::string Snapshot;
/**
* The ETag contains a value that you can use to perform operations conditionally.
*/
Azure::ETag ETag;
/**
* The date and time the container was last modified. Any operation that modifies the blob,
* including an update of the metadata or properties, changes the last-modified time of the
* blob.
*/
Azure::DateTime LastModified;
/**
* A string value that uniquely identifies the blob. This value is null if Blob Versioning is
* not enabled.
*/
Azure::Nullable<std::string> VersionId;
/**
* True if the blob data and metadata are completely encrypted using the specified algorithm.
* Otherwise, the value is set to false (when the blob is unencrypted, or if only parts of the
* blob/application metadata are encrypted).
*/
bool IsServerEncrypted = false;
/**
* The SHA-256 hash of the encryption key used to encrypt the blob data and metadata.
*/
Azure::Nullable<std::vector<uint8_t>> EncryptionKeySha256;
/**
* Name of the encryption scope used to encrypt the blob data and metadata.
*/
Azure::Nullable<std::string> EncryptionScope;
}; // struct CreateBlobSnapshotResult
/**
* @brief Response type for #Azure::Storage::Blobs::PageBlobClient::Create.
*/
struct CreatePageBlobResult final
{
/**
* Indicates if the page blob was successfully created in this operation.
*/
bool Created = true;
/**
* The ETag contains a value that you can use to perform operations conditionally.
*/
Azure::ETag ETag;
/**
* The date and time the container was last modified. Any operation that modifies the blob,
* including an update of the metadata or properties, changes the last-modified time of the
* blob.
*/
Azure::DateTime LastModified;
/**
* A string value that uniquely identifies the blob. This value is null if Blob Versioning is
* not enabled.
*/
Azure::Nullable<std::string> VersionId;
/**
* True if the blob data and metadata are completely encrypted using the specified algorithm.
* Otherwise, the value is set to false (when the blob is unencrypted, or if only parts of the
* blob/application metadata are encrypted).
*/
bool IsServerEncrypted = false;
/**
* The SHA-256 hash of the encryption key used to encrypt the blob data and metadata.
*/
Azure::Nullable<std::vector<uint8_t>> EncryptionKeySha256;
/**
* Name of the encryption scope used to encrypt the blob data and metadata.
*/
Azure::Nullable<std::string> EncryptionScope;
/**
* The current sequence number for a page blob. This value is null for block blobs or append
* blobs.
*/
Azure::Nullable<int64_t> SequenceNumber;
}; // struct CreatePageBlobResult
/**
* @brief Response type for #Azure::Storage::Blobs::BlobContainerClient::Delete.
*/
struct DeleteBlobContainerResult final
{
/**
* Indicates if the container was successfully deleted in this operation.
*/
bool Deleted = true;
}; // struct DeleteBlobContainerResult
/**
* @brief Response type for #Azure::Storage::Blobs::BlobClient::Delete.
*/
struct DeleteBlobResult final
{
/**
* Indicates if the blob was successfully deleted in this operation.
*/
bool Deleted = true;
}; // struct DeleteBlobResult
/**
* @brief Extensible enum used to specify whether base blob should be deleted in a delete blob
* operation.
*/
class DeleteSnapshotsOption final {
public:
DeleteSnapshotsOption() = default;
explicit DeleteSnapshotsOption(std::string value) : m_value(std::move(value)) {}
bool operator==(const DeleteSnapshotsOption& other) const { return m_value == other.m_value; }
bool operator!=(const DeleteSnapshotsOption& other) const { return !(*this == other); }
const std::string& ToString() const { return m_value; }
/**
* Delete the base blob and all snapshots.
*/
AZ_STORAGE_BLOBS_DLLEXPORT const static DeleteSnapshotsOption IncludeSnapshots;
/**
* Delete only the blob's snapshots and not the blob itself.
*/
AZ_STORAGE_BLOBS_DLLEXPORT const static DeleteSnapshotsOption OnlySnapshots;
private:
std::string m_value;
}; // extensible enum DeleteSnapshotsOption
/**
* @brief Response type for #Azure::Storage::Blobs::BlobClient::Download.
*/
struct DownloadBlobResult final
{
/**
* Content of the blob or blob range.
*/
std::unique_ptr<Azure::Core::IO::BodyStream> BodyStream;
/**
* Indicates the range of bytes returned.
*/
Azure::Core::Http::HttpRange ContentRange;
/**
* Size of the blob.
*/
int64_t BlobSize = 0;
/**
* The blob's type.
*/
Models::BlobType BlobType;
/**
* The request may return a CRC64 or MD5 hash for the downloaded range of data.
*/
Azure::Nullable<ContentHash> TransactionalContentHash;
/**
* Detailed information of the downloaded blob.
*/
DownloadBlobDetails Details;
}; // struct DownloadBlobResult
/**
* @brief Extensible enum used to identify encryption algorithm.
*/
class EncryptionAlgorithmType final {
public:
EncryptionAlgorithmType() = default;
explicit EncryptionAlgorithmType(std::string value) : m_value(std::move(value)) {}
bool operator==(const EncryptionAlgorithmType& other) const
{
return m_value == other.m_value;
}
bool operator!=(const EncryptionAlgorithmType& other) const { return !(*this == other); }
const std::string& ToString() const { return m_value; }
/**
* AES-256
*/
AZ_STORAGE_BLOBS_DLLEXPORT const static EncryptionAlgorithmType Aes256;
private:
std::string m_value;
}; // extensible enum EncryptionAlgorithmType
/**
* @brief Response type for #Azure::Storage::Blobs::BlockBlobClient::GetBlockList.
*/
struct GetBlockListResult final
{
/**
* The ETag contains a value that you can use to perform operations conditionally. Empty if
* the blob is not never committed.
*/
Azure::ETag ETag;
/**
* The date and time the container was last modified. Any operation that modifies the blob,
* including an update of the metadata or properties, changes the last-modified time of the
* blob. Invalid if the blob is never committed.
*/
Azure::DateTime LastModified;
/**
* Size of the blob. Invalid if the blob is never committed.
*/
int64_t BlobSize = 0;
/**
* Collection of committed blocks.
*/
std::vector<BlobBlock> CommittedBlocks;
/**
* Collection of uncommitted blocks.
*/
std::vector<BlobBlock> UncommittedBlocks;
}; // struct GetBlockListResult
enum class ListBlobContainersIncludeFlags
{
/**
* No extra data should be included.
*/
None = 0,
/**
* Metadata should be included.
*/
Metadata = 1,
/**
* Soft-deleted containers should be included in the response.
*/
Deleted = 2,
}; // bitwise enum ListBlobContainersIncludeFlags
inline ListBlobContainersIncludeFlags operator|(
ListBlobContainersIncludeFlags lhs,
ListBlobContainersIncludeFlags rhs)
{
using type = std::underlying_type_t<ListBlobContainersIncludeFlags>;
return static_cast<ListBlobContainersIncludeFlags>(
static_cast<type>(lhs) | static_cast<type>(rhs));
}
inline ListBlobContainersIncludeFlags& operator|=(
ListBlobContainersIncludeFlags& lhs,
ListBlobContainersIncludeFlags rhs)
{
lhs = lhs | rhs;
return lhs;
}
inline ListBlobContainersIncludeFlags operator&(
ListBlobContainersIncludeFlags lhs,
ListBlobContainersIncludeFlags rhs)
{
using type = std::underlying_type_t<ListBlobContainersIncludeFlags>;
return static_cast<ListBlobContainersIncludeFlags>(
static_cast<type>(lhs) & static_cast<type>(rhs));
}
inline ListBlobContainersIncludeFlags& operator&=(
ListBlobContainersIncludeFlags& lhs,
ListBlobContainersIncludeFlags rhs)
{
lhs = lhs & rhs;
return lhs;
}
enum class ListBlobsIncludeFlags
{
/**
* No extra data should be included.
*/
None = 0,
/**
* Metadata related to any current or previous copy operations should be included.
*/
Copy = 1,
/**
* Soft-deleted blobs should be included.
*/
Deleted = 2,
/**
* Metadata should be included.
*/
Metadata = 4,
/**
* Snapshots should be included.
*/
Snapshots = 8,
/**
* Versions of blobs should be included.
*/
Versions = 16,
/**
* Uncommitted blobs should be included.
*/
UncomittedBlobs = 32,
/**
* Tags should be included.
*/
Tags = 64,
}; // bitwise enum ListBlobsIncludeFlags
inline ListBlobsIncludeFlags operator|(ListBlobsIncludeFlags lhs, ListBlobsIncludeFlags rhs)
{
using type = std::underlying_type_t<ListBlobsIncludeFlags>;
return static_cast<ListBlobsIncludeFlags>(static_cast<type>(lhs) | static_cast<type>(rhs));
}
inline ListBlobsIncludeFlags& operator|=(ListBlobsIncludeFlags& lhs, ListBlobsIncludeFlags rhs)
{
lhs = lhs | rhs;
return lhs;
}
inline ListBlobsIncludeFlags operator&(ListBlobsIncludeFlags lhs, ListBlobsIncludeFlags rhs)
{
using type = std::underlying_type_t<ListBlobsIncludeFlags>;
return static_cast<ListBlobsIncludeFlags>(static_cast<type>(lhs) & static_cast<type>(rhs));
}
inline ListBlobsIncludeFlags& operator&=(ListBlobsIncludeFlags& lhs, ListBlobsIncludeFlags rhs)
{
lhs = lhs & rhs;
return lhs;
}
/**
* @brief Response type for Azure::Storage::Blobs::PageBlobClient::Resize.
*/
struct ResizePageBlobResult final
{
/**
* The ETag contains a value that you can use to perform operations conditionally.
*/
Azure::ETag ETag;
/**
* The date and time the container was last modified. Any operation that modifies the blob,
* including an update of the metadata or properties, changes the last-modified time of the
* blob.
*/
Azure::DateTime LastModified;
/**
* The current sequence number for a page blob. This value is null for block blobs or append
* blobs.
*/
int64_t SequenceNumber = 0;
}; // struct ResizePageBlobResult
/**
* @brief Extensible enum used to specify when a file's expiration time should be relative to.
*/
class ScheduleBlobExpiryOriginType final {
public:
ScheduleBlobExpiryOriginType() = default;
explicit ScheduleBlobExpiryOriginType(std::string value) : m_value(std::move(value)) {}
bool operator==(const ScheduleBlobExpiryOriginType& other) const
{
return m_value == other.m_value;
}
bool operator!=(const ScheduleBlobExpiryOriginType& other) const { return !(*this == other); }
const std::string& ToString() const { return m_value; }
/**
* Never expires.
*/
AZ_STORAGE_BLOBS_DLLEXPORT const static ScheduleBlobExpiryOriginType NeverExpire;
/**
* Relative to file's creation time.
*/
AZ_STORAGE_BLOBS_DLLEXPORT const static ScheduleBlobExpiryOriginType RelativeToCreation;
/**
* Relative to current time.
*/
AZ_STORAGE_BLOBS_DLLEXPORT const static ScheduleBlobExpiryOriginType RelativeToNow;
/**
* Absolute time.
*/
AZ_STORAGE_BLOBS_DLLEXPORT const static ScheduleBlobExpiryOriginType Absolute;
private:
std::string m_value;
}; // extensible enum ScheduleBlobExpiryOriginType
/**
* @brief Response type for #Azure::Storage::Blobs::AppendBlobClient::Seal.
*/
struct SealAppendBlobResult final
{
/**
* The ETag contains a value that you can use to perform operations conditionally.
*/
Azure::ETag ETag;
/**
* The date and time the container was last modified. Any operation that modifies the blob,
* including an update of the metadata or properties, changes the last-modified time of the
* blob.
*/
Azure::DateTime LastModified;
/**
* If the blob has been sealed. This value is null for block blobs or page blobs.
*/
bool IsSealed = true;
}; // struct SealAppendBlobResult
/**
* @brief Indicates how the service should modify the blob's sequence number.
*/
class SequenceNumberAction final {
public:
SequenceNumberAction() = default;
explicit SequenceNumberAction(std::string value) : m_value(std::move(value)) {}
bool operator==(const SequenceNumberAction& other) const { return m_value == other.m_value; }
bool operator!=(const SequenceNumberAction& other) const { return !(*this == other); }
const std::string& ToString() const { return m_value; }
/**
* Sets the sequence number to be the higher of the value included with the request and the
* value currently stored for the blob.
*/
AZ_STORAGE_BLOBS_DLLEXPORT const static SequenceNumberAction Max;
/**
* Sets the sequence number to the value included with the request.
*/
AZ_STORAGE_BLOBS_DLLEXPORT const static SequenceNumberAction Update;
/**
* Increments the value of the sequence number by 1.
*/
AZ_STORAGE_BLOBS_DLLEXPORT const static SequenceNumberAction Increment;
private:
std::string m_value;
}; // extensible enum SequenceNumberAction
/**
* @brief Statistics for the storage service.
*/
struct ServiceStatistics final
{
/**
* Geo-replication information for the secondary storage endpoint.
*/
Models::GeoReplication GeoReplication;
}; // struct ServiceStatistics
/**
* @brief Response type for #Azure::Storage::Blobs::BlobClient::SetAccessTier.
*/
struct SetBlobAccessTierResult final
{
}; // struct SetBlobAccessTierResult
/**
* @brief Response type for #Azure::Storage::Blobs::BlobContainerClient::SetAccessPolicy.
*/
struct SetBlobContainerAccessPolicyResult final
{
/**
* The ETag contains a value that you can use to perform operations conditionally.
*/
Azure::ETag ETag;
/**
* The date and time the container was last modified. Any operation that modifies the blob,
* including an update of the metadata or properties, changes the last-modified time of the
* blob.
*/
Azure::DateTime LastModified;
}; // struct SetBlobContainerAccessPolicyResult
/**
* @brief Response type for #Azure::Storage::Blobs::BlobContainerClient::SetMetadata.
*/
struct SetBlobContainerMetadataResult final
{
/**
* The ETag contains a value that you can use to perform operations conditionally.
*/
Azure::ETag ETag;
/**
* The date and time the container was last modified. Any operation that modifies the blob,
* including an update of the metadata or properties, changes the last-modified time of the
* blob.
*/
Azure::DateTime LastModified;
}; // struct SetBlobContainerMetadataResult
/**
* @brief Response type for
* #Azure::Storage::Files::DataLake::DataLakeFileClient::ScheduleDeletion.
*/
struct SetBlobExpiryResult final
{
/**
* The ETag contains a value that you can use to perform operations conditionally.
*/
Azure::ETag ETag;
/**
* The date and time the container was last modified. Any operation that modifies the blob,
* including an update of the metadata or properties, changes the last-modified time of the
* blob.
*/
Azure::DateTime LastModified;
}; // struct SetBlobExpiryResult
/**
* @brief Response type for #Azure::Storage::Blobs::BlobClient::SetHttpHeaders.
*/
struct SetBlobHttpHeadersResult final
{
/**
* The ETag contains a value that you can use to perform operations conditionally.
*/
Azure::ETag ETag;
/**
* The date and time the container was last modified. Any operation that modifies the blob,
* including an update of the metadata or properties, changes the last-modified time of the
* blob.
*/
Azure::DateTime LastModified;
/**
* The current sequence number for a page blob. This value is null for block blobs or append
* blobs.
*/
Azure::Nullable<int64_t> SequenceNumber;
}; // struct SetBlobHttpHeadersResult
/**
* @brief Response type for #Azure::Storage::Blobs::BlobClient::SetMetadata.
*/
struct SetBlobMetadataResult final
{
/**
* The ETag contains a value that you can use to perform operations conditionally.
*/
Azure::ETag ETag;
/**
* The date and time the container was last modified. Any operation that modifies the blob,
* including an update of the metadata or properties, changes the last-modified time of the
* blob.
*/
Azure::DateTime LastModified;
/**
* This value is always null, don't use it.
*/
Azure::Nullable<int64_t> SequenceNumber;
/**
* True if the blob data and metadata are completely encrypted using the specified algorithm.
* Otherwise, the value is set to false (when the blob is unencrypted, or if only parts of the
* blob/application metadata are encrypted).
*/
bool IsServerEncrypted = false;
/**
* The SHA-256 hash of the encryption key used to encrypt the blob data and metadata.
*/
Azure::Nullable<std::vector<uint8_t>> EncryptionKeySha256;
/**
* Name of the encryption scope used to encrypt the blob data and metadata.
*/
Azure::Nullable<std::string> EncryptionScope;
}; // struct SetBlobMetadataResult
/**
* @brief Response type for #Azure::Storage::Blobs::BlobClient::SetTags.
*/
struct SetBlobTagsResult final
{
}; // struct SetBlobTagsResult
/**
* @brief Response type for #Azure::Storage::Blobs::BlobServiceClient::SetProperties.
*/
struct SetServicePropertiesResult final
{
}; // struct SetServicePropertiesResult
/**
* @brief Response type for #Azure::Storage::Blobs::BlockBlobClient::StageBlockFromUri.
*/
struct StageBlockFromUriResult final
{
/**
* The request may return a CRC64 or MD5 hash for the downloaded range of data.
*/
Azure::Nullable<ContentHash> TransactionalContentHash;
/**
* True if the blob data and metadata are completely encrypted using the specified algorithm.
* Otherwise, the value is set to false (when the blob is unencrypted, or if only parts of the
* blob/application metadata are encrypted).
*/
bool IsServerEncrypted = false;
/**
* The SHA-256 hash of the encryption key used to encrypt the blob data and metadata.
*/
Azure::Nullable<std::vector<uint8_t>> EncryptionKeySha256;
/**
* Name of the encryption scope used to encrypt the blob data and metadata.
*/
Azure::Nullable<std::string> EncryptionScope;
}; // struct StageBlockFromUriResult
/**
* @brief Response type for #Azure::Storage::Blobs::BlockBlobClient::StageBlock.
*/
struct StageBlockResult final
{
/**
* The request may return a CRC64 or MD5 hash for the downloaded range of data.
*/
Azure::Nullable<ContentHash> TransactionalContentHash;
/**
* True if the blob data and metadata are completely encrypted using the specified algorithm.
* Otherwise, the value is set to false (when the blob is unencrypted, or if only parts of the
* blob/application metadata are encrypted).
*/
bool IsServerEncrypted = false;
/**
* The SHA-256 hash of the encryption key used to encrypt the blob data and metadata.
*/
Azure::Nullable<std::vector<uint8_t>> EncryptionKeySha256;
/**
* Name of the encryption scope used to encrypt the blob data and metadata.
*/
Azure::Nullable<std::string> EncryptionScope;
}; // struct StageBlockResult
/**
* @brief Response type for #Azure::Storage::Blobs::BlobClient::Undelete.
*/
struct UndeleteBlobResult final
{
}; // struct UndeleteBlobResult
/**
* @brief Response type for Azure::Storage::Blobs::PageBlobClient::UpdateSequenceNumber.
*/
struct UpdateSequenceNumberResult final
{
/**
* The ETag contains a value that you can use to perform operations conditionally.
*/
Azure::ETag ETag;
/**
* The date and time the container was last modified. Any operation that modifies the blob,
* including an update of the metadata or properties, changes the last-modified time of the
* blob.
*/
Azure::DateTime LastModified;
/**
* The current sequence number for a page blob. This value is null for block blobs or append
* blobs.
*/
int64_t SequenceNumber = 0;
}; // struct UpdateSequenceNumberResult
/**
* @brief Response type for #Azure::Storage::Blobs::BlockBlobClient::Upload.
*/
struct UploadBlockBlobResult final
{
/**
* The ETag contains a value that you can use to perform operations conditionally.
*/
Azure::ETag ETag;
/**
* The date and time the container was last modified. Any operation that modifies the blob,
* including an update of the metadata or properties, changes the last-modified time of the
* blob.
*/
Azure::DateTime LastModified;
/**
* A string value that uniquely identifies the blob. This value is null if Blob Versioning is
* not enabled.
*/
Azure::Nullable<std::string> VersionId;
/**
* True if the blob data and metadata are completely encrypted using the specified algorithm.
* Otherwise, the value is set to false (when the blob is unencrypted, or if only parts of the
* blob/application metadata are encrypted).
*/
bool IsServerEncrypted = false;
/**
* The SHA-256 hash of the encryption key used to encrypt the blob data and metadata.
*/
Azure::Nullable<std::vector<uint8_t>> EncryptionKeySha256;
/**
* Name of the encryption scope used to encrypt the blob data and metadata.
*/
Azure::Nullable<std::string> EncryptionScope;
/**
* The request may return a CRC64 or MD5 hash for the downloaded range of data.
*/
Azure::Nullable<ContentHash> TransactionalContentHash;
}; // struct UploadBlockBlobResult
/**
* @brief Response type for #Azure::Storage::Blobs::PageBlobClient::UploadPagesFromUri.
*/
struct UploadPagesFromUriResult final
{
/**
* The ETag contains a value that you can use to perform operations conditionally.
*/
Azure::ETag ETag;
/**
* The date and time the container was last modified. Any operation that modifies the blob,
* including an update of the metadata or properties, changes the last-modified time of the
* blob.
*/
Azure::DateTime LastModified;
/**
* The request may return a CRC64 or MD5 hash for the downloaded range of data.
*/
Azure::Nullable<ContentHash> TransactionalContentHash;
/**
* The current sequence number for a page blob. This value is null for block blobs or append
* blobs.
*/
int64_t SequenceNumber = 0;
/**
* True if the blob data and metadata are completely encrypted using the specified algorithm.
* Otherwise, the value is set to false (when the blob is unencrypted, or if only parts of the
* blob/application metadata are encrypted).
*/
bool IsServerEncrypted = false;
/**
* The SHA-256 hash of the encryption key used to encrypt the blob data and metadata.
*/
Azure::Nullable<std::vector<uint8_t>> EncryptionKeySha256;
/**
* Name of the encryption scope used to encrypt the blob data and metadata.
*/
Azure::Nullable<std::string> EncryptionScope;
}; // struct UploadPagesFromUriResult
/**
* @brief Response type for #Azure::Storage::Blobs::PageBlobClient::UploadPages.
*/
struct UploadPagesResult final
{
/**
* The ETag contains a value that you can use to perform operations conditionally.
*/
Azure::ETag ETag;
/**
* The date and time the container was last modified. Any operation that modifies the blob,
* including an update of the metadata or properties, changes the last-modified time of the
* blob.
*/
Azure::DateTime LastModified;
/**
* The request may return a CRC64 or MD5 hash for the downloaded range of data.
*/
Azure::Nullable<ContentHash> TransactionalContentHash;
/**
* The current sequence number for a page blob. This value is null for block blobs or append
* blobs.
*/
int64_t SequenceNumber = 0;
/**
* True if the blob data and metadata are completely encrypted using the specified algorithm.
* Otherwise, the value is set to false (when the blob is unencrypted, or if only parts of the
* blob/application metadata are encrypted).
*/
bool IsServerEncrypted = false;
/**
* The SHA-256 hash of the encryption key used to encrypt the blob data and metadata.
*/
Azure::Nullable<std::vector<uint8_t>> EncryptionKeySha256;
/**
* Name of the encryption scope used to encrypt the blob data and metadata.
*/
Azure::Nullable<std::string> EncryptionScope;
}; // struct UploadPagesResult
/**
* @brief A user delegation key that can be used to sign user delegation SAS.
*/
struct UserDelegationKey final
{
/**
* The immutable identifier for an object in the Microsoft identity system.
*/
std::string SignedObjectId;
/**
* A GUID that represents the Azure AD tenant that the user is from.
*/
std::string SignedTenantId;
/**
* The start time of the user delegation key.
*/
Azure::DateTime SignedStartsOn;
/**
* The expiry time of the user delegation key.
*/
Azure::DateTime SignedExpiresOn;
/**
* The service of the user delegation key can be used for.
*/
std::string SignedService;
/**
* The rest api version used to get user delegation key.
*/
std::string SignedVersion;
/**
* The signature of the user delegation key.
*/
std::string Value;
}; // struct UserDelegationKey
namespace _detail {
struct AcquireBlobContainerLeaseResult final
{
/**
* The ETag contains a value that you can use to perform operations conditionally.
*/
Azure::ETag ETag;
/**
* The date and time the container was last modified. Any operation that modifies the blob,
* including an update of the metadata or properties, changes the last-modified time of the
* blob.
*/
Azure::DateTime LastModified;
/**
* Uniquely identifies a container's or blob's lease.
*/
std::string LeaseId;
}; // struct AcquireBlobContainerLeaseResult
} // namespace _detail
namespace _detail {
struct AcquireBlobLeaseResult final
{
/**
* The ETag contains a value that you can use to perform operations conditionally.
*/
Azure::ETag ETag;
/**
* The date and time the container was last modified. Any operation that modifies the blob,
* including an update of the metadata or properties, changes the last-modified time of the
* blob.
*/
Azure::DateTime LastModified;
/**
* Uniquely identifies a container's or blob's lease.
*/
std::string LeaseId;
}; // struct AcquireBlobLeaseResult
} // namespace _detail
namespace _detail {
struct BreakBlobContainerLeaseResult final
{
/**
* The ETag contains a value that you can use to perform operations conditionally.
*/
Azure::ETag ETag;
/**
* The date and time the container was last modified. Any operation that modifies the blob,
* including an update of the metadata or properties, changes the last-modified time of the
* blob.
*/
Azure::DateTime LastModified;
/**
* Approximate time remaining in the lease period in seconds.
*/
int32_t LeaseTime = 0;
}; // struct BreakBlobContainerLeaseResult
} // namespace _detail
namespace _detail {
struct BreakBlobLeaseResult final
{
/**
* The ETag contains a value that you can use to perform operations conditionally.
*/
Azure::ETag ETag;
/**
* The date and time the container was last modified. Any operation that modifies the blob,
* including an update of the metadata or properties, changes the last-modified time of the
* blob.
*/
Azure::DateTime LastModified;
/**
* Approximate time remaining in the lease period in seconds.
*/
int32_t LeaseTime = 0;
}; // struct BreakBlobLeaseResult
} // namespace _detail
namespace _detail {
struct ChangeBlobContainerLeaseResult final
{
/**
* The ETag contains a value that you can use to perform operations conditionally.
*/
Azure::ETag ETag;
/**
* The date and time the container was last modified. Any operation that modifies the blob,
* including an update of the metadata or properties, changes the last-modified time of the
* blob.
*/
Azure::DateTime LastModified;
/**
* Uniquely identifies a container's or blob's lease.
*/
std::string LeaseId;
}; // struct ChangeBlobContainerLeaseResult
} // namespace _detail
namespace _detail {
struct ChangeBlobLeaseResult final
{
/**
* The ETag contains a value that you can use to perform operations conditionally.
*/
Azure::ETag ETag;
/**
* The date and time the container was last modified. Any operation that modifies the blob,
* including an update of the metadata or properties, changes the last-modified time of the
* blob.
*/
Azure::DateTime LastModified;
/**
* Uniquely identifies a container's or blob's lease.
*/
std::string LeaseId;
}; // struct ChangeBlobLeaseResult
} // namespace _detail
namespace _detail {
struct FindBlobsByTagsResult final
{
std::string ServiceEndpoint;
Azure::Nullable<std::string> ContinuationToken;
std::vector<TaggedBlobItem> Items;
}; // struct FindBlobsByTagsResult
} // namespace _detail
namespace _detail {
struct GetBlobTagsResult final
{
/**
* User-defined tags for this blob.
*/
std::map<std::string, std::string> Tags;
}; // struct GetBlobTagsResult
} // namespace _detail
namespace _detail {
struct GetPageRangesResult final
{
/**
* The ETag contains a value that you can use to perform operations conditionally.
*/
Azure::ETag ETag;
/**
* The date and time the container was last modified. Any operation that modifies the blob,
* including an update of the metadata or properties, changes the last-modified time of the
* blob.
*/
Azure::DateTime LastModified;
/**
* Size of the blob.
*/
int64_t BlobSize = 0;
std::vector<Azure::Core::Http::HttpRange> PageRanges;
std::vector<Azure::Core::Http::HttpRange> ClearRanges;
}; // struct GetPageRangesResult
} // namespace _detail
namespace _detail {
struct ListBlobContainersResult final
{
std::string ServiceEndpoint;
std::string Prefix;
Azure::Nullable<std::string> ContinuationToken;
std::vector<BlobContainerItem> Items;
}; // struct ListBlobContainersResult
} // namespace _detail
namespace _detail {
struct ListBlobsByHierarchyResult final
{
std::string ServiceEndpoint;
std::string BlobContainerName;
std::string Prefix;
std::string Delimiter;
Azure::Nullable<std::string> ContinuationToken;
std::vector<BlobItem> Items;
std::vector<std::string> BlobPrefixes;
}; // struct ListBlobsByHierarchyResult
} // namespace _detail
namespace _detail {
struct ListBlobsResult final
{
std::string ServiceEndpoint;
std::string BlobContainerName;
std::string Prefix;
Azure::Nullable<std::string> ContinuationToken;
std::vector<BlobItem> Items;
}; // struct ListBlobsResult
} // namespace _detail
namespace _detail {
struct ReleaseBlobContainerLeaseResult final
{
/**
* The ETag contains a value that you can use to perform operations conditionally.
*/
Azure::ETag ETag;
/**
* The date and time the container was last modified. Any operation that modifies the blob,
* including an update of the metadata or properties, changes the last-modified time of the
* blob.
*/
Azure::DateTime LastModified;
}; // struct ReleaseBlobContainerLeaseResult
} // namespace _detail
namespace _detail {
struct ReleaseBlobLeaseResult final
{
/**
* The ETag contains a value that you can use to perform operations conditionally.
*/
Azure::ETag ETag;
/**
* The date and time the container was last modified. Any operation that modifies the blob,
* including an update of the metadata or properties, changes the last-modified time of the
* blob.
*/
Azure::DateTime LastModified;
}; // struct ReleaseBlobLeaseResult
} // namespace _detail
namespace _detail {
struct RenewBlobContainerLeaseResult final
{
/**
* The ETag contains a value that you can use to perform operations conditionally.
*/
Azure::ETag ETag;
/**
* The date and time the container was last modified. Any operation that modifies the blob,
* including an update of the metadata or properties, changes the last-modified time of the
* blob.
*/
Azure::DateTime LastModified;
/**
* Uniquely identifies a container's or blob's lease.
*/
std::string LeaseId;
}; // struct RenewBlobContainerLeaseResult
} // namespace _detail
namespace _detail {
struct RenewBlobLeaseResult final
{
/**
* The ETag contains a value that you can use to perform operations conditionally.
*/
Azure::ETag ETag;
/**
* The date and time the container was last modified. Any operation that modifies the blob,
* including an update of the metadata or properties, changes the last-modified time of the
* blob.
*/
Azure::DateTime LastModified;
/**
* Uniquely identifies a container's or blob's lease.
*/
std::string LeaseId;
}; // struct RenewBlobLeaseResult
} // namespace _detail
namespace _detail {
struct StartBlobCopyFromUriResult final
{
/**
* The ETag contains a value that you can use to perform operations conditionally.
*/
Azure::ETag ETag;
/**
* The date and time the container was last modified. Any operation that modifies the blob,
* including an update of the metadata or properties, changes the last-modified time of the
* blob.
*/
Azure::DateTime LastModified;
/**
* String identifier for the last attempted Copy Blob operation where this blob was the
* destination. This value is null if this blob has never been the destination of a copy
* operation, or if this blob has been modified after a concluded copy operation.
*/
std::string CopyId;
/**
* State of the copy operation identified by the copy ID. Possible values include success,
* pending, aborted, failed etc. This value is null if this blob has never been the
* destination of a copy operation, or if this blob has been modified after a concluded copy
* operation.
*/
Models::CopyStatus CopyStatus;
/**
* A string value that uniquely identifies the blob. This value is null if Blob Versioning
* is not enabled.
*/
Azure::Nullable<std::string> VersionId;
}; // struct StartBlobCopyFromUriResult
} // namespace _detail
namespace _detail {
struct StartBlobCopyIncrementalResult final
{
/**
* The ETag contains a value that you can use to perform operations conditionally.
*/
Azure::ETag ETag;
/**
* The date and time the container was last modified. Any operation that modifies the blob,
* including an update of the metadata or properties, changes the last-modified time of the
* blob.
*/
Azure::DateTime LastModified;
/**
* String identifier for the last attempted Copy Blob operation where this blob was the
* destination. This value is null if this blob has never been the destination of a copy
* operation, or if this blob has been modified after a concluded copy operation.
*/
std::string CopyId;
/**
* State of the copy operation identified by the copy ID. Possible values include success,
* pending, aborted, failed etc. This value is null if this blob has never been the
* destination of a copy operation, or if this blob has been modified after a concluded copy
* operation.
*/
Models::CopyStatus CopyStatus;
/**
* A string value that uniquely identifies the blob. This value is null if Blob Versioning
* is not enabled.
*/
Azure::Nullable<std::string> VersionId;
}; // struct StartBlobCopyIncrementalResult
} // namespace _detail
namespace _detail {
struct SubmitBlobBatchResult final
{
std::string ContentType;
}; // struct SubmitBlobBatchResult
} // namespace _detail
namespace _detail {
struct UndeleteBlobContainerResult final
{
}; // struct UndeleteBlobContainerResult
} // namespace _detail
} // namespace Models
namespace _detail {
constexpr static const char* ApiVersion = "2020-02-10";
} // namespace _detail
namespace _detail {
using namespace Models;
inline std::string ListBlobContainersIncludeFlagsToString(
const ListBlobContainersIncludeFlags& val)
{
ListBlobContainersIncludeFlags value_list[] = {
ListBlobContainersIncludeFlags::Metadata,
ListBlobContainersIncludeFlags::Deleted,
};
const char* string_list[] = {
"metadata",
"deleted",
};
std::string ret;
for (size_t i = 0; i < sizeof(value_list) / sizeof(ListBlobContainersIncludeFlags); ++i)
{
if ((val & value_list[i]) == value_list[i])
{
if (!ret.empty())
{
ret += ",";
}
ret += string_list[i];
}
}
return ret;
}
inline std::string ListBlobsIncludeFlagsToString(const ListBlobsIncludeFlags& val)
{
ListBlobsIncludeFlags value_list[] = {
ListBlobsIncludeFlags::Copy,
ListBlobsIncludeFlags::Deleted,
ListBlobsIncludeFlags::Metadata,
ListBlobsIncludeFlags::Snapshots,
ListBlobsIncludeFlags::Versions,
ListBlobsIncludeFlags::UncomittedBlobs,
ListBlobsIncludeFlags::Tags,
};
const char* string_list[] = {
"copy",
"deleted",
"metadata",
"snapshots",
"versions",
"uncommittedblobs",
"tags",
};
std::string ret;
for (size_t i = 0; i < sizeof(value_list) / sizeof(ListBlobsIncludeFlags); ++i)
{
if ((val & value_list[i]) == value_list[i])
{
if (!ret.empty())
{
ret += ",";
}
ret += string_list[i];
}
}
return ret;
}
class BlobRestClient final {
public:
class Service final {
public:
struct ListBlobContainersOptions final
{
Azure::Nullable<int32_t> Timeout;
Azure::Nullable<std::string> Prefix;
Azure::Nullable<std::string> ContinuationToken;
Azure::Nullable<int32_t> MaxResults;
ListBlobContainersIncludeFlags Include = ListBlobContainersIncludeFlags::None;
}; // struct ListBlobContainersOptions
static Azure::Response<Models::_detail::ListBlobContainersResult> ListBlobContainers(
Azure::Core::Http::_internal::HttpPipeline& pipeline,
const Azure::Core::Url& url,
const ListBlobContainersOptions& options,
const Azure::Core::Context& context)
{
auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Get, url);
request.SetHeader("x-ms-version", "2020-02-10");
if (options.Timeout.HasValue())
{
request.GetUrl().AppendQueryParameter(
"timeout", std::to_string(options.Timeout.Value()));
}
request.GetUrl().AppendQueryParameter("comp", "list");
if (options.Prefix.HasValue())
{
request.GetUrl().AppendQueryParameter(
"prefix", _internal::UrlEncodeQueryParameter(options.Prefix.Value()));
}
if (options.ContinuationToken.HasValue())
{
request.GetUrl().AppendQueryParameter(
"marker", _internal::UrlEncodeQueryParameter(options.ContinuationToken.Value()));
}
if (options.MaxResults.HasValue())
{
request.GetUrl().AppendQueryParameter(
"maxresults", std::to_string(options.MaxResults.Value()));
}
std::string list_blob_containers_include_flags
= ListBlobContainersIncludeFlagsToString(options.Include);
if (!list_blob_containers_include_flags.empty())
{
request.GetUrl().AppendQueryParameter(
"include", _internal::UrlEncodeQueryParameter(list_blob_containers_include_flags));
}
auto pHttpResponse = pipeline.Send(request, context);
Azure::Core::Http::RawResponse& httpResponse = *pHttpResponse;
Models::_detail::ListBlobContainersResult response;
auto http_status_code = httpResponse.GetStatusCode();
if (http_status_code != Azure::Core::Http::HttpStatusCode::Ok)
{
throw StorageException::CreateFromResponse(std::move(pHttpResponse));
}
{
const auto& httpResponseBody = httpResponse.GetBody();
_internal::XmlReader reader(
reinterpret_cast<const char*>(httpResponseBody.data()), httpResponseBody.size());
response = ListBlobContainersResultInternalFromXml(reader);
}
return Azure::Response<Models::_detail::ListBlobContainersResult>(
std::move(response), std::move(pHttpResponse));
}
struct GetUserDelegationKeyOptions final
{
Azure::Nullable<int32_t> Timeout;
Azure::DateTime StartsOn;
Azure::DateTime ExpiresOn;
}; // struct GetUserDelegationKeyOptions
static Azure::Response<UserDelegationKey> GetUserDelegationKey(
Azure::Core::Http::_internal::HttpPipeline& pipeline,
const Azure::Core::Url& url,
const GetUserDelegationKeyOptions& options,
const Azure::Core::Context& context)
{
std::string xml_body;
{
_internal::XmlWriter writer;
GetUserDelegationKeyOptionsToXml(writer, options);
xml_body = writer.GetDocument();
writer.Write(_internal::XmlNode{_internal::XmlNodeType::End});
}
Azure::Core::IO::MemoryBodyStream xml_body_stream(
reinterpret_cast<const uint8_t*>(xml_body.data()), xml_body.length());
auto request = Azure::Core::Http::Request(
Azure::Core::Http::HttpMethod::Post, url, &xml_body_stream);
request.SetHeader("Content-Length", std::to_string(xml_body_stream.Length()));
request.GetUrl().AppendQueryParameter("restype", "service");
request.GetUrl().AppendQueryParameter("comp", "userdelegationkey");
request.SetHeader("x-ms-version", "2020-02-10");
if (options.Timeout.HasValue())
{
request.GetUrl().AppendQueryParameter(
"timeout", std::to_string(options.Timeout.Value()));
}
auto pHttpResponse = pipeline.Send(request, context);
Azure::Core::Http::RawResponse& httpResponse = *pHttpResponse;
UserDelegationKey response;
auto http_status_code = httpResponse.GetStatusCode();
if (http_status_code != Azure::Core::Http::HttpStatusCode::Ok)
{
throw StorageException::CreateFromResponse(std::move(pHttpResponse));
}
{
const auto& httpResponseBody = httpResponse.GetBody();
_internal::XmlReader reader(
reinterpret_cast<const char*>(httpResponseBody.data()), httpResponseBody.size());
response = UserDelegationKeyFromXml(reader);
}
return Azure::Response<UserDelegationKey>(std::move(response), std::move(pHttpResponse));
}
struct GetServicePropertiesOptions final
{
Azure::Nullable<int32_t> Timeout;
}; // struct GetServicePropertiesOptions
static Azure::Response<BlobServiceProperties> GetProperties(
Azure::Core::Http::_internal::HttpPipeline& pipeline,
const Azure::Core::Url& url,
const GetServicePropertiesOptions& options,
const Azure::Core::Context& context)
{
auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Get, url);
request.GetUrl().AppendQueryParameter("restype", "service");
request.GetUrl().AppendQueryParameter("comp", "properties");
request.SetHeader("x-ms-version", "2020-02-10");
if (options.Timeout.HasValue())
{
request.GetUrl().AppendQueryParameter(
"timeout", std::to_string(options.Timeout.Value()));
}
auto pHttpResponse = pipeline.Send(request, context);
Azure::Core::Http::RawResponse& httpResponse = *pHttpResponse;
BlobServiceProperties response;
auto http_status_code = httpResponse.GetStatusCode();
if (http_status_code != Azure::Core::Http::HttpStatusCode::Ok)
{
throw StorageException::CreateFromResponse(std::move(pHttpResponse));
}
{
const auto& httpResponseBody = httpResponse.GetBody();
_internal::XmlReader reader(
reinterpret_cast<const char*>(httpResponseBody.data()), httpResponseBody.size());
response = BlobServicePropertiesFromXml(reader);
}
return Azure::Response<BlobServiceProperties>(
std::move(response), std::move(pHttpResponse));
}
struct SetServicePropertiesOptions final
{
Azure::Nullable<int32_t> Timeout;
BlobServiceProperties Properties;
}; // struct SetServicePropertiesOptions
static Azure::Response<SetServicePropertiesResult> SetProperties(
Azure::Core::Http::_internal::HttpPipeline& pipeline,
const Azure::Core::Url& url,
const SetServicePropertiesOptions& options,
const Azure::Core::Context& context)
{
std::string xml_body;
{
_internal::XmlWriter writer;
SetServicePropertiesOptionsToXml(writer, options);
xml_body = writer.GetDocument();
writer.Write(_internal::XmlNode{_internal::XmlNodeType::End});
}
Azure::Core::IO::MemoryBodyStream xml_body_stream(
reinterpret_cast<const uint8_t*>(xml_body.data()), xml_body.length());
auto request = Azure::Core::Http::Request(
Azure::Core::Http::HttpMethod::Put, url, &xml_body_stream);
request.SetHeader("Content-Length", std::to_string(xml_body_stream.Length()));
request.GetUrl().AppendQueryParameter("restype", "service");
request.GetUrl().AppendQueryParameter("comp", "properties");
request.SetHeader("x-ms-version", "2020-02-10");
if (options.Timeout.HasValue())
{
request.GetUrl().AppendQueryParameter(
"timeout", std::to_string(options.Timeout.Value()));
}
auto pHttpResponse = pipeline.Send(request, context);
Azure::Core::Http::RawResponse& httpResponse = *pHttpResponse;
SetServicePropertiesResult response;
auto http_status_code = httpResponse.GetStatusCode();
if (http_status_code != Azure::Core::Http::HttpStatusCode::Accepted)
{
throw StorageException::CreateFromResponse(std::move(pHttpResponse));
}
return Azure::Response<SetServicePropertiesResult>(
std::move(response), std::move(pHttpResponse));
}
struct GetAccountInfoOptions final
{
Azure::Nullable<int32_t> Timeout;
}; // struct GetAccountInfoOptions
static Azure::Response<AccountInfo> GetAccountInfo(
Azure::Core::Http::_internal::HttpPipeline& pipeline,
const Azure::Core::Url& url,
const GetAccountInfoOptions& options,
const Azure::Core::Context& context)
{
auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Head, url);
request.GetUrl().AppendQueryParameter("restype", "account");
request.GetUrl().AppendQueryParameter("comp", "properties");
request.SetHeader("x-ms-version", "2020-02-10");
if (options.Timeout.HasValue())
{
request.GetUrl().AppendQueryParameter(
"timeout", std::to_string(options.Timeout.Value()));
}
auto pHttpResponse = pipeline.Send(request, context);
Azure::Core::Http::RawResponse& httpResponse = *pHttpResponse;
AccountInfo response;
auto http_status_code = httpResponse.GetStatusCode();
if (http_status_code != Azure::Core::Http::HttpStatusCode::Ok)
{
throw StorageException::CreateFromResponse(std::move(pHttpResponse));
}
response.SkuName = SkuName(httpResponse.GetHeaders().at("x-ms-sku-name"));
response.AccountKind = AccountKind(httpResponse.GetHeaders().at("x-ms-account-kind"));
response.IsHierarchicalNamespaceEnabled
= httpResponse.GetHeaders().at("x-ms-is-hns-enabled") == "true";
return Azure::Response<AccountInfo>(std::move(response), std::move(pHttpResponse));
}
struct GetServiceStatisticsOptions final
{
Azure::Nullable<int32_t> Timeout;
}; // struct GetServiceStatisticsOptions
static Azure::Response<ServiceStatistics> GetStatistics(
Azure::Core::Http::_internal::HttpPipeline& pipeline,
const Azure::Core::Url& url,
const GetServiceStatisticsOptions& options,
const Azure::Core::Context& context)
{
auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Get, url);
request.GetUrl().AppendQueryParameter("restype", "service");
request.GetUrl().AppendQueryParameter("comp", "stats");
request.SetHeader("x-ms-version", "2020-02-10");
if (options.Timeout.HasValue())
{
request.GetUrl().AppendQueryParameter(
"timeout", std::to_string(options.Timeout.Value()));
}
auto pHttpResponse = pipeline.Send(request, context);
Azure::Core::Http::RawResponse& httpResponse = *pHttpResponse;
ServiceStatistics response;
auto http_status_code = httpResponse.GetStatusCode();
if (http_status_code != Azure::Core::Http::HttpStatusCode::Ok)
{
throw StorageException::CreateFromResponse(std::move(pHttpResponse));
}
{
const auto& httpResponseBody = httpResponse.GetBody();
_internal::XmlReader reader(
reinterpret_cast<const char*>(httpResponseBody.data()), httpResponseBody.size());
response = ServiceStatisticsFromXml(reader);
}
return Azure::Response<ServiceStatistics>(std::move(response), std::move(pHttpResponse));
}
struct FindBlobsByTagsOptions final
{
Azure::Nullable<int32_t> Timeout;
std::string Where;
Azure::Nullable<std::string> ContinuationToken;
Azure::Nullable<int32_t> MaxResults;
}; // struct FindBlobsByTagsOptions
static Azure::Response<Models::_detail::FindBlobsByTagsResult> FindBlobsByTags(
Azure::Core::Http::_internal::HttpPipeline& pipeline,
const Azure::Core::Url& url,
const FindBlobsByTagsOptions& options,
const Azure::Core::Context& context)
{
auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Get, url);
request.SetHeader("x-ms-version", "2020-02-10");
if (options.Timeout.HasValue())
{
request.GetUrl().AppendQueryParameter(
"timeout", std::to_string(options.Timeout.Value()));
}
request.GetUrl().AppendQueryParameter("comp", "blobs");
request.GetUrl().AppendQueryParameter(
"where", _internal::UrlEncodeQueryParameter(options.Where));
if (options.ContinuationToken.HasValue())
{
request.GetUrl().AppendQueryParameter(
"marker", _internal::UrlEncodeQueryParameter(options.ContinuationToken.Value()));
}
if (options.MaxResults.HasValue())
{
request.GetUrl().AppendQueryParameter(
"maxresults", std::to_string(options.MaxResults.Value()));
}
auto pHttpResponse = pipeline.Send(request, context);
Azure::Core::Http::RawResponse& httpResponse = *pHttpResponse;
Models::_detail::FindBlobsByTagsResult response;
auto http_status_code = httpResponse.GetStatusCode();
if (http_status_code != Azure::Core::Http::HttpStatusCode::Ok)
{
throw StorageException::CreateFromResponse(std::move(pHttpResponse));
}
{
const auto& httpResponseBody = httpResponse.GetBody();
_internal::XmlReader reader(
reinterpret_cast<const char*>(httpResponseBody.data()), httpResponseBody.size());
response = FindBlobsByTagsResultInternalFromXml(reader);
}
return Azure::Response<Models::_detail::FindBlobsByTagsResult>(
std::move(response), std::move(pHttpResponse));
}
private:
static BlobServiceProperties BlobServicePropertiesFromXml(_internal::XmlReader& reader)
{
BlobServiceProperties ret;
enum class XmlTagName
{
k_StorageServiceProperties,
k_Logging,
k_HourMetrics,
k_MinuteMetrics,
k_Cors,
k_CorsRule,
k_DefaultServiceVersion,
k_DeleteRetentionPolicy,
k_StaticWebsite,
k_Unknown,
};
std::vector<XmlTagName> path;
while (true)
{
auto node = reader.Read();
if (node.Type == _internal::XmlNodeType::End)
{
break;
}
else if (node.Type == _internal::XmlNodeType::EndTag)
{
if (path.size() > 0)
{
path.pop_back();
}
else
{
break;
}
}
else if (node.Type == _internal::XmlNodeType::StartTag)
{
if (node.Name == "StorageServiceProperties")
{
path.emplace_back(XmlTagName::k_StorageServiceProperties);
}
else if (node.Name == "Logging")
{
path.emplace_back(XmlTagName::k_Logging);
}
else if (node.Name == "HourMetrics")
{
path.emplace_back(XmlTagName::k_HourMetrics);
}
else if (node.Name == "MinuteMetrics")
{
path.emplace_back(XmlTagName::k_MinuteMetrics);
}
else if (node.Name == "Cors")
{
path.emplace_back(XmlTagName::k_Cors);
}
else if (node.Name == "CorsRule")
{
path.emplace_back(XmlTagName::k_CorsRule);
}
else if (node.Name == "DefaultServiceVersion")
{
path.emplace_back(XmlTagName::k_DefaultServiceVersion);
}
else if (node.Name == "DeleteRetentionPolicy")
{
path.emplace_back(XmlTagName::k_DeleteRetentionPolicy);
}
else if (node.Name == "StaticWebsite")
{
path.emplace_back(XmlTagName::k_StaticWebsite);
}
else
{
path.emplace_back(XmlTagName::k_Unknown);
}
if (path.size() == 2 && path[0] == XmlTagName::k_StorageServiceProperties
&& path[1] == XmlTagName::k_Logging)
{
ret.Logging = AnalyticsLoggingFromXml(reader);
path.pop_back();
}
else if (
path.size() == 2 && path[0] == XmlTagName::k_StorageServiceProperties
&& path[1] == XmlTagName::k_HourMetrics)
{
ret.HourMetrics = MetricsFromXml(reader);
path.pop_back();
}
else if (
path.size() == 2 && path[0] == XmlTagName::k_StorageServiceProperties
&& path[1] == XmlTagName::k_MinuteMetrics)
{
ret.MinuteMetrics = MetricsFromXml(reader);
path.pop_back();
}
else if (
path.size() == 3 && path[0] == XmlTagName::k_StorageServiceProperties
&& path[1] == XmlTagName::k_Cors && path[2] == XmlTagName::k_CorsRule)
{
ret.Cors.emplace_back(CorsRuleFromXml(reader));
path.pop_back();
}
else if (
path.size() == 2 && path[0] == XmlTagName::k_StorageServiceProperties
&& path[1] == XmlTagName::k_DeleteRetentionPolicy)
{
ret.DeleteRetentionPolicy = RetentionPolicyFromXml(reader);
path.pop_back();
}
else if (
path.size() == 2 && path[0] == XmlTagName::k_StorageServiceProperties
&& path[1] == XmlTagName::k_StaticWebsite)
{
ret.StaticWebsite = StaticWebsiteFromXml(reader);
path.pop_back();
}
}
else if (node.Type == _internal::XmlNodeType::Text)
{
if (path.size() == 2 && path[0] == XmlTagName::k_StorageServiceProperties
&& path[1] == XmlTagName::k_DefaultServiceVersion)
{
ret.DefaultServiceVersion = node.Value;
}
}
}
return ret;
}
static Models::_detail::FindBlobsByTagsResult FindBlobsByTagsResultInternalFromXml(
_internal::XmlReader& reader)
{
Models::_detail::FindBlobsByTagsResult ret;
enum class XmlTagName
{
k_EnumerationResults,
k_NextMarker,
k_Blobs,
k_Blob,
k_Unknown,
};
std::vector<XmlTagName> path;
while (true)
{
auto node = reader.Read();
if (node.Type == _internal::XmlNodeType::End)
{
break;
}
else if (node.Type == _internal::XmlNodeType::EndTag)
{
if (path.size() > 0)
{
path.pop_back();
}
else
{
break;
}
}
else if (node.Type == _internal::XmlNodeType::StartTag)
{
if (node.Name == "EnumerationResults")
{
path.emplace_back(XmlTagName::k_EnumerationResults);
}
else if (node.Name == "NextMarker")
{
path.emplace_back(XmlTagName::k_NextMarker);
}
else if (node.Name == "Blobs")
{
path.emplace_back(XmlTagName::k_Blobs);
}
else if (node.Name == "Blob")
{
path.emplace_back(XmlTagName::k_Blob);
}
else
{
path.emplace_back(XmlTagName::k_Unknown);
}
if (path.size() == 3 && path[0] == XmlTagName::k_EnumerationResults
&& path[1] == XmlTagName::k_Blobs && path[2] == XmlTagName::k_Blob)
{
ret.Items.emplace_back(TaggedBlobItemFromXml(reader));
path.pop_back();
}
}
else if (node.Type == _internal::XmlNodeType::Text)
{
if (path.size() == 2 && path[0] == XmlTagName::k_EnumerationResults
&& path[1] == XmlTagName::k_NextMarker)
{
ret.ContinuationToken = node.Value;
}
}
else if (node.Type == _internal::XmlNodeType::Attribute)
{
if (path.size() == 1 && path[0] == XmlTagName::k_EnumerationResults
&& node.Name == "ServiceEndpoint")
{
ret.ServiceEndpoint = node.Value;
}
}
}
return ret;
}
static Models::_detail::ListBlobContainersResult ListBlobContainersResultInternalFromXml(
_internal::XmlReader& reader)
{
Models::_detail::ListBlobContainersResult ret;
enum class XmlTagName
{
k_EnumerationResults,
k_Prefix,
k_NextMarker,
k_Containers,
k_Container,
k_Unknown,
};
std::vector<XmlTagName> path;
while (true)
{
auto node = reader.Read();
if (node.Type == _internal::XmlNodeType::End)
{
break;
}
else if (node.Type == _internal::XmlNodeType::EndTag)
{
if (path.size() > 0)
{
path.pop_back();
}
else
{
break;
}
}
else if (node.Type == _internal::XmlNodeType::StartTag)
{
if (node.Name == "EnumerationResults")
{
path.emplace_back(XmlTagName::k_EnumerationResults);
}
else if (node.Name == "Prefix")
{
path.emplace_back(XmlTagName::k_Prefix);
}
else if (node.Name == "NextMarker")
{
path.emplace_back(XmlTagName::k_NextMarker);
}
else if (node.Name == "Containers")
{
path.emplace_back(XmlTagName::k_Containers);
}
else if (node.Name == "Container")
{
path.emplace_back(XmlTagName::k_Container);
}
else
{
path.emplace_back(XmlTagName::k_Unknown);
}
if (path.size() == 3 && path[0] == XmlTagName::k_EnumerationResults
&& path[1] == XmlTagName::k_Containers && path[2] == XmlTagName::k_Container)
{
ret.Items.emplace_back(BlobContainerItemFromXml(reader));
path.pop_back();
}
}
else if (node.Type == _internal::XmlNodeType::Text)
{
if (path.size() == 2 && path[0] == XmlTagName::k_EnumerationResults
&& path[1] == XmlTagName::k_Prefix)
{
ret.Prefix = node.Value;
}
else if (
path.size() == 2 && path[0] == XmlTagName::k_EnumerationResults
&& path[1] == XmlTagName::k_NextMarker)
{
ret.ContinuationToken = node.Value;
}
}
else if (node.Type == _internal::XmlNodeType::Attribute)
{
if (path.size() == 1 && path[0] == XmlTagName::k_EnumerationResults
&& node.Name == "ServiceEndpoint")
{
ret.ServiceEndpoint = node.Value;
}
}
}
return ret;
}
static ServiceStatistics ServiceStatisticsFromXml(_internal::XmlReader& reader)
{
ServiceStatistics ret;
enum class XmlTagName
{
k_StorageServiceStats,
k_GeoReplication,
k_Unknown,
};
std::vector<XmlTagName> path;
while (true)
{
auto node = reader.Read();
if (node.Type == _internal::XmlNodeType::End)
{
break;
}
else if (node.Type == _internal::XmlNodeType::EndTag)
{
if (path.size() > 0)
{
path.pop_back();
}
else
{
break;
}
}
else if (node.Type == _internal::XmlNodeType::StartTag)
{
if (node.Name == "StorageServiceStats")
{
path.emplace_back(XmlTagName::k_StorageServiceStats);
}
else if (node.Name == "GeoReplication")
{
path.emplace_back(XmlTagName::k_GeoReplication);
}
else
{
path.emplace_back(XmlTagName::k_Unknown);
}
if (path.size() == 2 && path[0] == XmlTagName::k_StorageServiceStats
&& path[1] == XmlTagName::k_GeoReplication)
{
ret.GeoReplication = GeoReplicationFromXml(reader);
path.pop_back();
}
}
else if (node.Type == _internal::XmlNodeType::Text)
{
}
}
return ret;
}
static UserDelegationKey UserDelegationKeyFromXml(_internal::XmlReader& reader)
{
UserDelegationKey ret;
enum class XmlTagName
{
k_UserDelegationKey,
k_SignedOid,
k_SignedTid,
k_SignedStart,
k_SignedExpiry,
k_SignedService,
k_SignedVersion,
k_Value,
k_Unknown,
};
std::vector<XmlTagName> path;
while (true)
{
auto node = reader.Read();
if (node.Type == _internal::XmlNodeType::End)
{
break;
}
else if (node.Type == _internal::XmlNodeType::EndTag)
{
if (path.size() > 0)
{
path.pop_back();
}
else
{
break;
}
}
else if (node.Type == _internal::XmlNodeType::StartTag)
{
if (node.Name == "UserDelegationKey")
{
path.emplace_back(XmlTagName::k_UserDelegationKey);
}
else if (node.Name == "SignedOid")
{
path.emplace_back(XmlTagName::k_SignedOid);
}
else if (node.Name == "SignedTid")
{
path.emplace_back(XmlTagName::k_SignedTid);
}
else if (node.Name == "SignedStart")
{
path.emplace_back(XmlTagName::k_SignedStart);
}
else if (node.Name == "SignedExpiry")
{
path.emplace_back(XmlTagName::k_SignedExpiry);
}
else if (node.Name == "SignedService")
{
path.emplace_back(XmlTagName::k_SignedService);
}
else if (node.Name == "SignedVersion")
{
path.emplace_back(XmlTagName::k_SignedVersion);
}
else if (node.Name == "Value")
{
path.emplace_back(XmlTagName::k_Value);
}
else
{
path.emplace_back(XmlTagName::k_Unknown);
}
}
else if (node.Type == _internal::XmlNodeType::Text)
{
if (path.size() == 2 && path[0] == XmlTagName::k_UserDelegationKey
&& path[1] == XmlTagName::k_SignedOid)
{
ret.SignedObjectId = node.Value;
}
else if (
path.size() == 2 && path[0] == XmlTagName::k_UserDelegationKey
&& path[1] == XmlTagName::k_SignedTid)
{
ret.SignedTenantId = node.Value;
}
else if (
path.size() == 2 && path[0] == XmlTagName::k_UserDelegationKey
&& path[1] == XmlTagName::k_SignedStart)
{
ret.SignedStartsOn
= Azure::DateTime::Parse(node.Value, Azure::DateTime::DateFormat::Rfc3339);
}
else if (
path.size() == 2 && path[0] == XmlTagName::k_UserDelegationKey
&& path[1] == XmlTagName::k_SignedExpiry)
{
ret.SignedExpiresOn
= Azure::DateTime::Parse(node.Value, Azure::DateTime::DateFormat::Rfc3339);
}
else if (
path.size() == 2 && path[0] == XmlTagName::k_UserDelegationKey
&& path[1] == XmlTagName::k_SignedService)
{
ret.SignedService = node.Value;
}
else if (
path.size() == 2 && path[0] == XmlTagName::k_UserDelegationKey
&& path[1] == XmlTagName::k_SignedVersion)
{
ret.SignedVersion = node.Value;
}
else if (
path.size() == 2 && path[0] == XmlTagName::k_UserDelegationKey
&& path[1] == XmlTagName::k_Value)
{
ret.Value = node.Value;
}
}
}
return ret;
}
static AnalyticsLogging AnalyticsLoggingFromXml(_internal::XmlReader& reader)
{
AnalyticsLogging ret;
enum class XmlTagName
{
k_Version,
k_Delete,
k_Read,
k_Write,
k_RetentionPolicy,
k_Unknown,
};
std::vector<XmlTagName> path;
while (true)
{
auto node = reader.Read();
if (node.Type == _internal::XmlNodeType::End)
{
break;
}
else if (node.Type == _internal::XmlNodeType::EndTag)
{
if (path.size() > 0)
{
path.pop_back();
}
else
{
break;
}
}
else if (node.Type == _internal::XmlNodeType::StartTag)
{
if (node.Name == "Version")
{
path.emplace_back(XmlTagName::k_Version);
}
else if (node.Name == "Delete")
{
path.emplace_back(XmlTagName::k_Delete);
}
else if (node.Name == "Read")
{
path.emplace_back(XmlTagName::k_Read);
}
else if (node.Name == "Write")
{
path.emplace_back(XmlTagName::k_Write);
}
else if (node.Name == "RetentionPolicy")
{
path.emplace_back(XmlTagName::k_RetentionPolicy);
}
else
{
path.emplace_back(XmlTagName::k_Unknown);
}
if (path.size() == 1 && path[0] == XmlTagName::k_RetentionPolicy)
{
ret.RetentionPolicy = RetentionPolicyFromXml(reader);
path.pop_back();
}
}
else if (node.Type == _internal::XmlNodeType::Text)
{
if (path.size() == 1 && path[0] == XmlTagName::k_Version)
{
ret.Version = node.Value;
}
else if (path.size() == 1 && path[0] == XmlTagName::k_Delete)
{
ret.Delete = node.Value == "true";
}
else if (path.size() == 1 && path[0] == XmlTagName::k_Read)
{
ret.Read = node.Value == "true";
}
else if (path.size() == 1 && path[0] == XmlTagName::k_Write)
{
ret.Write = node.Value == "true";
}
}
}
return ret;
}
static BlobContainerItem BlobContainerItemFromXml(_internal::XmlReader& reader)
{
BlobContainerItem ret;
enum class XmlTagName
{
k_Name,
k_Properties,
k_Etag,
k_LastModified,
k_PublicAccess,
k_HasImmutabilityPolicy,
k_HasLegalHold,
k_LeaseStatus,
k_LeaseState,
k_LeaseDuration,
k_DefaultEncryptionScope,
k_DenyEncryptionScopeOverride,
k_Metadata,
k_Deleted,
k_Version,
k_DeletedTime,
k_RemainingRetentionDays,
k_Unknown,
};
std::vector<XmlTagName> path;
while (true)
{
auto node = reader.Read();
if (node.Type == _internal::XmlNodeType::End)
{
break;
}
else if (node.Type == _internal::XmlNodeType::EndTag)
{
if (path.size() > 0)
{
path.pop_back();
}
else
{
break;
}
}
else if (node.Type == _internal::XmlNodeType::StartTag)
{
if (node.Name == "Name")
{
path.emplace_back(XmlTagName::k_Name);
}
else if (node.Name == "Properties")
{
path.emplace_back(XmlTagName::k_Properties);
}
else if (node.Name == "Etag")
{
path.emplace_back(XmlTagName::k_Etag);
}
else if (node.Name == "Last-Modified")
{
path.emplace_back(XmlTagName::k_LastModified);
}
else if (node.Name == "PublicAccess")
{
path.emplace_back(XmlTagName::k_PublicAccess);
}
else if (node.Name == "HasImmutabilityPolicy")
{
path.emplace_back(XmlTagName::k_HasImmutabilityPolicy);
}
else if (node.Name == "HasLegalHold")
{
path.emplace_back(XmlTagName::k_HasLegalHold);
}
else if (node.Name == "LeaseStatus")
{
path.emplace_back(XmlTagName::k_LeaseStatus);
}
else if (node.Name == "LeaseState")
{
path.emplace_back(XmlTagName::k_LeaseState);
}
else if (node.Name == "LeaseDuration")
{
path.emplace_back(XmlTagName::k_LeaseDuration);
}
else if (node.Name == "DefaultEncryptionScope")
{
path.emplace_back(XmlTagName::k_DefaultEncryptionScope);
}
else if (node.Name == "DenyEncryptionScopeOverride")
{
path.emplace_back(XmlTagName::k_DenyEncryptionScopeOverride);
}
else if (node.Name == "Metadata")
{
path.emplace_back(XmlTagName::k_Metadata);
}
else if (node.Name == "Deleted")
{
path.emplace_back(XmlTagName::k_Deleted);
}
else if (node.Name == "Version")
{
path.emplace_back(XmlTagName::k_Version);
}
else if (node.Name == "DeletedTime")
{
path.emplace_back(XmlTagName::k_DeletedTime);
}
else if (node.Name == "RemainingRetentionDays")
{
path.emplace_back(XmlTagName::k_RemainingRetentionDays);
}
else
{
path.emplace_back(XmlTagName::k_Unknown);
}
if (path.size() == 1 && path[0] == XmlTagName::k_Metadata)
{
ret.Details.Metadata = MetadataFromXml(reader);
path.pop_back();
}
}
else if (node.Type == _internal::XmlNodeType::Text)
{
if (path.size() == 1 && path[0] == XmlTagName::k_Name)
{
ret.Name = node.Value;
}
else if (
path.size() == 2 && path[0] == XmlTagName::k_Properties
&& path[1] == XmlTagName::k_Etag)
{
ret.Details.ETag = Azure::ETag(node.Value);
}
else if (
path.size() == 2 && path[0] == XmlTagName::k_Properties
&& path[1] == XmlTagName::k_LastModified)
{
ret.Details.LastModified
= Azure::DateTime::Parse(node.Value, Azure::DateTime::DateFormat::Rfc1123);
}
else if (
path.size() == 2 && path[0] == XmlTagName::k_Properties
&& path[1] == XmlTagName::k_PublicAccess)
{
ret.Details.AccessType = PublicAccessType(node.Value);
}
else if (
path.size() == 2 && path[0] == XmlTagName::k_Properties
&& path[1] == XmlTagName::k_HasImmutabilityPolicy)
{
ret.Details.HasImmutabilityPolicy = node.Value == "true";
}
else if (
path.size() == 2 && path[0] == XmlTagName::k_Properties
&& path[1] == XmlTagName::k_HasLegalHold)
{
ret.Details.HasLegalHold = node.Value == "true";
}
else if (
path.size() == 2 && path[0] == XmlTagName::k_Properties
&& path[1] == XmlTagName::k_LeaseStatus)
{
ret.Details.LeaseStatus = LeaseStatus(node.Value);
}
else if (
path.size() == 2 && path[0] == XmlTagName::k_Properties
&& path[1] == XmlTagName::k_LeaseState)
{
ret.Details.LeaseState = LeaseState(node.Value);
}
else if (
path.size() == 2 && path[0] == XmlTagName::k_Properties
&& path[1] == XmlTagName::k_LeaseDuration)
{
ret.Details.LeaseDuration = LeaseDurationType(node.Value);
}
else if (
path.size() == 2 && path[0] == XmlTagName::k_Properties
&& path[1] == XmlTagName::k_DefaultEncryptionScope)
{
ret.Details.DefaultEncryptionScope = node.Value;
}
else if (
path.size() == 2 && path[0] == XmlTagName::k_Properties
&& path[1] == XmlTagName::k_DenyEncryptionScopeOverride)
{
ret.Details.PreventEncryptionScopeOverride = node.Value == "true";
}
else if (path.size() == 1 && path[0] == XmlTagName::k_Deleted)
{
ret.IsDeleted = node.Value == "true";
}
else if (path.size() == 1 && path[0] == XmlTagName::k_Version)
{
ret.VersionId = node.Value;
}
else if (
path.size() == 2 && path[0] == XmlTagName::k_Properties
&& path[1] == XmlTagName::k_DeletedTime)
{
ret.Details.DeletedOn
= Azure::DateTime::Parse(node.Value, Azure::DateTime::DateFormat::Rfc1123);
}
else if (
path.size() == 2 && path[0] == XmlTagName::k_Properties
&& path[1] == XmlTagName::k_RemainingRetentionDays)
{
ret.Details.RemainingRetentionDays = std::stoi(node.Value);
}
}
}
return ret;
}
static CorsRule CorsRuleFromXml(_internal::XmlReader& reader)
{
CorsRule ret;
enum class XmlTagName
{
k_AllowedOrigins,
k_AllowedMethods,
k_MaxAgeInSeconds,
k_ExposedHeaders,
k_AllowedHeaders,
k_Unknown,
};
std::vector<XmlTagName> path;
while (true)
{
auto node = reader.Read();
if (node.Type == _internal::XmlNodeType::End)
{
break;
}
else if (node.Type == _internal::XmlNodeType::EndTag)
{
if (path.size() > 0)
{
path.pop_back();
}
else
{
break;
}
}
else if (node.Type == _internal::XmlNodeType::StartTag)
{
if (node.Name == "AllowedOrigins")
{
path.emplace_back(XmlTagName::k_AllowedOrigins);
}
else if (node.Name == "AllowedMethods")
{
path.emplace_back(XmlTagName::k_AllowedMethods);
}
else if (node.Name == "MaxAgeInSeconds")
{
path.emplace_back(XmlTagName::k_MaxAgeInSeconds);
}
else if (node.Name == "ExposedHeaders")
{
path.emplace_back(XmlTagName::k_ExposedHeaders);
}
else if (node.Name == "AllowedHeaders")
{
path.emplace_back(XmlTagName::k_AllowedHeaders);
}
else
{
path.emplace_back(XmlTagName::k_Unknown);
}
}
else if (node.Type == _internal::XmlNodeType::Text)
{
if (path.size() == 1 && path[0] == XmlTagName::k_AllowedOrigins)
{
ret.AllowedOrigins = node.Value;
}
else if (path.size() == 1 && path[0] == XmlTagName::k_AllowedMethods)
{
ret.AllowedMethods = node.Value;
}
else if (path.size() == 1 && path[0] == XmlTagName::k_MaxAgeInSeconds)
{
ret.MaxAgeInSeconds = std::stoi(node.Value);
}
else if (path.size() == 1 && path[0] == XmlTagName::k_ExposedHeaders)
{
ret.ExposedHeaders = node.Value;
}
else if (path.size() == 1 && path[0] == XmlTagName::k_AllowedHeaders)
{
ret.AllowedHeaders = node.Value;
}
}
}
return ret;
}
static GeoReplication GeoReplicationFromXml(_internal::XmlReader& reader)
{
GeoReplication ret;
enum class XmlTagName
{
k_Status,
k_LastSyncTime,
k_Unknown,
};
std::vector<XmlTagName> path;
while (true)
{
auto node = reader.Read();
if (node.Type == _internal::XmlNodeType::End)
{
break;
}
else if (node.Type == _internal::XmlNodeType::EndTag)
{
if (path.size() > 0)
{
path.pop_back();
}
else
{
break;
}
}
else if (node.Type == _internal::XmlNodeType::StartTag)
{
if (node.Name == "Status")
{
path.emplace_back(XmlTagName::k_Status);
}
else if (node.Name == "LastSyncTime")
{
path.emplace_back(XmlTagName::k_LastSyncTime);
}
else
{
path.emplace_back(XmlTagName::k_Unknown);
}
}
else if (node.Type == _internal::XmlNodeType::Text)
{
if (path.size() == 1 && path[0] == XmlTagName::k_Status)
{
ret.Status = GeoReplicationStatus(node.Value);
}
else if (path.size() == 1 && path[0] == XmlTagName::k_LastSyncTime)
{
ret.LastSyncedOn
= Azure::DateTime::Parse(node.Value, Azure::DateTime::DateFormat::Rfc1123);
}
}
}
return ret;
}
static Metrics MetricsFromXml(_internal::XmlReader& reader)
{
Metrics ret;
enum class XmlTagName
{
k_Version,
k_Enabled,
k_IncludeAPIs,
k_RetentionPolicy,
k_Unknown,
};
std::vector<XmlTagName> path;
while (true)
{
auto node = reader.Read();
if (node.Type == _internal::XmlNodeType::End)
{
break;
}
else if (node.Type == _internal::XmlNodeType::EndTag)
{
if (path.size() > 0)
{
path.pop_back();
}
else
{
break;
}
}
else if (node.Type == _internal::XmlNodeType::StartTag)
{
if (node.Name == "Version")
{
path.emplace_back(XmlTagName::k_Version);
}
else if (node.Name == "Enabled")
{
path.emplace_back(XmlTagName::k_Enabled);
}
else if (node.Name == "IncludeAPIs")
{
path.emplace_back(XmlTagName::k_IncludeAPIs);
}
else if (node.Name == "RetentionPolicy")
{
path.emplace_back(XmlTagName::k_RetentionPolicy);
}
else
{
path.emplace_back(XmlTagName::k_Unknown);
}
if (path.size() == 1 && path[0] == XmlTagName::k_RetentionPolicy)
{
ret.RetentionPolicy = RetentionPolicyFromXml(reader);
path.pop_back();
}
}
else if (node.Type == _internal::XmlNodeType::Text)
{
if (path.size() == 1 && path[0] == XmlTagName::k_Version)
{
ret.Version = node.Value;
}
else if (path.size() == 1 && path[0] == XmlTagName::k_Enabled)
{
ret.IsEnabled = node.Value == "true";
}
else if (path.size() == 1 && path[0] == XmlTagName::k_IncludeAPIs)
{
ret.IncludeApis = node.Value == "true";
}
}
}
return ret;
}
static RetentionPolicy RetentionPolicyFromXml(_internal::XmlReader& reader)
{
RetentionPolicy ret;
enum class XmlTagName
{
k_Enabled,
k_Days,
k_Unknown,
};
std::vector<XmlTagName> path;
while (true)
{
auto node = reader.Read();
if (node.Type == _internal::XmlNodeType::End)
{
break;
}
else if (node.Type == _internal::XmlNodeType::EndTag)
{
if (path.size() > 0)
{
path.pop_back();
}
else
{
break;
}
}
else if (node.Type == _internal::XmlNodeType::StartTag)
{
if (node.Name == "Enabled")
{
path.emplace_back(XmlTagName::k_Enabled);
}
else if (node.Name == "Days")
{
path.emplace_back(XmlTagName::k_Days);
}
else
{
path.emplace_back(XmlTagName::k_Unknown);
}
}
else if (node.Type == _internal::XmlNodeType::Text)
{
if (path.size() == 1 && path[0] == XmlTagName::k_Enabled)
{
ret.IsEnabled = node.Value == "true";
}
else if (path.size() == 1 && path[0] == XmlTagName::k_Days)
{
ret.Days = std::stoi(node.Value);
}
}
}
return ret;
}
static StaticWebsite StaticWebsiteFromXml(_internal::XmlReader& reader)
{
StaticWebsite ret;
enum class XmlTagName
{
k_Enabled,
k_IndexDocument,
k_DefaultIndexDocumentPath,
k_ErrorDocument404Path,
k_Unknown,
};
std::vector<XmlTagName> path;
while (true)
{
auto node = reader.Read();
if (node.Type == _internal::XmlNodeType::End)
{
break;
}
else if (node.Type == _internal::XmlNodeType::EndTag)
{
if (path.size() > 0)
{
path.pop_back();
}
else
{
break;
}
}
else if (node.Type == _internal::XmlNodeType::StartTag)
{
if (node.Name == "Enabled")
{
path.emplace_back(XmlTagName::k_Enabled);
}
else if (node.Name == "IndexDocument")
{
path.emplace_back(XmlTagName::k_IndexDocument);
}
else if (node.Name == "DefaultIndexDocumentPath")
{
path.emplace_back(XmlTagName::k_DefaultIndexDocumentPath);
}
else if (node.Name == "ErrorDocument404Path")
{
path.emplace_back(XmlTagName::k_ErrorDocument404Path);
}
else
{
path.emplace_back(XmlTagName::k_Unknown);
}
}
else if (node.Type == _internal::XmlNodeType::Text)
{
if (path.size() == 1 && path[0] == XmlTagName::k_Enabled)
{
ret.IsEnabled = node.Value == "true";
}
else if (path.size() == 1 && path[0] == XmlTagName::k_IndexDocument)
{
ret.IndexDocument = node.Value;
}
else if (path.size() == 1 && path[0] == XmlTagName::k_DefaultIndexDocumentPath)
{
ret.DefaultIndexDocumentPath = node.Value;
}
else if (path.size() == 1 && path[0] == XmlTagName::k_ErrorDocument404Path)
{
ret.ErrorDocument404Path = node.Value;
}
}
}
return ret;
}
static TaggedBlobItem TaggedBlobItemFromXml(_internal::XmlReader& reader)
{
TaggedBlobItem ret;
enum class XmlTagName
{
k_Name,
k_ContainerName,
k_Unknown,
};
std::vector<XmlTagName> path;
while (true)
{
auto node = reader.Read();
if (node.Type == _internal::XmlNodeType::End)
{
break;
}
else if (node.Type == _internal::XmlNodeType::EndTag)
{
if (path.size() > 0)
{
path.pop_back();
}
else
{
break;
}
}
else if (node.Type == _internal::XmlNodeType::StartTag)
{
if (node.Name == "Name")
{
path.emplace_back(XmlTagName::k_Name);
}
else if (node.Name == "ContainerName")
{
path.emplace_back(XmlTagName::k_ContainerName);
}
else
{
path.emplace_back(XmlTagName::k_Unknown);
}
}
else if (node.Type == _internal::XmlNodeType::Text)
{
if (path.size() == 1 && path[0] == XmlTagName::k_Name)
{
ret.BlobName = node.Value;
}
else if (path.size() == 1 && path[0] == XmlTagName::k_ContainerName)
{
ret.BlobContainerName = node.Value;
}
}
}
return ret;
}
static Metadata MetadataFromXml(_internal::XmlReader& reader)
{
Metadata ret;
int depth = 0;
std::string key;
while (true)
{
auto node = reader.Read();
if (node.Type == _internal::XmlNodeType::End)
{
break;
}
else if (node.Type == _internal::XmlNodeType::StartTag)
{
if (depth++ == 0)
{
key = node.Name;
}
}
else if (node.Type == _internal::XmlNodeType::EndTag)
{
if (depth-- == 0)
{
break;
}
}
else if (depth == 1 && node.Type == _internal::XmlNodeType::Text)
{
ret.emplace(std::move(key), node.Value);
}
}
return ret;
}
static void GetUserDelegationKeyOptionsToXml(
_internal::XmlWriter& writer,
const GetUserDelegationKeyOptions& options)
{
writer.Write(_internal::XmlNode{_internal::XmlNodeType::StartTag, "KeyInfo"});
writer.Write(_internal::XmlNode{_internal::XmlNodeType::StartTag, "Start"});
writer.Write(_internal::XmlNode{
_internal::XmlNodeType::Text,
std::string(),
options.StartsOn.ToString(
Azure::DateTime::DateFormat::Rfc3339,
Azure::DateTime::TimeFractionFormat::Truncate)});
writer.Write(_internal::XmlNode{_internal::XmlNodeType::EndTag});
writer.Write(_internal::XmlNode{_internal::XmlNodeType::StartTag, "Expiry"});
writer.Write(_internal::XmlNode{
_internal::XmlNodeType::Text,
std::string(),
options.ExpiresOn.ToString(
Azure::DateTime::DateFormat::Rfc3339,
Azure::DateTime::TimeFractionFormat::Truncate)});
writer.Write(_internal::XmlNode{_internal::XmlNodeType::EndTag});
writer.Write(_internal::XmlNode{_internal::XmlNodeType::EndTag});
}
static void SetServicePropertiesOptionsToXml(
_internal::XmlWriter& writer,
const SetServicePropertiesOptions& options)
{
writer.Write(
_internal::XmlNode{_internal::XmlNodeType::StartTag, "StorageServiceProperties"});
BlobServicePropertiesToXml(writer, options.Properties);
writer.Write(_internal::XmlNode{_internal::XmlNodeType::EndTag});
}
static void BlobServicePropertiesToXml(
_internal::XmlWriter& writer,
const BlobServiceProperties& options)
{
writer.Write(_internal::XmlNode{_internal::XmlNodeType::StartTag, "Logging"});
AnalyticsLoggingToXml(writer, options.Logging);
writer.Write(_internal::XmlNode{_internal::XmlNodeType::EndTag});
writer.Write(_internal::XmlNode{_internal::XmlNodeType::StartTag, "HourMetrics"});
MetricsToXml(writer, options.HourMetrics);
writer.Write(_internal::XmlNode{_internal::XmlNodeType::EndTag});
writer.Write(_internal::XmlNode{_internal::XmlNodeType::StartTag, "MinuteMetrics"});
MetricsToXml(writer, options.MinuteMetrics);
writer.Write(_internal::XmlNode{_internal::XmlNodeType::EndTag});
writer.Write(_internal::XmlNode{_internal::XmlNodeType::StartTag, "Cors"});
for (const auto& i : options.Cors)
{
CorsRuleToXml(writer, i);
}
writer.Write(_internal::XmlNode{_internal::XmlNodeType::EndTag});
if (options.DefaultServiceVersion.HasValue())
{
writer.Write(
_internal::XmlNode{_internal::XmlNodeType::StartTag, "DefaultServiceVersion"});
writer.Write(_internal::XmlNode{
_internal::XmlNodeType::Text,
std::string(),
options.DefaultServiceVersion.Value()});
writer.Write(_internal::XmlNode{_internal::XmlNodeType::EndTag});
}
writer.Write(
_internal::XmlNode{_internal::XmlNodeType::StartTag, "DeleteRetentionPolicy"});
RetentionPolicyToXml(writer, options.DeleteRetentionPolicy);
writer.Write(_internal::XmlNode{_internal::XmlNodeType::EndTag});
writer.Write(_internal::XmlNode{_internal::XmlNodeType::StartTag, "StaticWebsite"});
StaticWebsiteToXml(writer, options.StaticWebsite);
writer.Write(_internal::XmlNode{_internal::XmlNodeType::EndTag});
}
static void AnalyticsLoggingToXml(
_internal::XmlWriter& writer,
const AnalyticsLogging& options)
{
writer.Write(_internal::XmlNode{_internal::XmlNodeType::StartTag, "Version"});
writer.Write(
_internal::XmlNode{_internal::XmlNodeType::Text, std::string(), options.Version});
writer.Write(_internal::XmlNode{_internal::XmlNodeType::EndTag});
writer.Write(_internal::XmlNode{_internal::XmlNodeType::StartTag, "Delete"});
writer.Write(_internal::XmlNode{
_internal::XmlNodeType::Text, std::string(), options.Delete ? "true" : "false"});
writer.Write(_internal::XmlNode{_internal::XmlNodeType::EndTag});
writer.Write(_internal::XmlNode{_internal::XmlNodeType::StartTag, "Read"});
writer.Write(_internal::XmlNode{
_internal::XmlNodeType::Text, std::string(), options.Read ? "true" : "false"});
writer.Write(_internal::XmlNode{_internal::XmlNodeType::EndTag});
writer.Write(_internal::XmlNode{_internal::XmlNodeType::StartTag, "Write"});
writer.Write(_internal::XmlNode{
_internal::XmlNodeType::Text, std::string(), options.Write ? "true" : "false"});
writer.Write(_internal::XmlNode{_internal::XmlNodeType::EndTag});
writer.Write(_internal::XmlNode{_internal::XmlNodeType::StartTag, "RetentionPolicy"});
RetentionPolicyToXml(writer, options.RetentionPolicy);
writer.Write(_internal::XmlNode{_internal::XmlNodeType::EndTag});
}
static void CorsRuleToXml(_internal::XmlWriter& writer, const CorsRule& options)
{
writer.Write(_internal::XmlNode{_internal::XmlNodeType::StartTag, "CorsRule"});
writer.Write(_internal::XmlNode{_internal::XmlNodeType::StartTag, "AllowedOrigins"});
writer.Write(_internal::XmlNode{
_internal::XmlNodeType::Text, std::string(), options.AllowedOrigins});
writer.Write(_internal::XmlNode{_internal::XmlNodeType::EndTag});
writer.Write(_internal::XmlNode{_internal::XmlNodeType::StartTag, "AllowedMethods"});
writer.Write(_internal::XmlNode{
_internal::XmlNodeType::Text, std::string(), options.AllowedMethods});
writer.Write(_internal::XmlNode{_internal::XmlNodeType::EndTag});
writer.Write(_internal::XmlNode{_internal::XmlNodeType::StartTag, "AllowedHeaders"});
writer.Write(_internal::XmlNode{
_internal::XmlNodeType::Text, std::string(), options.AllowedHeaders});
writer.Write(_internal::XmlNode{_internal::XmlNodeType::EndTag});
writer.Write(_internal::XmlNode{_internal::XmlNodeType::StartTag, "ExposedHeaders"});
writer.Write(_internal::XmlNode{
_internal::XmlNodeType::Text, std::string(), options.ExposedHeaders});
writer.Write(_internal::XmlNode{_internal::XmlNodeType::EndTag});
writer.Write(_internal::XmlNode{_internal::XmlNodeType::StartTag, "MaxAgeInSeconds"});
writer.Write(_internal::XmlNode{
_internal::XmlNodeType::Text,
std::string(),
std::to_string(options.MaxAgeInSeconds)});
writer.Write(_internal::XmlNode{_internal::XmlNodeType::EndTag});
writer.Write(_internal::XmlNode{_internal::XmlNodeType::EndTag});
}
static void MetricsToXml(_internal::XmlWriter& writer, const Metrics& options)
{
writer.Write(_internal::XmlNode{_internal::XmlNodeType::StartTag, "Version"});
writer.Write(
_internal::XmlNode{_internal::XmlNodeType::Text, std::string(), options.Version});
writer.Write(_internal::XmlNode{_internal::XmlNodeType::EndTag});
writer.Write(_internal::XmlNode{_internal::XmlNodeType::StartTag, "Enabled"});
writer.Write(_internal::XmlNode{
_internal::XmlNodeType::Text, std::string(), options.IsEnabled ? "true" : "false"});
writer.Write(_internal::XmlNode{_internal::XmlNodeType::EndTag});
if (options.IncludeApis.HasValue())
{
writer.Write(_internal::XmlNode{_internal::XmlNodeType::StartTag, "IncludeAPIs"});
writer.Write(_internal::XmlNode{
_internal::XmlNodeType::Text,
std::string(),
options.IncludeApis.Value() ? "true" : "false"});
writer.Write(_internal::XmlNode{_internal::XmlNodeType::EndTag});
}
writer.Write(_internal::XmlNode{_internal::XmlNodeType::StartTag, "RetentionPolicy"});
RetentionPolicyToXml(writer, options.RetentionPolicy);
writer.Write(_internal::XmlNode{_internal::XmlNodeType::EndTag});
}
static void RetentionPolicyToXml(
_internal::XmlWriter& writer,
const RetentionPolicy& options)
{
writer.Write(_internal::XmlNode{_internal::XmlNodeType::StartTag, "Enabled"});
writer.Write(_internal::XmlNode{
_internal::XmlNodeType::Text, std::string(), options.IsEnabled ? "true" : "false"});
writer.Write(_internal::XmlNode{_internal::XmlNodeType::EndTag});
if (options.Days.HasValue())
{
writer.Write(_internal::XmlNode{_internal::XmlNodeType::StartTag, "Days"});
writer.Write(_internal::XmlNode{
_internal::XmlNodeType::Text, std::string(), std::to_string(options.Days.Value())});
writer.Write(_internal::XmlNode{_internal::XmlNodeType::EndTag});
}
}
static void StaticWebsiteToXml(_internal::XmlWriter& writer, const StaticWebsite& options)
{
writer.Write(_internal::XmlNode{_internal::XmlNodeType::StartTag, "Enabled"});
writer.Write(_internal::XmlNode{
_internal::XmlNodeType::Text, std::string(), options.IsEnabled ? "true" : "false"});
writer.Write(_internal::XmlNode{_internal::XmlNodeType::EndTag});
if (options.IndexDocument.HasValue())
{
writer.Write(_internal::XmlNode{_internal::XmlNodeType::StartTag, "IndexDocument"});
writer.Write(_internal::XmlNode{
_internal::XmlNodeType::Text, std::string(), options.IndexDocument.Value()});
writer.Write(_internal::XmlNode{_internal::XmlNodeType::EndTag});
}
if (options.DefaultIndexDocumentPath.HasValue())
{
writer.Write(
_internal::XmlNode{_internal::XmlNodeType::StartTag, "DefaultIndexDocumentPath"});
writer.Write(_internal::XmlNode{
_internal::XmlNodeType::Text,
std::string(),
options.DefaultIndexDocumentPath.Value()});
writer.Write(_internal::XmlNode{_internal::XmlNodeType::EndTag});
}
if (options.ErrorDocument404Path.HasValue())
{
writer.Write(
_internal::XmlNode{_internal::XmlNodeType::StartTag, "ErrorDocument404Path"});
writer.Write(_internal::XmlNode{
_internal::XmlNodeType::Text, std::string(), options.ErrorDocument404Path.Value()});
writer.Write(_internal::XmlNode{_internal::XmlNodeType::EndTag});
}
}
}; // class Service
class BlobContainer final {
public:
struct CreateBlobContainerOptions final
{
Azure::Nullable<int32_t> Timeout;
PublicAccessType AccessType = PublicAccessType::None;
Storage::Metadata Metadata;
Azure::Nullable<std::string> DefaultEncryptionScope;
Azure::Nullable<bool> PreventEncryptionScopeOverride;
}; // struct CreateBlobContainerOptions
static Azure::Response<CreateBlobContainerResult> Create(
Azure::Core::Http::_internal::HttpPipeline& pipeline,
const Azure::Core::Url& url,
const CreateBlobContainerOptions& options,
const Azure::Core::Context& context)
{
auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Put, url);
request.SetHeader("Content-Length", "0");
request.GetUrl().AppendQueryParameter("restype", "container");
request.SetHeader("x-ms-version", "2020-02-10");
if (options.Timeout.HasValue())
{
request.GetUrl().AppendQueryParameter(
"timeout", std::to_string(options.Timeout.Value()));
}
for (const auto& pair : options.Metadata)
{
request.SetHeader("x-ms-meta-" + pair.first, pair.second);
}
if (!options.AccessType.ToString().empty())
{
request.SetHeader("x-ms-blob-public-access", options.AccessType.ToString());
}
if (options.DefaultEncryptionScope.HasValue())
{
request.SetHeader(
"x-ms-default-encryption-scope", options.DefaultEncryptionScope.Value());
}
if (options.PreventEncryptionScopeOverride.HasValue())
{
request.SetHeader(
"x-ms-deny-encryption-scope-override",
options.PreventEncryptionScopeOverride.Value() ? "true" : "false");
}
auto pHttpResponse = pipeline.Send(request, context);
Azure::Core::Http::RawResponse& httpResponse = *pHttpResponse;
CreateBlobContainerResult response;
auto http_status_code = httpResponse.GetStatusCode();
if (http_status_code != Azure::Core::Http::HttpStatusCode::Created)
{
throw StorageException::CreateFromResponse(std::move(pHttpResponse));
}
response.ETag = Azure::ETag(httpResponse.GetHeaders().at("etag"));
response.LastModified = Azure::DateTime::Parse(
httpResponse.GetHeaders().at("last-modified"), Azure::DateTime::DateFormat::Rfc1123);
return Azure::Response<CreateBlobContainerResult>(
std::move(response), std::move(pHttpResponse));
}
struct DeleteBlobContainerOptions final
{
Azure::Nullable<int32_t> Timeout;
Azure::Nullable<std::string> LeaseId;
Azure::Nullable<Azure::DateTime> IfModifiedSince;
Azure::Nullable<Azure::DateTime> IfUnmodifiedSince;
}; // struct DeleteBlobContainerOptions
static Azure::Response<DeleteBlobContainerResult> Delete(
Azure::Core::Http::_internal::HttpPipeline& pipeline,
const Azure::Core::Url& url,
const DeleteBlobContainerOptions& options,
const Azure::Core::Context& context)
{
auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Delete, url);
request.GetUrl().AppendQueryParameter("restype", "container");
request.SetHeader("x-ms-version", "2020-02-10");
if (options.Timeout.HasValue())
{
request.GetUrl().AppendQueryParameter(
"timeout", std::to_string(options.Timeout.Value()));
}
if (options.LeaseId.HasValue())
{
request.SetHeader("x-ms-lease-id", options.LeaseId.Value());
}
if (options.IfModifiedSince.HasValue())
{
request.SetHeader(
"If-Modified-Since",
options.IfModifiedSince.Value().ToString(Azure::DateTime::DateFormat::Rfc1123));
}
if (options.IfUnmodifiedSince.HasValue())
{
request.SetHeader(
"If-Unmodified-Since",
options.IfUnmodifiedSince.Value().ToString(Azure::DateTime::DateFormat::Rfc1123));
}
auto pHttpResponse = pipeline.Send(request, context);
Azure::Core::Http::RawResponse& httpResponse = *pHttpResponse;
DeleteBlobContainerResult response;
auto http_status_code = httpResponse.GetStatusCode();
if (http_status_code != Azure::Core::Http::HttpStatusCode::Accepted)
{
throw StorageException::CreateFromResponse(std::move(pHttpResponse));
}
return Azure::Response<DeleteBlobContainerResult>(
std::move(response), std::move(pHttpResponse));
}
struct UndeleteBlobContainerOptions final
{
Azure::Nullable<int32_t> Timeout;
std::string DeletedBlobContainerName;
std::string DeletedBlobContainerVersion;
}; // struct UndeleteBlobContainerOptions
static Azure::Response<Models::_detail::UndeleteBlobContainerResult> Undelete(
Azure::Core::Http::_internal::HttpPipeline& pipeline,
const Azure::Core::Url& url,
const UndeleteBlobContainerOptions& options,
const Azure::Core::Context& context)
{
auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Put, url);
request.SetHeader("Content-Length", "0");
request.GetUrl().AppendQueryParameter("restype", "container");
request.GetUrl().AppendQueryParameter("comp", "undelete");
request.SetHeader("x-ms-version", "2020-02-10");
if (options.Timeout.HasValue())
{
request.GetUrl().AppendQueryParameter(
"timeout", std::to_string(options.Timeout.Value()));
}
request.SetHeader("x-ms-deleted-container-name", options.DeletedBlobContainerName);
request.SetHeader("x-ms-deleted-container-version", options.DeletedBlobContainerVersion);
auto pHttpResponse = pipeline.Send(request, context);
Azure::Core::Http::RawResponse& httpResponse = *pHttpResponse;
Models::_detail::UndeleteBlobContainerResult response;
auto http_status_code = httpResponse.GetStatusCode();
if (http_status_code != Azure::Core::Http::HttpStatusCode::Created)
{
throw StorageException::CreateFromResponse(std::move(pHttpResponse));
}
return Azure::Response<Models::_detail::UndeleteBlobContainerResult>(
std::move(response), std::move(pHttpResponse));
}
struct GetBlobContainerPropertiesOptions final
{
Azure::Nullable<int32_t> Timeout;
Azure::Nullable<std::string> LeaseId;
}; // struct GetBlobContainerPropertiesOptions
static Azure::Response<BlobContainerProperties> GetProperties(
Azure::Core::Http::_internal::HttpPipeline& pipeline,
const Azure::Core::Url& url,
const GetBlobContainerPropertiesOptions& options,
const Azure::Core::Context& context)
{
auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Head, url);
request.GetUrl().AppendQueryParameter("restype", "container");
request.SetHeader("x-ms-version", "2020-02-10");
if (options.Timeout.HasValue())
{
request.GetUrl().AppendQueryParameter(
"timeout", std::to_string(options.Timeout.Value()));
}
if (options.LeaseId.HasValue())
{
request.SetHeader("x-ms-lease-id", options.LeaseId.Value());
}
auto pHttpResponse = pipeline.Send(request, context);
Azure::Core::Http::RawResponse& httpResponse = *pHttpResponse;
BlobContainerProperties response;
auto http_status_code = httpResponse.GetStatusCode();
if (http_status_code != Azure::Core::Http::HttpStatusCode::Ok)
{
throw StorageException::CreateFromResponse(std::move(pHttpResponse));
}
response.ETag = Azure::ETag(httpResponse.GetHeaders().at("etag"));
response.LastModified = Azure::DateTime::Parse(
httpResponse.GetHeaders().at("last-modified"), Azure::DateTime::DateFormat::Rfc1123);
for (auto i = httpResponse.GetHeaders().lower_bound("x-ms-meta-");
i != httpResponse.GetHeaders().end() && i->first.substr(0, 10) == "x-ms-meta-";
++i)
{
response.Metadata.emplace(i->first.substr(10), i->second);
}
auto x_ms_blob_public_access__iterator
= httpResponse.GetHeaders().find("x-ms-blob-public-access");
if (x_ms_blob_public_access__iterator != httpResponse.GetHeaders().end())
{
response.AccessType = PublicAccessType(x_ms_blob_public_access__iterator->second);
}
response.HasImmutabilityPolicy
= httpResponse.GetHeaders().at("x-ms-has-immutability-policy") == "true";
response.HasLegalHold = httpResponse.GetHeaders().at("x-ms-has-legal-hold") == "true";
response.LeaseStatus = LeaseStatus(httpResponse.GetHeaders().at("x-ms-lease-status"));
response.LeaseState = LeaseState(httpResponse.GetHeaders().at("x-ms-lease-state"));
auto x_ms_lease_duration__iterator
= httpResponse.GetHeaders().find("x-ms-lease-duration");
if (x_ms_lease_duration__iterator != httpResponse.GetHeaders().end())
{
response.LeaseDuration = LeaseDurationType(x_ms_lease_duration__iterator->second);
}
auto x_ms_default_encryption_scope__iterator
= httpResponse.GetHeaders().find("x-ms-default-encryption-scope");
if (x_ms_default_encryption_scope__iterator != httpResponse.GetHeaders().end())
{
response.DefaultEncryptionScope = x_ms_default_encryption_scope__iterator->second;
}
auto x_ms_deny_encryption_scope_override__iterator
= httpResponse.GetHeaders().find("x-ms-deny-encryption-scope-override");
if (x_ms_deny_encryption_scope_override__iterator != httpResponse.GetHeaders().end())
{
response.PreventEncryptionScopeOverride
= x_ms_deny_encryption_scope_override__iterator->second == "true";
}
return Azure::Response<BlobContainerProperties>(
std::move(response), std::move(pHttpResponse));
}
struct SetBlobContainerMetadataOptions final
{
Azure::Nullable<int32_t> Timeout;
Storage::Metadata Metadata;
Azure::Nullable<std::string> LeaseId;
Azure::Nullable<Azure::DateTime> IfModifiedSince;
}; // struct SetBlobContainerMetadataOptions
static Azure::Response<SetBlobContainerMetadataResult> SetMetadata(
Azure::Core::Http::_internal::HttpPipeline& pipeline,
const Azure::Core::Url& url,
const SetBlobContainerMetadataOptions& options,
const Azure::Core::Context& context)
{
auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Put, url);
request.SetHeader("Content-Length", "0");
request.GetUrl().AppendQueryParameter("restype", "container");
request.GetUrl().AppendQueryParameter("comp", "metadata");
request.SetHeader("x-ms-version", "2020-02-10");
if (options.Timeout.HasValue())
{
request.GetUrl().AppendQueryParameter(
"timeout", std::to_string(options.Timeout.Value()));
}
for (const auto& pair : options.Metadata)
{
request.SetHeader("x-ms-meta-" + pair.first, pair.second);
}
if (options.LeaseId.HasValue())
{
request.SetHeader("x-ms-lease-id", options.LeaseId.Value());
}
if (options.IfModifiedSince.HasValue())
{
request.SetHeader(
"If-Modified-Since",
options.IfModifiedSince.Value().ToString(Azure::DateTime::DateFormat::Rfc1123));
}
auto pHttpResponse = pipeline.Send(request, context);
Azure::Core::Http::RawResponse& httpResponse = *pHttpResponse;
SetBlobContainerMetadataResult response;
auto http_status_code = httpResponse.GetStatusCode();
if (http_status_code != Azure::Core::Http::HttpStatusCode::Ok)
{
throw StorageException::CreateFromResponse(std::move(pHttpResponse));
}
response.ETag = Azure::ETag(httpResponse.GetHeaders().at("etag"));
response.LastModified = Azure::DateTime::Parse(
httpResponse.GetHeaders().at("last-modified"), Azure::DateTime::DateFormat::Rfc1123);
return Azure::Response<SetBlobContainerMetadataResult>(
std::move(response), std::move(pHttpResponse));
}
struct ListBlobsOptions final
{
Azure::Nullable<int32_t> Timeout;
Azure::Nullable<std::string> Prefix;
Azure::Nullable<std::string> ContinuationToken;
Azure::Nullable<int32_t> MaxResults;
ListBlobsIncludeFlags Include = ListBlobsIncludeFlags::None;
}; // struct ListBlobsOptions
static Azure::Response<Models::_detail::ListBlobsResult> ListBlobs(
Azure::Core::Http::_internal::HttpPipeline& pipeline,
const Azure::Core::Url& url,
const ListBlobsOptions& options,
const Azure::Core::Context& context)
{
auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Get, url);
request.SetHeader("x-ms-version", "2020-02-10");
if (options.Timeout.HasValue())
{
request.GetUrl().AppendQueryParameter(
"timeout", std::to_string(options.Timeout.Value()));
}
request.GetUrl().AppendQueryParameter("restype", "container");
request.GetUrl().AppendQueryParameter("comp", "list");
if (options.Prefix.HasValue())
{
request.GetUrl().AppendQueryParameter(
"prefix", _internal::UrlEncodeQueryParameter(options.Prefix.Value()));
}
if (options.ContinuationToken.HasValue())
{
request.GetUrl().AppendQueryParameter(
"marker", _internal::UrlEncodeQueryParameter(options.ContinuationToken.Value()));
}
if (options.MaxResults.HasValue())
{
request.GetUrl().AppendQueryParameter(
"maxresults", std::to_string(options.MaxResults.Value()));
}
std::string list_blobs_include_flags = ListBlobsIncludeFlagsToString(options.Include);
if (!list_blobs_include_flags.empty())
{
request.GetUrl().AppendQueryParameter(
"include", _internal::UrlEncodeQueryParameter(list_blobs_include_flags));
}
auto pHttpResponse = pipeline.Send(request, context);
Azure::Core::Http::RawResponse& httpResponse = *pHttpResponse;
Models::_detail::ListBlobsResult response;
auto http_status_code = httpResponse.GetStatusCode();
if (http_status_code != Azure::Core::Http::HttpStatusCode::Ok)
{
throw StorageException::CreateFromResponse(std::move(pHttpResponse));
}
{
const auto& httpResponseBody = httpResponse.GetBody();
_internal::XmlReader reader(
reinterpret_cast<const char*>(httpResponseBody.data()), httpResponseBody.size());
response = ListBlobsResultInternalFromXml(reader);
}
return Azure::Response<Models::_detail::ListBlobsResult>(
std::move(response), std::move(pHttpResponse));
}
struct ListBlobsByHierarchyOptions final
{
Azure::Nullable<int32_t> Timeout;
Azure::Nullable<std::string> Prefix;
Azure::Nullable<std::string> Delimiter;
Azure::Nullable<std::string> ContinuationToken;
Azure::Nullable<int32_t> MaxResults;
ListBlobsIncludeFlags Include = ListBlobsIncludeFlags::None;
}; // struct ListBlobsByHierarchyOptions
static Azure::Response<Models::_detail::ListBlobsByHierarchyResult> ListBlobsByHierarchy(
Azure::Core::Http::_internal::HttpPipeline& pipeline,
const Azure::Core::Url& url,
const ListBlobsByHierarchyOptions& options,
const Azure::Core::Context& context)
{
auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Get, url);
request.SetHeader("x-ms-version", "2020-02-10");
if (options.Timeout.HasValue())
{
request.GetUrl().AppendQueryParameter(
"timeout", std::to_string(options.Timeout.Value()));
}
request.GetUrl().AppendQueryParameter("restype", "container");
request.GetUrl().AppendQueryParameter("comp", "list");
if (options.Prefix.HasValue())
{
request.GetUrl().AppendQueryParameter(
"prefix", _internal::UrlEncodeQueryParameter(options.Prefix.Value()));
}
if (options.Delimiter.HasValue())
{
request.GetUrl().AppendQueryParameter(
"delimiter", _internal::UrlEncodeQueryParameter(options.Delimiter.Value()));
}
if (options.ContinuationToken.HasValue())
{
request.GetUrl().AppendQueryParameter(
"marker", _internal::UrlEncodeQueryParameter(options.ContinuationToken.Value()));
}
if (options.MaxResults.HasValue())
{
request.GetUrl().AppendQueryParameter(
"maxresults", std::to_string(options.MaxResults.Value()));
}
std::string list_blobs_include_flags = ListBlobsIncludeFlagsToString(options.Include);
if (!list_blobs_include_flags.empty())
{
request.GetUrl().AppendQueryParameter(
"include", _internal::UrlEncodeQueryParameter(list_blobs_include_flags));
}
auto pHttpResponse = pipeline.Send(request, context);
Azure::Core::Http::RawResponse& httpResponse = *pHttpResponse;
Models::_detail::ListBlobsByHierarchyResult response;
auto http_status_code = httpResponse.GetStatusCode();
if (http_status_code != Azure::Core::Http::HttpStatusCode::Ok)
{
throw StorageException::CreateFromResponse(std::move(pHttpResponse));
}
{
const auto& httpResponseBody = httpResponse.GetBody();
_internal::XmlReader reader(
reinterpret_cast<const char*>(httpResponseBody.data()), httpResponseBody.size());
response = ListBlobsByHierarchyResultInternalFromXml(reader);
}
return Azure::Response<Models::_detail::ListBlobsByHierarchyResult>(
std::move(response), std::move(pHttpResponse));
}
struct GetBlobContainerAccessPolicyOptions final
{
Azure::Nullable<int32_t> Timeout;
Azure::Nullable<std::string> LeaseId;
}; // struct GetBlobContainerAccessPolicyOptions
static Azure::Response<BlobContainerAccessPolicy> GetAccessPolicy(
Azure::Core::Http::_internal::HttpPipeline& pipeline,
const Azure::Core::Url& url,
const GetBlobContainerAccessPolicyOptions& options,
const Azure::Core::Context& context)
{
auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Get, url);
request.SetHeader("x-ms-version", "2020-02-10");
if (options.Timeout.HasValue())
{
request.GetUrl().AppendQueryParameter(
"timeout", std::to_string(options.Timeout.Value()));
}
request.GetUrl().AppendQueryParameter("restype", "container");
request.GetUrl().AppendQueryParameter("comp", "acl");
if (options.LeaseId.HasValue())
{
request.SetHeader("x-ms-lease-id", options.LeaseId.Value());
}
auto pHttpResponse = pipeline.Send(request, context);
Azure::Core::Http::RawResponse& httpResponse = *pHttpResponse;
BlobContainerAccessPolicy response;
auto http_status_code = httpResponse.GetStatusCode();
if (http_status_code != Azure::Core::Http::HttpStatusCode::Ok)
{
throw StorageException::CreateFromResponse(std::move(pHttpResponse));
}
{
const auto& httpResponseBody = httpResponse.GetBody();
_internal::XmlReader reader(
reinterpret_cast<const char*>(httpResponseBody.data()), httpResponseBody.size());
response = BlobContainerAccessPolicyFromXml(reader);
}
auto x_ms_blob_public_access__iterator
= httpResponse.GetHeaders().find("x-ms-blob-public-access");
if (x_ms_blob_public_access__iterator != httpResponse.GetHeaders().end())
{
response.AccessType = PublicAccessType(x_ms_blob_public_access__iterator->second);
}
return Azure::Response<BlobContainerAccessPolicy>(
std::move(response), std::move(pHttpResponse));
}
struct SetBlobContainerAccessPolicyOptions final
{
Azure::Nullable<int32_t> Timeout;
PublicAccessType AccessType = PublicAccessType::None;
Azure::Nullable<std::string> LeaseId;
Azure::Nullable<Azure::DateTime> IfModifiedSince;
Azure::Nullable<Azure::DateTime> IfUnmodifiedSince;
std::vector<SignedIdentifier> SignedIdentifiers;
}; // struct SetBlobContainerAccessPolicyOptions
static Azure::Response<SetBlobContainerAccessPolicyResult> SetAccessPolicy(
Azure::Core::Http::_internal::HttpPipeline& pipeline,
const Azure::Core::Url& url,
const SetBlobContainerAccessPolicyOptions& options,
const Azure::Core::Context& context)
{
std::string xml_body;
{
_internal::XmlWriter writer;
SetBlobContainerAccessPolicyOptionsToXml(writer, options);
xml_body = writer.GetDocument();
writer.Write(_internal::XmlNode{_internal::XmlNodeType::End});
}
Azure::Core::IO::MemoryBodyStream xml_body_stream(
reinterpret_cast<const uint8_t*>(xml_body.data()), xml_body.length());
auto request = Azure::Core::Http::Request(
Azure::Core::Http::HttpMethod::Put, url, &xml_body_stream);
request.SetHeader("Content-Length", std::to_string(xml_body_stream.Length()));
request.SetHeader("x-ms-version", "2020-02-10");
if (options.Timeout.HasValue())
{
request.GetUrl().AppendQueryParameter(
"timeout", std::to_string(options.Timeout.Value()));
}
request.GetUrl().AppendQueryParameter("restype", "container");
request.GetUrl().AppendQueryParameter("comp", "acl");
if (!options.AccessType.ToString().empty())
{
request.SetHeader("x-ms-blob-public-access", options.AccessType.ToString());
}
if (options.LeaseId.HasValue())
{
request.SetHeader("x-ms-lease-id", options.LeaseId.Value());
}
if (options.IfModifiedSince.HasValue())
{
request.SetHeader(
"If-Modified-Since",
options.IfModifiedSince.Value().ToString(Azure::DateTime::DateFormat::Rfc1123));
}
if (options.IfUnmodifiedSince.HasValue())
{
request.SetHeader(
"If-Unmodified-Since",
options.IfUnmodifiedSince.Value().ToString(Azure::DateTime::DateFormat::Rfc1123));
}
auto pHttpResponse = pipeline.Send(request, context);
Azure::Core::Http::RawResponse& httpResponse = *pHttpResponse;
SetBlobContainerAccessPolicyResult response;
auto http_status_code = httpResponse.GetStatusCode();
if (http_status_code != Azure::Core::Http::HttpStatusCode::Ok)
{
throw StorageException::CreateFromResponse(std::move(pHttpResponse));
}
response.ETag = Azure::ETag(httpResponse.GetHeaders().at("etag"));
response.LastModified = Azure::DateTime::Parse(
httpResponse.GetHeaders().at("last-modified"), Azure::DateTime::DateFormat::Rfc1123);
return Azure::Response<SetBlobContainerAccessPolicyResult>(
std::move(response), std::move(pHttpResponse));
}
struct AcquireBlobContainerLeaseOptions final
{
Azure::Nullable<int32_t> Timeout;
std::chrono::seconds LeaseDuration;
Azure::Nullable<std::string> ProposedLeaseId;
Azure::Nullable<Azure::DateTime> IfModifiedSince;
Azure::Nullable<Azure::DateTime> IfUnmodifiedSince;
}; // struct AcquireBlobContainerLeaseOptions
static Azure::Response<Models::_detail::AcquireBlobContainerLeaseResult> AcquireLease(
Azure::Core::Http::_internal::HttpPipeline& pipeline,
const Azure::Core::Url& url,
const AcquireBlobContainerLeaseOptions& options,
const Azure::Core::Context& context)
{
auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Put, url);
request.SetHeader("Content-Length", "0");
request.SetHeader("x-ms-version", "2020-02-10");
if (options.Timeout.HasValue())
{
request.GetUrl().AppendQueryParameter(
"timeout", std::to_string(options.Timeout.Value()));
}
request.GetUrl().AppendQueryParameter("restype", "container");
request.GetUrl().AppendQueryParameter("comp", "lease");
request.SetHeader("x-ms-lease-action", "acquire");
request.SetHeader("x-ms-lease-duration", std::to_string(options.LeaseDuration.count()));
if (options.ProposedLeaseId.HasValue())
{
request.SetHeader("x-ms-proposed-lease-id", options.ProposedLeaseId.Value());
}
if (options.IfModifiedSince.HasValue())
{
request.SetHeader(
"If-Modified-Since",
options.IfModifiedSince.Value().ToString(Azure::DateTime::DateFormat::Rfc1123));
}
if (options.IfUnmodifiedSince.HasValue())
{
request.SetHeader(
"If-Unmodified-Since",
options.IfUnmodifiedSince.Value().ToString(Azure::DateTime::DateFormat::Rfc1123));
}
auto pHttpResponse = pipeline.Send(request, context);
Azure::Core::Http::RawResponse& httpResponse = *pHttpResponse;
Models::_detail::AcquireBlobContainerLeaseResult response;
auto http_status_code = httpResponse.GetStatusCode();
if (http_status_code != Azure::Core::Http::HttpStatusCode::Created)
{
throw StorageException::CreateFromResponse(std::move(pHttpResponse));
}
response.ETag = Azure::ETag(httpResponse.GetHeaders().at("etag"));
response.LastModified = Azure::DateTime::Parse(
httpResponse.GetHeaders().at("last-modified"), Azure::DateTime::DateFormat::Rfc1123);
response.LeaseId = httpResponse.GetHeaders().at("x-ms-lease-id");
return Azure::Response<Models::_detail::AcquireBlobContainerLeaseResult>(
std::move(response), std::move(pHttpResponse));
}
struct RenewBlobContainerLeaseOptions final
{
Azure::Nullable<int32_t> Timeout;
std::string LeaseId;
Azure::Nullable<Azure::DateTime> IfModifiedSince;
Azure::Nullable<Azure::DateTime> IfUnmodifiedSince;
}; // struct RenewBlobContainerLeaseOptions
static Azure::Response<Models::_detail::RenewBlobContainerLeaseResult> RenewLease(
Azure::Core::Http::_internal::HttpPipeline& pipeline,
const Azure::Core::Url& url,
const RenewBlobContainerLeaseOptions& options,
const Azure::Core::Context& context)
{
auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Put, url);
request.SetHeader("Content-Length", "0");
request.SetHeader("x-ms-version", "2020-02-10");
if (options.Timeout.HasValue())
{
request.GetUrl().AppendQueryParameter(
"timeout", std::to_string(options.Timeout.Value()));
}
request.GetUrl().AppendQueryParameter("restype", "container");
request.GetUrl().AppendQueryParameter("comp", "lease");
request.SetHeader("x-ms-lease-action", "renew");
request.SetHeader("x-ms-lease-id", options.LeaseId);
if (options.IfModifiedSince.HasValue())
{
request.SetHeader(
"If-Modified-Since",
options.IfModifiedSince.Value().ToString(Azure::DateTime::DateFormat::Rfc1123));
}
if (options.IfUnmodifiedSince.HasValue())
{
request.SetHeader(
"If-Unmodified-Since",
options.IfUnmodifiedSince.Value().ToString(Azure::DateTime::DateFormat::Rfc1123));
}
auto pHttpResponse = pipeline.Send(request, context);
Azure::Core::Http::RawResponse& httpResponse = *pHttpResponse;
Models::_detail::RenewBlobContainerLeaseResult response;
auto http_status_code = httpResponse.GetStatusCode();
if (http_status_code != Azure::Core::Http::HttpStatusCode::Ok)
{
throw StorageException::CreateFromResponse(std::move(pHttpResponse));
}
response.ETag = Azure::ETag(httpResponse.GetHeaders().at("etag"));
response.LastModified = Azure::DateTime::Parse(
httpResponse.GetHeaders().at("last-modified"), Azure::DateTime::DateFormat::Rfc1123);
response.LeaseId = httpResponse.GetHeaders().at("x-ms-lease-id");
return Azure::Response<Models::_detail::RenewBlobContainerLeaseResult>(
std::move(response), std::move(pHttpResponse));
}
struct ChangeBlobContainerLeaseOptions final
{
Azure::Nullable<int32_t> Timeout;
std::string LeaseId;
std::string ProposedLeaseId;
Azure::Nullable<Azure::DateTime> IfModifiedSince;
Azure::Nullable<Azure::DateTime> IfUnmodifiedSince;
}; // struct ChangeBlobContainerLeaseOptions
static Azure::Response<Models::_detail::ChangeBlobContainerLeaseResult> ChangeLease(
Azure::Core::Http::_internal::HttpPipeline& pipeline,
const Azure::Core::Url& url,
const ChangeBlobContainerLeaseOptions& options,
const Azure::Core::Context& context)
{
auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Put, url);
request.SetHeader("Content-Length", "0");
request.SetHeader("x-ms-version", "2020-02-10");
if (options.Timeout.HasValue())
{
request.GetUrl().AppendQueryParameter(
"timeout", std::to_string(options.Timeout.Value()));
}
request.GetUrl().AppendQueryParameter("restype", "container");
request.GetUrl().AppendQueryParameter("comp", "lease");
request.SetHeader("x-ms-lease-action", "change");
request.SetHeader("x-ms-lease-id", options.LeaseId);
request.SetHeader("x-ms-proposed-lease-id", options.ProposedLeaseId);
if (options.IfModifiedSince.HasValue())
{
request.SetHeader(
"If-Modified-Since",
options.IfModifiedSince.Value().ToString(Azure::DateTime::DateFormat::Rfc1123));
}
if (options.IfUnmodifiedSince.HasValue())
{
request.SetHeader(
"If-Unmodified-Since",
options.IfUnmodifiedSince.Value().ToString(Azure::DateTime::DateFormat::Rfc1123));
}
auto pHttpResponse = pipeline.Send(request, context);
Azure::Core::Http::RawResponse& httpResponse = *pHttpResponse;
Models::_detail::ChangeBlobContainerLeaseResult response;
auto http_status_code = httpResponse.GetStatusCode();
if (http_status_code != Azure::Core::Http::HttpStatusCode::Ok)
{
throw StorageException::CreateFromResponse(std::move(pHttpResponse));
}
response.ETag = Azure::ETag(httpResponse.GetHeaders().at("etag"));
response.LastModified = Azure::DateTime::Parse(
httpResponse.GetHeaders().at("last-modified"), Azure::DateTime::DateFormat::Rfc1123);
response.LeaseId = httpResponse.GetHeaders().at("x-ms-lease-id");
return Azure::Response<Models::_detail::ChangeBlobContainerLeaseResult>(
std::move(response), std::move(pHttpResponse));
}
struct ReleaseBlobContainerLeaseOptions final
{
Azure::Nullable<int32_t> Timeout;
std::string LeaseId;
Azure::Nullable<Azure::DateTime> IfModifiedSince;
Azure::Nullable<Azure::DateTime> IfUnmodifiedSince;
}; // struct ReleaseBlobContainerLeaseOptions
static Azure::Response<Models::_detail::ReleaseBlobContainerLeaseResult> ReleaseLease(
Azure::Core::Http::_internal::HttpPipeline& pipeline,
const Azure::Core::Url& url,
const ReleaseBlobContainerLeaseOptions& options,
const Azure::Core::Context& context)
{
auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Put, url);
request.SetHeader("Content-Length", "0");
request.SetHeader("x-ms-version", "2020-02-10");
if (options.Timeout.HasValue())
{
request.GetUrl().AppendQueryParameter(
"timeout", std::to_string(options.Timeout.Value()));
}
request.GetUrl().AppendQueryParameter("restype", "container");
request.GetUrl().AppendQueryParameter("comp", "lease");
request.SetHeader("x-ms-lease-action", "release");
request.SetHeader("x-ms-lease-id", options.LeaseId);
if (options.IfModifiedSince.HasValue())
{
request.SetHeader(
"If-Modified-Since",
options.IfModifiedSince.Value().ToString(Azure::DateTime::DateFormat::Rfc1123));
}
if (options.IfUnmodifiedSince.HasValue())
{
request.SetHeader(
"If-Unmodified-Since",
options.IfUnmodifiedSince.Value().ToString(Azure::DateTime::DateFormat::Rfc1123));
}
auto pHttpResponse = pipeline.Send(request, context);
Azure::Core::Http::RawResponse& httpResponse = *pHttpResponse;
Models::_detail::ReleaseBlobContainerLeaseResult response;
auto http_status_code = httpResponse.GetStatusCode();
if (http_status_code != Azure::Core::Http::HttpStatusCode::Ok)
{
throw StorageException::CreateFromResponse(std::move(pHttpResponse));
}
response.ETag = Azure::ETag(httpResponse.GetHeaders().at("etag"));
response.LastModified = Azure::DateTime::Parse(
httpResponse.GetHeaders().at("last-modified"), Azure::DateTime::DateFormat::Rfc1123);
return Azure::Response<Models::_detail::ReleaseBlobContainerLeaseResult>(
std::move(response), std::move(pHttpResponse));
}
struct BreakBlobContainerLeaseOptions final
{
Azure::Nullable<int32_t> Timeout;
Azure::Nullable<std::chrono::seconds> BreakPeriod;
Azure::Nullable<Azure::DateTime> IfModifiedSince;
Azure::Nullable<Azure::DateTime> IfUnmodifiedSince;
}; // struct BreakBlobContainerLeaseOptions
static Azure::Response<Models::_detail::BreakBlobContainerLeaseResult> BreakLease(
Azure::Core::Http::_internal::HttpPipeline& pipeline,
const Azure::Core::Url& url,
const BreakBlobContainerLeaseOptions& options,
const Azure::Core::Context& context)
{
auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Put, url);
request.SetHeader("Content-Length", "0");
request.SetHeader("x-ms-version", "2020-02-10");
if (options.Timeout.HasValue())
{
request.GetUrl().AppendQueryParameter(
"timeout", std::to_string(options.Timeout.Value()));
}
request.GetUrl().AppendQueryParameter("restype", "container");
request.GetUrl().AppendQueryParameter("comp", "lease");
request.SetHeader("x-ms-lease-action", "break");
if (options.BreakPeriod.HasValue())
{
request.SetHeader(
"x-ms-lease-break-period", std::to_string(options.BreakPeriod.Value().count()));
}
if (options.IfModifiedSince.HasValue())
{
request.SetHeader(
"If-Modified-Since",
options.IfModifiedSince.Value().ToString(Azure::DateTime::DateFormat::Rfc1123));
}
if (options.IfUnmodifiedSince.HasValue())
{
request.SetHeader(
"If-Unmodified-Since",
options.IfUnmodifiedSince.Value().ToString(Azure::DateTime::DateFormat::Rfc1123));
}
auto pHttpResponse = pipeline.Send(request, context);
Azure::Core::Http::RawResponse& httpResponse = *pHttpResponse;
Models::_detail::BreakBlobContainerLeaseResult response;
auto http_status_code = httpResponse.GetStatusCode();
if (http_status_code != Azure::Core::Http::HttpStatusCode::Accepted)
{
throw StorageException::CreateFromResponse(std::move(pHttpResponse));
}
response.ETag = Azure::ETag(httpResponse.GetHeaders().at("etag"));
response.LastModified = Azure::DateTime::Parse(
httpResponse.GetHeaders().at("last-modified"), Azure::DateTime::DateFormat::Rfc1123);
response.LeaseTime = std::stoi(httpResponse.GetHeaders().at("x-ms-lease-time"));
return Azure::Response<Models::_detail::BreakBlobContainerLeaseResult>(
std::move(response), std::move(pHttpResponse));
}
private:
static BlobContainerAccessPolicy BlobContainerAccessPolicyFromXml(
_internal::XmlReader& reader)
{
BlobContainerAccessPolicy ret;
enum class XmlTagName
{
k_SignedIdentifiers,
k_SignedIdentifier,
k_Unknown,
};
std::vector<XmlTagName> path;
while (true)
{
auto node = reader.Read();
if (node.Type == _internal::XmlNodeType::End)
{
break;
}
else if (node.Type == _internal::XmlNodeType::EndTag)
{
if (path.size() > 0)
{
path.pop_back();
}
else
{
break;
}
}
else if (node.Type == _internal::XmlNodeType::StartTag)
{
if (node.Name == "SignedIdentifiers")
{
path.emplace_back(XmlTagName::k_SignedIdentifiers);
}
else if (node.Name == "SignedIdentifier")
{
path.emplace_back(XmlTagName::k_SignedIdentifier);
}
else
{
path.emplace_back(XmlTagName::k_Unknown);
}
if (path.size() == 2 && path[0] == XmlTagName::k_SignedIdentifiers
&& path[1] == XmlTagName::k_SignedIdentifier)
{
ret.SignedIdentifiers.emplace_back(SignedIdentifierFromXml(reader));
path.pop_back();
}
}
else if (node.Type == _internal::XmlNodeType::Text)
{
}
}
return ret;
}
static Models::_detail::ListBlobsByHierarchyResult
ListBlobsByHierarchyResultInternalFromXml(_internal::XmlReader& reader)
{
Models::_detail::ListBlobsByHierarchyResult ret;
enum class XmlTagName
{
k_EnumerationResults,
k_Prefix,
k_Delimiter,
k_NextMarker,
k_Blobs,
k_Blob,
k_BlobPrefix,
k_Name,
k_Unknown,
};
std::vector<XmlTagName> path;
while (true)
{
auto node = reader.Read();
if (node.Type == _internal::XmlNodeType::End)
{
break;
}
else if (node.Type == _internal::XmlNodeType::EndTag)
{
if (path.size() > 0)
{
path.pop_back();
}
else
{
break;
}
}
else if (node.Type == _internal::XmlNodeType::StartTag)
{
if (node.Name == "EnumerationResults")
{
path.emplace_back(XmlTagName::k_EnumerationResults);
}
else if (node.Name == "Prefix")
{
path.emplace_back(XmlTagName::k_Prefix);
}
else if (node.Name == "Delimiter")
{
path.emplace_back(XmlTagName::k_Delimiter);
}
else if (node.Name == "NextMarker")
{
path.emplace_back(XmlTagName::k_NextMarker);
}
else if (node.Name == "Blobs")
{
path.emplace_back(XmlTagName::k_Blobs);
}
else if (node.Name == "Blob")
{
path.emplace_back(XmlTagName::k_Blob);
}
else if (node.Name == "BlobPrefix")
{
path.emplace_back(XmlTagName::k_BlobPrefix);
}
else if (node.Name == "Name")
{
path.emplace_back(XmlTagName::k_Name);
}
else
{
path.emplace_back(XmlTagName::k_Unknown);
}
if (path.size() == 3 && path[0] == XmlTagName::k_EnumerationResults
&& path[1] == XmlTagName::k_Blobs && path[2] == XmlTagName::k_Blob)
{
ret.Items.emplace_back(BlobItemFromXml(reader));
path.pop_back();
}
}
else if (node.Type == _internal::XmlNodeType::Text)
{
if (path.size() == 2 && path[0] == XmlTagName::k_EnumerationResults
&& path[1] == XmlTagName::k_Prefix)
{
ret.Prefix = node.Value;
}
else if (
path.size() == 2 && path[0] == XmlTagName::k_EnumerationResults
&& path[1] == XmlTagName::k_Delimiter)
{
ret.Delimiter = node.Value;
}
else if (
path.size() == 2 && path[0] == XmlTagName::k_EnumerationResults
&& path[1] == XmlTagName::k_NextMarker)
{
ret.ContinuationToken = node.Value;
}
else if (
path.size() == 4 && path[0] == XmlTagName::k_EnumerationResults
&& path[1] == XmlTagName::k_Blobs && path[2] == XmlTagName::k_BlobPrefix
&& path[3] == XmlTagName::k_Name)
{
ret.BlobPrefixes.emplace_back(node.Value);
}
}
else if (node.Type == _internal::XmlNodeType::Attribute)
{
if (path.size() == 1 && path[0] == XmlTagName::k_EnumerationResults
&& node.Name == "ServiceEndpoint")
{
ret.ServiceEndpoint = node.Value;
}
else if (
path.size() == 1 && path[0] == XmlTagName::k_EnumerationResults
&& node.Name == "ContainerName")
{
ret.BlobContainerName = node.Value;
}
}
}
return ret;
}
static Models::_detail::ListBlobsResult ListBlobsResultInternalFromXml(
_internal::XmlReader& reader)
{
Models::_detail::ListBlobsResult ret;
enum class XmlTagName
{
k_EnumerationResults,
k_Prefix,
k_NextMarker,
k_Blobs,
k_Blob,
k_Unknown,
};
std::vector<XmlTagName> path;
while (true)
{
auto node = reader.Read();
if (node.Type == _internal::XmlNodeType::End)
{
break;
}
else if (node.Type == _internal::XmlNodeType::EndTag)
{
if (path.size() > 0)
{
path.pop_back();
}
else
{
break;
}
}
else if (node.Type == _internal::XmlNodeType::StartTag)
{
if (node.Name == "EnumerationResults")
{
path.emplace_back(XmlTagName::k_EnumerationResults);
}
else if (node.Name == "Prefix")
{
path.emplace_back(XmlTagName::k_Prefix);
}
else if (node.Name == "NextMarker")
{
path.emplace_back(XmlTagName::k_NextMarker);
}
else if (node.Name == "Blobs")
{
path.emplace_back(XmlTagName::k_Blobs);
}
else if (node.Name == "Blob")
{
path.emplace_back(XmlTagName::k_Blob);
}
else
{
path.emplace_back(XmlTagName::k_Unknown);
}
if (path.size() == 3 && path[0] == XmlTagName::k_EnumerationResults
&& path[1] == XmlTagName::k_Blobs && path[2] == XmlTagName::k_Blob)
{
ret.Items.emplace_back(BlobItemFromXml(reader));
path.pop_back();
}
}
else if (node.Type == _internal::XmlNodeType::Text)
{
if (path.size() == 2 && path[0] == XmlTagName::k_EnumerationResults
&& path[1] == XmlTagName::k_Prefix)
{
ret.Prefix = node.Value;
}
else if (
path.size() == 2 && path[0] == XmlTagName::k_EnumerationResults
&& path[1] == XmlTagName::k_NextMarker)
{
ret.ContinuationToken = node.Value;
}
}
else if (node.Type == _internal::XmlNodeType::Attribute)
{
if (path.size() == 1 && path[0] == XmlTagName::k_EnumerationResults
&& node.Name == "ServiceEndpoint")
{
ret.ServiceEndpoint = node.Value;
}
else if (
path.size() == 1 && path[0] == XmlTagName::k_EnumerationResults
&& node.Name == "ContainerName")
{
ret.BlobContainerName = node.Value;
}
}
}
return ret;
}
static BlobItem BlobItemFromXml(_internal::XmlReader& reader)
{
BlobItem ret;
enum class XmlTagName
{
k_Name,
k_Deleted,
k_Snapshot,
k_VersionId,
k_IsCurrentVersion,
k_Properties,
k_ContentType,
k_ContentEncoding,
k_ContentLanguage,
k_ContentMD5,
k_CacheControl,
k_ContentDisposition,
k_CreationTime,
k_ExpiryTime,
k_LastAccessTime,
k_LastModified,
k_Etag,
k_ContentLength,
k_BlobType,
k_AccessTier,
k_AccessTierInferred,
k_AccessTierChangeTime,
k_ArchiveStatus,
k_RehydratePriority,
k_LeaseStatus,
k_LeaseState,
k_LeaseDuration,
k_ServerEncrypted,
k_CustomerProvidedKeySha256,
k_EncryptionScope,
k_Sealed,
k_xmsblobsequencenumber,
k_CopyId,
k_CopyStatus,
k_CopySource,
k_CopyProgress,
k_CopyCompletionTime,
k_CopyStatusDescription,
k_IncrementalCopy,
k_CopyDestinationSnapshot,
k_DeletedTime,
k_RemainingRetentionDays,
k_Metadata,
k_OrMetadata,
k_Tags,
k_TagSet,
k_Unknown,
};
std::vector<XmlTagName> path;
while (true)
{
auto node = reader.Read();
if (node.Type == _internal::XmlNodeType::End)
{
break;
}
else if (node.Type == _internal::XmlNodeType::EndTag)
{
if (path.size() > 0)
{
path.pop_back();
}
else
{
break;
}
}
else if (node.Type == _internal::XmlNodeType::StartTag)
{
if (node.Name == "Name")
{
path.emplace_back(XmlTagName::k_Name);
}
else if (node.Name == "Deleted")
{
path.emplace_back(XmlTagName::k_Deleted);
}
else if (node.Name == "Snapshot")
{
path.emplace_back(XmlTagName::k_Snapshot);
}
else if (node.Name == "VersionId")
{
path.emplace_back(XmlTagName::k_VersionId);
}
else if (node.Name == "IsCurrentVersion")
{
path.emplace_back(XmlTagName::k_IsCurrentVersion);
}
else if (node.Name == "Properties")
{
path.emplace_back(XmlTagName::k_Properties);
}
else if (node.Name == "Content-Type")
{
path.emplace_back(XmlTagName::k_ContentType);
}
else if (node.Name == "Content-Encoding")
{
path.emplace_back(XmlTagName::k_ContentEncoding);
}
else if (node.Name == "Content-Language")
{
path.emplace_back(XmlTagName::k_ContentLanguage);
}
else if (node.Name == "Content-MD5")
{
path.emplace_back(XmlTagName::k_ContentMD5);
}
else if (node.Name == "Cache-Control")
{
path.emplace_back(XmlTagName::k_CacheControl);
}
else if (node.Name == "Content-Disposition")
{
path.emplace_back(XmlTagName::k_ContentDisposition);
}
else if (node.Name == "Creation-Time")
{
path.emplace_back(XmlTagName::k_CreationTime);
}
else if (node.Name == "Expiry-Time")
{
path.emplace_back(XmlTagName::k_ExpiryTime);
}
else if (node.Name == "LastAccessTime")
{
path.emplace_back(XmlTagName::k_LastAccessTime);
}
else if (node.Name == "Last-Modified")
{
path.emplace_back(XmlTagName::k_LastModified);
}
else if (node.Name == "Etag")
{
path.emplace_back(XmlTagName::k_Etag);
}
else if (node.Name == "Content-Length")
{
path.emplace_back(XmlTagName::k_ContentLength);
}
else if (node.Name == "BlobType")
{
path.emplace_back(XmlTagName::k_BlobType);
}
else if (node.Name == "AccessTier")
{
path.emplace_back(XmlTagName::k_AccessTier);
}
else if (node.Name == "AccessTierInferred")
{
path.emplace_back(XmlTagName::k_AccessTierInferred);
}
else if (node.Name == "AccessTierChangeTime")
{
path.emplace_back(XmlTagName::k_AccessTierChangeTime);
}
else if (node.Name == "ArchiveStatus")
{
path.emplace_back(XmlTagName::k_ArchiveStatus);
}
else if (node.Name == "RehydratePriority")
{
path.emplace_back(XmlTagName::k_RehydratePriority);
}
else if (node.Name == "LeaseStatus")
{
path.emplace_back(XmlTagName::k_LeaseStatus);
}
else if (node.Name == "LeaseState")
{
path.emplace_back(XmlTagName::k_LeaseState);
}
else if (node.Name == "LeaseDuration")
{
path.emplace_back(XmlTagName::k_LeaseDuration);
}
else if (node.Name == "ServerEncrypted")
{
path.emplace_back(XmlTagName::k_ServerEncrypted);
}
else if (node.Name == "CustomerProvidedKeySha256")
{
path.emplace_back(XmlTagName::k_CustomerProvidedKeySha256);
}
else if (node.Name == "EncryptionScope")
{
path.emplace_back(XmlTagName::k_EncryptionScope);
}
else if (node.Name == "Sealed")
{
path.emplace_back(XmlTagName::k_Sealed);
}
else if (node.Name == "x-ms-blob-sequence-number")
{
path.emplace_back(XmlTagName::k_xmsblobsequencenumber);
}
else if (node.Name == "CopyId")
{
path.emplace_back(XmlTagName::k_CopyId);
}
else if (node.Name == "CopyStatus")
{
path.emplace_back(XmlTagName::k_CopyStatus);
}
else if (node.Name == "CopySource")
{
path.emplace_back(XmlTagName::k_CopySource);
}
else if (node.Name == "CopyProgress")
{
path.emplace_back(XmlTagName::k_CopyProgress);
}
else if (node.Name == "CopyCompletionTime")
{
path.emplace_back(XmlTagName::k_CopyCompletionTime);
}
else if (node.Name == "CopyStatusDescription")
{
path.emplace_back(XmlTagName::k_CopyStatusDescription);
}
else if (node.Name == "IncrementalCopy")
{
path.emplace_back(XmlTagName::k_IncrementalCopy);
}
else if (node.Name == "CopyDestinationSnapshot")
{
path.emplace_back(XmlTagName::k_CopyDestinationSnapshot);
}
else if (node.Name == "DeletedTime")
{
path.emplace_back(XmlTagName::k_DeletedTime);
}
else if (node.Name == "RemainingRetentionDays")
{
path.emplace_back(XmlTagName::k_RemainingRetentionDays);
}
else if (node.Name == "Metadata")
{
path.emplace_back(XmlTagName::k_Metadata);
}
else if (node.Name == "OrMetadata")
{
path.emplace_back(XmlTagName::k_OrMetadata);
}
else if (node.Name == "Tags")
{
path.emplace_back(XmlTagName::k_Tags);
}
else if (node.Name == "TagSet")
{
path.emplace_back(XmlTagName::k_TagSet);
}
else
{
path.emplace_back(XmlTagName::k_Unknown);
}
if (path.size() == 1 && path[0] == XmlTagName::k_Metadata)
{
ret.Details.Metadata = MetadataFromXml(reader);
path.pop_back();
}
else if (path.size() == 1 && path[0] == XmlTagName::k_OrMetadata)
{
ret.Details.ObjectReplicationSourceProperties
= ObjectReplicationSourcePropertiesFromXml(reader);
path.pop_back();
}
else if (
path.size() == 2 && path[0] == XmlTagName::k_Tags
&& path[1] == XmlTagName::k_TagSet)
{
ret.Details.Tags = TagsFromXml(reader);
path.pop_back();
}
}
else if (node.Type == _internal::XmlNodeType::Text)
{
if (path.size() == 1 && path[0] == XmlTagName::k_Name)
{
ret.Name = node.Value;
}
else if (path.size() == 1 && path[0] == XmlTagName::k_Deleted)
{
ret.IsDeleted = node.Value == "true";
}
else if (path.size() == 1 && path[0] == XmlTagName::k_Snapshot)
{
ret.Snapshot = node.Value;
}
else if (path.size() == 1 && path[0] == XmlTagName::k_VersionId)
{
ret.VersionId = node.Value;
}
else if (path.size() == 1 && path[0] == XmlTagName::k_IsCurrentVersion)
{
ret.IsCurrentVersion = node.Value == "true";
}
else if (
path.size() == 2 && path[0] == XmlTagName::k_Properties
&& path[1] == XmlTagName::k_ContentType)
{
ret.Details.HttpHeaders.ContentType = node.Value;
}
else if (
path.size() == 2 && path[0] == XmlTagName::k_Properties
&& path[1] == XmlTagName::k_ContentEncoding)
{
ret.Details.HttpHeaders.ContentEncoding = node.Value;
}
else if (
path.size() == 2 && path[0] == XmlTagName::k_Properties
&& path[1] == XmlTagName::k_ContentLanguage)
{
ret.Details.HttpHeaders.ContentLanguage = node.Value;
}
else if (
path.size() == 2 && path[0] == XmlTagName::k_Properties
&& path[1] == XmlTagName::k_ContentMD5)
{
ret.Details.HttpHeaders.ContentHash.Value
= Azure::Core::Convert::Base64Decode(node.Value);
}
else if (
path.size() == 2 && path[0] == XmlTagName::k_Properties
&& path[1] == XmlTagName::k_CacheControl)
{
ret.Details.HttpHeaders.CacheControl = node.Value;
}
else if (
path.size() == 2 && path[0] == XmlTagName::k_Properties
&& path[1] == XmlTagName::k_ContentDisposition)
{
ret.Details.HttpHeaders.ContentDisposition = node.Value;
}
else if (
path.size() == 2 && path[0] == XmlTagName::k_Properties
&& path[1] == XmlTagName::k_CreationTime)
{
ret.Details.CreatedOn
= Azure::DateTime::Parse(node.Value, Azure::DateTime::DateFormat::Rfc1123);
}
else if (
path.size() == 2 && path[0] == XmlTagName::k_Properties
&& path[1] == XmlTagName::k_ExpiryTime)
{
ret.Details.ExpiresOn
= Azure::DateTime::Parse(node.Value, Azure::DateTime::DateFormat::Rfc1123);
}
else if (
path.size() == 2 && path[0] == XmlTagName::k_Properties
&& path[1] == XmlTagName::k_LastAccessTime)
{
ret.Details.LastAccessedOn
= Azure::DateTime::Parse(node.Value, Azure::DateTime::DateFormat::Rfc1123);
}
else if (
path.size() == 2 && path[0] == XmlTagName::k_Properties
&& path[1] == XmlTagName::k_LastModified)
{
ret.Details.LastModified
= Azure::DateTime::Parse(node.Value, Azure::DateTime::DateFormat::Rfc1123);
}
else if (
path.size() == 2 && path[0] == XmlTagName::k_Properties
&& path[1] == XmlTagName::k_Etag)
{
ret.Details.ETag = Azure::ETag(node.Value);
}
else if (
path.size() == 2 && path[0] == XmlTagName::k_Properties
&& path[1] == XmlTagName::k_ContentLength)
{
ret.BlobSize = std::stoll(node.Value);
}
else if (
path.size() == 2 && path[0] == XmlTagName::k_Properties
&& path[1] == XmlTagName::k_BlobType)
{
ret.BlobType = BlobType(node.Value);
}
else if (
path.size() == 2 && path[0] == XmlTagName::k_Properties
&& path[1] == XmlTagName::k_AccessTier)
{
ret.Details.AccessTier = AccessTier(node.Value);
}
else if (
path.size() == 2 && path[0] == XmlTagName::k_Properties
&& path[1] == XmlTagName::k_AccessTierInferred)
{
ret.Details.IsAccessTierInferred = node.Value == "true";
}
else if (
path.size() == 2 && path[0] == XmlTagName::k_Properties
&& path[1] == XmlTagName::k_AccessTierChangeTime)
{
ret.Details.AccessTierChangedOn
= Azure::DateTime::Parse(node.Value, Azure::DateTime::DateFormat::Rfc1123);
}
else if (
path.size() == 2 && path[0] == XmlTagName::k_Properties
&& path[1] == XmlTagName::k_ArchiveStatus)
{
ret.Details.ArchiveStatus = ArchiveStatus(node.Value);
}
else if (
path.size() == 2 && path[0] == XmlTagName::k_Properties
&& path[1] == XmlTagName::k_RehydratePriority)
{
ret.Details.RehydratePriority = RehydratePriority(node.Value);
}
else if (
path.size() == 2 && path[0] == XmlTagName::k_Properties
&& path[1] == XmlTagName::k_LeaseStatus)
{
ret.Details.LeaseStatus = LeaseStatus(node.Value);
}
else if (
path.size() == 2 && path[0] == XmlTagName::k_Properties
&& path[1] == XmlTagName::k_LeaseState)
{
ret.Details.LeaseState = LeaseState(node.Value);
}
else if (
path.size() == 2 && path[0] == XmlTagName::k_Properties
&& path[1] == XmlTagName::k_LeaseDuration)
{
ret.Details.LeaseDuration = LeaseDurationType(node.Value);
}
else if (
path.size() == 2 && path[0] == XmlTagName::k_Properties
&& path[1] == XmlTagName::k_ServerEncrypted)
{
ret.Details.IsServerEncrypted = node.Value == "true";
}
else if (
path.size() == 2 && path[0] == XmlTagName::k_Properties
&& path[1] == XmlTagName::k_CustomerProvidedKeySha256)
{
ret.Details.EncryptionKeySha256 = Azure::Core::Convert::Base64Decode(node.Value);
}
else if (
path.size() == 2 && path[0] == XmlTagName::k_Properties
&& path[1] == XmlTagName::k_EncryptionScope)
{
ret.Details.EncryptionScope = node.Value;
}
else if (
path.size() == 2 && path[0] == XmlTagName::k_Properties
&& path[1] == XmlTagName::k_Sealed)
{
ret.Details.IsSealed = node.Value == "true";
}
else if (
path.size() == 2 && path[0] == XmlTagName::k_Properties
&& path[1] == XmlTagName::k_xmsblobsequencenumber)
{
ret.Details.SequenceNumber = std::stoll(node.Value);
}
else if (
path.size() == 2 && path[0] == XmlTagName::k_Properties
&& path[1] == XmlTagName::k_CopyId)
{
ret.Details.CopyId = node.Value;
}
else if (
path.size() == 2 && path[0] == XmlTagName::k_Properties
&& path[1] == XmlTagName::k_CopyStatus)
{
ret.Details.CopyStatus = CopyStatus(node.Value);
}
else if (
path.size() == 2 && path[0] == XmlTagName::k_Properties
&& path[1] == XmlTagName::k_CopySource)
{
ret.Details.CopySource = node.Value;
}
else if (
path.size() == 2 && path[0] == XmlTagName::k_Properties
&& path[1] == XmlTagName::k_CopyProgress)
{
ret.Details.CopyProgress = node.Value;
}
else if (
path.size() == 2 && path[0] == XmlTagName::k_Properties
&& path[1] == XmlTagName::k_CopyCompletionTime)
{
ret.Details.CopyCompletedOn
= Azure::DateTime::Parse(node.Value, Azure::DateTime::DateFormat::Rfc1123);
}
else if (
path.size() == 2 && path[0] == XmlTagName::k_Properties
&& path[1] == XmlTagName::k_CopyStatusDescription)
{
ret.Details.CopyStatusDescription = node.Value;
}
else if (
path.size() == 2 && path[0] == XmlTagName::k_Properties
&& path[1] == XmlTagName::k_IncrementalCopy)
{
ret.Details.IsIncrementalCopy = node.Value == "true";
}
else if (
path.size() == 2 && path[0] == XmlTagName::k_Properties
&& path[1] == XmlTagName::k_CopyDestinationSnapshot)
{
ret.Details.IncrementalCopyDestinationSnapshot = node.Value;
}
else if (
path.size() == 2 && path[0] == XmlTagName::k_Properties
&& path[1] == XmlTagName::k_DeletedTime)
{
ret.Details.DeletedOn
= Azure::DateTime::Parse(node.Value, Azure::DateTime::DateFormat::Rfc1123);
}
else if (
path.size() == 2 && path[0] == XmlTagName::k_Properties
&& path[1] == XmlTagName::k_RemainingRetentionDays)
{
ret.Details.RemainingRetentionDays = std::stoi(node.Value);
}
}
}
return ret;
}
static SignedIdentifier SignedIdentifierFromXml(_internal::XmlReader& reader)
{
SignedIdentifier ret;
enum class XmlTagName
{
k_Id,
k_AccessPolicy,
k_Start,
k_Expiry,
k_Permission,
k_Unknown,
};
std::vector<XmlTagName> path;
while (true)
{
auto node = reader.Read();
if (node.Type == _internal::XmlNodeType::End)
{
break;
}
else if (node.Type == _internal::XmlNodeType::EndTag)
{
if (path.size() > 0)
{
path.pop_back();
}
else
{
break;
}
}
else if (node.Type == _internal::XmlNodeType::StartTag)
{
if (node.Name == "Id")
{
path.emplace_back(XmlTagName::k_Id);
}
else if (node.Name == "AccessPolicy")
{
path.emplace_back(XmlTagName::k_AccessPolicy);
}
else if (node.Name == "Start")
{
path.emplace_back(XmlTagName::k_Start);
}
else if (node.Name == "Expiry")
{
path.emplace_back(XmlTagName::k_Expiry);
}
else if (node.Name == "Permission")
{
path.emplace_back(XmlTagName::k_Permission);
}
else
{
path.emplace_back(XmlTagName::k_Unknown);
}
}
else if (node.Type == _internal::XmlNodeType::Text)
{
if (path.size() == 1 && path[0] == XmlTagName::k_Id)
{
ret.Id = node.Value;
}
else if (
path.size() == 2 && path[0] == XmlTagName::k_AccessPolicy
&& path[1] == XmlTagName::k_Start)
{
ret.StartsOn
= Azure::DateTime::Parse(node.Value, Azure::DateTime::DateFormat::Rfc3339);
}
else if (
path.size() == 2 && path[0] == XmlTagName::k_AccessPolicy
&& path[1] == XmlTagName::k_Expiry)
{
ret.ExpiresOn
= Azure::DateTime::Parse(node.Value, Azure::DateTime::DateFormat::Rfc3339);
}
else if (
path.size() == 2 && path[0] == XmlTagName::k_AccessPolicy
&& path[1] == XmlTagName::k_Permission)
{
ret.Permissions = node.Value;
}
}
}
return ret;
}
static std::map<std::string, std::string> TagsFromXml(_internal::XmlReader& reader)
{
std::map<std::string, std::string> ret;
int depth = 0;
std::string key;
bool is_key = false;
bool is_value = false;
while (true)
{
auto node = reader.Read();
if (node.Type == _internal::XmlNodeType::End)
{
break;
}
else if (node.Type == _internal::XmlNodeType::StartTag)
{
++depth;
if (node.Name == "Key")
{
is_key = true;
}
else if (node.Name == "Value")
{
is_value = true;
}
}
else if (node.Type == _internal::XmlNodeType::EndTag)
{
if (depth-- == 0)
{
break;
}
}
if (depth == 2 && node.Type == _internal::XmlNodeType::Text)
{
if (is_key)
{
key = node.Value;
is_key = false;
}
else if (is_value)
{
ret.emplace(std::move(key), node.Value);
is_value = false;
}
}
}
return ret;
}
static std::vector<ObjectReplicationPolicy> ObjectReplicationSourcePropertiesFromXml(
_internal::XmlReader& reader)
{
int depth = 0;
std::map<std::string, std::vector<ObjectReplicationRule>> orPropertiesMap;
std::string policyId;
std::string ruleId;
while (true)
{
auto node = reader.Read();
if (node.Type == _internal::XmlNodeType::End)
{
break;
}
else if (node.Type == _internal::XmlNodeType::StartTag)
{
++depth;
std::string startTagName = node.Name;
if (startTagName.substr(0, 3) == "or-")
{
auto underscorePos = startTagName.find('_', 3);
policyId
= std::string(startTagName.begin() + 3, startTagName.begin() + underscorePos);
ruleId = startTagName.substr(underscorePos + 1);
}
}
else if (node.Type == _internal::XmlNodeType::EndTag)
{
if (depth-- == 0)
{
break;
}
}
if (depth == 1 && node.Type == _internal::XmlNodeType::Text)
{
ObjectReplicationRule rule;
rule.RuleId = std::move(ruleId);
rule.ReplicationStatus = ObjectReplicationStatus(node.Value);
orPropertiesMap[policyId].emplace_back(std::move(rule));
}
}
std::vector<ObjectReplicationPolicy> ret;
for (auto& property : orPropertiesMap)
{
ObjectReplicationPolicy policy;
policy.PolicyId = property.first;
policy.Rules = std::move(property.second);
ret.emplace_back(std::move(policy));
}
return ret;
}
static Metadata MetadataFromXml(_internal::XmlReader& reader)
{
Metadata ret;
int depth = 0;
std::string key;
while (true)
{
auto node = reader.Read();
if (node.Type == _internal::XmlNodeType::End)
{
break;
}
else if (node.Type == _internal::XmlNodeType::StartTag)
{
if (depth++ == 0)
{
key = node.Name;
}
}
else if (node.Type == _internal::XmlNodeType::EndTag)
{
if (depth-- == 0)
{
break;
}
}
else if (depth == 1 && node.Type == _internal::XmlNodeType::Text)
{
ret.emplace(std::move(key), node.Value);
}
}
return ret;
}
static void SetBlobContainerAccessPolicyOptionsToXml(
_internal::XmlWriter& writer,
const SetBlobContainerAccessPolicyOptions& options)
{
writer.Write(_internal::XmlNode{_internal::XmlNodeType::StartTag, "SignedIdentifiers"});
for (const auto& i : options.SignedIdentifiers)
{
SignedIdentifierToXml(writer, i);
}
writer.Write(_internal::XmlNode{_internal::XmlNodeType::EndTag});
}
static void SignedIdentifierToXml(
_internal::XmlWriter& writer,
const SignedIdentifier& options)
{
writer.Write(_internal::XmlNode{_internal::XmlNodeType::StartTag, "SignedIdentifier"});
writer.Write(_internal::XmlNode{_internal::XmlNodeType::StartTag, "Id"});
writer.Write(_internal::XmlNode{_internal::XmlNodeType::Text, std::string(), options.Id});
writer.Write(_internal::XmlNode{_internal::XmlNodeType::EndTag});
writer.Write(_internal::XmlNode{_internal::XmlNodeType::StartTag, "AccessPolicy"});
if (options.StartsOn.HasValue())
{
writer.Write(_internal::XmlNode{_internal::XmlNodeType::StartTag, "Start"});
writer.Write(_internal::XmlNode{
_internal::XmlNodeType::Text,
std::string(),
options.StartsOn.Value().ToString(
Azure::DateTime::DateFormat::Rfc3339,
Azure::DateTime::TimeFractionFormat::AllDigits)});
writer.Write(_internal::XmlNode{_internal::XmlNodeType::EndTag});
}
if (options.ExpiresOn.HasValue())
{
writer.Write(_internal::XmlNode{_internal::XmlNodeType::StartTag, "Expiry"});
writer.Write(_internal::XmlNode{
_internal::XmlNodeType::Text,
std::string(),
options.ExpiresOn.Value().ToString(
Azure::DateTime::DateFormat::Rfc3339,
Azure::DateTime::TimeFractionFormat::AllDigits)});
writer.Write(_internal::XmlNode{_internal::XmlNodeType::EndTag});
}
writer.Write(_internal::XmlNode{_internal::XmlNodeType::StartTag, "Permission"});
writer.Write(
_internal::XmlNode{_internal::XmlNodeType::Text, std::string(), options.Permissions});
writer.Write(_internal::XmlNode{_internal::XmlNodeType::EndTag});
writer.Write(_internal::XmlNode{_internal::XmlNodeType::EndTag});
writer.Write(_internal::XmlNode{_internal::XmlNodeType::EndTag});
}
}; // class BlobContainer
class Blob final {
public:
struct DownloadBlobOptions final
{
Azure::Nullable<int32_t> Timeout;
Azure::Nullable<Azure::Core::Http::HttpRange> Range;
Azure::Nullable<HashAlgorithm> RangeHashAlgorithm;
Azure::Nullable<std::string> EncryptionKey;
Azure::Nullable<std::vector<uint8_t>> EncryptionKeySha256;
Azure::Nullable<EncryptionAlgorithmType> EncryptionAlgorithm;
Azure::Nullable<std::string> LeaseId;
Azure::Nullable<Azure::DateTime> IfModifiedSince;
Azure::Nullable<Azure::DateTime> IfUnmodifiedSince;
Azure::ETag IfMatch;
Azure::ETag IfNoneMatch;
Azure::Nullable<std::string> IfTags;
}; // struct DownloadBlobOptions
static Azure::Response<DownloadBlobResult> Download(
Azure::Core::Http::_internal::HttpPipeline& pipeline,
const Azure::Core::Url& url,
const DownloadBlobOptions& options,
const Azure::Core::Context& context)
{
auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Get, url, false);
request.SetHeader("x-ms-version", "2020-02-10");
if (options.Timeout.HasValue())
{
request.GetUrl().AppendQueryParameter(
"timeout", std::to_string(options.Timeout.Value()));
}
if (options.Range.HasValue())
{
std::string headerValue = "bytes=" + std::to_string(options.Range.Value().Offset) + "-";
if (options.Range.Value().Length.HasValue())
{
headerValue += std::to_string(
options.Range.Value().Offset + options.Range.Value().Length.Value() - 1);
}
request.SetHeader("x-ms-range", std::move(headerValue));
}
if (options.EncryptionKey.HasValue())
{
request.SetHeader("x-ms-encryption-key", options.EncryptionKey.Value());
}
if (options.EncryptionKeySha256.HasValue())
{
request.SetHeader(
"x-ms-encryption-key-sha256",
Azure::Core::Convert::Base64Encode(options.EncryptionKeySha256.Value()));
}
if (options.EncryptionAlgorithm.HasValue())
{
request.SetHeader(
"x-ms-encryption-algorithm", options.EncryptionAlgorithm.Value().ToString());
}
if (options.IfModifiedSince.HasValue())
{
request.SetHeader(
"If-Modified-Since",
options.IfModifiedSince.Value().ToString(Azure::DateTime::DateFormat::Rfc1123));
}
if (options.IfUnmodifiedSince.HasValue())
{
request.SetHeader(
"If-Unmodified-Since",
options.IfUnmodifiedSince.Value().ToString(Azure::DateTime::DateFormat::Rfc1123));
}
if (options.IfMatch.HasValue() && !options.IfMatch.ToString().empty())
{
request.SetHeader("If-Match", options.IfMatch.ToString());
}
if (options.IfNoneMatch.HasValue() && !options.IfNoneMatch.ToString().empty())
{
request.SetHeader("If-None-Match", options.IfNoneMatch.ToString());
}
if (options.IfTags.HasValue())
{
request.SetHeader("x-ms-if-tags", options.IfTags.Value());
}
if (options.LeaseId.HasValue())
{
request.SetHeader("x-ms-lease-id", options.LeaseId.Value());
}
if (options.RangeHashAlgorithm.HasValue())
{
if (options.RangeHashAlgorithm.Value() == HashAlgorithm::Md5)
{
request.SetHeader("x-ms-range-get-content-md5", "true");
}
else if (options.RangeHashAlgorithm.Value() == HashAlgorithm::Crc64)
{
request.SetHeader("x-ms-range-get-content-crc64", "true");
}
}
auto pHttpResponse = pipeline.Send(request, context);
Azure::Core::Http::RawResponse& httpResponse = *pHttpResponse;
DownloadBlobResult response;
auto http_status_code = httpResponse.GetStatusCode();
if (!(http_status_code == Azure::Core::Http::HttpStatusCode::Ok
|| http_status_code == Azure::Core::Http::HttpStatusCode::PartialContent))
{
throw StorageException::CreateFromResponse(std::move(pHttpResponse));
}
response.BodyStream = httpResponse.ExtractBodyStream();
{
const auto& headers = httpResponse.GetHeaders();
auto content_md5_iterator = headers.find("content-md5");
if (content_md5_iterator != headers.end())
{
ContentHash hash;
hash.Algorithm = HashAlgorithm::Md5;
hash.Value = Azure::Core::Convert::Base64Decode(content_md5_iterator->second);
response.TransactionalContentHash = std::move(hash);
}
auto x_ms_content_crc64_iterator = headers.find("x-ms-content-crc64");
if (x_ms_content_crc64_iterator != headers.end())
{
ContentHash hash;
hash.Algorithm = HashAlgorithm::Crc64;
hash.Value = Azure::Core::Convert::Base64Decode(x_ms_content_crc64_iterator->second);
response.TransactionalContentHash = std::move(hash);
}
}
response.BlobType = BlobType(httpResponse.GetHeaders().at("x-ms-blob-type"));
auto content_range_iterator = httpResponse.GetHeaders().find("content-range");
if (content_range_iterator != httpResponse.GetHeaders().end())
{
const std::string& content_range = content_range_iterator->second;
auto bytes_pos = content_range.find("bytes ");
auto dash_pos = content_range.find("-", bytes_pos + 6);
auto slash_pos = content_range.find("/", dash_pos + 1);
int64_t range_start_offset = std::stoll(std::string(
content_range.begin() + bytes_pos + 6, content_range.begin() + dash_pos));
int64_t range_end_offset = std::stoll(std::string(
content_range.begin() + dash_pos + 1, content_range.begin() + slash_pos));
response.ContentRange = Azure::Core::Http::HttpRange{
range_start_offset, range_end_offset - range_start_offset + 1};
}
else
{
response.ContentRange = Azure::Core::Http::HttpRange{
0, std::stoll(httpResponse.GetHeaders().at("content-length"))};
}
if (content_range_iterator != httpResponse.GetHeaders().end())
{
const std::string& content_range = content_range_iterator->second;
auto slash_pos = content_range.find("/");
response.BlobSize = std::stoll(content_range.substr(slash_pos + 1));
}
else
{
response.BlobSize = std::stoll(httpResponse.GetHeaders().at("content-length"));
}
response.Details.ETag = Azure::ETag(httpResponse.GetHeaders().at("etag"));
response.Details.LastModified = Azure::DateTime::Parse(
httpResponse.GetHeaders().at("last-modified"), Azure::DateTime::DateFormat::Rfc1123);
auto content_type__iterator = httpResponse.GetHeaders().find("content-type");
if (content_type__iterator != httpResponse.GetHeaders().end())
{
response.Details.HttpHeaders.ContentType = content_type__iterator->second;
}
auto content_encoding__iterator = httpResponse.GetHeaders().find("content-encoding");
if (content_encoding__iterator != httpResponse.GetHeaders().end())
{
response.Details.HttpHeaders.ContentEncoding = content_encoding__iterator->second;
}
auto content_language__iterator = httpResponse.GetHeaders().find("content-language");
if (content_language__iterator != httpResponse.GetHeaders().end())
{
response.Details.HttpHeaders.ContentLanguage = content_language__iterator->second;
}
auto cache_control__iterator = httpResponse.GetHeaders().find("cache-control");
if (cache_control__iterator != httpResponse.GetHeaders().end())
{
response.Details.HttpHeaders.CacheControl = cache_control__iterator->second;
}
if (http_status_code == Azure::Core::Http::HttpStatusCode::Ok)
{
auto content_md5__iterator = httpResponse.GetHeaders().find("content-md5");
if (content_md5__iterator != httpResponse.GetHeaders().end())
{
response.Details.HttpHeaders.ContentHash.Value
= Azure::Core::Convert::Base64Decode(content_md5__iterator->second);
}
}
auto x_ms_blob_content_md5__iterator
= httpResponse.GetHeaders().find("x-ms-blob-content-md5");
if (x_ms_blob_content_md5__iterator != httpResponse.GetHeaders().end())
{
response.Details.HttpHeaders.ContentHash.Value
= Azure::Core::Convert::Base64Decode(x_ms_blob_content_md5__iterator->second);
}
auto content_disposition__iterator
= httpResponse.GetHeaders().find("content-disposition");
if (content_disposition__iterator != httpResponse.GetHeaders().end())
{
response.Details.HttpHeaders.ContentDisposition = content_disposition__iterator->second;
}
for (auto i = httpResponse.GetHeaders().lower_bound("x-ms-meta-");
i != httpResponse.GetHeaders().end() && i->first.substr(0, 10) == "x-ms-meta-";
++i)
{
response.Details.Metadata.emplace(i->first.substr(10), i->second);
}
response.Details.IsServerEncrypted
= httpResponse.GetHeaders().at("x-ms-server-encrypted") == "true";
auto x_ms_encryption_key_sha256__iterator
= httpResponse.GetHeaders().find("x-ms-encryption-key-sha256");
if (x_ms_encryption_key_sha256__iterator != httpResponse.GetHeaders().end())
{
response.Details.EncryptionKeySha256
= Azure::Core::Convert::Base64Decode(x_ms_encryption_key_sha256__iterator->second);
}
auto x_ms_encryption_scope__iterator
= httpResponse.GetHeaders().find("x-ms-encryption-scope");
if (x_ms_encryption_scope__iterator != httpResponse.GetHeaders().end())
{
response.Details.EncryptionScope = x_ms_encryption_scope__iterator->second;
}
auto x_ms_lease_status__iterator = httpResponse.GetHeaders().find("x-ms-lease-status");
if (x_ms_lease_status__iterator != httpResponse.GetHeaders().end())
{
response.Details.LeaseStatus = LeaseStatus(x_ms_lease_status__iterator->second);
}
auto x_ms_lease_state__iterator = httpResponse.GetHeaders().find("x-ms-lease-state");
if (x_ms_lease_state__iterator != httpResponse.GetHeaders().end())
{
response.Details.LeaseState = LeaseState(x_ms_lease_state__iterator->second);
}
auto x_ms_lease_duration__iterator
= httpResponse.GetHeaders().find("x-ms-lease-duration");
if (x_ms_lease_duration__iterator != httpResponse.GetHeaders().end())
{
response.Details.LeaseDuration
= LeaseDurationType(x_ms_lease_duration__iterator->second);
}
response.Details.CreatedOn = Azure::DateTime::Parse(
httpResponse.GetHeaders().at("x-ms-creation-time"),
Azure::DateTime::DateFormat::Rfc1123);
auto x_ms_expiry_time__iterator = httpResponse.GetHeaders().find("x-ms-expiry-time");
if (x_ms_expiry_time__iterator != httpResponse.GetHeaders().end())
{
response.Details.ExpiresOn = Azure::DateTime::Parse(
x_ms_expiry_time__iterator->second, Azure::DateTime::DateFormat::Rfc1123);
}
auto x_ms_last_access_time__iterator
= httpResponse.GetHeaders().find("x-ms-last-access-time");
if (x_ms_last_access_time__iterator != httpResponse.GetHeaders().end())
{
response.Details.LastAccessedOn = Azure::DateTime::Parse(
x_ms_last_access_time__iterator->second, Azure::DateTime::DateFormat::Rfc1123);
}
auto x_ms_blob_sequence_number__iterator
= httpResponse.GetHeaders().find("x-ms-blob-sequence-number");
if (x_ms_blob_sequence_number__iterator != httpResponse.GetHeaders().end())
{
response.Details.SequenceNumber
= std::stoll(x_ms_blob_sequence_number__iterator->second);
}
auto x_ms_blob_committed_block_count__iterator
= httpResponse.GetHeaders().find("x-ms-blob-committed-block-count");
if (x_ms_blob_committed_block_count__iterator != httpResponse.GetHeaders().end())
{
response.Details.CommittedBlockCount
= std::stoi(x_ms_blob_committed_block_count__iterator->second);
}
auto x_ms_blob_sealed__iterator = httpResponse.GetHeaders().find("x-ms-blob-sealed");
if (x_ms_blob_sealed__iterator != httpResponse.GetHeaders().end())
{
response.Details.IsSealed = x_ms_blob_sealed__iterator->second == "true";
}
auto x_ms_or_policy_id__iterator = httpResponse.GetHeaders().find("x-ms-or-policy-id");
if (x_ms_or_policy_id__iterator != httpResponse.GetHeaders().end())
{
response.Details.ObjectReplicationDestinationPolicyId
= x_ms_or_policy_id__iterator->second;
}
{
std::map<std::string, std::vector<ObjectReplicationRule>> orPropertiesMap;
for (auto i = httpResponse.GetHeaders().lower_bound("x-ms-or-");
i != httpResponse.GetHeaders().end() && i->first.substr(0, 8) == "x-ms-or-";
++i)
{
const std::string& header = i->first;
auto underscorePos = header.find('_', 8);
if (underscorePos == std::string::npos)
{
continue;
}
std::string policyId
= std::string(header.begin() + 8, header.begin() + underscorePos);
std::string ruleId = header.substr(underscorePos + 1);
ObjectReplicationRule rule;
rule.RuleId = std::move(ruleId);
rule.ReplicationStatus = ObjectReplicationStatus(i->second);
orPropertiesMap[policyId].emplace_back(std::move(rule));
}
for (auto& property : orPropertiesMap)
{
ObjectReplicationPolicy policy;
policy.PolicyId = property.first;
policy.Rules = std::move(property.second);
response.Details.ObjectReplicationSourceProperties.emplace_back(std::move(policy));
}
}
auto x_ms_tag_count__iterator = httpResponse.GetHeaders().find("x-ms-tag-count");
if (x_ms_tag_count__iterator != httpResponse.GetHeaders().end())
{
response.Details.TagCount = std::stoi(x_ms_tag_count__iterator->second);
}
auto x_ms_copy_id__iterator = httpResponse.GetHeaders().find("x-ms-copy-id");
if (x_ms_copy_id__iterator != httpResponse.GetHeaders().end())
{
response.Details.CopyId = x_ms_copy_id__iterator->second;
}
auto x_ms_copy_source__iterator = httpResponse.GetHeaders().find("x-ms-copy-source");
if (x_ms_copy_source__iterator != httpResponse.GetHeaders().end())
{
response.Details.CopySource = x_ms_copy_source__iterator->second;
}
auto x_ms_copy_status__iterator = httpResponse.GetHeaders().find("x-ms-copy-status");
if (x_ms_copy_status__iterator != httpResponse.GetHeaders().end())
{
response.Details.CopyStatus = CopyStatus(x_ms_copy_status__iterator->second);
}
auto x_ms_copy_status_description__iterator
= httpResponse.GetHeaders().find("x-ms-copy-status-description");
if (x_ms_copy_status_description__iterator != httpResponse.GetHeaders().end())
{
response.Details.CopyStatusDescription = x_ms_copy_status_description__iterator->second;
}
auto x_ms_copy_progress__iterator = httpResponse.GetHeaders().find("x-ms-copy-progress");
if (x_ms_copy_progress__iterator != httpResponse.GetHeaders().end())
{
response.Details.CopyProgress = x_ms_copy_progress__iterator->second;
}
auto x_ms_copy_completion_time__iterator
= httpResponse.GetHeaders().find("x-ms-copy-completion-time");
if (x_ms_copy_completion_time__iterator != httpResponse.GetHeaders().end())
{
response.Details.CopyCompletedOn = Azure::DateTime::Parse(
x_ms_copy_completion_time__iterator->second, Azure::DateTime::DateFormat::Rfc1123);
}
auto x_ms_version_id__iterator = httpResponse.GetHeaders().find("x-ms-version-id");
if (x_ms_version_id__iterator != httpResponse.GetHeaders().end())
{
response.Details.VersionId = x_ms_version_id__iterator->second;
}
auto x_ms_is_current_version__iterator
= httpResponse.GetHeaders().find("x-ms-is-current-version");
if (x_ms_is_current_version__iterator != httpResponse.GetHeaders().end())
{
response.Details.IsCurrentVersion = x_ms_is_current_version__iterator->second == "true";
}
return Azure::Response<DownloadBlobResult>(std::move(response), std::move(pHttpResponse));
}
struct DeleteBlobOptions final
{
Azure::Nullable<int32_t> Timeout;
Azure::Nullable<DeleteSnapshotsOption> DeleteSnapshots;
Azure::Nullable<std::string> LeaseId;
Azure::Nullable<Azure::DateTime> IfModifiedSince;
Azure::Nullable<Azure::DateTime> IfUnmodifiedSince;
Azure::ETag IfMatch;
Azure::ETag IfNoneMatch;
Azure::Nullable<std::string> IfTags;
}; // struct DeleteBlobOptions
static Azure::Core::Http::Request DeleteCreateMessage(
const Azure::Core::Url& url,
const DeleteBlobOptions& options)
{
auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Delete, url);
request.SetHeader("x-ms-version", "2020-02-10");
if (options.Timeout.HasValue())
{
request.GetUrl().AppendQueryParameter(
"timeout", std::to_string(options.Timeout.Value()));
}
if (options.DeleteSnapshots.HasValue())
{
request.SetHeader("x-ms-delete-snapshots", options.DeleteSnapshots.Value().ToString());
}
if (options.LeaseId.HasValue())
{
request.SetHeader("x-ms-lease-id", options.LeaseId.Value());
}
if (options.IfModifiedSince.HasValue())
{
request.SetHeader(
"If-Modified-Since",
options.IfModifiedSince.Value().ToString(Azure::DateTime::DateFormat::Rfc1123));
}
if (options.IfUnmodifiedSince.HasValue())
{
request.SetHeader(
"If-Unmodified-Since",
options.IfUnmodifiedSince.Value().ToString(Azure::DateTime::DateFormat::Rfc1123));
}
if (options.IfMatch.HasValue() && !options.IfMatch.ToString().empty())
{
request.SetHeader("If-Match", options.IfMatch.ToString());
}
if (options.IfNoneMatch.HasValue() && !options.IfNoneMatch.ToString().empty())
{
request.SetHeader("If-None-Match", options.IfNoneMatch.ToString());
}
if (options.IfTags.HasValue())
{
request.SetHeader("x-ms-if-tags", options.IfTags.Value());
}
return request;
}
static Azure::Response<DeleteBlobResult> DeleteCreateResponse(
std::unique_ptr<Azure::Core::Http::RawResponse> pHttpResponse,
const Azure::Core::Context& context)
{
(void)context;
Azure::Core::Http::RawResponse& httpResponse = *pHttpResponse;
DeleteBlobResult response;
auto http_status_code = httpResponse.GetStatusCode();
if (http_status_code != Azure::Core::Http::HttpStatusCode::Accepted)
{
throw StorageException::CreateFromResponse(std::move(pHttpResponse));
}
return Azure::Response<DeleteBlobResult>(std::move(response), std::move(pHttpResponse));
}
static Azure::Response<DeleteBlobResult> Delete(
Azure::Core::Http::_internal::HttpPipeline& pipeline,
const Azure::Core::Url& url,
const DeleteBlobOptions& options,
const Azure::Core::Context& context)
{
auto request = DeleteCreateMessage(url, options);
auto pHttpResponse = pipeline.Send(request, context);
return DeleteCreateResponse(std::move(pHttpResponse), context);
}
struct SetBlobExpiryOptions final
{
Azure::Nullable<int32_t> Timeout;
ScheduleBlobExpiryOriginType ExpiryOrigin;
Azure::Nullable<std::string> ExpiryTime;
}; // struct SetBlobExpiryOptions
static Azure::Response<SetBlobExpiryResult> ScheduleDeletion(
Azure::Core::Http::_internal::HttpPipeline& pipeline,
const Azure::Core::Url& url,
const SetBlobExpiryOptions& options,
const Azure::Core::Context& context)
{
auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Put, url);
request.SetHeader("Content-Length", "0");
request.SetHeader("x-ms-version", "2020-02-10");
if (options.Timeout.HasValue())
{
request.GetUrl().AppendQueryParameter(
"timeout", std::to_string(options.Timeout.Value()));
}
request.GetUrl().AppendQueryParameter("comp", "expiry");
request.SetHeader("x-ms-expiry-option", options.ExpiryOrigin.ToString());
if (options.ExpiryTime.HasValue())
{
request.SetHeader("x-ms-expiry-time", options.ExpiryTime.Value());
}
auto pHttpResponse = pipeline.Send(request, context);
Azure::Core::Http::RawResponse& httpResponse = *pHttpResponse;
SetBlobExpiryResult response;
auto http_status_code = httpResponse.GetStatusCode();
if (http_status_code != Azure::Core::Http::HttpStatusCode::Ok)
{
throw StorageException::CreateFromResponse(std::move(pHttpResponse));
}
response.ETag = Azure::ETag(httpResponse.GetHeaders().at("etag"));
response.LastModified = Azure::DateTime::Parse(
httpResponse.GetHeaders().at("last-modified"), Azure::DateTime::DateFormat::Rfc1123);
return Azure::Response<SetBlobExpiryResult>(
std::move(response), std::move(pHttpResponse));
}
struct UndeleteBlobOptions final
{
Azure::Nullable<int32_t> Timeout;
}; // struct UndeleteBlobOptions
static Azure::Response<UndeleteBlobResult> Undelete(
Azure::Core::Http::_internal::HttpPipeline& pipeline,
const Azure::Core::Url& url,
const UndeleteBlobOptions& options,
const Azure::Core::Context& context)
{
auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Put, url);
request.SetHeader("Content-Length", "0");
request.SetHeader("x-ms-version", "2020-02-10");
if (options.Timeout.HasValue())
{
request.GetUrl().AppendQueryParameter(
"timeout", std::to_string(options.Timeout.Value()));
}
request.GetUrl().AppendQueryParameter("comp", "undelete");
auto pHttpResponse = pipeline.Send(request, context);
Azure::Core::Http::RawResponse& httpResponse = *pHttpResponse;
UndeleteBlobResult response;
auto http_status_code = httpResponse.GetStatusCode();
if (http_status_code != Azure::Core::Http::HttpStatusCode::Ok)
{
throw StorageException::CreateFromResponse(std::move(pHttpResponse));
}
return Azure::Response<UndeleteBlobResult>(std::move(response), std::move(pHttpResponse));
}
struct GetBlobPropertiesOptions final
{
Azure::Nullable<int32_t> Timeout;
Azure::Nullable<std::string> EncryptionKey;
Azure::Nullable<std::vector<uint8_t>> EncryptionKeySha256;
Azure::Nullable<EncryptionAlgorithmType> EncryptionAlgorithm;
Azure::Nullable<std::string> LeaseId;
Azure::Nullable<Azure::DateTime> IfModifiedSince;
Azure::Nullable<Azure::DateTime> IfUnmodifiedSince;
Azure::ETag IfMatch;
Azure::ETag IfNoneMatch;
Azure::Nullable<std::string> IfTags;
}; // struct GetBlobPropertiesOptions
static Azure::Response<BlobProperties> GetProperties(
Azure::Core::Http::_internal::HttpPipeline& pipeline,
const Azure::Core::Url& url,
const GetBlobPropertiesOptions& options,
const Azure::Core::Context& context)
{
auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Head, url);
request.SetHeader("x-ms-version", "2020-02-10");
if (options.Timeout.HasValue())
{
request.GetUrl().AppendQueryParameter(
"timeout", std::to_string(options.Timeout.Value()));
}
if (options.EncryptionKey.HasValue())
{
request.SetHeader("x-ms-encryption-key", options.EncryptionKey.Value());
}
if (options.EncryptionKeySha256.HasValue())
{
request.SetHeader(
"x-ms-encryption-key-sha256",
Azure::Core::Convert::Base64Encode(options.EncryptionKeySha256.Value()));
}
if (options.EncryptionAlgorithm.HasValue())
{
request.SetHeader(
"x-ms-encryption-algorithm", options.EncryptionAlgorithm.Value().ToString());
}
if (options.LeaseId.HasValue())
{
request.SetHeader("x-ms-lease-id", options.LeaseId.Value());
}
if (options.IfModifiedSince.HasValue())
{
request.SetHeader(
"If-Modified-Since",
options.IfModifiedSince.Value().ToString(Azure::DateTime::DateFormat::Rfc1123));
}
if (options.IfUnmodifiedSince.HasValue())
{
request.SetHeader(
"If-Unmodified-Since",
options.IfUnmodifiedSince.Value().ToString(Azure::DateTime::DateFormat::Rfc1123));
}
if (options.IfMatch.HasValue() && !options.IfMatch.ToString().empty())
{
request.SetHeader("If-Match", options.IfMatch.ToString());
}
if (options.IfNoneMatch.HasValue() && !options.IfNoneMatch.ToString().empty())
{
request.SetHeader("If-None-Match", options.IfNoneMatch.ToString());
}
if (options.IfTags.HasValue())
{
request.SetHeader("x-ms-if-tags", options.IfTags.Value());
}
auto pHttpResponse = pipeline.Send(request, context);
Azure::Core::Http::RawResponse& httpResponse = *pHttpResponse;
BlobProperties response;
auto http_status_code = httpResponse.GetStatusCode();
if (http_status_code != Azure::Core::Http::HttpStatusCode::Ok)
{
throw StorageException::CreateFromResponse(std::move(pHttpResponse));
}
response.ETag = Azure::ETag(httpResponse.GetHeaders().at("etag"));
response.LastModified = Azure::DateTime::Parse(
httpResponse.GetHeaders().at("last-modified"), Azure::DateTime::DateFormat::Rfc1123);
response.CreatedOn = Azure::DateTime::Parse(
httpResponse.GetHeaders().at("x-ms-creation-time"),
Azure::DateTime::DateFormat::Rfc1123);
auto x_ms_expiry_time__iterator = httpResponse.GetHeaders().find("x-ms-expiry-time");
if (x_ms_expiry_time__iterator != httpResponse.GetHeaders().end())
{
response.ExpiresOn = Azure::DateTime::Parse(
x_ms_expiry_time__iterator->second, Azure::DateTime::DateFormat::Rfc1123);
}
auto x_ms_last_access_time__iterator
= httpResponse.GetHeaders().find("x-ms-last-access-time");
if (x_ms_last_access_time__iterator != httpResponse.GetHeaders().end())
{
response.LastAccessedOn = Azure::DateTime::Parse(
x_ms_last_access_time__iterator->second, Azure::DateTime::DateFormat::Rfc1123);
}
for (auto i = httpResponse.GetHeaders().lower_bound("x-ms-meta-");
i != httpResponse.GetHeaders().end() && i->first.substr(0, 10) == "x-ms-meta-";
++i)
{
response.Metadata.emplace(i->first.substr(10), i->second);
}
response.BlobType = BlobType(httpResponse.GetHeaders().at("x-ms-blob-type"));
auto x_ms_lease_status__iterator = httpResponse.GetHeaders().find("x-ms-lease-status");
if (x_ms_lease_status__iterator != httpResponse.GetHeaders().end())
{
response.LeaseStatus = LeaseStatus(x_ms_lease_status__iterator->second);
}
auto x_ms_lease_state__iterator = httpResponse.GetHeaders().find("x-ms-lease-state");
if (x_ms_lease_state__iterator != httpResponse.GetHeaders().end())
{
response.LeaseState = LeaseState(x_ms_lease_state__iterator->second);
}
auto x_ms_lease_duration__iterator
= httpResponse.GetHeaders().find("x-ms-lease-duration");
if (x_ms_lease_duration__iterator != httpResponse.GetHeaders().end())
{
response.LeaseDuration = LeaseDurationType(x_ms_lease_duration__iterator->second);
}
response.BlobSize = std::stoll(httpResponse.GetHeaders().at("content-length"));
auto content_type__iterator = httpResponse.GetHeaders().find("content-type");
if (content_type__iterator != httpResponse.GetHeaders().end())
{
response.HttpHeaders.ContentType = content_type__iterator->second;
}
auto content_encoding__iterator = httpResponse.GetHeaders().find("content-encoding");
if (content_encoding__iterator != httpResponse.GetHeaders().end())
{
response.HttpHeaders.ContentEncoding = content_encoding__iterator->second;
}
auto content_language__iterator = httpResponse.GetHeaders().find("content-language");
if (content_language__iterator != httpResponse.GetHeaders().end())
{
response.HttpHeaders.ContentLanguage = content_language__iterator->second;
}
auto cache_control__iterator = httpResponse.GetHeaders().find("cache-control");
if (cache_control__iterator != httpResponse.GetHeaders().end())
{
response.HttpHeaders.CacheControl = cache_control__iterator->second;
}
auto content_md5__iterator = httpResponse.GetHeaders().find("content-md5");
if (content_md5__iterator != httpResponse.GetHeaders().end())
{
response.HttpHeaders.ContentHash.Value
= Azure::Core::Convert::Base64Decode(content_md5__iterator->second);
}
auto x_ms_blob_content_md5__iterator
= httpResponse.GetHeaders().find("x-ms-blob-content-md5");
if (x_ms_blob_content_md5__iterator != httpResponse.GetHeaders().end())
{
response.HttpHeaders.ContentHash.Value
= Azure::Core::Convert::Base64Decode(x_ms_blob_content_md5__iterator->second);
}
auto content_disposition__iterator
= httpResponse.GetHeaders().find("content-disposition");
if (content_disposition__iterator != httpResponse.GetHeaders().end())
{
response.HttpHeaders.ContentDisposition = content_disposition__iterator->second;
}
auto x_ms_blob_sequence_number__iterator
= httpResponse.GetHeaders().find("x-ms-blob-sequence-number");
if (x_ms_blob_sequence_number__iterator != httpResponse.GetHeaders().end())
{
response.SequenceNumber = std::stoll(x_ms_blob_sequence_number__iterator->second);
}
auto x_ms_blob_committed_block_count__iterator
= httpResponse.GetHeaders().find("x-ms-blob-committed-block-count");
if (x_ms_blob_committed_block_count__iterator != httpResponse.GetHeaders().end())
{
response.CommittedBlockCount
= std::stoi(x_ms_blob_committed_block_count__iterator->second);
}
auto x_ms_blob_sealed__iterator = httpResponse.GetHeaders().find("x-ms-blob-sealed");
if (x_ms_blob_sealed__iterator != httpResponse.GetHeaders().end())
{
response.IsSealed = x_ms_blob_sealed__iterator->second == "true";
}
response.IsServerEncrypted
= httpResponse.GetHeaders().at("x-ms-server-encrypted") == "true";
auto x_ms_encryption_key_sha256__iterator
= httpResponse.GetHeaders().find("x-ms-encryption-key-sha256");
if (x_ms_encryption_key_sha256__iterator != httpResponse.GetHeaders().end())
{
response.EncryptionKeySha256
= Azure::Core::Convert::Base64Decode(x_ms_encryption_key_sha256__iterator->second);
}
auto x_ms_encryption_scope__iterator
= httpResponse.GetHeaders().find("x-ms-encryption-scope");
if (x_ms_encryption_scope__iterator != httpResponse.GetHeaders().end())
{
response.EncryptionScope = x_ms_encryption_scope__iterator->second;
}
auto x_ms_access_tier__iterator = httpResponse.GetHeaders().find("x-ms-access-tier");
if (x_ms_access_tier__iterator != httpResponse.GetHeaders().end())
{
response.AccessTier = AccessTier(x_ms_access_tier__iterator->second);
}
auto x_ms_access_tier_inferred__iterator
= httpResponse.GetHeaders().find("x-ms-access-tier-inferred");
if (x_ms_access_tier_inferred__iterator != httpResponse.GetHeaders().end())
{
response.IsAccessTierInferred = x_ms_access_tier_inferred__iterator->second == "true";
}
auto x_ms_archive_status__iterator
= httpResponse.GetHeaders().find("x-ms-archive-status");
if (x_ms_archive_status__iterator != httpResponse.GetHeaders().end())
{
response.ArchiveStatus = ArchiveStatus(x_ms_archive_status__iterator->second);
}
auto x_ms_rehydrate_priority__iterator
= httpResponse.GetHeaders().find("x-ms-rehydrate-priority");
if (x_ms_rehydrate_priority__iterator != httpResponse.GetHeaders().end())
{
response.RehydratePriority
= RehydratePriority(x_ms_rehydrate_priority__iterator->second);
}
auto x_ms_access_tier_change_time__iterator
= httpResponse.GetHeaders().find("x-ms-access-tier-change-time");
if (x_ms_access_tier_change_time__iterator != httpResponse.GetHeaders().end())
{
response.AccessTierChangedOn = Azure::DateTime::Parse(
x_ms_access_tier_change_time__iterator->second,
Azure::DateTime::DateFormat::Rfc1123);
}
auto x_ms_copy_id__iterator = httpResponse.GetHeaders().find("x-ms-copy-id");
if (x_ms_copy_id__iterator != httpResponse.GetHeaders().end())
{
response.CopyId = x_ms_copy_id__iterator->second;
}
auto x_ms_copy_source__iterator = httpResponse.GetHeaders().find("x-ms-copy-source");
if (x_ms_copy_source__iterator != httpResponse.GetHeaders().end())
{
response.CopySource = x_ms_copy_source__iterator->second;
}
auto x_ms_copy_status__iterator = httpResponse.GetHeaders().find("x-ms-copy-status");
if (x_ms_copy_status__iterator != httpResponse.GetHeaders().end())
{
response.CopyStatus = CopyStatus(x_ms_copy_status__iterator->second);
}
auto x_ms_copy_status_description__iterator
= httpResponse.GetHeaders().find("x-ms-copy-status-description");
if (x_ms_copy_status_description__iterator != httpResponse.GetHeaders().end())
{
response.CopyStatusDescription = x_ms_copy_status_description__iterator->second;
}
auto x_ms_incremental_copy__iterator
= httpResponse.GetHeaders().find("x-ms-incremental-copy");
if (x_ms_incremental_copy__iterator != httpResponse.GetHeaders().end())
{
response.IsIncrementalCopy = x_ms_incremental_copy__iterator->second == "true";
}
auto x_ms_copy_destination_snapshot__iterator
= httpResponse.GetHeaders().find("x-ms-copy-destination-snapshot");
if (x_ms_copy_destination_snapshot__iterator != httpResponse.GetHeaders().end())
{
response.IncrementalCopyDestinationSnapshot
= x_ms_copy_destination_snapshot__iterator->second;
}
auto x_ms_copy_progress__iterator = httpResponse.GetHeaders().find("x-ms-copy-progress");
if (x_ms_copy_progress__iterator != httpResponse.GetHeaders().end())
{
response.CopyProgress = x_ms_copy_progress__iterator->second;
}
auto x_ms_copy_completion_time__iterator
= httpResponse.GetHeaders().find("x-ms-copy-completion-time");
if (x_ms_copy_completion_time__iterator != httpResponse.GetHeaders().end())
{
response.CopyCompletedOn = Azure::DateTime::Parse(
x_ms_copy_completion_time__iterator->second, Azure::DateTime::DateFormat::Rfc1123);
}
auto x_ms_or_policy_id__iterator = httpResponse.GetHeaders().find("x-ms-or-policy-id");
if (x_ms_or_policy_id__iterator != httpResponse.GetHeaders().end())
{
response.ObjectReplicationDestinationPolicyId = x_ms_or_policy_id__iterator->second;
}
{
std::map<std::string, std::vector<ObjectReplicationRule>> orPropertiesMap;
for (auto i = httpResponse.GetHeaders().lower_bound("x-ms-or-");
i != httpResponse.GetHeaders().end() && i->first.substr(0, 8) == "x-ms-or-";
++i)
{
const std::string& header = i->first;
auto underscorePos = header.find('_', 8);
if (underscorePos == std::string::npos)
{
continue;
}
std::string policyId
= std::string(header.begin() + 8, header.begin() + underscorePos);
std::string ruleId = header.substr(underscorePos + 1);
ObjectReplicationRule rule;
rule.RuleId = std::move(ruleId);
rule.ReplicationStatus = ObjectReplicationStatus(i->second);
orPropertiesMap[policyId].emplace_back(std::move(rule));
}
for (auto& property : orPropertiesMap)
{
ObjectReplicationPolicy policy;
policy.PolicyId = property.first;
policy.Rules = std::move(property.second);
response.ObjectReplicationSourceProperties.emplace_back(std::move(policy));
}
}
auto x_ms_tag_count__iterator = httpResponse.GetHeaders().find("x-ms-tag-count");
if (x_ms_tag_count__iterator != httpResponse.GetHeaders().end())
{
response.TagCount = std::stoi(x_ms_tag_count__iterator->second);
}
auto x_ms_version_id__iterator = httpResponse.GetHeaders().find("x-ms-version-id");
if (x_ms_version_id__iterator != httpResponse.GetHeaders().end())
{
response.VersionId = x_ms_version_id__iterator->second;
}
auto x_ms_is_current_version__iterator
= httpResponse.GetHeaders().find("x-ms-is-current-version");
if (x_ms_is_current_version__iterator != httpResponse.GetHeaders().end())
{
response.IsCurrentVersion = x_ms_is_current_version__iterator->second == "true";
}
return Azure::Response<BlobProperties>(std::move(response), std::move(pHttpResponse));
}
struct SetBlobHttpHeadersOptions final
{
Azure::Nullable<int32_t> Timeout;
BlobHttpHeaders HttpHeaders;
Azure::Nullable<std::string> LeaseId;
Azure::Nullable<Azure::DateTime> IfModifiedSince;
Azure::Nullable<Azure::DateTime> IfUnmodifiedSince;
Azure::ETag IfMatch;
Azure::ETag IfNoneMatch;
Azure::Nullable<std::string> IfTags;
}; // struct SetBlobHttpHeadersOptions
static Azure::Response<SetBlobHttpHeadersResult> SetHttpHeaders(
Azure::Core::Http::_internal::HttpPipeline& pipeline,
const Azure::Core::Url& url,
const SetBlobHttpHeadersOptions& options,
const Azure::Core::Context& context)
{
auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Put, url);
request.SetHeader("Content-Length", "0");
request.GetUrl().AppendQueryParameter("comp", "properties");
request.SetHeader("x-ms-version", "2020-02-10");
if (options.Timeout.HasValue())
{
request.GetUrl().AppendQueryParameter(
"timeout", std::to_string(options.Timeout.Value()));
}
if (!options.HttpHeaders.ContentType.empty())
{
request.SetHeader("x-ms-blob-content-type", options.HttpHeaders.ContentType);
}
if (!options.HttpHeaders.ContentEncoding.empty())
{
request.SetHeader("x-ms-blob-content-encoding", options.HttpHeaders.ContentEncoding);
}
if (!options.HttpHeaders.ContentLanguage.empty())
{
request.SetHeader("x-ms-blob-content-language", options.HttpHeaders.ContentLanguage);
}
if (!options.HttpHeaders.CacheControl.empty())
{
request.SetHeader("x-ms-blob-cache-control", options.HttpHeaders.CacheControl);
}
if (!Azure::Core::Convert::Base64Encode(options.HttpHeaders.ContentHash.Value).empty())
{
request.SetHeader(
"x-ms-blob-content-md5",
Azure::Core::Convert::Base64Encode(options.HttpHeaders.ContentHash.Value));
}
if (!options.HttpHeaders.ContentDisposition.empty())
{
request.SetHeader(
"x-ms-blob-content-disposition", options.HttpHeaders.ContentDisposition);
}
if (options.LeaseId.HasValue())
{
request.SetHeader("x-ms-lease-id", options.LeaseId.Value());
}
if (options.IfModifiedSince.HasValue())
{
request.SetHeader(
"If-Modified-Since",
options.IfModifiedSince.Value().ToString(Azure::DateTime::DateFormat::Rfc1123));
}
if (options.IfUnmodifiedSince.HasValue())
{
request.SetHeader(
"If-Unmodified-Since",
options.IfUnmodifiedSince.Value().ToString(Azure::DateTime::DateFormat::Rfc1123));
}
if (options.IfMatch.HasValue() && !options.IfMatch.ToString().empty())
{
request.SetHeader("If-Match", options.IfMatch.ToString());
}
if (options.IfNoneMatch.HasValue() && !options.IfNoneMatch.ToString().empty())
{
request.SetHeader("If-None-Match", options.IfNoneMatch.ToString());
}
if (options.IfTags.HasValue())
{
request.SetHeader("x-ms-if-tags", options.IfTags.Value());
}
auto pHttpResponse = pipeline.Send(request, context);
Azure::Core::Http::RawResponse& httpResponse = *pHttpResponse;
SetBlobHttpHeadersResult response;
auto http_status_code = httpResponse.GetStatusCode();
if (http_status_code != Azure::Core::Http::HttpStatusCode::Ok)
{
throw StorageException::CreateFromResponse(std::move(pHttpResponse));
}
response.ETag = Azure::ETag(httpResponse.GetHeaders().at("etag"));
response.LastModified = Azure::DateTime::Parse(
httpResponse.GetHeaders().at("last-modified"), Azure::DateTime::DateFormat::Rfc1123);
auto x_ms_blob_sequence_number__iterator
= httpResponse.GetHeaders().find("x-ms-blob-sequence-number");
if (x_ms_blob_sequence_number__iterator != httpResponse.GetHeaders().end())
{
response.SequenceNumber = std::stoll(x_ms_blob_sequence_number__iterator->second);
}
return Azure::Response<SetBlobHttpHeadersResult>(
std::move(response), std::move(pHttpResponse));
}
struct SetBlobMetadataOptions final
{
Azure::Nullable<int32_t> Timeout;
Storage::Metadata Metadata;
Azure::Nullable<std::string> EncryptionKey;
Azure::Nullable<std::vector<uint8_t>> EncryptionKeySha256;
Azure::Nullable<EncryptionAlgorithmType> EncryptionAlgorithm;
Azure::Nullable<std::string> EncryptionScope;
Azure::Nullable<std::string> LeaseId;
Azure::Nullable<Azure::DateTime> IfModifiedSince;
Azure::Nullable<Azure::DateTime> IfUnmodifiedSince;
Azure::ETag IfMatch;
Azure::ETag IfNoneMatch;
Azure::Nullable<std::string> IfTags;
}; // struct SetBlobMetadataOptions
static Azure::Response<SetBlobMetadataResult> SetMetadata(
Azure::Core::Http::_internal::HttpPipeline& pipeline,
const Azure::Core::Url& url,
const SetBlobMetadataOptions& options,
const Azure::Core::Context& context)
{
auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Put, url);
request.SetHeader("Content-Length", "0");
request.GetUrl().AppendQueryParameter("comp", "metadata");
request.SetHeader("x-ms-version", "2020-02-10");
if (options.Timeout.HasValue())
{
request.GetUrl().AppendQueryParameter(
"timeout", std::to_string(options.Timeout.Value()));
}
for (const auto& pair : options.Metadata)
{
request.SetHeader("x-ms-meta-" + pair.first, pair.second);
}
if (options.EncryptionKey.HasValue())
{
request.SetHeader("x-ms-encryption-key", options.EncryptionKey.Value());
}
if (options.EncryptionKeySha256.HasValue())
{
request.SetHeader(
"x-ms-encryption-key-sha256",
Azure::Core::Convert::Base64Encode(options.EncryptionKeySha256.Value()));
}
if (options.EncryptionAlgorithm.HasValue())
{
request.SetHeader(
"x-ms-encryption-algorithm", options.EncryptionAlgorithm.Value().ToString());
}
if (options.EncryptionScope.HasValue())
{
request.SetHeader("x-ms-encryption-scope", options.EncryptionScope.Value());
}
if (options.LeaseId.HasValue())
{
request.SetHeader("x-ms-lease-id", options.LeaseId.Value());
}
if (options.IfModifiedSince.HasValue())
{
request.SetHeader(
"If-Modified-Since",
options.IfModifiedSince.Value().ToString(Azure::DateTime::DateFormat::Rfc1123));
}
if (options.IfUnmodifiedSince.HasValue())
{
request.SetHeader(
"If-Unmodified-Since",
options.IfUnmodifiedSince.Value().ToString(Azure::DateTime::DateFormat::Rfc1123));
}
if (options.IfMatch.HasValue() && !options.IfMatch.ToString().empty())
{
request.SetHeader("If-Match", options.IfMatch.ToString());
}
if (options.IfNoneMatch.HasValue() && !options.IfNoneMatch.ToString().empty())
{
request.SetHeader("If-None-Match", options.IfNoneMatch.ToString());
}
if (options.IfTags.HasValue())
{
request.SetHeader("x-ms-if-tags", options.IfTags.Value());
}
auto pHttpResponse = pipeline.Send(request, context);
Azure::Core::Http::RawResponse& httpResponse = *pHttpResponse;
SetBlobMetadataResult response;
auto http_status_code = httpResponse.GetStatusCode();
if (http_status_code != Azure::Core::Http::HttpStatusCode::Ok)
{
throw StorageException::CreateFromResponse(std::move(pHttpResponse));
}
response.ETag = Azure::ETag(httpResponse.GetHeaders().at("etag"));
response.LastModified = Azure::DateTime::Parse(
httpResponse.GetHeaders().at("last-modified"), Azure::DateTime::DateFormat::Rfc1123);
auto x_ms_blob_sequence_number__iterator
= httpResponse.GetHeaders().find("x-ms-blob-sequence-number");
if (x_ms_blob_sequence_number__iterator != httpResponse.GetHeaders().end())
{
response.SequenceNumber = std::stoll(x_ms_blob_sequence_number__iterator->second);
}
response.IsServerEncrypted
= httpResponse.GetHeaders().at("x-ms-request-server-encrypted") == "true";
auto x_ms_encryption_key_sha256__iterator
= httpResponse.GetHeaders().find("x-ms-encryption-key-sha256");
if (x_ms_encryption_key_sha256__iterator != httpResponse.GetHeaders().end())
{
response.EncryptionKeySha256
= Azure::Core::Convert::Base64Decode(x_ms_encryption_key_sha256__iterator->second);
}
auto x_ms_encryption_scope__iterator
= httpResponse.GetHeaders().find("x-ms-encryption-scope");
if (x_ms_encryption_scope__iterator != httpResponse.GetHeaders().end())
{
response.EncryptionScope = x_ms_encryption_scope__iterator->second;
}
return Azure::Response<SetBlobMetadataResult>(
std::move(response), std::move(pHttpResponse));
}
struct SetBlobAccessTierOptions final
{
Azure::Nullable<int32_t> Timeout;
Models::AccessTier AccessTier;
Azure::Nullable<Models::RehydratePriority> RehydratePriority;
Azure::Nullable<std::string> LeaseId;
Azure::Nullable<std::string> IfTags;
}; // struct SetBlobAccessTierOptions
static Azure::Core::Http::Request SetAccessTierCreateMessage(
const Azure::Core::Url& url,
const SetBlobAccessTierOptions& options)
{
auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Put, url);
request.SetHeader("Content-Length", "0");
request.GetUrl().AppendQueryParameter("comp", "tier");
request.SetHeader("x-ms-version", "2020-02-10");
if (options.Timeout.HasValue())
{
request.GetUrl().AppendQueryParameter(
"timeout", std::to_string(options.Timeout.Value()));
}
request.SetHeader("x-ms-access-tier", options.AccessTier.ToString());
if (options.RehydratePriority.HasValue())
{
request.SetHeader(
"x-ms-rehydrate-priority", options.RehydratePriority.Value().ToString());
}
if (options.LeaseId.HasValue())
{
request.SetHeader("x-ms-lease-id", options.LeaseId.Value());
}
if (options.IfTags.HasValue())
{
request.SetHeader("x-ms-if-tags", options.IfTags.Value());
}
return request;
}
static Azure::Response<SetBlobAccessTierResult> SetAccessTierCreateResponse(
std::unique_ptr<Azure::Core::Http::RawResponse> pHttpResponse,
const Azure::Core::Context& context)
{
(void)context;
Azure::Core::Http::RawResponse& httpResponse = *pHttpResponse;
SetBlobAccessTierResult response;
auto http_status_code = httpResponse.GetStatusCode();
if (!(http_status_code == Azure::Core::Http::HttpStatusCode::Ok
|| http_status_code == Azure::Core::Http::HttpStatusCode::Accepted))
{
throw StorageException::CreateFromResponse(std::move(pHttpResponse));
}
return Azure::Response<SetBlobAccessTierResult>(
std::move(response), std::move(pHttpResponse));
}
static Azure::Response<SetBlobAccessTierResult> SetAccessTier(
Azure::Core::Http::_internal::HttpPipeline& pipeline,
const Azure::Core::Url& url,
const SetBlobAccessTierOptions& options,
const Azure::Core::Context& context)
{
auto request = SetAccessTierCreateMessage(url, options);
auto pHttpResponse = pipeline.Send(request, context);
return SetAccessTierCreateResponse(std::move(pHttpResponse), context);
}
struct StartBlobCopyFromUriOptions final
{
Azure::Nullable<int32_t> Timeout;
Storage::Metadata Metadata;
std::map<std::string, std::string> Tags;
std::string SourceUri;
Azure::Nullable<std::string> LeaseId;
Azure::Nullable<Models::AccessTier> AccessTier;
Azure::Nullable<Models::RehydratePriority> RehydratePriority;
Azure::Nullable<Azure::DateTime> IfModifiedSince;
Azure::Nullable<Azure::DateTime> IfUnmodifiedSince;
Azure::ETag IfMatch;
Azure::ETag IfNoneMatch;
Azure::Nullable<std::string> IfTags;
Azure::Nullable<Azure::DateTime> SourceIfModifiedSince;
Azure::Nullable<Azure::DateTime> SourceIfUnmodifiedSince;
Azure::ETag SourceIfMatch;
Azure::ETag SourceIfNoneMatch;
Azure::Nullable<std::string> SourceIfTags;
Azure::Nullable<std::string> SourceLeaseId;
Azure::Nullable<bool> ShouldSealDestination;
}; // struct StartBlobCopyFromUriOptions
static Azure::Response<Models::_detail::StartBlobCopyFromUriResult> StartCopyFromUri(
Azure::Core::Http::_internal::HttpPipeline& pipeline,
const Azure::Core::Url& url,
const StartBlobCopyFromUriOptions& options,
const Azure::Core::Context& context)
{
auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Put, url);
request.SetHeader("Content-Length", "0");
request.SetHeader("x-ms-version", "2020-02-10");
if (options.Timeout.HasValue())
{
request.GetUrl().AppendQueryParameter(
"timeout", std::to_string(options.Timeout.Value()));
}
for (const auto& pair : options.Metadata)
{
request.SetHeader("x-ms-meta-" + pair.first, pair.second);
}
if (!options.Tags.empty())
{
std::string blobTagsValue;
for (const auto& tag : options.Tags)
{
if (!blobTagsValue.empty())
{
blobTagsValue += "&";
}
blobTagsValue += _internal::UrlEncodeQueryParameter(tag.first) + "="
+ _internal::UrlEncodeQueryParameter(tag.second);
}
request.SetHeader("x-ms-tags", std::move(blobTagsValue));
}
request.SetHeader("x-ms-copy-source", options.SourceUri);
if (options.LeaseId.HasValue())
{
request.SetHeader("x-ms-lease-id", options.LeaseId.Value());
}
if (options.AccessTier.HasValue())
{
request.SetHeader("x-ms-access-tier", options.AccessTier.Value().ToString());
}
if (options.RehydratePriority.HasValue())
{
request.SetHeader(
"x-ms-rehydrate-priority", options.RehydratePriority.Value().ToString());
}
if (options.ShouldSealDestination.HasValue())
{
request.SetHeader(
"x-ms-seal-blob", options.ShouldSealDestination.Value() ? "true" : "false");
}
if (options.IfModifiedSince.HasValue())
{
request.SetHeader(
"If-Modified-Since",
options.IfModifiedSince.Value().ToString(Azure::DateTime::DateFormat::Rfc1123));
}
if (options.IfUnmodifiedSince.HasValue())
{
request.SetHeader(
"If-Unmodified-Since",
options.IfUnmodifiedSince.Value().ToString(Azure::DateTime::DateFormat::Rfc1123));
}
if (options.IfMatch.HasValue() && !options.IfMatch.ToString().empty())
{
request.SetHeader("If-Match", options.IfMatch.ToString());
}
if (options.IfNoneMatch.HasValue() && !options.IfNoneMatch.ToString().empty())
{
request.SetHeader("If-None-Match", options.IfNoneMatch.ToString());
}
if (options.IfTags.HasValue())
{
request.SetHeader("x-ms-if-tags", options.IfTags.Value());
}
if (options.SourceIfModifiedSince.HasValue())
{
request.SetHeader(
"x-ms-source-if-modified-since",
options.SourceIfModifiedSince.Value().ToString(
Azure::DateTime::DateFormat::Rfc1123));
}
if (options.SourceIfUnmodifiedSince.HasValue())
{
request.SetHeader(
"x-ms-source-if-unmodified-since",
options.SourceIfUnmodifiedSince.Value().ToString(
Azure::DateTime::DateFormat::Rfc1123));
}
if (options.SourceIfMatch.HasValue() && !options.SourceIfMatch.ToString().empty())
{
request.SetHeader("x-ms-source-if-match", options.SourceIfMatch.ToString());
}
if (options.SourceIfNoneMatch.HasValue() && !options.SourceIfNoneMatch.ToString().empty())
{
request.SetHeader("x-ms-source-if-none-match", options.SourceIfNoneMatch.ToString());
}
if (options.SourceIfTags.HasValue())
{
request.SetHeader("x-ms-source-if-tags", options.SourceIfTags.Value());
}
if (options.SourceLeaseId.HasValue())
{
request.SetHeader("x-ms-source-lease-id", options.SourceLeaseId.Value());
}
auto pHttpResponse = pipeline.Send(request, context);
Azure::Core::Http::RawResponse& httpResponse = *pHttpResponse;
Models::_detail::StartBlobCopyFromUriResult response;
auto http_status_code = httpResponse.GetStatusCode();
if (http_status_code != Azure::Core::Http::HttpStatusCode::Accepted)
{
throw StorageException::CreateFromResponse(std::move(pHttpResponse));
}
response.ETag = Azure::ETag(httpResponse.GetHeaders().at("etag"));
response.LastModified = Azure::DateTime::Parse(
httpResponse.GetHeaders().at("last-modified"), Azure::DateTime::DateFormat::Rfc1123);
response.CopyId = httpResponse.GetHeaders().at("x-ms-copy-id");
response.CopyStatus = CopyStatus(httpResponse.GetHeaders().at("x-ms-copy-status"));
auto x_ms_version_id__iterator = httpResponse.GetHeaders().find("x-ms-version-id");
if (x_ms_version_id__iterator != httpResponse.GetHeaders().end())
{
response.VersionId = x_ms_version_id__iterator->second;
}
return Azure::Response<Models::_detail::StartBlobCopyFromUriResult>(
std::move(response), std::move(pHttpResponse));
}
struct AbortBlobCopyFromUriOptions final
{
Azure::Nullable<int32_t> Timeout;
std::string CopyId;
Azure::Nullable<std::string> LeaseId;
}; // struct AbortBlobCopyFromUriOptions
static Azure::Response<AbortBlobCopyFromUriResult> AbortCopyFromUri(
Azure::Core::Http::_internal::HttpPipeline& pipeline,
const Azure::Core::Url& url,
const AbortBlobCopyFromUriOptions& options,
const Azure::Core::Context& context)
{
auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Put, url);
request.SetHeader("Content-Length", "0");
request.SetHeader("x-ms-version", "2020-02-10");
if (options.Timeout.HasValue())
{
request.GetUrl().AppendQueryParameter(
"timeout", std::to_string(options.Timeout.Value()));
}
request.GetUrl().AppendQueryParameter("comp", "copy");
request.GetUrl().AppendQueryParameter(
"copyid", _internal::UrlEncodeQueryParameter(options.CopyId));
request.SetHeader("x-ms-copy-action", "abort");
if (options.LeaseId.HasValue())
{
request.SetHeader("x-ms-lease-id", options.LeaseId.Value());
}
auto pHttpResponse = pipeline.Send(request, context);
Azure::Core::Http::RawResponse& httpResponse = *pHttpResponse;
AbortBlobCopyFromUriResult response;
auto http_status_code = httpResponse.GetStatusCode();
if (http_status_code != Azure::Core::Http::HttpStatusCode::NoContent)
{
throw StorageException::CreateFromResponse(std::move(pHttpResponse));
}
return Azure::Response<AbortBlobCopyFromUriResult>(
std::move(response), std::move(pHttpResponse));
}
struct CreateBlobSnapshotOptions final
{
Azure::Nullable<int32_t> Timeout;
Storage::Metadata Metadata;
Azure::Nullable<std::string> LeaseId;
Azure::Nullable<std::string> EncryptionKey;
Azure::Nullable<std::vector<uint8_t>> EncryptionKeySha256;
Azure::Nullable<EncryptionAlgorithmType> EncryptionAlgorithm;
Azure::Nullable<std::string> EncryptionScope;
Azure::Nullable<Azure::DateTime> IfModifiedSince;
Azure::Nullable<Azure::DateTime> IfUnmodifiedSince;
Azure::ETag IfMatch;
Azure::ETag IfNoneMatch;
Azure::Nullable<std::string> IfTags;
}; // struct CreateBlobSnapshotOptions
static Azure::Response<CreateBlobSnapshotResult> CreateSnapshot(
Azure::Core::Http::_internal::HttpPipeline& pipeline,
const Azure::Core::Url& url,
const CreateBlobSnapshotOptions& options,
const Azure::Core::Context& context)
{
auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Put, url);
request.SetHeader("Content-Length", "0");
request.GetUrl().AppendQueryParameter("comp", "snapshot");
request.SetHeader("x-ms-version", "2020-02-10");
if (options.Timeout.HasValue())
{
request.GetUrl().AppendQueryParameter(
"timeout", std::to_string(options.Timeout.Value()));
}
if (options.EncryptionKey.HasValue())
{
request.SetHeader("x-ms-encryption-key", options.EncryptionKey.Value());
}
if (options.EncryptionKeySha256.HasValue())
{
request.SetHeader(
"x-ms-encryption-key-sha256",
Azure::Core::Convert::Base64Encode(options.EncryptionKeySha256.Value()));
}
if (options.EncryptionAlgorithm.HasValue())
{
request.SetHeader(
"x-ms-encryption-algorithm", options.EncryptionAlgorithm.Value().ToString());
}
if (options.EncryptionScope.HasValue())
{
request.SetHeader("x-ms-encryption-scope", options.EncryptionScope.Value());
}
for (const auto& pair : options.Metadata)
{
request.SetHeader("x-ms-meta-" + pair.first, pair.second);
}
if (options.LeaseId.HasValue())
{
request.SetHeader("x-ms-lease-id", options.LeaseId.Value());
}
if (options.IfModifiedSince.HasValue())
{
request.SetHeader(
"If-Modified-Since",
options.IfModifiedSince.Value().ToString(Azure::DateTime::DateFormat::Rfc1123));
}
if (options.IfUnmodifiedSince.HasValue())
{
request.SetHeader(
"If-Unmodified-Since",
options.IfUnmodifiedSince.Value().ToString(Azure::DateTime::DateFormat::Rfc1123));
}
if (options.IfMatch.HasValue() && !options.IfMatch.ToString().empty())
{
request.SetHeader("If-Match", options.IfMatch.ToString());
}
if (options.IfNoneMatch.HasValue() && !options.IfNoneMatch.ToString().empty())
{
request.SetHeader("If-None-Match", options.IfNoneMatch.ToString());
}
if (options.IfTags.HasValue())
{
request.SetHeader("x-ms-if-tags", options.IfTags.Value());
}
auto pHttpResponse = pipeline.Send(request, context);
Azure::Core::Http::RawResponse& httpResponse = *pHttpResponse;
CreateBlobSnapshotResult response;
auto http_status_code = httpResponse.GetStatusCode();
if (http_status_code != Azure::Core::Http::HttpStatusCode::Created)
{
throw StorageException::CreateFromResponse(std::move(pHttpResponse));
}
response.ETag = Azure::ETag(httpResponse.GetHeaders().at("etag"));
response.LastModified = Azure::DateTime::Parse(
httpResponse.GetHeaders().at("last-modified"), Azure::DateTime::DateFormat::Rfc1123);
response.IsServerEncrypted
= httpResponse.GetHeaders().at("x-ms-request-server-encrypted") == "true";
auto x_ms_encryption_key_sha256__iterator
= httpResponse.GetHeaders().find("x-ms-encryption-key-sha256");
if (x_ms_encryption_key_sha256__iterator != httpResponse.GetHeaders().end())
{
response.EncryptionKeySha256
= Azure::Core::Convert::Base64Decode(x_ms_encryption_key_sha256__iterator->second);
}
auto x_ms_encryption_scope__iterator
= httpResponse.GetHeaders().find("x-ms-encryption-scope");
if (x_ms_encryption_scope__iterator != httpResponse.GetHeaders().end())
{
response.EncryptionScope = x_ms_encryption_scope__iterator->second;
}
response.Snapshot = httpResponse.GetHeaders().at("x-ms-snapshot");
auto x_ms_version_id__iterator = httpResponse.GetHeaders().find("x-ms-version-id");
if (x_ms_version_id__iterator != httpResponse.GetHeaders().end())
{
response.VersionId = x_ms_version_id__iterator->second;
}
return Azure::Response<CreateBlobSnapshotResult>(
std::move(response), std::move(pHttpResponse));
}
struct GetBlobTagsOptions final
{
Azure::Nullable<int32_t> Timeout;
Azure::Nullable<std::string> IfTags;
}; // struct GetBlobTagsOptions
static Azure::Response<Models::_detail::GetBlobTagsResult> GetTags(
Azure::Core::Http::_internal::HttpPipeline& pipeline,
const Azure::Core::Url& url,
const GetBlobTagsOptions& options,
const Azure::Core::Context& context)
{
auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Get, url);
request.SetHeader("x-ms-version", "2020-02-10");
if (options.Timeout.HasValue())
{
request.GetUrl().AppendQueryParameter(
"timeout", std::to_string(options.Timeout.Value()));
}
request.GetUrl().AppendQueryParameter("comp", "tags");
if (options.IfTags.HasValue())
{
request.SetHeader("x-ms-if-tags", options.IfTags.Value());
}
auto pHttpResponse = pipeline.Send(request, context);
Azure::Core::Http::RawResponse& httpResponse = *pHttpResponse;
Models::_detail::GetBlobTagsResult response;
auto http_status_code = httpResponse.GetStatusCode();
if (http_status_code != Azure::Core::Http::HttpStatusCode::Ok)
{
throw StorageException::CreateFromResponse(std::move(pHttpResponse));
}
{
const auto& httpResponseBody = httpResponse.GetBody();
_internal::XmlReader reader(
reinterpret_cast<const char*>(httpResponseBody.data()), httpResponseBody.size());
response = GetBlobTagsResultInternalFromXml(reader);
}
return Azure::Response<Models::_detail::GetBlobTagsResult>(
std::move(response), std::move(pHttpResponse));
}
struct SetBlobTagsOptions final
{
Azure::Nullable<int32_t> Timeout;
std::map<std::string, std::string> Tags;
Azure::Nullable<std::string> IfTags;
}; // struct SetBlobTagsOptions
static Azure::Response<SetBlobTagsResult> SetTags(
Azure::Core::Http::_internal::HttpPipeline& pipeline,
const Azure::Core::Url& url,
const SetBlobTagsOptions& options,
const Azure::Core::Context& context)
{
std::string xml_body;
{
_internal::XmlWriter writer;
SetBlobTagsOptionsToXml(writer, options);
xml_body = writer.GetDocument();
writer.Write(_internal::XmlNode{_internal::XmlNodeType::End});
}
Azure::Core::IO::MemoryBodyStream xml_body_stream(
reinterpret_cast<const uint8_t*>(xml_body.data()), xml_body.length());
auto request = Azure::Core::Http::Request(
Azure::Core::Http::HttpMethod::Put, url, &xml_body_stream);
request.SetHeader("Content-Length", std::to_string(xml_body_stream.Length()));
request.SetHeader("x-ms-version", "2020-02-10");
if (options.Timeout.HasValue())
{
request.GetUrl().AppendQueryParameter(
"timeout", std::to_string(options.Timeout.Value()));
}
request.GetUrl().AppendQueryParameter("comp", "tags");
request.SetHeader("Content-Type", "application/xml; charset=UTF-8");
if (options.IfTags.HasValue())
{
request.SetHeader("x-ms-if-tags", options.IfTags.Value());
}
auto pHttpResponse = pipeline.Send(request, context);
Azure::Core::Http::RawResponse& httpResponse = *pHttpResponse;
SetBlobTagsResult response;
auto http_status_code = httpResponse.GetStatusCode();
if (http_status_code != Azure::Core::Http::HttpStatusCode::NoContent)
{
throw StorageException::CreateFromResponse(std::move(pHttpResponse));
}
return Azure::Response<SetBlobTagsResult>(std::move(response), std::move(pHttpResponse));
}
struct AcquireBlobLeaseOptions final
{
Azure::Nullable<int32_t> Timeout;
std::chrono::seconds LeaseDuration;
Azure::Nullable<std::string> ProposedLeaseId;
Azure::Nullable<Azure::DateTime> IfModifiedSince;
Azure::Nullable<Azure::DateTime> IfUnmodifiedSince;
Azure::ETag IfMatch;
Azure::ETag IfNoneMatch;
Azure::Nullable<std::string> IfTags;
}; // struct AcquireBlobLeaseOptions
static Azure::Response<Models::_detail::AcquireBlobLeaseResult> AcquireLease(
Azure::Core::Http::_internal::HttpPipeline& pipeline,
const Azure::Core::Url& url,
const AcquireBlobLeaseOptions& options,
const Azure::Core::Context& context)
{
auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Put, url);
request.SetHeader("Content-Length", "0");
request.SetHeader("x-ms-version", "2020-02-10");
if (options.Timeout.HasValue())
{
request.GetUrl().AppendQueryParameter(
"timeout", std::to_string(options.Timeout.Value()));
}
request.GetUrl().AppendQueryParameter("comp", "lease");
request.SetHeader("x-ms-lease-action", "acquire");
request.SetHeader("x-ms-lease-duration", std::to_string(options.LeaseDuration.count()));
if (options.ProposedLeaseId.HasValue())
{
request.SetHeader("x-ms-proposed-lease-id", options.ProposedLeaseId.Value());
}
if (options.IfModifiedSince.HasValue())
{
request.SetHeader(
"If-Modified-Since",
options.IfModifiedSince.Value().ToString(Azure::DateTime::DateFormat::Rfc1123));
}
if (options.IfUnmodifiedSince.HasValue())
{
request.SetHeader(
"If-Unmodified-Since",
options.IfUnmodifiedSince.Value().ToString(Azure::DateTime::DateFormat::Rfc1123));
}
if (options.IfMatch.HasValue() && !options.IfMatch.ToString().empty())
{
request.SetHeader("If-Match", options.IfMatch.ToString());
}
if (options.IfNoneMatch.HasValue() && !options.IfNoneMatch.ToString().empty())
{
request.SetHeader("If-None-Match", options.IfNoneMatch.ToString());
}
if (options.IfTags.HasValue())
{
request.SetHeader("x-ms-if-tags", options.IfTags.Value());
}
auto pHttpResponse = pipeline.Send(request, context);
Azure::Core::Http::RawResponse& httpResponse = *pHttpResponse;
Models::_detail::AcquireBlobLeaseResult response;
auto http_status_code = httpResponse.GetStatusCode();
if (http_status_code != Azure::Core::Http::HttpStatusCode::Created)
{
throw StorageException::CreateFromResponse(std::move(pHttpResponse));
}
response.ETag = Azure::ETag(httpResponse.GetHeaders().at("etag"));
response.LastModified = Azure::DateTime::Parse(
httpResponse.GetHeaders().at("last-modified"), Azure::DateTime::DateFormat::Rfc1123);
response.LeaseId = httpResponse.GetHeaders().at("x-ms-lease-id");
return Azure::Response<Models::_detail::AcquireBlobLeaseResult>(
std::move(response), std::move(pHttpResponse));
}
struct RenewBlobLeaseOptions final
{
Azure::Nullable<int32_t> Timeout;
std::string LeaseId;
Azure::Nullable<Azure::DateTime> IfModifiedSince;
Azure::Nullable<Azure::DateTime> IfUnmodifiedSince;
Azure::ETag IfMatch;
Azure::ETag IfNoneMatch;
Azure::Nullable<std::string> IfTags;
}; // struct RenewBlobLeaseOptions
static Azure::Response<Models::_detail::RenewBlobLeaseResult> RenewLease(
Azure::Core::Http::_internal::HttpPipeline& pipeline,
const Azure::Core::Url& url,
const RenewBlobLeaseOptions& options,
const Azure::Core::Context& context)
{
auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Put, url);
request.SetHeader("Content-Length", "0");
request.SetHeader("x-ms-version", "2020-02-10");
if (options.Timeout.HasValue())
{
request.GetUrl().AppendQueryParameter(
"timeout", std::to_string(options.Timeout.Value()));
}
request.GetUrl().AppendQueryParameter("comp", "lease");
request.SetHeader("x-ms-lease-action", "renew");
request.SetHeader("x-ms-lease-id", options.LeaseId);
if (options.IfModifiedSince.HasValue())
{
request.SetHeader(
"If-Modified-Since",
options.IfModifiedSince.Value().ToString(Azure::DateTime::DateFormat::Rfc1123));
}
if (options.IfUnmodifiedSince.HasValue())
{
request.SetHeader(
"If-Unmodified-Since",
options.IfUnmodifiedSince.Value().ToString(Azure::DateTime::DateFormat::Rfc1123));
}
if (options.IfMatch.HasValue() && !options.IfMatch.ToString().empty())
{
request.SetHeader("If-Match", options.IfMatch.ToString());
}
if (options.IfNoneMatch.HasValue() && !options.IfNoneMatch.ToString().empty())
{
request.SetHeader("If-None-Match", options.IfNoneMatch.ToString());
}
if (options.IfTags.HasValue())
{
request.SetHeader("x-ms-if-tags", options.IfTags.Value());
}
auto pHttpResponse = pipeline.Send(request, context);
Azure::Core::Http::RawResponse& httpResponse = *pHttpResponse;
Models::_detail::RenewBlobLeaseResult response;
auto http_status_code = httpResponse.GetStatusCode();
if (http_status_code != Azure::Core::Http::HttpStatusCode::Ok)
{
throw StorageException::CreateFromResponse(std::move(pHttpResponse));
}
response.ETag = Azure::ETag(httpResponse.GetHeaders().at("etag"));
response.LastModified = Azure::DateTime::Parse(
httpResponse.GetHeaders().at("last-modified"), Azure::DateTime::DateFormat::Rfc1123);
response.LeaseId = httpResponse.GetHeaders().at("x-ms-lease-id");
return Azure::Response<Models::_detail::RenewBlobLeaseResult>(
std::move(response), std::move(pHttpResponse));
}
struct ChangeBlobLeaseOptions final
{
Azure::Nullable<int32_t> Timeout;
std::string LeaseId;
std::string ProposedLeaseId;
Azure::Nullable<Azure::DateTime> IfModifiedSince;
Azure::Nullable<Azure::DateTime> IfUnmodifiedSince;
Azure::ETag IfMatch;
Azure::ETag IfNoneMatch;
Azure::Nullable<std::string> IfTags;
}; // struct ChangeBlobLeaseOptions
static Azure::Response<Models::_detail::ChangeBlobLeaseResult> ChangeLease(
Azure::Core::Http::_internal::HttpPipeline& pipeline,
const Azure::Core::Url& url,
const ChangeBlobLeaseOptions& options,
const Azure::Core::Context& context)
{
auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Put, url);
request.SetHeader("Content-Length", "0");
request.SetHeader("x-ms-version", "2020-02-10");
if (options.Timeout.HasValue())
{
request.GetUrl().AppendQueryParameter(
"timeout", std::to_string(options.Timeout.Value()));
}
request.GetUrl().AppendQueryParameter("comp", "lease");
request.SetHeader("x-ms-lease-action", "change");
request.SetHeader("x-ms-lease-id", options.LeaseId);
request.SetHeader("x-ms-proposed-lease-id", options.ProposedLeaseId);
if (options.IfModifiedSince.HasValue())
{
request.SetHeader(
"If-Modified-Since",
options.IfModifiedSince.Value().ToString(Azure::DateTime::DateFormat::Rfc1123));
}
if (options.IfUnmodifiedSince.HasValue())
{
request.SetHeader(
"If-Unmodified-Since",
options.IfUnmodifiedSince.Value().ToString(Azure::DateTime::DateFormat::Rfc1123));
}
if (options.IfMatch.HasValue() && !options.IfMatch.ToString().empty())
{
request.SetHeader("If-Match", options.IfMatch.ToString());
}
if (options.IfNoneMatch.HasValue() && !options.IfNoneMatch.ToString().empty())
{
request.SetHeader("If-None-Match", options.IfNoneMatch.ToString());
}
if (options.IfTags.HasValue())
{
request.SetHeader("x-ms-if-tags", options.IfTags.Value());
}
auto pHttpResponse = pipeline.Send(request, context);
Azure::Core::Http::RawResponse& httpResponse = *pHttpResponse;
Models::_detail::ChangeBlobLeaseResult response;
auto http_status_code = httpResponse.GetStatusCode();
if (http_status_code != Azure::Core::Http::HttpStatusCode::Ok)
{
throw StorageException::CreateFromResponse(std::move(pHttpResponse));
}
response.ETag = Azure::ETag(httpResponse.GetHeaders().at("etag"));
response.LastModified = Azure::DateTime::Parse(
httpResponse.GetHeaders().at("last-modified"), Azure::DateTime::DateFormat::Rfc1123);
response.LeaseId = httpResponse.GetHeaders().at("x-ms-lease-id");
return Azure::Response<Models::_detail::ChangeBlobLeaseResult>(
std::move(response), std::move(pHttpResponse));
}
struct ReleaseBlobLeaseOptions final
{
Azure::Nullable<int32_t> Timeout;
std::string LeaseId;
Azure::Nullable<Azure::DateTime> IfModifiedSince;
Azure::Nullable<Azure::DateTime> IfUnmodifiedSince;
Azure::ETag IfMatch;
Azure::ETag IfNoneMatch;
Azure::Nullable<std::string> IfTags;
}; // struct ReleaseBlobLeaseOptions
static Azure::Response<Models::_detail::ReleaseBlobLeaseResult> ReleaseLease(
Azure::Core::Http::_internal::HttpPipeline& pipeline,
const Azure::Core::Url& url,
const ReleaseBlobLeaseOptions& options,
const Azure::Core::Context& context)
{
auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Put, url);
request.SetHeader("Content-Length", "0");
request.SetHeader("x-ms-version", "2020-02-10");
if (options.Timeout.HasValue())
{
request.GetUrl().AppendQueryParameter(
"timeout", std::to_string(options.Timeout.Value()));
}
request.GetUrl().AppendQueryParameter("comp", "lease");
request.SetHeader("x-ms-lease-action", "release");
request.SetHeader("x-ms-lease-id", options.LeaseId);
if (options.IfModifiedSince.HasValue())
{
request.SetHeader(
"If-Modified-Since",
options.IfModifiedSince.Value().ToString(Azure::DateTime::DateFormat::Rfc1123));
}
if (options.IfUnmodifiedSince.HasValue())
{
request.SetHeader(
"If-Unmodified-Since",
options.IfUnmodifiedSince.Value().ToString(Azure::DateTime::DateFormat::Rfc1123));
}
if (options.IfMatch.HasValue() && !options.IfMatch.ToString().empty())
{
request.SetHeader("If-Match", options.IfMatch.ToString());
}
if (options.IfNoneMatch.HasValue() && !options.IfNoneMatch.ToString().empty())
{
request.SetHeader("If-None-Match", options.IfNoneMatch.ToString());
}
if (options.IfTags.HasValue())
{
request.SetHeader("x-ms-if-tags", options.IfTags.Value());
}
auto pHttpResponse = pipeline.Send(request, context);
Azure::Core::Http::RawResponse& httpResponse = *pHttpResponse;
Models::_detail::ReleaseBlobLeaseResult response;
auto http_status_code = httpResponse.GetStatusCode();
if (http_status_code != Azure::Core::Http::HttpStatusCode::Ok)
{
throw StorageException::CreateFromResponse(std::move(pHttpResponse));
}
response.ETag = Azure::ETag(httpResponse.GetHeaders().at("etag"));
response.LastModified = Azure::DateTime::Parse(
httpResponse.GetHeaders().at("last-modified"), Azure::DateTime::DateFormat::Rfc1123);
return Azure::Response<Models::_detail::ReleaseBlobLeaseResult>(
std::move(response), std::move(pHttpResponse));
}
struct BreakBlobLeaseOptions final
{
Azure::Nullable<int32_t> Timeout;
Azure::Nullable<std::chrono::seconds> BreakPeriod;
Azure::Nullable<Azure::DateTime> IfModifiedSince;
Azure::Nullable<Azure::DateTime> IfUnmodifiedSince;
Azure::ETag IfMatch;
Azure::ETag IfNoneMatch;
Azure::Nullable<std::string> IfTags;
}; // struct BreakBlobLeaseOptions
static Azure::Response<Models::_detail::BreakBlobLeaseResult> BreakLease(
Azure::Core::Http::_internal::HttpPipeline& pipeline,
const Azure::Core::Url& url,
const BreakBlobLeaseOptions& options,
const Azure::Core::Context& context)
{
auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Put, url);
request.SetHeader("Content-Length", "0");
request.SetHeader("x-ms-version", "2020-02-10");
if (options.Timeout.HasValue())
{
request.GetUrl().AppendQueryParameter(
"timeout", std::to_string(options.Timeout.Value()));
}
request.GetUrl().AppendQueryParameter("comp", "lease");
request.SetHeader("x-ms-lease-action", "break");
if (options.BreakPeriod.HasValue())
{
request.SetHeader(
"x-ms-lease-break-period", std::to_string(options.BreakPeriod.Value().count()));
}
if (options.IfModifiedSince.HasValue())
{
request.SetHeader(
"If-Modified-Since",
options.IfModifiedSince.Value().ToString(Azure::DateTime::DateFormat::Rfc1123));
}
if (options.IfUnmodifiedSince.HasValue())
{
request.SetHeader(
"If-Unmodified-Since",
options.IfUnmodifiedSince.Value().ToString(Azure::DateTime::DateFormat::Rfc1123));
}
if (options.IfMatch.HasValue() && !options.IfMatch.ToString().empty())
{
request.SetHeader("If-Match", options.IfMatch.ToString());
}
if (options.IfNoneMatch.HasValue() && !options.IfNoneMatch.ToString().empty())
{
request.SetHeader("If-None-Match", options.IfNoneMatch.ToString());
}
if (options.IfTags.HasValue())
{
request.SetHeader("x-ms-if-tags", options.IfTags.Value());
}
auto pHttpResponse = pipeline.Send(request, context);
Azure::Core::Http::RawResponse& httpResponse = *pHttpResponse;
Models::_detail::BreakBlobLeaseResult response;
auto http_status_code = httpResponse.GetStatusCode();
if (http_status_code != Azure::Core::Http::HttpStatusCode::Accepted)
{
throw StorageException::CreateFromResponse(std::move(pHttpResponse));
}
response.ETag = Azure::ETag(httpResponse.GetHeaders().at("etag"));
response.LastModified = Azure::DateTime::Parse(
httpResponse.GetHeaders().at("last-modified"), Azure::DateTime::DateFormat::Rfc1123);
response.LeaseTime = std::stoi(httpResponse.GetHeaders().at("x-ms-lease-time"));
return Azure::Response<Models::_detail::BreakBlobLeaseResult>(
std::move(response), std::move(pHttpResponse));
}
private:
static Models::_detail::GetBlobTagsResult GetBlobTagsResultInternalFromXml(
_internal::XmlReader& reader)
{
Models::_detail::GetBlobTagsResult ret;
enum class XmlTagName
{
k_Tags,
k_TagSet,
k_Unknown,
};
std::vector<XmlTagName> path;
while (true)
{
auto node = reader.Read();
if (node.Type == _internal::XmlNodeType::End)
{
break;
}
else if (node.Type == _internal::XmlNodeType::EndTag)
{
if (path.size() > 0)
{
path.pop_back();
}
else
{
break;
}
}
else if (node.Type == _internal::XmlNodeType::StartTag)
{
if (node.Name == "Tags")
{
path.emplace_back(XmlTagName::k_Tags);
}
else if (node.Name == "TagSet")
{
path.emplace_back(XmlTagName::k_TagSet);
}
else
{
path.emplace_back(XmlTagName::k_Unknown);
}
if (path.size() == 2 && path[0] == XmlTagName::k_Tags
&& path[1] == XmlTagName::k_TagSet)
{
ret.Tags = TagsFromXml(reader);
path.pop_back();
}
}
else if (node.Type == _internal::XmlNodeType::Text)
{
}
}
return ret;
}
static std::map<std::string, std::string> TagsFromXml(_internal::XmlReader& reader)
{
std::map<std::string, std::string> ret;
int depth = 0;
std::string key;
bool is_key = false;
bool is_value = false;
while (true)
{
auto node = reader.Read();
if (node.Type == _internal::XmlNodeType::End)
{
break;
}
else if (node.Type == _internal::XmlNodeType::StartTag)
{
++depth;
if (node.Name == "Key")
{
is_key = true;
}
else if (node.Name == "Value")
{
is_value = true;
}
}
else if (node.Type == _internal::XmlNodeType::EndTag)
{
if (depth-- == 0)
{
break;
}
}
if (depth == 2 && node.Type == _internal::XmlNodeType::Text)
{
if (is_key)
{
key = node.Value;
is_key = false;
}
else if (is_value)
{
ret.emplace(std::move(key), node.Value);
is_value = false;
}
}
}
return ret;
}
static void SetBlobTagsOptionsToXml(
_internal::XmlWriter& writer,
const SetBlobTagsOptions& options)
{
writer.Write(_internal::XmlNode{_internal::XmlNodeType::StartTag, "Tags"});
writer.Write(_internal::XmlNode{_internal::XmlNodeType::StartTag, "TagSet"});
for (const auto& i : options.Tags)
{
writer.Write(_internal::XmlNode{_internal::XmlNodeType::StartTag, "Tag"});
writer.Write(_internal::XmlNode{_internal::XmlNodeType::StartTag, "Key"});
writer.Write(_internal::XmlNode{_internal::XmlNodeType::Text, std::string(), i.first});
writer.Write(_internal::XmlNode{_internal::XmlNodeType::EndTag});
writer.Write(_internal::XmlNode{_internal::XmlNodeType::StartTag, "Value"});
writer.Write(_internal::XmlNode{_internal::XmlNodeType::Text, std::string(), i.second});
writer.Write(_internal::XmlNode{_internal::XmlNodeType::EndTag});
writer.Write(_internal::XmlNode{_internal::XmlNodeType::EndTag});
}
writer.Write(_internal::XmlNode{_internal::XmlNodeType::EndTag});
writer.Write(_internal::XmlNode{_internal::XmlNodeType::EndTag});
}
}; // class Blob
class BlockBlob final {
public:
struct UploadBlockBlobOptions final
{
Azure::Nullable<int32_t> Timeout;
Azure::Nullable<ContentHash> TransactionalContentHash;
BlobHttpHeaders HttpHeaders;
Storage::Metadata Metadata;
std::map<std::string, std::string> Tags;
Azure::Nullable<std::string> LeaseId;
Azure::Nullable<Models::AccessTier> AccessTier;
Azure::Nullable<std::string> EncryptionKey;
Azure::Nullable<std::vector<uint8_t>> EncryptionKeySha256;
Azure::Nullable<EncryptionAlgorithmType> EncryptionAlgorithm;
Azure::Nullable<std::string> EncryptionScope;
Azure::Nullable<Azure::DateTime> IfModifiedSince;
Azure::Nullable<Azure::DateTime> IfUnmodifiedSince;
Azure::ETag IfMatch;
Azure::ETag IfNoneMatch;
Azure::Nullable<std::string> IfTags;
}; // struct UploadBlockBlobOptions
static Azure::Response<UploadBlockBlobResult> Upload(
Azure::Core::Http::_internal::HttpPipeline& pipeline,
const Azure::Core::Url& url,
Azure::Core::IO::BodyStream& requestBody,
const UploadBlockBlobOptions& options,
const Azure::Core::Context& context)
{
auto request
= Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Put, url, &requestBody);
request.SetHeader("Content-Length", std::to_string(requestBody.Length()));
request.SetHeader("x-ms-version", "2020-02-10");
if (options.Timeout.HasValue())
{
request.GetUrl().AppendQueryParameter(
"timeout", std::to_string(options.Timeout.Value()));
}
if (options.EncryptionKey.HasValue())
{
request.SetHeader("x-ms-encryption-key", options.EncryptionKey.Value());
}
if (options.EncryptionKeySha256.HasValue())
{
request.SetHeader(
"x-ms-encryption-key-sha256",
Azure::Core::Convert::Base64Encode(options.EncryptionKeySha256.Value()));
}
if (options.EncryptionAlgorithm.HasValue())
{
request.SetHeader(
"x-ms-encryption-algorithm", options.EncryptionAlgorithm.Value().ToString());
}
if (options.EncryptionScope.HasValue())
{
request.SetHeader("x-ms-encryption-scope", options.EncryptionScope.Value());
}
if (options.TransactionalContentHash.HasValue())
{
if (options.TransactionalContentHash.Value().Algorithm == HashAlgorithm::Md5)
{
request.SetHeader(
"Content-MD5",
Azure::Core::Convert::Base64Encode(
options.TransactionalContentHash.Value().Value));
}
else if (options.TransactionalContentHash.Value().Algorithm == HashAlgorithm::Crc64)
{
request.SetHeader(
"x-ms-content-crc64",
Azure::Core::Convert::Base64Encode(
options.TransactionalContentHash.Value().Value));
}
}
if (!options.HttpHeaders.ContentType.empty())
{
request.SetHeader("x-ms-blob-content-type", options.HttpHeaders.ContentType);
}
if (!options.HttpHeaders.ContentEncoding.empty())
{
request.SetHeader("x-ms-blob-content-encoding", options.HttpHeaders.ContentEncoding);
}
if (!options.HttpHeaders.ContentLanguage.empty())
{
request.SetHeader("x-ms-blob-content-language", options.HttpHeaders.ContentLanguage);
}
if (!options.HttpHeaders.CacheControl.empty())
{
request.SetHeader("x-ms-blob-cache-control", options.HttpHeaders.CacheControl);
}
if (!Azure::Core::Convert::Base64Encode(options.HttpHeaders.ContentHash.Value).empty())
{
request.SetHeader(
"x-ms-blob-content-md5",
Azure::Core::Convert::Base64Encode(options.HttpHeaders.ContentHash.Value));
}
if (!options.HttpHeaders.ContentDisposition.empty())
{
request.SetHeader(
"x-ms-blob-content-disposition", options.HttpHeaders.ContentDisposition);
}
for (const auto& pair : options.Metadata)
{
request.SetHeader("x-ms-meta-" + pair.first, pair.second);
}
if (!options.Tags.empty())
{
std::string blobTagsValue;
for (const auto& tag : options.Tags)
{
if (!blobTagsValue.empty())
{
blobTagsValue += "&";
}
blobTagsValue += _internal::UrlEncodeQueryParameter(tag.first) + "="
+ _internal::UrlEncodeQueryParameter(tag.second);
}
request.SetHeader("x-ms-tags", std::move(blobTagsValue));
}
if (options.LeaseId.HasValue())
{
request.SetHeader("x-ms-lease-id", options.LeaseId.Value());
}
request.SetHeader("x-ms-blob-type", "BlockBlob");
if (options.AccessTier.HasValue())
{
request.SetHeader("x-ms-access-tier", options.AccessTier.Value().ToString());
}
if (options.IfModifiedSince.HasValue())
{
request.SetHeader(
"If-Modified-Since",
options.IfModifiedSince.Value().ToString(Azure::DateTime::DateFormat::Rfc1123));
}
if (options.IfUnmodifiedSince.HasValue())
{
request.SetHeader(
"If-Unmodified-Since",
options.IfUnmodifiedSince.Value().ToString(Azure::DateTime::DateFormat::Rfc1123));
}
if (options.IfMatch.HasValue() && !options.IfMatch.ToString().empty())
{
request.SetHeader("If-Match", options.IfMatch.ToString());
}
if (options.IfNoneMatch.HasValue() && !options.IfNoneMatch.ToString().empty())
{
request.SetHeader("If-None-Match", options.IfNoneMatch.ToString());
}
if (options.IfTags.HasValue())
{
request.SetHeader("x-ms-if-tags", options.IfTags.Value());
}
auto pHttpResponse = pipeline.Send(request, context);
Azure::Core::Http::RawResponse& httpResponse = *pHttpResponse;
UploadBlockBlobResult response;
auto http_status_code = httpResponse.GetStatusCode();
if (http_status_code != Azure::Core::Http::HttpStatusCode::Created)
{
throw StorageException::CreateFromResponse(std::move(pHttpResponse));
}
response.ETag = Azure::ETag(httpResponse.GetHeaders().at("etag"));
response.LastModified = Azure::DateTime::Parse(
httpResponse.GetHeaders().at("last-modified"), Azure::DateTime::DateFormat::Rfc1123);
{
const auto& headers = httpResponse.GetHeaders();
auto content_md5_iterator = headers.find("content-md5");
if (content_md5_iterator != headers.end())
{
ContentHash hash;
hash.Algorithm = HashAlgorithm::Md5;
hash.Value = Azure::Core::Convert::Base64Decode(content_md5_iterator->second);
response.TransactionalContentHash = std::move(hash);
}
auto x_ms_content_crc64_iterator = headers.find("x-ms-content-crc64");
if (x_ms_content_crc64_iterator != headers.end())
{
ContentHash hash;
hash.Algorithm = HashAlgorithm::Crc64;
hash.Value = Azure::Core::Convert::Base64Decode(x_ms_content_crc64_iterator->second);
response.TransactionalContentHash = std::move(hash);
}
}
auto x_ms_version_id__iterator = httpResponse.GetHeaders().find("x-ms-version-id");
if (x_ms_version_id__iterator != httpResponse.GetHeaders().end())
{
response.VersionId = x_ms_version_id__iterator->second;
}
response.IsServerEncrypted
= httpResponse.GetHeaders().at("x-ms-request-server-encrypted") == "true";
auto x_ms_encryption_key_sha256__iterator
= httpResponse.GetHeaders().find("x-ms-encryption-key-sha256");
if (x_ms_encryption_key_sha256__iterator != httpResponse.GetHeaders().end())
{
response.EncryptionKeySha256
= Azure::Core::Convert::Base64Decode(x_ms_encryption_key_sha256__iterator->second);
}
auto x_ms_encryption_scope__iterator
= httpResponse.GetHeaders().find("x-ms-encryption-scope");
if (x_ms_encryption_scope__iterator != httpResponse.GetHeaders().end())
{
response.EncryptionScope = x_ms_encryption_scope__iterator->second;
}
return Azure::Response<UploadBlockBlobResult>(
std::move(response), std::move(pHttpResponse));
}
struct StageBlockOptions final
{
Azure::Nullable<int32_t> Timeout;
std::string BlockId;
Azure::Nullable<ContentHash> TransactionalContentHash;
Azure::Nullable<std::string> LeaseId;
Azure::Nullable<std::string> EncryptionKey;
Azure::Nullable<std::vector<uint8_t>> EncryptionKeySha256;
Azure::Nullable<EncryptionAlgorithmType> EncryptionAlgorithm;
Azure::Nullable<std::string> EncryptionScope;
}; // struct StageBlockOptions
static Azure::Response<StageBlockResult> StageBlock(
Azure::Core::Http::_internal::HttpPipeline& pipeline,
const Azure::Core::Url& url,
Azure::Core::IO::BodyStream& requestBody,
const StageBlockOptions& options,
const Azure::Core::Context& context)
{
auto request
= Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Put, url, &requestBody);
request.SetHeader("Content-Length", std::to_string(requestBody.Length()));
request.GetUrl().AppendQueryParameter("comp", "block");
request.GetUrl().AppendQueryParameter(
"blockid", _internal::UrlEncodeQueryParameter(options.BlockId));
request.SetHeader("x-ms-version", "2020-02-10");
if (options.Timeout.HasValue())
{
request.GetUrl().AppendQueryParameter(
"timeout", std::to_string(options.Timeout.Value()));
}
if (options.TransactionalContentHash.HasValue())
{
if (options.TransactionalContentHash.Value().Algorithm == HashAlgorithm::Md5)
{
request.SetHeader(
"Content-MD5",
Azure::Core::Convert::Base64Encode(
options.TransactionalContentHash.Value().Value));
}
else if (options.TransactionalContentHash.Value().Algorithm == HashAlgorithm::Crc64)
{
request.SetHeader(
"x-ms-content-crc64",
Azure::Core::Convert::Base64Encode(
options.TransactionalContentHash.Value().Value));
}
}
if (options.LeaseId.HasValue())
{
request.SetHeader("x-ms-lease-id", options.LeaseId.Value());
}
if (options.EncryptionKey.HasValue())
{
request.SetHeader("x-ms-encryption-key", options.EncryptionKey.Value());
}
if (options.EncryptionKeySha256.HasValue())
{
request.SetHeader(
"x-ms-encryption-key-sha256",
Azure::Core::Convert::Base64Encode(options.EncryptionKeySha256.Value()));
}
if (options.EncryptionAlgorithm.HasValue())
{
request.SetHeader(
"x-ms-encryption-algorithm", options.EncryptionAlgorithm.Value().ToString());
}
if (options.EncryptionScope.HasValue())
{
request.SetHeader("x-ms-encryption-scope", options.EncryptionScope.Value());
}
auto pHttpResponse = pipeline.Send(request, context);
Azure::Core::Http::RawResponse& httpResponse = *pHttpResponse;
StageBlockResult response;
auto http_status_code = httpResponse.GetStatusCode();
if (http_status_code != Azure::Core::Http::HttpStatusCode::Created)
{
throw StorageException::CreateFromResponse(std::move(pHttpResponse));
}
{
const auto& headers = httpResponse.GetHeaders();
auto content_md5_iterator = headers.find("content-md5");
if (content_md5_iterator != headers.end())
{
ContentHash hash;
hash.Algorithm = HashAlgorithm::Md5;
hash.Value = Azure::Core::Convert::Base64Decode(content_md5_iterator->second);
response.TransactionalContentHash = std::move(hash);
}
auto x_ms_content_crc64_iterator = headers.find("x-ms-content-crc64");
if (x_ms_content_crc64_iterator != headers.end())
{
ContentHash hash;
hash.Algorithm = HashAlgorithm::Crc64;
hash.Value = Azure::Core::Convert::Base64Decode(x_ms_content_crc64_iterator->second);
response.TransactionalContentHash = std::move(hash);
}
}
response.IsServerEncrypted
= httpResponse.GetHeaders().at("x-ms-request-server-encrypted") == "true";
auto x_ms_encryption_key_sha256__iterator
= httpResponse.GetHeaders().find("x-ms-encryption-key-sha256");
if (x_ms_encryption_key_sha256__iterator != httpResponse.GetHeaders().end())
{
response.EncryptionKeySha256
= Azure::Core::Convert::Base64Decode(x_ms_encryption_key_sha256__iterator->second);
}
auto x_ms_encryption_scope__iterator
= httpResponse.GetHeaders().find("x-ms-encryption-scope");
if (x_ms_encryption_scope__iterator != httpResponse.GetHeaders().end())
{
response.EncryptionScope = x_ms_encryption_scope__iterator->second;
}
return Azure::Response<StageBlockResult>(std::move(response), std::move(pHttpResponse));
}
struct StageBlockFromUriOptions final
{
Azure::Nullable<int32_t> Timeout;
std::string BlockId;
std::string SourceUri;
Azure::Nullable<Azure::Core::Http::HttpRange> SourceRange;
Azure::Nullable<ContentHash> TransactionalContentHash;
Azure::Nullable<std::string> LeaseId;
Azure::Nullable<std::string> EncryptionKey;
Azure::Nullable<std::vector<uint8_t>> EncryptionKeySha256;
Azure::Nullable<EncryptionAlgorithmType> EncryptionAlgorithm;
Azure::Nullable<std::string> EncryptionScope;
Azure::Nullable<Azure::DateTime> SourceIfModifiedSince;
Azure::Nullable<Azure::DateTime> SourceIfUnmodifiedSince;
Azure::ETag SourceIfMatch;
Azure::ETag SourceIfNoneMatch;
}; // struct StageBlockFromUriOptions
static Azure::Response<StageBlockFromUriResult> StageBlockFromUri(
Azure::Core::Http::_internal::HttpPipeline& pipeline,
const Azure::Core::Url& url,
const StageBlockFromUriOptions& options,
const Azure::Core::Context& context)
{
auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Put, url);
request.SetHeader("Content-Length", "0");
request.GetUrl().AppendQueryParameter("comp", "block");
request.GetUrl().AppendQueryParameter(
"blockid", _internal::UrlEncodeQueryParameter(options.BlockId));
request.SetHeader("x-ms-version", "2020-02-10");
if (options.Timeout.HasValue())
{
request.GetUrl().AppendQueryParameter(
"timeout", std::to_string(options.Timeout.Value()));
}
request.SetHeader("x-ms-copy-source", options.SourceUri);
if (options.SourceRange.HasValue())
{
std::string headerValue
= "bytes=" + std::to_string(options.SourceRange.Value().Offset) + "-";
if (options.SourceRange.Value().Length.HasValue())
{
headerValue += std::to_string(
options.SourceRange.Value().Offset + options.SourceRange.Value().Length.Value()
- 1);
}
request.SetHeader("x-ms-source_range", std::move(headerValue));
}
if (options.TransactionalContentHash.HasValue())
{
if (options.TransactionalContentHash.Value().Algorithm == HashAlgorithm::Md5)
{
request.SetHeader(
"x-ms-source-content-md5",
Azure::Core::Convert::Base64Encode(
options.TransactionalContentHash.Value().Value));
}
else if (options.TransactionalContentHash.Value().Algorithm == HashAlgorithm::Crc64)
{
request.SetHeader(
"x-ms-source-content-crc64",
Azure::Core::Convert::Base64Encode(
options.TransactionalContentHash.Value().Value));
}
}
if (options.LeaseId.HasValue())
{
request.SetHeader("x-ms-lease-id", options.LeaseId.Value());
}
if (options.EncryptionKey.HasValue())
{
request.SetHeader("x-ms-encryption-key", options.EncryptionKey.Value());
}
if (options.EncryptionKeySha256.HasValue())
{
request.SetHeader(
"x-ms-encryption-key-sha256",
Azure::Core::Convert::Base64Encode(options.EncryptionKeySha256.Value()));
}
if (options.EncryptionAlgorithm.HasValue())
{
request.SetHeader(
"x-ms-encryption-algorithm", options.EncryptionAlgorithm.Value().ToString());
}
if (options.EncryptionScope.HasValue())
{
request.SetHeader("x-ms-encryption-scope", options.EncryptionScope.Value());
}
if (options.SourceIfModifiedSince.HasValue())
{
request.SetHeader(
"x-ms-source-if-modified-since",
options.SourceIfModifiedSince.Value().ToString(
Azure::DateTime::DateFormat::Rfc1123));
}
if (options.SourceIfUnmodifiedSince.HasValue())
{
request.SetHeader(
"x-ms-source-if-unmodified-since",
options.SourceIfUnmodifiedSince.Value().ToString(
Azure::DateTime::DateFormat::Rfc1123));
}
if (options.SourceIfMatch.HasValue() && !options.SourceIfMatch.ToString().empty())
{
request.SetHeader("x-ms-source-if-match", options.SourceIfMatch.ToString());
}
if (options.SourceIfNoneMatch.HasValue() && !options.SourceIfNoneMatch.ToString().empty())
{
request.SetHeader("x-ms-source-if-none-match", options.SourceIfNoneMatch.ToString());
}
auto pHttpResponse = pipeline.Send(request, context);
Azure::Core::Http::RawResponse& httpResponse = *pHttpResponse;
StageBlockFromUriResult response;
auto http_status_code = httpResponse.GetStatusCode();
if (http_status_code != Azure::Core::Http::HttpStatusCode::Created)
{
throw StorageException::CreateFromResponse(std::move(pHttpResponse));
}
{
const auto& headers = httpResponse.GetHeaders();
auto content_md5_iterator = headers.find("content-md5");
if (content_md5_iterator != headers.end())
{
ContentHash hash;
hash.Algorithm = HashAlgorithm::Md5;
hash.Value = Azure::Core::Convert::Base64Decode(content_md5_iterator->second);
response.TransactionalContentHash = std::move(hash);
}
auto x_ms_content_crc64_iterator = headers.find("x-ms-content-crc64");
if (x_ms_content_crc64_iterator != headers.end())
{
ContentHash hash;
hash.Algorithm = HashAlgorithm::Crc64;
hash.Value = Azure::Core::Convert::Base64Decode(x_ms_content_crc64_iterator->second);
response.TransactionalContentHash = std::move(hash);
}
}
response.IsServerEncrypted
= httpResponse.GetHeaders().at("x-ms-request-server-encrypted") == "true";
auto x_ms_encryption_key_sha256__iterator
= httpResponse.GetHeaders().find("x-ms-encryption-key-sha256");
if (x_ms_encryption_key_sha256__iterator != httpResponse.GetHeaders().end())
{
response.EncryptionKeySha256
= Azure::Core::Convert::Base64Decode(x_ms_encryption_key_sha256__iterator->second);
}
auto x_ms_encryption_scope__iterator
= httpResponse.GetHeaders().find("x-ms-encryption-scope");
if (x_ms_encryption_scope__iterator != httpResponse.GetHeaders().end())
{
response.EncryptionScope = x_ms_encryption_scope__iterator->second;
}
return Azure::Response<StageBlockFromUriResult>(
std::move(response), std::move(pHttpResponse));
}
struct CommitBlockListOptions final
{
Azure::Nullable<int32_t> Timeout;
std::vector<std::pair<BlockType, std::string>> BlockList;
BlobHttpHeaders HttpHeaders;
Storage::Metadata Metadata;
std::map<std::string, std::string> Tags;
Azure::Nullable<std::string> LeaseId;
Azure::Nullable<std::string> EncryptionKey;
Azure::Nullable<std::vector<uint8_t>> EncryptionKeySha256;
Azure::Nullable<EncryptionAlgorithmType> EncryptionAlgorithm;
Azure::Nullable<std::string> EncryptionScope;
Azure::Nullable<Azure::DateTime> IfModifiedSince;
Azure::Nullable<Azure::DateTime> IfUnmodifiedSince;
Azure::ETag IfMatch;
Azure::ETag IfNoneMatch;
Azure::Nullable<std::string> IfTags;
Azure::Nullable<Models::AccessTier> AccessTier;
}; // struct CommitBlockListOptions
static Azure::Response<CommitBlockListResult> CommitBlockList(
Azure::Core::Http::_internal::HttpPipeline& pipeline,
const Azure::Core::Url& url,
const CommitBlockListOptions& options,
const Azure::Core::Context& context)
{
std::string xml_body;
{
_internal::XmlWriter writer;
CommitBlockListOptionsToXml(writer, options);
xml_body = writer.GetDocument();
writer.Write(_internal::XmlNode{_internal::XmlNodeType::End});
}
Azure::Core::IO::MemoryBodyStream xml_body_stream(
reinterpret_cast<const uint8_t*>(xml_body.data()), xml_body.length());
auto request = Azure::Core::Http::Request(
Azure::Core::Http::HttpMethod::Put, url, &xml_body_stream);
request.SetHeader("Content-Length", std::to_string(xml_body_stream.Length()));
request.GetUrl().AppendQueryParameter("comp", "blocklist");
request.SetHeader("x-ms-version", "2020-02-10");
if (options.Timeout.HasValue())
{
request.GetUrl().AppendQueryParameter(
"timeout", std::to_string(options.Timeout.Value()));
}
if (!options.HttpHeaders.ContentType.empty())
{
request.SetHeader("x-ms-blob-content-type", options.HttpHeaders.ContentType);
}
if (!options.HttpHeaders.ContentEncoding.empty())
{
request.SetHeader("x-ms-blob-content-encoding", options.HttpHeaders.ContentEncoding);
}
if (!options.HttpHeaders.ContentLanguage.empty())
{
request.SetHeader("x-ms-blob-content-language", options.HttpHeaders.ContentLanguage);
}
if (!options.HttpHeaders.CacheControl.empty())
{
request.SetHeader("x-ms-blob-cache-control", options.HttpHeaders.CacheControl);
}
if (!Azure::Core::Convert::Base64Encode(options.HttpHeaders.ContentHash.Value).empty())
{
request.SetHeader(
"x-ms-blob-content-md5",
Azure::Core::Convert::Base64Encode(options.HttpHeaders.ContentHash.Value));
}
if (!options.HttpHeaders.ContentDisposition.empty())
{
request.SetHeader(
"x-ms-blob-content-disposition", options.HttpHeaders.ContentDisposition);
}
for (const auto& pair : options.Metadata)
{
request.SetHeader("x-ms-meta-" + pair.first, pair.second);
}
if (!options.Tags.empty())
{
std::string blobTagsValue;
for (const auto& tag : options.Tags)
{
if (!blobTagsValue.empty())
{
blobTagsValue += "&";
}
blobTagsValue += _internal::UrlEncodeQueryParameter(tag.first) + "="
+ _internal::UrlEncodeQueryParameter(tag.second);
}
request.SetHeader("x-ms-tags", std::move(blobTagsValue));
}
if (options.LeaseId.HasValue())
{
request.SetHeader("x-ms-lease-id", options.LeaseId.Value());
}
if (options.EncryptionKey.HasValue())
{
request.SetHeader("x-ms-encryption-key", options.EncryptionKey.Value());
}
if (options.EncryptionKeySha256.HasValue())
{
request.SetHeader(
"x-ms-encryption-key-sha256",
Azure::Core::Convert::Base64Encode(options.EncryptionKeySha256.Value()));
}
if (options.EncryptionAlgorithm.HasValue())
{
request.SetHeader(
"x-ms-encryption-algorithm", options.EncryptionAlgorithm.Value().ToString());
}
if (options.EncryptionScope.HasValue())
{
request.SetHeader("x-ms-encryption-scope", options.EncryptionScope.Value());
}
if (options.AccessTier.HasValue())
{
request.SetHeader("x-ms-access-tier", options.AccessTier.Value().ToString());
}
if (options.IfModifiedSince.HasValue())
{
request.SetHeader(
"If-Modified-Since",
options.IfModifiedSince.Value().ToString(Azure::DateTime::DateFormat::Rfc1123));
}
if (options.IfUnmodifiedSince.HasValue())
{
request.SetHeader(
"If-Unmodified-Since",
options.IfUnmodifiedSince.Value().ToString(Azure::DateTime::DateFormat::Rfc1123));
}
if (options.IfMatch.HasValue() && !options.IfMatch.ToString().empty())
{
request.SetHeader("If-Match", options.IfMatch.ToString());
}
if (options.IfNoneMatch.HasValue() && !options.IfNoneMatch.ToString().empty())
{
request.SetHeader("If-None-Match", options.IfNoneMatch.ToString());
}
if (options.IfTags.HasValue())
{
request.SetHeader("x-ms-if-tags", options.IfTags.Value());
}
auto pHttpResponse = pipeline.Send(request, context);
Azure::Core::Http::RawResponse& httpResponse = *pHttpResponse;
CommitBlockListResult response;
auto http_status_code = httpResponse.GetStatusCode();
if (http_status_code != Azure::Core::Http::HttpStatusCode::Created)
{
throw StorageException::CreateFromResponse(std::move(pHttpResponse));
}
response.ETag = Azure::ETag(httpResponse.GetHeaders().at("etag"));
response.LastModified = Azure::DateTime::Parse(
httpResponse.GetHeaders().at("last-modified"), Azure::DateTime::DateFormat::Rfc1123);
auto x_ms_version_id__iterator = httpResponse.GetHeaders().find("x-ms-version-id");
if (x_ms_version_id__iterator != httpResponse.GetHeaders().end())
{
response.VersionId = x_ms_version_id__iterator->second;
}
response.IsServerEncrypted
= httpResponse.GetHeaders().at("x-ms-request-server-encrypted") == "true";
auto x_ms_encryption_key_sha256__iterator
= httpResponse.GetHeaders().find("x-ms-encryption-key-sha256");
if (x_ms_encryption_key_sha256__iterator != httpResponse.GetHeaders().end())
{
response.EncryptionKeySha256
= Azure::Core::Convert::Base64Decode(x_ms_encryption_key_sha256__iterator->second);
}
auto x_ms_encryption_scope__iterator
= httpResponse.GetHeaders().find("x-ms-encryption-scope");
if (x_ms_encryption_scope__iterator != httpResponse.GetHeaders().end())
{
response.EncryptionScope = x_ms_encryption_scope__iterator->second;
}
return Azure::Response<CommitBlockListResult>(
std::move(response), std::move(pHttpResponse));
}
struct GetBlockListOptions final
{
Azure::Nullable<int32_t> Timeout;
BlockListType ListType = BlockListType::Committed;
Azure::Nullable<std::string> LeaseId;
Azure::Nullable<std::string> IfTags;
}; // struct GetBlockListOptions
static Azure::Response<GetBlockListResult> GetBlockList(
Azure::Core::Http::_internal::HttpPipeline& pipeline,
const Azure::Core::Url& url,
const GetBlockListOptions& options,
const Azure::Core::Context& context)
{
auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Get, url);
request.GetUrl().AppendQueryParameter("comp", "blocklist");
request.GetUrl().AppendQueryParameter(
"blocklisttype", _internal::UrlEncodeQueryParameter(options.ListType.ToString()));
request.SetHeader("x-ms-version", "2020-02-10");
if (options.Timeout.HasValue())
{
request.GetUrl().AppendQueryParameter(
"timeout", std::to_string(options.Timeout.Value()));
}
if (options.LeaseId.HasValue())
{
request.SetHeader("x-ms-lease-id", options.LeaseId.Value());
}
if (options.IfTags.HasValue())
{
request.SetHeader("x-ms-if-tags", options.IfTags.Value());
}
auto pHttpResponse = pipeline.Send(request, context);
Azure::Core::Http::RawResponse& httpResponse = *pHttpResponse;
GetBlockListResult response;
auto http_status_code = httpResponse.GetStatusCode();
if (http_status_code != Azure::Core::Http::HttpStatusCode::Ok)
{
throw StorageException::CreateFromResponse(std::move(pHttpResponse));
}
{
const auto& httpResponseBody = httpResponse.GetBody();
_internal::XmlReader reader(
reinterpret_cast<const char*>(httpResponseBody.data()), httpResponseBody.size());
response = GetBlockListResultFromXml(reader);
}
auto etag__iterator = httpResponse.GetHeaders().find("etag");
if (etag__iterator != httpResponse.GetHeaders().end())
{
response.ETag = Azure::ETag(httpResponse.GetHeaders().at("etag"));
}
auto last_modified__iterator = httpResponse.GetHeaders().find("last-modified");
if (last_modified__iterator != httpResponse.GetHeaders().end())
{
response.LastModified = Azure::DateTime::Parse(
last_modified__iterator->second, Azure::DateTime::DateFormat::Rfc1123);
}
auto x_ms_blob_content_length__iterator
= httpResponse.GetHeaders().find("x-ms-blob-content-length");
if (x_ms_blob_content_length__iterator != httpResponse.GetHeaders().end())
{
response.BlobSize = std::stoll(x_ms_blob_content_length__iterator->second);
}
return Azure::Response<GetBlockListResult>(std::move(response), std::move(pHttpResponse));
}
private:
static GetBlockListResult GetBlockListResultFromXml(_internal::XmlReader& reader)
{
GetBlockListResult ret;
enum class XmlTagName
{
k_BlockList,
k_CommittedBlocks,
k_Block,
k_UncommittedBlocks,
k_Unknown,
};
std::vector<XmlTagName> path;
while (true)
{
auto node = reader.Read();
if (node.Type == _internal::XmlNodeType::End)
{
break;
}
else if (node.Type == _internal::XmlNodeType::EndTag)
{
if (path.size() > 0)
{
path.pop_back();
}
else
{
break;
}
}
else if (node.Type == _internal::XmlNodeType::StartTag)
{
if (node.Name == "BlockList")
{
path.emplace_back(XmlTagName::k_BlockList);
}
else if (node.Name == "CommittedBlocks")
{
path.emplace_back(XmlTagName::k_CommittedBlocks);
}
else if (node.Name == "Block")
{
path.emplace_back(XmlTagName::k_Block);
}
else if (node.Name == "UncommittedBlocks")
{
path.emplace_back(XmlTagName::k_UncommittedBlocks);
}
else
{
path.emplace_back(XmlTagName::k_Unknown);
}
if (path.size() == 3 && path[0] == XmlTagName::k_BlockList
&& path[1] == XmlTagName::k_CommittedBlocks && path[2] == XmlTagName::k_Block)
{
ret.CommittedBlocks.emplace_back(BlobBlockFromXml(reader));
path.pop_back();
}
else if (
path.size() == 3 && path[0] == XmlTagName::k_BlockList
&& path[1] == XmlTagName::k_UncommittedBlocks && path[2] == XmlTagName::k_Block)
{
ret.UncommittedBlocks.emplace_back(BlobBlockFromXml(reader));
path.pop_back();
}
}
else if (node.Type == _internal::XmlNodeType::Text)
{
}
}
return ret;
}
static BlobBlock BlobBlockFromXml(_internal::XmlReader& reader)
{
BlobBlock ret;
enum class XmlTagName
{
k_Name,
k_Size,
k_Unknown,
};
std::vector<XmlTagName> path;
while (true)
{
auto node = reader.Read();
if (node.Type == _internal::XmlNodeType::End)
{
break;
}
else if (node.Type == _internal::XmlNodeType::EndTag)
{
if (path.size() > 0)
{
path.pop_back();
}
else
{
break;
}
}
else if (node.Type == _internal::XmlNodeType::StartTag)
{
if (node.Name == "Name")
{
path.emplace_back(XmlTagName::k_Name);
}
else if (node.Name == "Size")
{
path.emplace_back(XmlTagName::k_Size);
}
else
{
path.emplace_back(XmlTagName::k_Unknown);
}
}
else if (node.Type == _internal::XmlNodeType::Text)
{
if (path.size() == 1 && path[0] == XmlTagName::k_Name)
{
ret.Name = node.Value;
}
else if (path.size() == 1 && path[0] == XmlTagName::k_Size)
{
ret.Size = std::stoll(node.Value);
}
}
}
return ret;
}
static void CommitBlockListOptionsToXml(
_internal::XmlWriter& writer,
const CommitBlockListOptions& options)
{
writer.Write(_internal::XmlNode{_internal::XmlNodeType::StartTag, "BlockList"});
for (const auto& i : options.BlockList)
{
writer.Write(
_internal::XmlNode{_internal::XmlNodeType::StartTag, i.first.ToString(), i.second});
}
writer.Write(_internal::XmlNode{_internal::XmlNodeType::EndTag});
}
}; // class BlockBlob
class PageBlob final {
public:
struct CreatePageBlobOptions final
{
Azure::Nullable<int32_t> Timeout;
int64_t BlobSize = -1;
Azure::Nullable<int64_t> SequenceNumber;
BlobHttpHeaders HttpHeaders;
Storage::Metadata Metadata;
Azure::Nullable<std::string> LeaseId;
Azure::Nullable<Models::AccessTier> AccessTier;
Azure::Nullable<std::string> EncryptionKey;
Azure::Nullable<std::vector<uint8_t>> EncryptionKeySha256;
Azure::Nullable<EncryptionAlgorithmType> EncryptionAlgorithm;
Azure::Nullable<std::string> EncryptionScope;
Azure::Nullable<Azure::DateTime> IfModifiedSince;
Azure::Nullable<Azure::DateTime> IfUnmodifiedSince;
Azure::ETag IfMatch;
Azure::ETag IfNoneMatch;
Azure::Nullable<std::string> IfTags;
std::map<std::string, std::string> Tags;
}; // struct CreatePageBlobOptions
static Azure::Response<CreatePageBlobResult> Create(
Azure::Core::Http::_internal::HttpPipeline& pipeline,
const Azure::Core::Url& url,
const CreatePageBlobOptions& options,
const Azure::Core::Context& context)
{
auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Put, url);
request.SetHeader("Content-Length", "0");
request.SetHeader("x-ms-version", "2020-02-10");
if (options.Timeout.HasValue())
{
request.GetUrl().AppendQueryParameter(
"timeout", std::to_string(options.Timeout.Value()));
}
if (!options.HttpHeaders.ContentType.empty())
{
request.SetHeader("x-ms-blob-content-type", options.HttpHeaders.ContentType);
}
if (!options.HttpHeaders.ContentEncoding.empty())
{
request.SetHeader("x-ms-blob-content-encoding", options.HttpHeaders.ContentEncoding);
}
if (!options.HttpHeaders.ContentLanguage.empty())
{
request.SetHeader("x-ms-blob-content-language", options.HttpHeaders.ContentLanguage);
}
if (!options.HttpHeaders.CacheControl.empty())
{
request.SetHeader("x-ms-blob-cache-control", options.HttpHeaders.CacheControl);
}
if (!Azure::Core::Convert::Base64Encode(options.HttpHeaders.ContentHash.Value).empty())
{
request.SetHeader(
"x-ms-blob-content-md5",
Azure::Core::Convert::Base64Encode(options.HttpHeaders.ContentHash.Value));
}
if (!options.HttpHeaders.ContentDisposition.empty())
{
request.SetHeader(
"x-ms-blob-content-disposition", options.HttpHeaders.ContentDisposition);
}
for (const auto& pair : options.Metadata)
{
request.SetHeader("x-ms-meta-" + pair.first, pair.second);
}
if (!options.Tags.empty())
{
std::string blobTagsValue;
for (const auto& tag : options.Tags)
{
if (!blobTagsValue.empty())
{
blobTagsValue += "&";
}
blobTagsValue += _internal::UrlEncodeQueryParameter(tag.first) + "="
+ _internal::UrlEncodeQueryParameter(tag.second);
}
request.SetHeader("x-ms-tags", std::move(blobTagsValue));
}
if (options.LeaseId.HasValue())
{
request.SetHeader("x-ms-lease-id", options.LeaseId.Value());
}
request.SetHeader("x-ms-blob-type", "PageBlob");
request.SetHeader("x-ms-blob-content-length", std::to_string(options.BlobSize));
if (options.SequenceNumber.HasValue())
{
request.SetHeader(
"x-ms-blob-sequence-number", std::to_string(options.SequenceNumber.Value()));
}
if (options.AccessTier.HasValue())
{
request.SetHeader("x-ms-access-tier", options.AccessTier.Value().ToString());
}
if (options.EncryptionKey.HasValue())
{
request.SetHeader("x-ms-encryption-key", options.EncryptionKey.Value());
}
if (options.EncryptionKeySha256.HasValue())
{
request.SetHeader(
"x-ms-encryption-key-sha256",
Azure::Core::Convert::Base64Encode(options.EncryptionKeySha256.Value()));
}
if (options.EncryptionAlgorithm.HasValue())
{
request.SetHeader(
"x-ms-encryption-algorithm", options.EncryptionAlgorithm.Value().ToString());
}
if (options.EncryptionScope.HasValue())
{
request.SetHeader("x-ms-encryption-scope", options.EncryptionScope.Value());
}
if (options.IfModifiedSince.HasValue())
{
request.SetHeader(
"If-Modified-Since",
options.IfModifiedSince.Value().ToString(Azure::DateTime::DateFormat::Rfc1123));
}
if (options.IfUnmodifiedSince.HasValue())
{
request.SetHeader(
"If-Unmodified-Since",
options.IfUnmodifiedSince.Value().ToString(Azure::DateTime::DateFormat::Rfc1123));
}
if (options.IfMatch.HasValue() && !options.IfMatch.ToString().empty())
{
request.SetHeader("If-Match", options.IfMatch.ToString());
}
if (options.IfNoneMatch.HasValue() && !options.IfNoneMatch.ToString().empty())
{
request.SetHeader("If-None-Match", options.IfNoneMatch.ToString());
}
if (options.IfTags.HasValue())
{
request.SetHeader("x-ms-if-tags", options.IfTags.Value());
}
auto pHttpResponse = pipeline.Send(request, context);
Azure::Core::Http::RawResponse& httpResponse = *pHttpResponse;
CreatePageBlobResult response;
auto http_status_code = httpResponse.GetStatusCode();
if (http_status_code != Azure::Core::Http::HttpStatusCode::Created)
{
throw StorageException::CreateFromResponse(std::move(pHttpResponse));
}
response.ETag = Azure::ETag(httpResponse.GetHeaders().at("etag"));
response.LastModified = Azure::DateTime::Parse(
httpResponse.GetHeaders().at("last-modified"), Azure::DateTime::DateFormat::Rfc1123);
auto x_ms_version_id__iterator = httpResponse.GetHeaders().find("x-ms-version-id");
if (x_ms_version_id__iterator != httpResponse.GetHeaders().end())
{
response.VersionId = x_ms_version_id__iterator->second;
}
response.IsServerEncrypted
= httpResponse.GetHeaders().at("x-ms-request-server-encrypted") == "true";
auto x_ms_encryption_key_sha256__iterator
= httpResponse.GetHeaders().find("x-ms-encryption-key-sha256");
if (x_ms_encryption_key_sha256__iterator != httpResponse.GetHeaders().end())
{
response.EncryptionKeySha256
= Azure::Core::Convert::Base64Decode(x_ms_encryption_key_sha256__iterator->second);
}
auto x_ms_encryption_scope__iterator
= httpResponse.GetHeaders().find("x-ms-encryption-scope");
if (x_ms_encryption_scope__iterator != httpResponse.GetHeaders().end())
{
response.EncryptionScope = x_ms_encryption_scope__iterator->second;
}
return Azure::Response<CreatePageBlobResult>(
std::move(response), std::move(pHttpResponse));
}
struct UploadPageBlobPagesOptions final
{
Azure::Nullable<int32_t> Timeout;
Azure::Core::Http::HttpRange Range;
Azure::Nullable<ContentHash> TransactionalContentHash;
Azure::Nullable<std::string> LeaseId;
Azure::Nullable<int64_t> IfSequenceNumberLessThanOrEqualTo;
Azure::Nullable<int64_t> IfSequenceNumberLessThan;
Azure::Nullable<int64_t> IfSequenceNumberEqualTo;
Azure::Nullable<std::string> EncryptionKey;
Azure::Nullable<std::vector<uint8_t>> EncryptionKeySha256;
Azure::Nullable<EncryptionAlgorithmType> EncryptionAlgorithm;
Azure::Nullable<std::string> EncryptionScope;
Azure::Nullable<Azure::DateTime> IfModifiedSince;
Azure::Nullable<Azure::DateTime> IfUnmodifiedSince;
Azure::ETag IfMatch;
Azure::ETag IfNoneMatch;
Azure::Nullable<std::string> IfTags;
}; // struct UploadPageBlobPagesOptions
static Azure::Response<UploadPagesResult> UploadPages(
Azure::Core::Http::_internal::HttpPipeline& pipeline,
const Azure::Core::Url& url,
Azure::Core::IO::BodyStream& requestBody,
const UploadPageBlobPagesOptions& options,
const Azure::Core::Context& context)
{
auto request
= Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Put, url, &requestBody);
request.SetHeader("Content-Length", std::to_string(requestBody.Length()));
request.GetUrl().AppendQueryParameter("comp", "page");
request.SetHeader("x-ms-version", "2020-02-10");
if (options.Timeout.HasValue())
{
request.GetUrl().AppendQueryParameter(
"timeout", std::to_string(options.Timeout.Value()));
}
{
std::string headerValue = "bytes=" + std::to_string(options.Range.Offset) + "-";
if (options.Range.Length.HasValue())
{
headerValue
+= std::to_string(options.Range.Offset + options.Range.Length.Value() - 1);
}
request.SetHeader("x-ms-range", std::move(headerValue));
}
if (options.TransactionalContentHash.HasValue())
{
if (options.TransactionalContentHash.Value().Algorithm == HashAlgorithm::Md5)
{
request.SetHeader(
"Content-MD5",
Azure::Core::Convert::Base64Encode(
options.TransactionalContentHash.Value().Value));
}
else if (options.TransactionalContentHash.Value().Algorithm == HashAlgorithm::Crc64)
{
request.SetHeader(
"x-ms-content-crc64",
Azure::Core::Convert::Base64Encode(
options.TransactionalContentHash.Value().Value));
}
}
request.SetHeader("x-ms-page-write", "update");
if (options.LeaseId.HasValue())
{
request.SetHeader("x-ms-lease-id", options.LeaseId.Value());
}
if (options.IfSequenceNumberLessThanOrEqualTo.HasValue())
{
request.SetHeader(
"x-ms-if-sequence-number-le",
std::to_string(options.IfSequenceNumberLessThanOrEqualTo.Value()));
}
if (options.IfSequenceNumberLessThan.HasValue())
{
request.SetHeader(
"x-ms-if-sequence-number-lt",
std::to_string(options.IfSequenceNumberLessThan.Value()));
}
if (options.IfSequenceNumberEqualTo.HasValue())
{
request.SetHeader(
"x-ms-if-sequence-number-eq",
std::to_string(options.IfSequenceNumberEqualTo.Value()));
}
if (options.EncryptionKey.HasValue())
{
request.SetHeader("x-ms-encryption-key", options.EncryptionKey.Value());
}
if (options.EncryptionKeySha256.HasValue())
{
request.SetHeader(
"x-ms-encryption-key-sha256",
Azure::Core::Convert::Base64Encode(options.EncryptionKeySha256.Value()));
}
if (options.EncryptionAlgorithm.HasValue())
{
request.SetHeader(
"x-ms-encryption-algorithm", options.EncryptionAlgorithm.Value().ToString());
}
if (options.EncryptionScope.HasValue())
{
request.SetHeader("x-ms-encryption-scope", options.EncryptionScope.Value());
}
if (options.IfModifiedSince.HasValue())
{
request.SetHeader(
"If-Modified-Since",
options.IfModifiedSince.Value().ToString(Azure::DateTime::DateFormat::Rfc1123));
}
if (options.IfUnmodifiedSince.HasValue())
{
request.SetHeader(
"If-Unmodified-Since",
options.IfUnmodifiedSince.Value().ToString(Azure::DateTime::DateFormat::Rfc1123));
}
if (options.IfMatch.HasValue() && !options.IfMatch.ToString().empty())
{
request.SetHeader("If-Match", options.IfMatch.ToString());
}
if (options.IfNoneMatch.HasValue() && !options.IfNoneMatch.ToString().empty())
{
request.SetHeader("If-None-Match", options.IfNoneMatch.ToString());
}
if (options.IfTags.HasValue())
{
request.SetHeader("x-ms-if-tags", options.IfTags.Value());
}
auto pHttpResponse = pipeline.Send(request, context);
Azure::Core::Http::RawResponse& httpResponse = *pHttpResponse;
UploadPagesResult response;
auto http_status_code = httpResponse.GetStatusCode();
if (http_status_code != Azure::Core::Http::HttpStatusCode::Created)
{
throw StorageException::CreateFromResponse(std::move(pHttpResponse));
}
response.ETag = Azure::ETag(httpResponse.GetHeaders().at("etag"));
response.LastModified = Azure::DateTime::Parse(
httpResponse.GetHeaders().at("last-modified"), Azure::DateTime::DateFormat::Rfc1123);
{
const auto& headers = httpResponse.GetHeaders();
auto content_md5_iterator = headers.find("content-md5");
if (content_md5_iterator != headers.end())
{
ContentHash hash;
hash.Algorithm = HashAlgorithm::Md5;
hash.Value = Azure::Core::Convert::Base64Decode(content_md5_iterator->second);
response.TransactionalContentHash = std::move(hash);
}
auto x_ms_content_crc64_iterator = headers.find("x-ms-content-crc64");
if (x_ms_content_crc64_iterator != headers.end())
{
ContentHash hash;
hash.Algorithm = HashAlgorithm::Crc64;
hash.Value = Azure::Core::Convert::Base64Decode(x_ms_content_crc64_iterator->second);
response.TransactionalContentHash = std::move(hash);
}
}
response.SequenceNumber
= std::stoll(httpResponse.GetHeaders().at("x-ms-blob-sequence-number"));
response.IsServerEncrypted
= httpResponse.GetHeaders().at("x-ms-request-server-encrypted") == "true";
auto x_ms_encryption_key_sha256__iterator
= httpResponse.GetHeaders().find("x-ms-encryption-key-sha256");
if (x_ms_encryption_key_sha256__iterator != httpResponse.GetHeaders().end())
{
response.EncryptionKeySha256
= Azure::Core::Convert::Base64Decode(x_ms_encryption_key_sha256__iterator->second);
}
auto x_ms_encryption_scope__iterator
= httpResponse.GetHeaders().find("x-ms-encryption-scope");
if (x_ms_encryption_scope__iterator != httpResponse.GetHeaders().end())
{
response.EncryptionScope = x_ms_encryption_scope__iterator->second;
}
return Azure::Response<UploadPagesResult>(std::move(response), std::move(pHttpResponse));
}
struct UploadPageBlobPagesFromUriOptions final
{
Azure::Nullable<int32_t> Timeout;
std::string SourceUri;
Azure::Core::Http::HttpRange SourceRange;
Azure::Core::Http::HttpRange Range;
Azure::Nullable<ContentHash> TransactionalContentHash;
Azure::Nullable<std::string> LeaseId;
Azure::Nullable<int64_t> IfSequenceNumberLessThanOrEqualTo;
Azure::Nullable<int64_t> IfSequenceNumberLessThan;
Azure::Nullable<int64_t> IfSequenceNumberEqualTo;
Azure::Nullable<std::string> EncryptionKey;
Azure::Nullable<std::vector<uint8_t>> EncryptionKeySha256;
Azure::Nullable<EncryptionAlgorithmType> EncryptionAlgorithm;
Azure::Nullable<std::string> EncryptionScope;
Azure::Nullable<Azure::DateTime> IfModifiedSince;
Azure::Nullable<Azure::DateTime> IfUnmodifiedSince;
Azure::ETag IfMatch;
Azure::ETag IfNoneMatch;
Azure::Nullable<std::string> IfTags;
Azure::Nullable<Azure::DateTime> SourceIfModifiedSince;
Azure::Nullable<Azure::DateTime> SourceIfUnmodifiedSince;
Azure::ETag SourceIfMatch;
Azure::ETag SourceIfNoneMatch;
}; // struct UploadPageBlobPagesFromUriOptions
static Azure::Response<UploadPagesFromUriResult> UploadPagesFromUri(
Azure::Core::Http::_internal::HttpPipeline& pipeline,
const Azure::Core::Url& url,
const UploadPageBlobPagesFromUriOptions& options,
const Azure::Core::Context& context)
{
auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Put, url);
request.SetHeader("Content-Length", "0");
request.GetUrl().AppendQueryParameter("comp", "page");
request.SetHeader("x-ms-version", "2020-02-10");
if (options.Timeout.HasValue())
{
request.GetUrl().AppendQueryParameter(
"timeout", std::to_string(options.Timeout.Value()));
}
{
std::string headerValue = "bytes=" + std::to_string(options.Range.Offset) + "-";
if (options.Range.Length.HasValue())
{
headerValue
+= std::to_string(options.Range.Offset + options.Range.Length.Value() - 1);
}
request.SetHeader("x-ms-range", std::move(headerValue));
}
request.SetHeader("x-ms-copy-source", options.SourceUri);
{
std::string headerValue = "bytes=" + std::to_string(options.SourceRange.Offset) + "-";
if (options.SourceRange.Length.HasValue())
{
headerValue += std::to_string(
options.SourceRange.Offset + options.SourceRange.Length.Value() - 1);
}
request.SetHeader("x-ms-source-range", std::move(headerValue));
}
if (options.TransactionalContentHash.HasValue())
{
if (options.TransactionalContentHash.Value().Algorithm == HashAlgorithm::Md5)
{
request.SetHeader(
"x-ms-source-content-md5",
Azure::Core::Convert::Base64Encode(
options.TransactionalContentHash.Value().Value));
}
else if (options.TransactionalContentHash.Value().Algorithm == HashAlgorithm::Crc64)
{
request.SetHeader(
"x-ms-source-content-crc64",
Azure::Core::Convert::Base64Encode(
options.TransactionalContentHash.Value().Value));
}
}
request.SetHeader("x-ms-page-write", "update");
if (options.LeaseId.HasValue())
{
request.SetHeader("x-ms-lease-id", options.LeaseId.Value());
}
if (options.IfSequenceNumberLessThanOrEqualTo.HasValue())
{
request.SetHeader(
"x-ms-if-sequence-number-le",
std::to_string(options.IfSequenceNumberLessThanOrEqualTo.Value()));
}
if (options.IfSequenceNumberLessThan.HasValue())
{
request.SetHeader(
"x-ms-if-sequence-number-lt",
std::to_string(options.IfSequenceNumberLessThan.Value()));
}
if (options.IfSequenceNumberEqualTo.HasValue())
{
request.SetHeader(
"x-ms-if-sequence-number-eq",
std::to_string(options.IfSequenceNumberEqualTo.Value()));
}
if (options.EncryptionKey.HasValue())
{
request.SetHeader("x-ms-encryption-key", options.EncryptionKey.Value());
}
if (options.EncryptionKeySha256.HasValue())
{
request.SetHeader(
"x-ms-encryption-key-sha256",
Azure::Core::Convert::Base64Encode(options.EncryptionKeySha256.Value()));
}
if (options.EncryptionAlgorithm.HasValue())
{
request.SetHeader(
"x-ms-encryption-algorithm", options.EncryptionAlgorithm.Value().ToString());
}
if (options.EncryptionScope.HasValue())
{
request.SetHeader("x-ms-encryption-scope", options.EncryptionScope.Value());
}
if (options.IfModifiedSince.HasValue())
{
request.SetHeader(
"If-Modified-Since",
options.IfModifiedSince.Value().ToString(Azure::DateTime::DateFormat::Rfc1123));
}
if (options.IfUnmodifiedSince.HasValue())
{
request.SetHeader(
"If-Unmodified-Since",
options.IfUnmodifiedSince.Value().ToString(Azure::DateTime::DateFormat::Rfc1123));
}
if (options.IfMatch.HasValue() && !options.IfMatch.ToString().empty())
{
request.SetHeader("If-Match", options.IfMatch.ToString());
}
if (options.IfNoneMatch.HasValue() && !options.IfNoneMatch.ToString().empty())
{
request.SetHeader("If-None-Match", options.IfNoneMatch.ToString());
}
if (options.IfTags.HasValue())
{
request.SetHeader("x-ms-if-tags", options.IfTags.Value());
}
if (options.SourceIfModifiedSince.HasValue())
{
request.SetHeader(
"x-ms-source-if-modified-since",
options.SourceIfModifiedSince.Value().ToString(
Azure::DateTime::DateFormat::Rfc1123));
}
if (options.SourceIfUnmodifiedSince.HasValue())
{
request.SetHeader(
"x-ms-source-if-unmodified-since",
options.SourceIfUnmodifiedSince.Value().ToString(
Azure::DateTime::DateFormat::Rfc1123));
}
if (options.SourceIfMatch.HasValue() && !options.SourceIfMatch.ToString().empty())
{
request.SetHeader("x-ms-source-if-match", options.SourceIfMatch.ToString());
}
if (options.SourceIfNoneMatch.HasValue() && !options.SourceIfNoneMatch.ToString().empty())
{
request.SetHeader("x-ms-source-if-none-match", options.SourceIfNoneMatch.ToString());
}
auto pHttpResponse = pipeline.Send(request, context);
Azure::Core::Http::RawResponse& httpResponse = *pHttpResponse;
UploadPagesFromUriResult response;
auto http_status_code = httpResponse.GetStatusCode();
if (http_status_code != Azure::Core::Http::HttpStatusCode::Created)
{
throw StorageException::CreateFromResponse(std::move(pHttpResponse));
}
response.ETag = Azure::ETag(httpResponse.GetHeaders().at("etag"));
response.LastModified = Azure::DateTime::Parse(
httpResponse.GetHeaders().at("last-modified"), Azure::DateTime::DateFormat::Rfc1123);
{
const auto& headers = httpResponse.GetHeaders();
auto content_md5_iterator = headers.find("content-md5");
if (content_md5_iterator != headers.end())
{
ContentHash hash;
hash.Algorithm = HashAlgorithm::Md5;
hash.Value = Azure::Core::Convert::Base64Decode(content_md5_iterator->second);
response.TransactionalContentHash = std::move(hash);
}
auto x_ms_content_crc64_iterator = headers.find("x-ms-content-crc64");
if (x_ms_content_crc64_iterator != headers.end())
{
ContentHash hash;
hash.Algorithm = HashAlgorithm::Crc64;
hash.Value = Azure::Core::Convert::Base64Decode(x_ms_content_crc64_iterator->second);
response.TransactionalContentHash = std::move(hash);
}
}
response.SequenceNumber
= std::stoll(httpResponse.GetHeaders().at("x-ms-blob-sequence-number"));
response.IsServerEncrypted
= httpResponse.GetHeaders().at("x-ms-request-server-encrypted") == "true";
auto x_ms_encryption_key_sha256__iterator
= httpResponse.GetHeaders().find("x-ms-encryption-key-sha256");
if (x_ms_encryption_key_sha256__iterator != httpResponse.GetHeaders().end())
{
response.EncryptionKeySha256
= Azure::Core::Convert::Base64Decode(x_ms_encryption_key_sha256__iterator->second);
}
auto x_ms_encryption_scope__iterator
= httpResponse.GetHeaders().find("x-ms-encryption-scope");
if (x_ms_encryption_scope__iterator != httpResponse.GetHeaders().end())
{
response.EncryptionScope = x_ms_encryption_scope__iterator->second;
}
return Azure::Response<UploadPagesFromUriResult>(
std::move(response), std::move(pHttpResponse));
}
struct ClearPageBlobPagesOptions final
{
Azure::Nullable<int32_t> Timeout;
Azure::Core::Http::HttpRange Range;
Azure::Nullable<std::string> LeaseId;
Azure::Nullable<int64_t> IfSequenceNumberLessThanOrEqualTo;
Azure::Nullable<int64_t> IfSequenceNumberLessThan;
Azure::Nullable<int64_t> IfSequenceNumberEqualTo;
Azure::Nullable<std::string> EncryptionKey;
Azure::Nullable<std::vector<uint8_t>> EncryptionKeySha256;
Azure::Nullable<EncryptionAlgorithmType> EncryptionAlgorithm;
Azure::Nullable<std::string> EncryptionScope;
Azure::Nullable<Azure::DateTime> IfModifiedSince;
Azure::Nullable<Azure::DateTime> IfUnmodifiedSince;
Azure::ETag IfMatch;
Azure::ETag IfNoneMatch;
Azure::Nullable<std::string> IfTags;
}; // struct ClearPageBlobPagesOptions
static Azure::Response<ClearPagesResult> ClearPages(
Azure::Core::Http::_internal::HttpPipeline& pipeline,
const Azure::Core::Url& url,
const ClearPageBlobPagesOptions& options,
const Azure::Core::Context& context)
{
auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Put, url);
request.SetHeader("Content-Length", "0");
request.GetUrl().AppendQueryParameter("comp", "page");
request.SetHeader("x-ms-version", "2020-02-10");
if (options.Timeout.HasValue())
{
request.GetUrl().AppendQueryParameter(
"timeout", std::to_string(options.Timeout.Value()));
}
{
std::string headerValue = "bytes=" + std::to_string(options.Range.Offset) + "-";
if (options.Range.Length.HasValue())
{
headerValue
+= std::to_string(options.Range.Offset + options.Range.Length.Value() - 1);
}
request.SetHeader("x-ms-range", std::move(headerValue));
}
request.SetHeader("x-ms-page-write", "clear");
if (options.LeaseId.HasValue())
{
request.SetHeader("x-ms-lease-id", options.LeaseId.Value());
}
if (options.IfSequenceNumberLessThanOrEqualTo.HasValue())
{
request.SetHeader(
"x-ms-if-sequence-number-le",
std::to_string(options.IfSequenceNumberLessThanOrEqualTo.Value()));
}
if (options.IfSequenceNumberLessThan.HasValue())
{
request.SetHeader(
"x-ms-if-sequence-number-lt",
std::to_string(options.IfSequenceNumberLessThan.Value()));
}
if (options.IfSequenceNumberEqualTo.HasValue())
{
request.SetHeader(
"x-ms-if-sequence-number-eq",
std::to_string(options.IfSequenceNumberEqualTo.Value()));
}
if (options.EncryptionKey.HasValue())
{
request.SetHeader("x-ms-encryption-key", options.EncryptionKey.Value());
}
if (options.EncryptionKeySha256.HasValue())
{
request.SetHeader(
"x-ms-encryption-key-sha256",
Azure::Core::Convert::Base64Encode(options.EncryptionKeySha256.Value()));
}
if (options.EncryptionAlgorithm.HasValue())
{
request.SetHeader(
"x-ms-encryption-algorithm", options.EncryptionAlgorithm.Value().ToString());
}
if (options.EncryptionScope.HasValue())
{
request.SetHeader("x-ms-encryption-scope", options.EncryptionScope.Value());
}
if (options.IfModifiedSince.HasValue())
{
request.SetHeader(
"If-Modified-Since",
options.IfModifiedSince.Value().ToString(Azure::DateTime::DateFormat::Rfc1123));
}
if (options.IfUnmodifiedSince.HasValue())
{
request.SetHeader(
"If-Unmodified-Since",
options.IfUnmodifiedSince.Value().ToString(Azure::DateTime::DateFormat::Rfc1123));
}
if (options.IfMatch.HasValue() && !options.IfMatch.ToString().empty())
{
request.SetHeader("If-Match", options.IfMatch.ToString());
}
if (options.IfNoneMatch.HasValue() && !options.IfNoneMatch.ToString().empty())
{
request.SetHeader("If-None-Match", options.IfNoneMatch.ToString());
}
if (options.IfTags.HasValue())
{
request.SetHeader("x-ms-if-tags", options.IfTags.Value());
}
auto pHttpResponse = pipeline.Send(request, context);
Azure::Core::Http::RawResponse& httpResponse = *pHttpResponse;
ClearPagesResult response;
auto http_status_code = httpResponse.GetStatusCode();
if (http_status_code != Azure::Core::Http::HttpStatusCode::Created)
{
throw StorageException::CreateFromResponse(std::move(pHttpResponse));
}
response.ETag = Azure::ETag(httpResponse.GetHeaders().at("etag"));
response.LastModified = Azure::DateTime::Parse(
httpResponse.GetHeaders().at("last-modified"), Azure::DateTime::DateFormat::Rfc1123);
response.SequenceNumber
= std::stoll(httpResponse.GetHeaders().at("x-ms-blob-sequence-number"));
return Azure::Response<ClearPagesResult>(std::move(response), std::move(pHttpResponse));
}
struct ResizePageBlobOptions final
{
Azure::Nullable<int32_t> Timeout;
int64_t BlobSize = -1;
Azure::Nullable<std::string> LeaseId;
Azure::Nullable<Azure::DateTime> IfModifiedSince;
Azure::Nullable<Azure::DateTime> IfUnmodifiedSince;
Azure::ETag IfMatch;
Azure::ETag IfNoneMatch;
Azure::Nullable<std::string> IfTags;
}; // struct ResizePageBlobOptions
static Azure::Response<ResizePageBlobResult> Resize(
Azure::Core::Http::_internal::HttpPipeline& pipeline,
const Azure::Core::Url& url,
const ResizePageBlobOptions& options,
const Azure::Core::Context& context)
{
auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Put, url);
request.SetHeader("Content-Length", "0");
request.GetUrl().AppendQueryParameter("comp", "properties");
request.SetHeader("x-ms-version", "2020-02-10");
if (options.Timeout.HasValue())
{
request.GetUrl().AppendQueryParameter(
"timeout", std::to_string(options.Timeout.Value()));
}
request.SetHeader("x-ms-blob-content-length", std::to_string(options.BlobSize));
if (options.LeaseId.HasValue())
{
request.SetHeader("x-ms-lease-id", options.LeaseId.Value());
}
if (options.IfModifiedSince.HasValue())
{
request.SetHeader(
"If-Modified-Since",
options.IfModifiedSince.Value().ToString(Azure::DateTime::DateFormat::Rfc1123));
}
if (options.IfUnmodifiedSince.HasValue())
{
request.SetHeader(
"If-Unmodified-Since",
options.IfUnmodifiedSince.Value().ToString(Azure::DateTime::DateFormat::Rfc1123));
}
if (options.IfMatch.HasValue() && !options.IfMatch.ToString().empty())
{
request.SetHeader("If-Match", options.IfMatch.ToString());
}
if (options.IfNoneMatch.HasValue() && !options.IfNoneMatch.ToString().empty())
{
request.SetHeader("If-None-Match", options.IfNoneMatch.ToString());
}
if (options.IfTags.HasValue())
{
request.SetHeader("x-ms-if-tags", options.IfTags.Value());
}
auto pHttpResponse = pipeline.Send(request, context);
Azure::Core::Http::RawResponse& httpResponse = *pHttpResponse;
ResizePageBlobResult response;
auto http_status_code = httpResponse.GetStatusCode();
if (http_status_code != Azure::Core::Http::HttpStatusCode::Ok)
{
throw StorageException::CreateFromResponse(std::move(pHttpResponse));
}
response.ETag = Azure::ETag(httpResponse.GetHeaders().at("etag"));
response.LastModified = Azure::DateTime::Parse(
httpResponse.GetHeaders().at("last-modified"), Azure::DateTime::DateFormat::Rfc1123);
response.SequenceNumber
= std::stoll(httpResponse.GetHeaders().at("x-ms-blob-sequence-number"));
return Azure::Response<ResizePageBlobResult>(
std::move(response), std::move(pHttpResponse));
}
struct UpdatePageBlobSequenceNumberOptions final
{
Azure::Nullable<int32_t> Timeout;
SequenceNumberAction Action;
Azure::Nullable<int64_t> SequenceNumber;
Azure::Nullable<std::string> LeaseId;
Azure::Nullable<Azure::DateTime> IfModifiedSince;
Azure::Nullable<Azure::DateTime> IfUnmodifiedSince;
Azure::ETag IfMatch;
Azure::ETag IfNoneMatch;
Azure::Nullable<std::string> IfTags;
}; // struct UpdatePageBlobSequenceNumberOptions
static Azure::Response<UpdateSequenceNumberResult> UpdateSequenceNumber(
Azure::Core::Http::_internal::HttpPipeline& pipeline,
const Azure::Core::Url& url,
const UpdatePageBlobSequenceNumberOptions& options,
const Azure::Core::Context& context)
{
auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Put, url);
request.SetHeader("Content-Length", "0");
request.GetUrl().AppendQueryParameter("comp", "properties");
request.SetHeader("x-ms-version", "2020-02-10");
if (options.Timeout.HasValue())
{
request.GetUrl().AppendQueryParameter(
"timeout", std::to_string(options.Timeout.Value()));
}
if (options.LeaseId.HasValue())
{
request.SetHeader("x-ms-lease-id", options.LeaseId.Value());
}
if (options.IfModifiedSince.HasValue())
{
request.SetHeader(
"If-Modified-Since",
options.IfModifiedSince.Value().ToString(Azure::DateTime::DateFormat::Rfc1123));
}
if (options.IfUnmodifiedSince.HasValue())
{
request.SetHeader(
"If-Unmodified-Since",
options.IfUnmodifiedSince.Value().ToString(Azure::DateTime::DateFormat::Rfc1123));
}
if (options.IfMatch.HasValue() && !options.IfMatch.ToString().empty())
{
request.SetHeader("If-Match", options.IfMatch.ToString());
}
if (options.IfNoneMatch.HasValue() && !options.IfNoneMatch.ToString().empty())
{
request.SetHeader("If-None-Match", options.IfNoneMatch.ToString());
}
if (options.IfTags.HasValue())
{
request.SetHeader("x-ms-if-tags", options.IfTags.Value());
}
request.SetHeader("x-ms-sequence-number-action", options.Action.ToString());
if (options.SequenceNumber.HasValue())
{
request.SetHeader(
"x-ms-blob-sequence-number", std::to_string(options.SequenceNumber.Value()));
}
auto pHttpResponse = pipeline.Send(request, context);
Azure::Core::Http::RawResponse& httpResponse = *pHttpResponse;
UpdateSequenceNumberResult response;
auto http_status_code = httpResponse.GetStatusCode();
if (http_status_code != Azure::Core::Http::HttpStatusCode::Ok)
{
throw StorageException::CreateFromResponse(std::move(pHttpResponse));
}
response.ETag = Azure::ETag(httpResponse.GetHeaders().at("etag"));
response.LastModified = Azure::DateTime::Parse(
httpResponse.GetHeaders().at("last-modified"), Azure::DateTime::DateFormat::Rfc1123);
response.SequenceNumber
= std::stoll(httpResponse.GetHeaders().at("x-ms-blob-sequence-number"));
return Azure::Response<UpdateSequenceNumberResult>(
std::move(response), std::move(pHttpResponse));
}
struct GetPageBlobPageRangesOptions final
{
Azure::Nullable<int32_t> Timeout;
Azure::Nullable<std::string> PreviousSnapshot;
Azure::Nullable<std::string> PreviousSnapshotUrl;
Azure::Nullable<Azure::Core::Http::HttpRange> Range;
Azure::Nullable<std::string> LeaseId;
Azure::Nullable<Azure::DateTime> IfModifiedSince;
Azure::Nullable<Azure::DateTime> IfUnmodifiedSince;
Azure::ETag IfMatch;
Azure::ETag IfNoneMatch;
Azure::Nullable<std::string> IfTags;
}; // struct GetPageBlobPageRangesOptions
static Azure::Response<Models::_detail::GetPageRangesResult> GetPageRanges(
Azure::Core::Http::_internal::HttpPipeline& pipeline,
const Azure::Core::Url& url,
const GetPageBlobPageRangesOptions& options,
const Azure::Core::Context& context)
{
auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Get, url);
request.GetUrl().AppendQueryParameter("comp", "pagelist");
if (options.PreviousSnapshot.HasValue())
{
request.GetUrl().AppendQueryParameter(
"prevsnapshot",
_internal::UrlEncodeQueryParameter(options.PreviousSnapshot.Value()));
}
request.SetHeader("x-ms-version", "2020-02-10");
if (options.Timeout.HasValue())
{
request.GetUrl().AppendQueryParameter(
"timeout", std::to_string(options.Timeout.Value()));
}
if (options.Range.HasValue())
{
std::string headerValue = "bytes=" + std::to_string(options.Range.Value().Offset) + "-";
if (options.Range.Value().Length.HasValue())
{
headerValue += std::to_string(
options.Range.Value().Offset + options.Range.Value().Length.Value() - 1);
}
request.SetHeader("x-ms-range", std::move(headerValue));
}
if (options.LeaseId.HasValue())
{
request.SetHeader("x-ms-lease-id", options.LeaseId.Value());
}
if (options.PreviousSnapshotUrl.HasValue())
{
request.SetHeader("x-ms-previous-snapshot-url", options.PreviousSnapshotUrl.Value());
}
if (options.IfModifiedSince.HasValue())
{
request.SetHeader(
"If-Modified-Since",
options.IfModifiedSince.Value().ToString(Azure::DateTime::DateFormat::Rfc1123));
}
if (options.IfUnmodifiedSince.HasValue())
{
request.SetHeader(
"If-Unmodified-Since",
options.IfUnmodifiedSince.Value().ToString(Azure::DateTime::DateFormat::Rfc1123));
}
if (options.IfMatch.HasValue() && !options.IfMatch.ToString().empty())
{
request.SetHeader("If-Match", options.IfMatch.ToString());
}
if (options.IfNoneMatch.HasValue() && !options.IfNoneMatch.ToString().empty())
{
request.SetHeader("If-None-Match", options.IfNoneMatch.ToString());
}
if (options.IfTags.HasValue())
{
request.SetHeader("x-ms-if-tags", options.IfTags.Value());
}
auto pHttpResponse = pipeline.Send(request, context);
Azure::Core::Http::RawResponse& httpResponse = *pHttpResponse;
Models::_detail::GetPageRangesResult response;
auto http_status_code = httpResponse.GetStatusCode();
if (http_status_code != Azure::Core::Http::HttpStatusCode::Ok)
{
throw StorageException::CreateFromResponse(std::move(pHttpResponse));
}
{
const auto& httpResponseBody = httpResponse.GetBody();
_internal::XmlReader reader(
reinterpret_cast<const char*>(httpResponseBody.data()), httpResponseBody.size());
response = GetPageRangesResultInternalFromXml(reader);
}
response.ETag = Azure::ETag(httpResponse.GetHeaders().at("etag"));
response.LastModified = Azure::DateTime::Parse(
httpResponse.GetHeaders().at("last-modified"), Azure::DateTime::DateFormat::Rfc1123);
response.BlobSize = std::stoll(httpResponse.GetHeaders().at("x-ms-blob-content-length"));
return Azure::Response<Models::_detail::GetPageRangesResult>(
std::move(response), std::move(pHttpResponse));
}
struct StartBlobCopyIncrementalOptions final
{
Azure::Nullable<int32_t> Timeout;
std::string CopySource;
Azure::Nullable<Azure::DateTime> IfModifiedSince;
Azure::Nullable<Azure::DateTime> IfUnmodifiedSince;
Azure::ETag IfMatch;
Azure::ETag IfNoneMatch;
Azure::Nullable<std::string> IfTags;
}; // struct StartBlobCopyIncrementalOptions
static Azure::Response<Models::_detail::StartBlobCopyIncrementalResult>
StartCopyIncremental(
Azure::Core::Http::_internal::HttpPipeline& pipeline,
const Azure::Core::Url& url,
const StartBlobCopyIncrementalOptions& options,
const Azure::Core::Context& context)
{
auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Put, url);
request.SetHeader("Content-Length", "0");
request.GetUrl().AppendQueryParameter("comp", "incrementalcopy");
request.SetHeader("x-ms-version", "2020-02-10");
if (options.Timeout.HasValue())
{
request.GetUrl().AppendQueryParameter(
"timeout", std::to_string(options.Timeout.Value()));
}
request.SetHeader("x-ms-copy-source", options.CopySource);
if (options.IfModifiedSince.HasValue())
{
request.SetHeader(
"If-Modified-Since",
options.IfModifiedSince.Value().ToString(Azure::DateTime::DateFormat::Rfc1123));
}
if (options.IfUnmodifiedSince.HasValue())
{
request.SetHeader(
"If-Unmodified-Since",
options.IfUnmodifiedSince.Value().ToString(Azure::DateTime::DateFormat::Rfc1123));
}
if (options.IfMatch.HasValue() && !options.IfMatch.ToString().empty())
{
request.SetHeader("If-Match", options.IfMatch.ToString());
}
if (options.IfNoneMatch.HasValue() && !options.IfNoneMatch.ToString().empty())
{
request.SetHeader("If-None-Match", options.IfNoneMatch.ToString());
}
if (options.IfTags.HasValue())
{
request.SetHeader("x-ms-if-tags", options.IfTags.Value());
}
auto pHttpResponse = pipeline.Send(request, context);
Azure::Core::Http::RawResponse& httpResponse = *pHttpResponse;
Models::_detail::StartBlobCopyIncrementalResult response;
auto http_status_code = httpResponse.GetStatusCode();
if (http_status_code != Azure::Core::Http::HttpStatusCode::Accepted)
{
throw StorageException::CreateFromResponse(std::move(pHttpResponse));
}
response.ETag = Azure::ETag(httpResponse.GetHeaders().at("etag"));
response.LastModified = Azure::DateTime::Parse(
httpResponse.GetHeaders().at("last-modified"), Azure::DateTime::DateFormat::Rfc1123);
response.CopyId = httpResponse.GetHeaders().at("x-ms-copy-id");
response.CopyStatus = CopyStatus(httpResponse.GetHeaders().at("x-ms-copy-status"));
auto x_ms_version_id__iterator = httpResponse.GetHeaders().find("x-ms-version-id");
if (x_ms_version_id__iterator != httpResponse.GetHeaders().end())
{
response.VersionId = x_ms_version_id__iterator->second;
}
return Azure::Response<Models::_detail::StartBlobCopyIncrementalResult>(
std::move(response), std::move(pHttpResponse));
}
private:
static Models::_detail::GetPageRangesResult GetPageRangesResultInternalFromXml(
_internal::XmlReader& reader)
{
Models::_detail::GetPageRangesResult ret;
enum class XmlTagName
{
k_PageList,
k_PageRange,
k_ClearRange,
k_Unknown,
};
std::vector<XmlTagName> path;
while (true)
{
auto node = reader.Read();
if (node.Type == _internal::XmlNodeType::End)
{
break;
}
else if (node.Type == _internal::XmlNodeType::EndTag)
{
if (path.size() > 0)
{
path.pop_back();
}
else
{
break;
}
}
else if (node.Type == _internal::XmlNodeType::StartTag)
{
if (node.Name == "PageList")
{
path.emplace_back(XmlTagName::k_PageList);
}
else if (node.Name == "PageRange")
{
path.emplace_back(XmlTagName::k_PageRange);
}
else if (node.Name == "ClearRange")
{
path.emplace_back(XmlTagName::k_ClearRange);
}
else
{
path.emplace_back(XmlTagName::k_Unknown);
}
if (path.size() == 2 && path[0] == XmlTagName::k_PageList
&& path[1] == XmlTagName::k_PageRange)
{
ret.PageRanges.emplace_back(PageRangesFromXml(reader));
path.pop_back();
}
else if (
path.size() == 2 && path[0] == XmlTagName::k_PageList
&& path[1] == XmlTagName::k_ClearRange)
{
ret.ClearRanges.emplace_back(ClearRangesFromXml(reader));
path.pop_back();
}
}
else if (node.Type == _internal::XmlNodeType::Text)
{
}
}
return ret;
}
static Azure::Core::Http::HttpRange ClearRangesFromXml(_internal::XmlReader& reader)
{
int depth = 0;
bool is_start = false;
bool is_end = false;
int64_t start = 0;
int64_t end = 0;
while (true)
{
auto node = reader.Read();
if (node.Type == _internal::XmlNodeType::End)
{
break;
}
else if (node.Type == _internal::XmlNodeType::StartTag && node.Name == "Start")
{
++depth;
is_start = true;
}
else if (node.Type == _internal::XmlNodeType::StartTag && node.Name == "End")
{
++depth;
is_end = true;
}
else if (node.Type == _internal::XmlNodeType::EndTag)
{
is_start = false;
is_end = false;
if (depth-- == 0)
{
break;
}
}
if (depth == 1 && node.Type == _internal::XmlNodeType::Text)
{
if (is_start)
{
start = std::stoll(node.Value);
}
else if (is_end)
{
end = std::stoll(node.Value);
}
}
}
Azure::Core::Http::HttpRange ret;
ret.Offset = start;
ret.Length = end - start + 1;
return ret;
}
static Azure::Core::Http::HttpRange PageRangesFromXml(_internal::XmlReader& reader)
{
int depth = 0;
bool is_start = false;
bool is_end = false;
int64_t start = 0;
int64_t end = 0;
while (true)
{
auto node = reader.Read();
if (node.Type == _internal::XmlNodeType::End)
{
break;
}
else if (node.Type == _internal::XmlNodeType::StartTag && node.Name == "Start")
{
++depth;
is_start = true;
}
else if (node.Type == _internal::XmlNodeType::StartTag && node.Name == "End")
{
++depth;
is_end = true;
}
else if (node.Type == _internal::XmlNodeType::EndTag)
{
is_start = false;
is_end = false;
if (depth-- == 0)
{
break;
}
}
if (depth == 1 && node.Type == _internal::XmlNodeType::Text)
{
if (is_start)
{
start = std::stoll(node.Value);
}
else if (is_end)
{
end = std::stoll(node.Value);
}
}
}
Azure::Core::Http::HttpRange ret;
ret.Offset = start;
ret.Length = end - start + 1;
return ret;
}
}; // class PageBlob
class AppendBlob final {
public:
struct CreateAppendBlobOptions final
{
Azure::Nullable<int32_t> Timeout;
BlobHttpHeaders HttpHeaders;
Storage::Metadata Metadata;
std::map<std::string, std::string> Tags;
Azure::Nullable<std::string> LeaseId;
Azure::Nullable<std::string> EncryptionKey;
Azure::Nullable<std::vector<uint8_t>> EncryptionKeySha256;
Azure::Nullable<EncryptionAlgorithmType> EncryptionAlgorithm;
Azure::Nullable<std::string> EncryptionScope;
Azure::Nullable<Azure::DateTime> IfModifiedSince;
Azure::Nullable<Azure::DateTime> IfUnmodifiedSince;
Azure::ETag IfMatch;
Azure::ETag IfNoneMatch;
Azure::Nullable<std::string> IfTags;
}; // struct CreateAppendBlobOptions
static Azure::Response<CreateAppendBlobResult> Create(
Azure::Core::Http::_internal::HttpPipeline& pipeline,
const Azure::Core::Url& url,
const CreateAppendBlobOptions& options,
const Azure::Core::Context& context)
{
auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Put, url);
request.SetHeader("Content-Length", "0");
request.SetHeader("x-ms-version", "2020-02-10");
if (options.Timeout.HasValue())
{
request.GetUrl().AppendQueryParameter(
"timeout", std::to_string(options.Timeout.Value()));
}
if (!options.HttpHeaders.ContentType.empty())
{
request.SetHeader("x-ms-blob-content-type", options.HttpHeaders.ContentType);
}
if (!options.HttpHeaders.ContentEncoding.empty())
{
request.SetHeader("x-ms-blob-content-encoding", options.HttpHeaders.ContentEncoding);
}
if (!options.HttpHeaders.ContentLanguage.empty())
{
request.SetHeader("x-ms-blob-content-language", options.HttpHeaders.ContentLanguage);
}
if (!options.HttpHeaders.CacheControl.empty())
{
request.SetHeader("x-ms-blob-cache-control", options.HttpHeaders.CacheControl);
}
if (!Azure::Core::Convert::Base64Encode(options.HttpHeaders.ContentHash.Value).empty())
{
request.SetHeader(
"x-ms-blob-content-md5",
Azure::Core::Convert::Base64Encode(options.HttpHeaders.ContentHash.Value));
}
if (!options.HttpHeaders.ContentDisposition.empty())
{
request.SetHeader(
"x-ms-blob-content-disposition", options.HttpHeaders.ContentDisposition);
}
for (const auto& pair : options.Metadata)
{
request.SetHeader("x-ms-meta-" + pair.first, pair.second);
}
if (!options.Tags.empty())
{
std::string blobTagsValue;
for (const auto& tag : options.Tags)
{
if (!blobTagsValue.empty())
{
blobTagsValue += "&";
}
blobTagsValue += _internal::UrlEncodeQueryParameter(tag.first) + "="
+ _internal::UrlEncodeQueryParameter(tag.second);
}
request.SetHeader("x-ms-tags", std::move(blobTagsValue));
}
if (options.LeaseId.HasValue())
{
request.SetHeader("x-ms-lease-id", options.LeaseId.Value());
}
request.SetHeader("x-ms-blob-type", "AppendBlob");
if (options.EncryptionKey.HasValue())
{
request.SetHeader("x-ms-encryption-key", options.EncryptionKey.Value());
}
if (options.EncryptionKeySha256.HasValue())
{
request.SetHeader(
"x-ms-encryption-key-sha256",
Azure::Core::Convert::Base64Encode(options.EncryptionKeySha256.Value()));
}
if (options.EncryptionAlgorithm.HasValue())
{
request.SetHeader(
"x-ms-encryption-algorithm", options.EncryptionAlgorithm.Value().ToString());
}
if (options.EncryptionScope.HasValue())
{
request.SetHeader("x-ms-encryption-scope", options.EncryptionScope.Value());
}
if (options.IfModifiedSince.HasValue())
{
request.SetHeader(
"If-Modified-Since",
options.IfModifiedSince.Value().ToString(Azure::DateTime::DateFormat::Rfc1123));
}
if (options.IfUnmodifiedSince.HasValue())
{
request.SetHeader(
"If-Unmodified-Since",
options.IfUnmodifiedSince.Value().ToString(Azure::DateTime::DateFormat::Rfc1123));
}
if (options.IfMatch.HasValue() && !options.IfMatch.ToString().empty())
{
request.SetHeader("If-Match", options.IfMatch.ToString());
}
if (options.IfNoneMatch.HasValue() && !options.IfNoneMatch.ToString().empty())
{
request.SetHeader("If-None-Match", options.IfNoneMatch.ToString());
}
if (options.IfTags.HasValue())
{
request.SetHeader("x-ms-if-tags", options.IfTags.Value());
}
auto pHttpResponse = pipeline.Send(request, context);
Azure::Core::Http::RawResponse& httpResponse = *pHttpResponse;
CreateAppendBlobResult response;
auto http_status_code = httpResponse.GetStatusCode();
if (http_status_code != Azure::Core::Http::HttpStatusCode::Created)
{
throw StorageException::CreateFromResponse(std::move(pHttpResponse));
}
response.ETag = Azure::ETag(httpResponse.GetHeaders().at("etag"));
response.LastModified = Azure::DateTime::Parse(
httpResponse.GetHeaders().at("last-modified"), Azure::DateTime::DateFormat::Rfc1123);
auto x_ms_version_id__iterator = httpResponse.GetHeaders().find("x-ms-version-id");
if (x_ms_version_id__iterator != httpResponse.GetHeaders().end())
{
response.VersionId = x_ms_version_id__iterator->second;
}
response.IsServerEncrypted
= httpResponse.GetHeaders().at("x-ms-request-server-encrypted") == "true";
auto x_ms_encryption_key_sha256__iterator
= httpResponse.GetHeaders().find("x-ms-encryption-key-sha256");
if (x_ms_encryption_key_sha256__iterator != httpResponse.GetHeaders().end())
{
response.EncryptionKeySha256
= Azure::Core::Convert::Base64Decode(x_ms_encryption_key_sha256__iterator->second);
}
auto x_ms_encryption_scope__iterator
= httpResponse.GetHeaders().find("x-ms-encryption-scope");
if (x_ms_encryption_scope__iterator != httpResponse.GetHeaders().end())
{
response.EncryptionScope = x_ms_encryption_scope__iterator->second;
}
return Azure::Response<CreateAppendBlobResult>(
std::move(response), std::move(pHttpResponse));
}
struct AppendBlockOptions final
{
Azure::Nullable<int32_t> Timeout;
Azure::Nullable<ContentHash> TransactionalContentHash;
Azure::Nullable<std::string> LeaseId;
Azure::Nullable<int64_t> MaxSize;
Azure::Nullable<int64_t> AppendPosition;
Azure::Nullable<std::string> EncryptionKey;
Azure::Nullable<std::vector<uint8_t>> EncryptionKeySha256;
Azure::Nullable<EncryptionAlgorithmType> EncryptionAlgorithm;
Azure::Nullable<std::string> EncryptionScope;
Azure::Nullable<Azure::DateTime> IfModifiedSince;
Azure::Nullable<Azure::DateTime> IfUnmodifiedSince;
Azure::ETag IfMatch;
Azure::ETag IfNoneMatch;
Azure::Nullable<std::string> IfTags;
}; // struct AppendBlockOptions
static Azure::Response<AppendBlockResult> AppendBlock(
Azure::Core::Http::_internal::HttpPipeline& pipeline,
const Azure::Core::Url& url,
Azure::Core::IO::BodyStream& requestBody,
const AppendBlockOptions& options,
const Azure::Core::Context& context)
{
auto request
= Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Put, url, &requestBody);
request.SetHeader("Content-Length", std::to_string(requestBody.Length()));
request.GetUrl().AppendQueryParameter("comp", "appendblock");
request.SetHeader("x-ms-version", "2020-02-10");
if (options.Timeout.HasValue())
{
request.GetUrl().AppendQueryParameter(
"timeout", std::to_string(options.Timeout.Value()));
}
if (options.TransactionalContentHash.HasValue())
{
if (options.TransactionalContentHash.Value().Algorithm == HashAlgorithm::Md5)
{
request.SetHeader(
"Content-MD5",
Azure::Core::Convert::Base64Encode(
options.TransactionalContentHash.Value().Value));
}
else if (options.TransactionalContentHash.Value().Algorithm == HashAlgorithm::Crc64)
{
request.SetHeader(
"x-ms-content-crc64",
Azure::Core::Convert::Base64Encode(
options.TransactionalContentHash.Value().Value));
}
}
if (options.LeaseId.HasValue())
{
request.SetHeader("x-ms-lease-id", options.LeaseId.Value());
}
if (options.MaxSize.HasValue())
{
request.SetHeader(
"x-ms-blob-condition-maxsize", std::to_string(options.MaxSize.Value()));
}
if (options.AppendPosition.HasValue())
{
request.SetHeader(
"x-ms-blob-condition-appendpos", std::to_string(options.AppendPosition.Value()));
}
if (options.EncryptionKey.HasValue())
{
request.SetHeader("x-ms-encryption-key", options.EncryptionKey.Value());
}
if (options.EncryptionKeySha256.HasValue())
{
request.SetHeader(
"x-ms-encryption-key-sha256",
Azure::Core::Convert::Base64Encode(options.EncryptionKeySha256.Value()));
}
if (options.EncryptionAlgorithm.HasValue())
{
request.SetHeader(
"x-ms-encryption-algorithm", options.EncryptionAlgorithm.Value().ToString());
}
if (options.EncryptionScope.HasValue())
{
request.SetHeader("x-ms-encryption-scope", options.EncryptionScope.Value());
}
if (options.IfModifiedSince.HasValue())
{
request.SetHeader(
"If-Modified-Since",
options.IfModifiedSince.Value().ToString(Azure::DateTime::DateFormat::Rfc1123));
}
if (options.IfUnmodifiedSince.HasValue())
{
request.SetHeader(
"If-Unmodified-Since",
options.IfUnmodifiedSince.Value().ToString(Azure::DateTime::DateFormat::Rfc1123));
}
if (options.IfMatch.HasValue() && !options.IfMatch.ToString().empty())
{
request.SetHeader("If-Match", options.IfMatch.ToString());
}
if (options.IfNoneMatch.HasValue() && !options.IfNoneMatch.ToString().empty())
{
request.SetHeader("If-None-Match", options.IfNoneMatch.ToString());
}
if (options.IfTags.HasValue())
{
request.SetHeader("x-ms-if-tags", options.IfTags.Value());
}
auto pHttpResponse = pipeline.Send(request, context);
Azure::Core::Http::RawResponse& httpResponse = *pHttpResponse;
AppendBlockResult response;
auto http_status_code = httpResponse.GetStatusCode();
if (http_status_code != Azure::Core::Http::HttpStatusCode::Created)
{
throw StorageException::CreateFromResponse(std::move(pHttpResponse));
}
response.ETag = Azure::ETag(httpResponse.GetHeaders().at("etag"));
response.LastModified = Azure::DateTime::Parse(
httpResponse.GetHeaders().at("last-modified"), Azure::DateTime::DateFormat::Rfc1123);
{
const auto& headers = httpResponse.GetHeaders();
auto content_md5_iterator = headers.find("content-md5");
if (content_md5_iterator != headers.end())
{
ContentHash hash;
hash.Algorithm = HashAlgorithm::Md5;
hash.Value = Azure::Core::Convert::Base64Decode(content_md5_iterator->second);
response.TransactionalContentHash = std::move(hash);
}
auto x_ms_content_crc64_iterator = headers.find("x-ms-content-crc64");
if (x_ms_content_crc64_iterator != headers.end())
{
ContentHash hash;
hash.Algorithm = HashAlgorithm::Crc64;
hash.Value = Azure::Core::Convert::Base64Decode(x_ms_content_crc64_iterator->second);
response.TransactionalContentHash = std::move(hash);
}
}
response.AppendOffset
= std::stoll(httpResponse.GetHeaders().at("x-ms-blob-append-offset"));
response.CommittedBlockCount
= std::stoi(httpResponse.GetHeaders().at("x-ms-blob-committed-block-count"));
response.IsServerEncrypted
= httpResponse.GetHeaders().at("x-ms-request-server-encrypted") == "true";
auto x_ms_encryption_key_sha256__iterator
= httpResponse.GetHeaders().find("x-ms-encryption-key-sha256");
if (x_ms_encryption_key_sha256__iterator != httpResponse.GetHeaders().end())
{
response.EncryptionKeySha256
= Azure::Core::Convert::Base64Decode(x_ms_encryption_key_sha256__iterator->second);
}
auto x_ms_encryption_scope__iterator
= httpResponse.GetHeaders().find("x-ms-encryption-scope");
if (x_ms_encryption_scope__iterator != httpResponse.GetHeaders().end())
{
response.EncryptionScope = x_ms_encryption_scope__iterator->second;
}
return Azure::Response<AppendBlockResult>(std::move(response), std::move(pHttpResponse));
}
struct AppendBlockFromUriOptions final
{
Azure::Nullable<int32_t> Timeout;
std::string SourceUri;
Azure::Nullable<Azure::Core::Http::HttpRange> SourceRange;
Azure::Nullable<ContentHash> TransactionalContentHash;
Azure::Nullable<std::string> LeaseId;
Azure::Nullable<int64_t> MaxSize;
Azure::Nullable<int64_t> AppendPosition;
Azure::Nullable<std::string> EncryptionKey;
Azure::Nullable<std::vector<uint8_t>> EncryptionKeySha256;
Azure::Nullable<EncryptionAlgorithmType> EncryptionAlgorithm;
Azure::Nullable<std::string> EncryptionScope;
Azure::Nullable<Azure::DateTime> IfModifiedSince;
Azure::Nullable<Azure::DateTime> IfUnmodifiedSince;
Azure::ETag IfMatch;
Azure::ETag IfNoneMatch;
Azure::Nullable<std::string> IfTags;
}; // struct AppendBlockFromUriOptions
static Azure::Response<AppendBlockFromUriResult> AppendBlockFromUri(
Azure::Core::Http::_internal::HttpPipeline& pipeline,
const Azure::Core::Url& url,
const AppendBlockFromUriOptions& options,
const Azure::Core::Context& context)
{
auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Put, url);
request.SetHeader("Content-Length", "0");
request.GetUrl().AppendQueryParameter("comp", "appendblock");
request.SetHeader("x-ms-version", "2020-02-10");
if (options.Timeout.HasValue())
{
request.GetUrl().AppendQueryParameter(
"timeout", std::to_string(options.Timeout.Value()));
}
request.SetHeader("x-ms-copy-source", options.SourceUri);
if (options.SourceRange.HasValue())
{
std::string headerValue
= "bytes=" + std::to_string(options.SourceRange.Value().Offset) + "-";
if (options.SourceRange.Value().Length.HasValue())
{
headerValue += std::to_string(
options.SourceRange.Value().Offset + options.SourceRange.Value().Length.Value()
- 1);
}
request.SetHeader("x-ms-source-range", std::move(headerValue));
}
if (options.TransactionalContentHash.HasValue())
{
if (options.TransactionalContentHash.Value().Algorithm == HashAlgorithm::Md5)
{
request.SetHeader(
"x-ms-source-content-md5",
Azure::Core::Convert::Base64Encode(
options.TransactionalContentHash.Value().Value));
}
else if (options.TransactionalContentHash.Value().Algorithm == HashAlgorithm::Crc64)
{
request.SetHeader(
"x-ms-source-content-crc64",
Azure::Core::Convert::Base64Encode(
options.TransactionalContentHash.Value().Value));
}
}
if (options.LeaseId.HasValue())
{
request.SetHeader("x-ms-lease-id", options.LeaseId.Value());
}
if (options.MaxSize.HasValue())
{
request.SetHeader(
"x-ms-blob-condition-maxsize", std::to_string(options.MaxSize.Value()));
}
if (options.AppendPosition.HasValue())
{
request.SetHeader(
"x-ms-blob-condition-appendpos", std::to_string(options.AppendPosition.Value()));
}
if (options.EncryptionKey.HasValue())
{
request.SetHeader("x-ms-encryption-key", options.EncryptionKey.Value());
}
if (options.EncryptionKeySha256.HasValue())
{
request.SetHeader(
"x-ms-encryption-key-sha256",
Azure::Core::Convert::Base64Encode(options.EncryptionKeySha256.Value()));
}
if (options.EncryptionAlgorithm.HasValue())
{
request.SetHeader(
"x-ms-encryption-algorithm", options.EncryptionAlgorithm.Value().ToString());
}
if (options.EncryptionScope.HasValue())
{
request.SetHeader("x-ms-encryption-scope", options.EncryptionScope.Value());
}
if (options.IfModifiedSince.HasValue())
{
request.SetHeader(
"If-Modified-Since",
options.IfModifiedSince.Value().ToString(Azure::DateTime::DateFormat::Rfc1123));
}
if (options.IfUnmodifiedSince.HasValue())
{
request.SetHeader(
"If-Unmodified-Since",
options.IfUnmodifiedSince.Value().ToString(Azure::DateTime::DateFormat::Rfc1123));
}
if (options.IfMatch.HasValue() && !options.IfMatch.ToString().empty())
{
request.SetHeader("If-Match", options.IfMatch.ToString());
}
if (options.IfNoneMatch.HasValue() && !options.IfNoneMatch.ToString().empty())
{
request.SetHeader("If-None-Match", options.IfNoneMatch.ToString());
}
if (options.IfTags.HasValue())
{
request.SetHeader("x-ms-if-tags", options.IfTags.Value());
}
auto pHttpResponse = pipeline.Send(request, context);
Azure::Core::Http::RawResponse& httpResponse = *pHttpResponse;
AppendBlockFromUriResult response;
auto http_status_code = httpResponse.GetStatusCode();
if (http_status_code != Azure::Core::Http::HttpStatusCode::Created)
{
throw StorageException::CreateFromResponse(std::move(pHttpResponse));
}
response.ETag = Azure::ETag(httpResponse.GetHeaders().at("etag"));
response.LastModified = Azure::DateTime::Parse(
httpResponse.GetHeaders().at("last-modified"), Azure::DateTime::DateFormat::Rfc1123);
{
const auto& headers = httpResponse.GetHeaders();
auto content_md5_iterator = headers.find("content-md5");
if (content_md5_iterator != headers.end())
{
ContentHash hash;
hash.Algorithm = HashAlgorithm::Md5;
hash.Value = Azure::Core::Convert::Base64Decode(content_md5_iterator->second);
response.TransactionalContentHash = std::move(hash);
}
auto x_ms_content_crc64_iterator = headers.find("x-ms-content-crc64");
if (x_ms_content_crc64_iterator != headers.end())
{
ContentHash hash;
hash.Algorithm = HashAlgorithm::Crc64;
hash.Value = Azure::Core::Convert::Base64Decode(x_ms_content_crc64_iterator->second);
response.TransactionalContentHash = std::move(hash);
}
}
response.AppendOffset
= std::stoll(httpResponse.GetHeaders().at("x-ms-blob-append-offset"));
response.CommittedBlockCount
= std::stoi(httpResponse.GetHeaders().at("x-ms-blob-committed-block-count"));
response.IsServerEncrypted
= httpResponse.GetHeaders().at("x-ms-request-server-encrypted") == "true";
auto x_ms_encryption_key_sha256__iterator
= httpResponse.GetHeaders().find("x-ms-encryption-key-sha256");
if (x_ms_encryption_key_sha256__iterator != httpResponse.GetHeaders().end())
{
response.EncryptionKeySha256
= Azure::Core::Convert::Base64Decode(x_ms_encryption_key_sha256__iterator->second);
}
auto x_ms_encryption_scope__iterator
= httpResponse.GetHeaders().find("x-ms-encryption-scope");
if (x_ms_encryption_scope__iterator != httpResponse.GetHeaders().end())
{
response.EncryptionScope = x_ms_encryption_scope__iterator->second;
}
return Azure::Response<AppendBlockFromUriResult>(
std::move(response), std::move(pHttpResponse));
}
struct SealAppendBlobOptions final
{
Azure::Nullable<int32_t> Timeout;
Azure::Nullable<std::string> LeaseId;
Azure::Nullable<Azure::DateTime> IfModifiedSince;
Azure::Nullable<Azure::DateTime> IfUnmodifiedSince;
Azure::ETag IfMatch;
Azure::ETag IfNoneMatch;
Azure::Nullable<std::string> IfTags;
Azure::Nullable<int64_t> AppendPosition;
}; // struct SealAppendBlobOptions
static Azure::Response<SealAppendBlobResult> Seal(
Azure::Core::Http::_internal::HttpPipeline& pipeline,
const Azure::Core::Url& url,
const SealAppendBlobOptions& options,
const Azure::Core::Context& context)
{
auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Put, url);
request.SetHeader("Content-Length", "0");
request.GetUrl().AppendQueryParameter("comp", "seal");
request.SetHeader("x-ms-version", "2020-02-10");
if (options.Timeout.HasValue())
{
request.GetUrl().AppendQueryParameter(
"timeout", std::to_string(options.Timeout.Value()));
}
if (options.LeaseId.HasValue())
{
request.SetHeader("x-ms-lease-id", options.LeaseId.Value());
}
if (options.IfModifiedSince.HasValue())
{
request.SetHeader(
"If-Modified-Since",
options.IfModifiedSince.Value().ToString(Azure::DateTime::DateFormat::Rfc1123));
}
if (options.IfUnmodifiedSince.HasValue())
{
request.SetHeader(
"If-Unmodified-Since",
options.IfUnmodifiedSince.Value().ToString(Azure::DateTime::DateFormat::Rfc1123));
}
if (options.IfMatch.HasValue() && !options.IfMatch.ToString().empty())
{
request.SetHeader("If-Match", options.IfMatch.ToString());
}
if (options.IfNoneMatch.HasValue() && !options.IfNoneMatch.ToString().empty())
{
request.SetHeader("If-None-Match", options.IfNoneMatch.ToString());
}
if (options.IfTags.HasValue())
{
request.SetHeader("x-ms-if-tags", options.IfTags.Value());
}
if (options.AppendPosition.HasValue())
{
request.SetHeader(
"x-ms-blob-condition-appendpos", std::to_string(options.AppendPosition.Value()));
}
auto pHttpResponse = pipeline.Send(request, context);
Azure::Core::Http::RawResponse& httpResponse = *pHttpResponse;
SealAppendBlobResult response;
auto http_status_code = httpResponse.GetStatusCode();
if (http_status_code != Azure::Core::Http::HttpStatusCode::Ok)
{
throw StorageException::CreateFromResponse(std::move(pHttpResponse));
}
response.ETag = Azure::ETag(httpResponse.GetHeaders().at("etag"));
response.LastModified = Azure::DateTime::Parse(
httpResponse.GetHeaders().at("last-modified"), Azure::DateTime::DateFormat::Rfc1123);
return Azure::Response<SealAppendBlobResult>(
std::move(response), std::move(pHttpResponse));
}
private:
}; // class AppendBlob
class BlobBatch final {
public:
struct SubmitBlobBatchOptions final
{
Azure::Nullable<int32_t> Timeout;
std::string ContentType;
}; // struct SubmitBlobBatchOptions
static Azure::Response<Models::_detail::SubmitBlobBatchResult> SubmitBatch(
Azure::Core::Http::_internal::HttpPipeline& pipeline,
const Azure::Core::Url& url,
Azure::Core::IO::BodyStream& requestBody,
const SubmitBlobBatchOptions& options,
const Azure::Core::Context& context)
{
auto request
= Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Post, url, &requestBody);
request.SetHeader("Content-Length", std::to_string(requestBody.Length()));
request.GetUrl().AppendQueryParameter("comp", "batch");
request.SetHeader("x-ms-version", "2020-02-10");
if (options.Timeout.HasValue())
{
request.GetUrl().AppendQueryParameter(
"timeout", std::to_string(options.Timeout.Value()));
}
request.SetHeader("Content-Type", options.ContentType);
auto pHttpResponse = pipeline.Send(request, context);
Azure::Core::Http::RawResponse& httpResponse = *pHttpResponse;
Models::_detail::SubmitBlobBatchResult response;
auto http_status_code = httpResponse.GetStatusCode();
if (http_status_code != Azure::Core::Http::HttpStatusCode::Accepted)
{
throw StorageException::CreateFromResponse(std::move(pHttpResponse));
}
response.ContentType = httpResponse.GetHeaders().at("content-type");
return Azure::Response<Models::_detail::SubmitBlobBatchResult>(
std::move(response), std::move(pHttpResponse));
}
private:
}; // class BlobBatch
}; // class BlobRestClient
} // namespace _detail
}}} // namespace Azure::Storage::Blobs
|
#include "BallTracker.hpp"
#include "BallFilter.hpp"
#include <Utils.hpp>
#include <Processor.hpp>
#include <SystemState.hpp>
using namespace std;
using namespace boost;
using namespace Geometry2d;
// Balls closer together than this will be removed
static const float Distance_Limit = 0.2;
// Maximum distance between observations on consecutive frames to
// result in a possible acquisition.
static const float Acquisition_Match_Distance = 0.5;
// Age of a track, in microseconds, at which is it dropped
static const RJ::Seconds Drop_Possible_Track_Time(0.5);
static const RJ::Seconds Drop_Real_Track_Time(0.5);
static const float Position_Uncertainty = 0.5;
// Quickly removes element <i> from a vector without the preserving order of
// later elements
template <class T>
void fastRemove(T& v, unsigned int i) {
assert(i < v.size());
int last = v.size() - 1;
swap(v[i], v[last]);
v.pop_back();
}
BallTracker::BallTracker() {}
void drawX(SystemState* state, Point center, const QColor& color = Qt::red) {
static const float R = Ball_Radius;
state->drawLine(center + Point(-R, R), center + Point(R, -R), color);
state->drawLine(center + Point(R, R), center + Point(-R, -R), color);
}
void BallTracker::run(const vector<BallObservation>& obs, SystemState* state) {
auto n = obs.size();
vector<const BallObservation*> goodObs;
goodObs.resize(obs.size());
for (unsigned int i = 0; i < n; ++i) {
goodObs[i] = &obs[i];
}
#if 0
// Remove balls that are too close to other balls
if (n <= 20)
{
for (unsigned int i = 0; i < n; ++i)
{
for (unsigned int j = 0; j < n; ++j)
{
if (i != j && (goodObs[i] || goodObs[j]))
{
if (obs[i].pos.nearPoint(obs[j].pos, Distance_Limit))
{
// Balls are too close together: remove them both
if (goodObs[i])
{
drawX(state, obs[i].pos);
goodObs[i] = 0;
}
if (goodObs[j])
{
drawX(state, obs[j].pos);
goodObs[j] = 0;
}
}
}
}
}
// Remove null entries from goodObs, not preserving order
for (unsigned int i = 0; i < goodObs.size(); ++i)
{
if (goodObs[i] == 0)
{
fastRemove(goodObs, i);
--i;
}
}
}
#endif
RJ::Time now = RJ::now();
// FIXME - What time?
RJ::Time predictTime = now;
// Rectangle that defines the boundaries of the field.
// Note that we are working in team space.
const Rect field(
Point(-Field_Dimensions::Current_Dimensions.Width() / 2, 0),
Point(Field_Dimensions::Current_Dimensions.Width() / 2,
Field_Dimensions::Current_Dimensions.Length()));
// Update the real ball
if (_ballFilter) {
// Get a prediction for this frame from the filter
float velocityUncertainty = 0;
Ball prediction =
_ballFilter->predict(predictTime, &velocityUncertainty);
Point windowCenter = prediction.pos;
float windowRadius =
Position_Uncertainty +
velocityUncertainty *
RJ::Seconds(predictTime - _lastTrackTime).count();
state->drawCircle(windowCenter, windowRadius, Qt::white);
// Find the closest new observation to the real ball's predicted
// position
float bestDist = -1;
unsigned int best = 0;
for (unsigned int i = 0; i < goodObs.size(); ++i) {
float d = goodObs[i]->pos.distTo(windowCenter);
if (goodObs[i]->time > _lastTrackTime && d <= windowRadius &&
(bestDist < 0 || d < bestDist)) {
bestDist = d;
best = i;
}
}
if (bestDist >= 0) {
// Update the filter
_ballFilter->updateEstimate(*goodObs[best]);
_lastTrackTime = goodObs[best]->time;
// Update the real track
state->ball = _ballFilter->predict(
RJ::Time(chrono::microseconds(state->logFrame->command_time())),
nullptr);
// Don't use this observation for a possible track since it's the
// real track
fastRemove(goodObs, best);
}
// If we haven't found an update in a long time, drop the real ball
// track
if ((now - _lastTrackTime) >= Drop_Real_Track_Time) {
_ballFilter.reset();
state->ball.valid = true;
}
} else {
state->ball.valid = true;
}
// Update possible tracks
for (unsigned int i = 0; i < _possibleTracks.size(); ++i) {
// Find the closest new observation to this track which is within
// Acquisition_Match_Distance
float bestDist = -1;
unsigned int best = 0;
for (unsigned int j = 0; j < goodObs.size(); ++j) {
float d = goodObs[j]->pos.distTo(_possibleTracks[i].obs.pos);
if (field.containsPoint(goodObs[j]->pos) &&
d <= Acquisition_Match_Distance &&
(bestDist < 0 || d < bestDist)) {
bestDist = d;
best = j;
}
}
if (bestDist >= 0) {
// Update this track
_possibleTracks[i].current = true;
_possibleTracks[i].obs = *goodObs[best];
++_possibleTracks[i].numFrames;
// Remove from goodObs
fastRemove(goodObs, best);
drawX(state, _possibleTracks[i].obs.pos, Qt::yellow);
} else {
_possibleTracks[i].current = false;
}
if ((now - _possibleTracks[i].obs.time) >= Drop_Possible_Track_Time) {
fastRemove(_possibleTracks, i);
--i;
}
}
// Any remaining observations will start new tracks
for (unsigned int i = 0; i < goodObs.size(); ++i) {
if (field.containsPoint(goodObs[i]->pos)) {
_possibleTracks.push_back(PossibleTrack(*goodObs[i]));
}
}
// Try to acquire the real ball
if (!_ballFilter) {
for (unsigned int i = 0; i < _possibleTracks.size(); ++i) {
if (_possibleTracks[i].current &&
_possibleTracks[i].numFrames >= 3) {
_ballFilter = std::make_shared<BallFilter>();
// First update and prediction
_ballFilter->updateEstimate(_possibleTracks[i].obs);
_lastTrackTime = _possibleTracks[i].obs.time;
state->ball = _ballFilter->predict(
RJ::Time(
chrono::microseconds(state->logFrame->command_time())),
nullptr);
fastRemove(_possibleTracks, i);
break;
}
}
}
}
|
/* @STSHELL_LICENSE_START@
*
* __ _______ ___________
* / |/ / __ \/ ___/_ __/
* / /|_/ / / / /\__ \ / /
* / / / / /_/ /___/ // /
* /_/ /_/\____//____//_/
*
* Multi-Objective System Tuner
* Copyright (c) 2007-2022 Politecnico di Milano
*
* Development leader: Vittorio Zaccaria
* Main developers: Vittorio Zaccaria, Gianluca Palermo, Fabrizio Castro
*
*
* @STSHELL_LICENSE_END@ */
#include "st_design_space.h"
#include <iostream>
#include <st_object.h>
#include <st_map.h>
#include <st_vector.h>
#include <st_shell_variables.h>
#include <st_parser.h>
#include <st_optimizer.h>
#include <st_doe.h>
#include <st_opt_utils.h>
class st_placket_burman : public st_doe {
public:
st_placket_burman() {}
string get_information();
st_vector *generate_doe(st_env *env);
};
string st_placket_burman::get_information() { return "Box behnken DoE"; }
vector<string> center_representation(int n) {
vector<string> repr(n);
for (int i = 0; i < n; i++)
repr[i] = "0";
return repr;
}
st_vector *st_placket_burman::generate_doe(st_env *env) {
st_assert(env->current_driver);
prs_display_message("Generating Placket-Burman DoE");
st_vector *doe = new st_vector();
int num_of_prs = env->current_design_space->ds_parameters.size();
if (num_of_prs < 2) {
prs_display_error(
"Too few parameters, at least two parameters are needed for this DoE.");
return NULL;
}
int n = 0;
// vector<string> apr;
vector<string> apr = center_representation(num_of_prs);
string tmp_apr;
st_point actual_point;
int additional_experiments;
if (num_of_prs < 12) {
additional_experiments = 11;
tmp_apr = "-+-+++---+-";
} else if (num_of_prs < 20) {
additional_experiments = 19;
tmp_apr = "-+--++++-+-+----++-";
} else if (num_of_prs < 24) {
additional_experiments = 23;
tmp_apr = "-++++-+-++--++--+-+----";
} else {
prs_display_error("Too many parameters! Value not supported by this DoE.");
return NULL;
}
for (int i_params = 0; i_params < num_of_prs; i_params++) {
apr[i_params] = "+";
}
env->current_design_space->convert_factorial_representation(
env, actual_point, apr, TWO_LEVEL_FF_MODE_CLASSIC);
env->current_design_space->print_factorial_design(env, apr, n);
doe->insert(n++, actual_point);
for (int i_params = 0; i_params < num_of_prs; i_params++) {
apr[i_params] = "-";
}
env->current_design_space->convert_factorial_representation(
env, actual_point, apr, TWO_LEVEL_FF_MODE_CLASSIC);
env->current_design_space->print_factorial_design(env, apr, n);
doe->insert(n++, actual_point);
for (int i_experiments = 0; i_experiments < additional_experiments;
i_experiments++) {
for (int i_params = 0; i_params < num_of_prs; i_params++) {
apr[i_params] =
tmp_apr[(i_params + i_experiments) % additional_experiments];
}
env->current_design_space->convert_factorial_representation(
env, actual_point, apr, TWO_LEVEL_FF_MODE_CLASSIC);
env->current_design_space->print_factorial_design(env, apr, n);
doe->insert(n++, actual_point);
}
return doe;
}
extern "C" {
st_doe *doe_generate_doe() { return new st_placket_burman(); }
st_command *get_help() {
const char *ref[] = {NULL};
const char *ref_help[] = {NULL};
st_command *help = new st_command(
multiple_opts,
" Plackett–Burman DoEs are experimental designs presented in 1946 by "
"Robin L. Plackett and J. P. Burman. Their goal was to find experimental "
"designs for investigating the dependence of some measured quantity on a "
"number of independent variables (factors), each taking L levels, in "
"such a way as to minimize the variance of the estimates of these "
"dependencies using a limited number of experiments. Interactions "
"between the factors were considered negligible. The solution to this "
"problem is to find an experimental design where each combination of "
"levels for any pair of factors appears the same number of times, "
"throughout all the experimental runs (refer table). A complete "
"factorial design would satisfy this criterion, but the idea was to find "
"smaller design. ",
"", ref, ref_help,
"This design of experiments generates design by using the PLACKETT "
"BURMAN technique. ",
STDRET);
help->alt_command_name = "Placket Burman Design of Experiments";
help->alt_command_synopsys = "doe_load_doe st_placket_burman";
help->alt_command_type = "doe";
return help;
};
}
|
// (C) Copyright Gennadiy Rozental 2001.
// 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/test for the library home page.
//
//!@file
//!@brief Random generator
// ***************************************************************************
#ifndef BOOST_TEST_DATA_MONOMORPHIC_GENERATORS_RANDOM_HPP_101512GER
#define BOOST_TEST_DATA_MONOMORPHIC_GENERATORS_RANDOM_HPP_101512GER
// Boost.Test
#include <boost/test/data/config.hpp>
#if !defined(BOOST_TEST_NO_RANDOM_DATASET_AVAILABLE) || defined(BOOST_TEST_DOXYGEN_DOC__)
#include <boost/test/data/monomorphic/generate.hpp>
#include <boost/test/data/monomorphic/generators/keywords.hpp>
// STL
#include <random>
#include <boost/test/detail/suppress_warnings.hpp>
//____________________________________________________________________________//
namespace boost {
namespace unit_test {
namespace data {
namespace {
nfp::keyword<struct seed_t> seed;
nfp::keyword<struct distribution_t> distribution;
nfp::keyword<struct engine_t> engine;
} // local namespace
namespace monomorphic {
namespace ds_detail {
template<typename SampleType>
struct default_distribution {
typedef typename mpl::if_<std::is_integral<SampleType>,
std::uniform_int_distribution<SampleType>,
std::uniform_real_distribution<SampleType>>::type type;
};
} // namespace ds_detail
// ************************************************************************** //
// ************** random_t ************** //
// ************************************************************************** //
/*!@brief Generator for the random sequences
*
* This class implements the generator concept (see @ref boost::unit_test::data::monomorphic::generated_by) for implementing
* a random number generator.
*/
template<typename SampleType = double,
typename DistributionType = typename ds_detail::default_distribution<SampleType>::type,
typename EngineType = std::default_random_engine>
class random_t {
public:
typedef SampleType sample;
typedef DistributionType distr_type;
typedef EngineType engine_type;
random_t()
: m_distribution()
, m_engine( std::random_device()() )
{}
explicit random_t( distr_type&& d )
: m_distribution( std::forward<distr_type>(d) )
, m_engine( std::random_device()() ){}
random_t( engine_type&& e, distr_type&& d )
: m_distribution( std::forward<distr_type>(d) )
, m_engine( std::forward<engine_type>(e) ){}
// Generator interface
data::size_t capacity() const { return BOOST_TEST_DS_INFINITE_SIZE; }
SampleType next()
{
return m_distribution( m_engine );
}
void reset() {}
//! Sets the seed of the pseudo-random number engine.
template<typename SeedType>
void seed( SeedType&& seed ) { m_engine.seed( std::forward<SeedType>( seed ) ); }
private:
// Data members
DistributionType m_distribution;
EngineType m_engine;
};
//____________________________________________________________________________//
} // namespace monomorphic
//! @brief Returns an infinite sequence of random numbers.
//!
//! The following overloads are available:
//! @code
//! auto d = random();
//! auto d = random(begin, end);
//! auto d = random(params);
//! @endcode
//!
//!
//! - The first overload uses the default distribution, which is uniform and which elements
//! are @c double type (the values are in [0, 1) ).
//! - The second overload generates numbers in the given interval. The distribution is uniform (in [begin, end)
//! for real numbers, and in [begin, end] for integers). The type of the distribution is deduced from the type
//! of the @c begin and @c end parameters.
//! - The third overload generates numbers using the named parameter inside @c params , which are:
//! - @c distribution: the distribution used. In this overload, since the type of the samples cannot be deduced,
//! the samples are of type @c double and the distribution is uniform real in [0, 1).
//! - @c seed: the seed for generating the values
//! - @c engine: the random number generator engine
//!
//! The function returns an object that implements the dataset API.
//! @note This function is available only for C++11 capable compilers.
inline monomorphic::generated_by< monomorphic::random_t<>> random()
{
return monomorphic::generated_by<monomorphic::random_t<>>( monomorphic::random_t<>() );
}
//____________________________________________________________________________//
/// @overload boost::unit_test::data::random()
template<typename SampleType>
inline monomorphic::generated_by< monomorphic::random_t<SampleType>>
random( SampleType begin, SampleType end )
{
typedef monomorphic::random_t<SampleType> Gen;
typedef typename Gen::distr_type distr_type;
return monomorphic::generated_by<Gen>( Gen( distr_type(begin,end) ) );
}
//____________________________________________________________________________//
namespace ds_detail {
template<typename Params>
struct random_gen_type {
typedef typename nfp::param_type<Params,decltype(distribution),std::uniform_real_distribution<>>::type distr_type;
typedef typename nfp::param_type<Params,decltype(engine),std::default_random_engine>::type engine_type;
typedef typename distr_type::result_type sample_type;
typedef monomorphic::random_t<sample_type,distr_type,engine_type> type;
};
}
/// @overload boost::unit_test::data::random()
template<typename Params>
inline monomorphic::generated_by<typename ds_detail::random_gen_type<Params>::type>
random( Params const& params )
{
typedef typename ds_detail::random_gen_type<Params>::type Gen;
typedef typename Gen::distr_type distr_type;
typedef typename Gen::engine_type engine_type;
std::random_device rd;
engine_type E;
// engine_type E( rd );
if( params.has(engine) )
E = params[engine];
distr_type D;
if( params.has(distribution) )
D = params[distribution];
Gen G( std::move(E), std::move(D) );
if( params.has(seed) )
G.seed( params[seed] );
return monomorphic::generated_by<Gen>( std::move(G) );
}
} // namespace data
} // namespace unit_test
} // namespace boost
#include <boost/test/detail/enable_warnings.hpp>
#endif // BOOST_TEST_NO_RANDOM_DATASET_AVAILABLE
#endif // BOOST_TEST_DATA_MONOMORPHIC_GENERATORS_RANDOM_HPP_101512GER
|
/*******************************************************************************
*
*Copyright: armuxinxian@aliyun.com
*
*Author: fangzhenmu
*
*File name: csf_message_error.hpp
*
*Version: 1.0
*
*Date: 22-3月-2019 22:38:33
*
*Description: Class(csf_message_error) 用于描述模块通信的错误
*
*Others:
*
*History:
*
*******************************************************************************/
#if !defined(CSF_MESSAGE_ERROR_H_INCLUDED_)
#define CSF_MESSAGE_ERROR_H_INCLUDED_
#include "csf_error.hpp"
namespace csf
{
namespace core
{
namespace system
{
namespace message
{
/**
* 用于描述模块通信的错误
* @author fangzhenmu
* @version 1.0
* @created 22-3月-2019 22:38:33
*/
class csf_message_error : public csf::core::module::csf_error
{
public:
inline explicit csf_message_error() {
}
/**
* 表示根据错误码(code)和错误描述(description)创建一个csf_message_error。
*
* @param code 表示错误码编码
* @param description 表示错误描述信息
*/
inline explicit csf_message_error(const csf_int32 code, const csf_string& description) {
}
/**
* 表示根据错误码(code)和错误描述(description)创建一个csf_message_error。
*
* @param code 表示错误码编码
* @param description 表示错误描述信息
*/
inline explicit csf_message_error(const csf_int32 code, const csf_char* description) {
}
virtual ~csf_message_error() {
}
};
}
}
}
}
#endif // !defined(CSF_MESSAGE_ERROR_H_INCLUDED_)
|
#include "opensslcpp/opensslcpp.hpp"
#include <iostream>
namespace OpensslCpp {
/**
* Ctors functions
*/
OpensslCpp::OpensslCpp() : _cert(new OpensslX509Cpp), _crl(new OpensslX509CRLCpp){
ERR_load_crypto_strings();
OpenSSL_add_all_algorithms();
}
OpensslCpp::~OpensslCpp() {
EVP_cleanup();
CRYPTO_cleanup_all_ex_data();
ERR_free_strings();
}
/**
* Private methods
*/
/**
* Create a BIO object with the BIO_new() function and put it in the
* unordered_map<string, OpensslBIOCpp>. The string is the name of the bio
* @input name Name of the BIO
* @input type BIO_METHOD to create the BIO
* @output void No return. The bio is put in the unordered_map.
*/
void OpensslCpp::newBIO(std::string name, BIO_METHOD* type) {
_bio[name] = std::make_shared<OpensslBIOCpp>(type);
}
/**
* Create a BIO object with the BIO_new_file() function and put it in the
* unordered_map<string, OpensslBIOCpp>. The string is the name of the bio
* @input name Name of the BIO
* @input filename Name of the file that you want to operate on
* @intput mode Mode used to open the file
* @output void No return. The bio is put in the unordered_map.
*/
void OpensslCpp::newBIOFile(std::string name, std::string filename, char* mode) {
_bio[name] = std::make_shared<OpensslBIOCpp>(filename, mode);
}
/**
* Create a BIO object with the BIO_new_fp() function and put it in the
* unordered_map<string, OpensslBIOCpp>. The string is the name of the bio
* @input name Name of the BIO
* @input stream File stream that you want to operate on
* @input flags BIO flags
* @output void No return. The bio is put in the unordered_map.
*/
void OpensslCpp::newBIOFp(std::string name, FILE* stream, int flags) {
_bio[name] = std::make_shared<OpensslBIOCpp>(stream, flags);
}
/**
* Wrapper for BIO_puts
*/
void OpensslCpp::puts(std::string bioname, std::string message) {
_bio[bioname]->puts(message.c_str());
}
/**
* Wrapper for BIO_printf
*/
void OpensslCpp::printf(std::string bioname, std::string message) {
_bio[bioname]->printf(message.c_str());
}
void OpensslCpp::loadCert(std::string certFilename) {
_certFilestr = certFilename;
_cert->loadCert(_certFilestr);
}
void OpensslCpp::loadCRL(std::string crlFilename) {
_crlFilestr = crlFilename;
_crl->loadCRL(crlFilename);
}
void OpensslCpp::printCertSerialNumber() {
std::string bioname = _certFilestr + "serialnumber";
newBIOFp(bioname, stdout, BIO_NOCLOSE);
_bio[bioname]->printf("Serial number is ");
i2a_ASN1_INTEGER(_bio[bioname]->getBIO(), _cert->getSerialNumberASN1());
_bio[bioname]->printf("\n");
}
void OpensslCpp::printCertificate() {
_cert->printCertificate();
}
void OpensslCpp::printCRL() {
_crl->printCRL();
}
void OpensslCpp::printCRLRevokedCerts() {
_crl->printRevokedCerts();
}
void OpensslCpp::printPublicKey(std::string bioname) {
_bio[bioname]->printf("Public key is ");
_bio[bioname]->printf("%d key \n\n", EVP_PKEY_bits(_cert->getPublicKey()));
_bio[bioname]->writePEMPublicKey(_cert->getPublicKey());
}
/**
* Verify if a certificate is in the revokation list. You need to load the certificate and the CRL before.
* @input void Using _cert and _crl
* @output revoked Boolean. If the certificate is in the CRL, revoked = 1, 0 otherwise
*/
bool OpensslCpp::verifyRevokationCert() {
if(std::find(_crl->getSerialRevokedCerts().begin(), _crl->getSerialRevokedCerts().end(), _cert->getSerialNumberHex()) == _crl->getSerialRevokedCerts().end()) {
std::cout << "there false" << std::endl;
return false;
}
else {
std::cout << "there true" << _cert->getSerialNumberHex() << std::endl;
return true;
}
}
}
|
#include "demo/xor_pattern/xor.h"
#include "etl/scope_guard.h"
#include "etl/armv7m/instructions.h"
#include "vga/arena.h"
#include "vga/timing.h"
#include "vga/vga.h"
#include "demo/config.h"
#include "demo/input.h"
#include "demo/xor_pattern/rasterizer.h"
DEMO_REQUIRE_RESOLUTION(800, 600)
namespace demo {
namespace xor_pattern {
struct Demo {
Rasterizer rasterizer{800};
vga::Band const band{&rasterizer, 600, nullptr};
};
void run() {
vga::arena_reset();
input_init();
auto d = vga::arena_make<Demo>();
vga::configure_band_list(&d->band);
ETL_ON_SCOPE_EXIT { vga::clear_band_list(); };
vga::video_on();
while (!user_button_pressed()) {
vga::sync_to_vblank();
}
vga::wait_for_vblank();
vga::video_off();
}
} // namespace xor_pattern
} // namespace demo
|
//===--- TypeCheckType.cpp - Type Validation ------------------------------===//
//
// 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 validation for Swift types, emitting semantic errors as
// appropriate and checking default initializer values.
//
//===----------------------------------------------------------------------===//
#include "TypeChecker.h"
#include "TypeCheckAvailability.h"
#include "TypeCheckConcurrency.h"
#include "TypeCheckProtocol.h"
#include "TypeCheckType.h"
#include "TypoCorrection.h"
#include "swift/AST/ASTDemangler.h"
#include "swift/AST/ASTVisitor.h"
#include "swift/AST/ASTWalker.h"
#include "swift/AST/DiagnosticsParse.h"
#include "swift/AST/ExistentialLayout.h"
#include "swift/AST/ForeignErrorConvention.h"
#include "swift/AST/GenericEnvironment.h"
#include "swift/AST/NameLookup.h"
#include "swift/AST/ParameterList.h"
#include "swift/AST/PrettyStackTrace.h"
#include "swift/AST/ProtocolConformance.h"
#include "swift/AST/SILLayout.h"
#include "swift/AST/SourceFile.h"
#include "swift/AST/TypeCheckRequests.h"
#include "swift/AST/TypeLoc.h"
#include "swift/AST/TypeResolutionStage.h"
#include "swift/Basic/SourceManager.h"
#include "swift/Basic/Statistic.h"
#include "swift/Basic/StringExtras.h"
#include "swift/ClangImporter/ClangImporter.h"
#include "swift/Strings.h"
#include "swift/Subsystems.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/DeclBase.h"
#include "clang/AST/DeclTemplate.h"
#include "llvm/ADT/APInt.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/ADT/Twine.h"
#include "llvm/Support/SaveAndRestore.h"
using namespace swift;
#define DEBUG_TYPE "TypeCheckType"
/// Type resolution.
TypeResolution
TypeResolution::forStructural(DeclContext *dc, TypeResolutionOptions options,
OpenUnboundGenericTypeFn unboundTyOpener,
HandlePlaceholderTypeReprFn placeholderHandler) {
return TypeResolution(dc, TypeResolutionStage::Structural, options,
unboundTyOpener, placeholderHandler);
}
TypeResolution
TypeResolution::forInterface(DeclContext *dc, TypeResolutionOptions options,
OpenUnboundGenericTypeFn unboundTyOpener,
HandlePlaceholderTypeReprFn placeholderHandler) {
return forInterface(dc, dc->getGenericEnvironmentOfContext(), options,
unboundTyOpener, placeholderHandler);
}
TypeResolution
TypeResolution::forInterface(DeclContext *dc, GenericEnvironment *genericEnv,
TypeResolutionOptions options,
OpenUnboundGenericTypeFn unboundTyOpener,
HandlePlaceholderTypeReprFn placeholderHandler) {
TypeResolution result(dc, TypeResolutionStage::Interface, options,
unboundTyOpener, placeholderHandler);
result.genericEnv = genericEnv;
return result;
}
TypeResolution TypeResolution::withOptions(TypeResolutionOptions opts) const {
TypeResolution result(dc, stage, opts, unboundTyOpener, placeholderHandler);
result.genericEnv = genericEnv;
return result;
}
ASTContext &TypeResolution::getASTContext() const {
return dc->getASTContext();
}
GenericSignature TypeResolution::getGenericSignature() const {
assert(
stage == TypeResolutionStage::Interface &&
"Structural resolution shouldn't require generic signature computation");
if (genericEnv)
return genericEnv->getGenericSignature();
return dc->getGenericSignatureOfContext();
}
// FIXME: It would be nice to have a 'DescriptiveTypeKind' abstraction instead.
static DescriptiveDeclKind describeDeclOfType(Type t) {
if (!t) {
return DescriptiveDeclKind::Type;
}
if (auto *NTD = t->getAnyNominal()) {
return NTD->getDescriptiveKind();
}
return DescriptiveDeclKind::Type;
}
Type TypeResolution::resolveDependentMemberType(
Type baseTy, DeclContext *DC,
SourceRange baseRange,
ComponentIdentTypeRepr *ref) const {
// FIXME(ModQual): Reject qualified names immediately; they cannot be
// dependent member types.
Identifier refIdentifier = ref->getNameRef().getBaseIdentifier();
switch (stage) {
case TypeResolutionStage::Structural:
return DependentMemberType::get(baseTy, refIdentifier);
case TypeResolutionStage::Interface:
// Handled below.
break;
}
assert(stage == TypeResolutionStage::Interface);
auto genericSig = getGenericSignature();
if (!genericSig)
return ErrorType::get(baseTy);
// Look for a nested type with the given name.
if (auto nestedType = genericSig->lookupNestedType(baseTy, refIdentifier)) {
// Record the type we found.
ref->setValue(nestedType, nullptr);
} else {
ASTContext &ctx = DC->getASTContext();
// Resolve the base to a potential archetype.
// Perform typo correction.
TypoCorrectionResults corrections(ref->getNameRef(), ref->getNameLoc());
TypeChecker::performTypoCorrection(DC, DeclRefKind::Ordinary,
MetatypeType::get(baseTy),
defaultMemberLookupOptions,
corrections, genericSig);
// Check whether we have a single type result.
auto singleType = cast_or_null<TypeDecl>(
corrections.getUniqueCandidateMatching([](ValueDecl *result) {
return isa<TypeDecl>(result);
}));
// If we don't have a single result, complain and fail.
if (!singleType) {
auto name = ref->getNameRef();
auto nameLoc = ref->getNameLoc();
const auto kind = describeDeclOfType(baseTy);
ctx.Diags.diagnose(nameLoc, diag::invalid_member_type, name, kind, baseTy)
.highlight(baseRange);
corrections.noteAllCandidates();
return ErrorType::get(ctx);
}
// We have a single type result. Suggest it.
ctx.Diags.diagnose(ref->getNameLoc(), diag::invalid_member_type_suggest,
baseTy, ref->getNameRef(),
singleType->getBaseName())
.fixItReplace(ref->getNameLoc().getSourceRange(),
singleType->getBaseName().userFacingName());
// Correct to the single type result.
ref->overwriteNameRef(singleType->createNameRef());
ref->setValue(singleType, nullptr);
}
auto *concrete = ref->getBoundDecl();
// If the nested type has been resolved to an associated type, use it.
if (auto assocType = dyn_cast<AssociatedTypeDecl>(concrete)) {
return DependentMemberType::get(baseTy, assocType);
}
// There are two situations possible here:
//
// 1. Member comes from the protocol, which means that it has been
// found through a conformance constraint placed on base e.g. `T: P`.
// In this case member is a `typealias` declaration located in
// protocol or protocol extension.
//
// 2. Member comes from struct/enum/class type, which means that it
// has been found through same-type constraint on base e.g. `T == Q`.
//
// If this is situation #2 we need to make sure to switch base to
// a concrete type (according to equivalence class) otherwise we'd
// end up using incorrect generic signature while attempting to form
// a substituted type for the member we found.
if (!concrete->getDeclContext()->getSelfProtocolDecl()) {
if (auto concreteTy = genericSig->getConcreteType(baseTy))
baseTy = concreteTy;
else {
baseTy = genericSig->getSuperclassBound(baseTy);
assert(baseTy);
}
}
return TypeChecker::substMemberTypeWithBase(DC->getParentModule(), concrete,
baseTy);
}
bool TypeResolution::areSameType(Type type1, Type type2) const {
if (type1->isEqual(type2))
return true;
// If neither type has a type parameter, we're done.
if (!type1->hasTypeParameter() && !type2->hasTypeParameter()) {
return false;
}
if (stage == TypeResolutionStage::Interface) {
// If we have a generic signature, canonicalize using it.
if (auto genericSig = getGenericSignature()) {
// If both are type parameters, we can use a cheaper check
// that avoids transforming the type and computing anchors.
if (type1->isTypeParameter() && type2->isTypeParameter()) {
return genericSig->areSameTypeParameterInContext(type1, type2);
}
return genericSig.getCanonicalTypeInContext(type1) ==
genericSig.getCanonicalTypeInContext(type2);
}
}
// Otherwise, perform a structural check.
assert(stage == TypeResolutionStage::Structural);
// FIXME: We should be performing a deeper equality check here.
// If both refer to associated types with the same name, they'll implicitly
// be considered equivalent.
auto depMem1 = type1->getAs<DependentMemberType>();
if (!depMem1) return false;
auto depMem2 = type2->getAs<DependentMemberType>();
if (!depMem2) return false;
if (depMem1->getName() != depMem2->getName()) return false;
return areSameType(depMem1->getBase(), depMem2->getBase());
}
Type TypeChecker::getOptionalType(SourceLoc loc, Type elementType) {
ASTContext &ctx = elementType->getASTContext();
if (!ctx.getOptionalDecl()) {
ctx.Diags.diagnose(loc, diag::sugar_type_not_found, 1);
return ErrorType::get(ctx);
}
return OptionalType::get(elementType);
}
Type
TypeChecker::getDynamicBridgedThroughObjCClass(DeclContext *dc,
Type dynamicType,
Type valueType) {
// We can only bridge from class or Objective-C existential types.
if (!dynamicType->satisfiesClassConstraint())
return Type();
// If the value type cannot be bridged, we're done.
if (!valueType->isPotentiallyBridgedValueType())
return Type();
return dc->getASTContext().getBridgedToObjC(dc, valueType);
}
/// Retrieve the identity form of the opaque type archetype type.
static Type getIdentityOpaqueTypeArchetypeType(
OpaqueTypeDecl *opaqueDecl, unsigned ordinal) {
auto outerGenericSignature = opaqueDecl->getNamingDecl()
->getInnermostDeclContext()
->getGenericSignatureOfContext();
SubstitutionMap subs;
if (outerGenericSignature)
subs = outerGenericSignature->getIdentitySubstitutionMap();
Type interfaceType = opaqueDecl->getOpaqueGenericParams()[ordinal];
return OpaqueTypeArchetypeType::get(opaqueDecl, interfaceType, subs);
}
Type TypeResolution::resolveTypeInContext(TypeDecl *typeDecl,
DeclContext *foundDC,
bool isSpecialized) const {
auto fromDC = getDeclContext();
ASTContext &ctx = fromDC->getASTContext();
// If we found a generic parameter, map to the archetype if there is one.
if (auto genericParam = dyn_cast<GenericTypeParamDecl>(typeDecl)) {
// If this generic parameter is for an opaque type, map to the opened
// archetype.
if (auto opaqueDecl = dyn_cast<OpaqueTypeDecl>(getDeclContext())) {
if (genericParam->getDepth() ==
opaqueDecl->getOpaqueGenericParams().front()->getDepth()) {
return getIdentityOpaqueTypeArchetypeType(
opaqueDecl, genericParam->getIndex());
}
}
return genericParam->getDeclaredInterfaceType();
}
if (!isSpecialized) {
// If we are referring to a type within its own context, and we have either
// a generic type with no generic arguments or a non-generic type, use the
// type within the context.
if (auto *nominalType = dyn_cast<NominalTypeDecl>(typeDecl)) {
for (auto *parentDC = fromDC; !parentDC->isModuleScopeContext();
parentDC = parentDC->getParentForLookup()) {
auto *parentNominal = parentDC->getSelfNominalTypeDecl();
if (parentNominal == nominalType)
return parentDC->getDeclaredInterfaceType();
if (isa<ExtensionDecl>(parentDC)) {
auto *extendedType = parentNominal;
while (extendedType != nullptr) {
if (extendedType == nominalType)
return extendedType->getDeclaredInterfaceType();
extendedType = extendedType->getParent()->getSelfNominalTypeDecl();
}
}
}
}
// If we're inside an extension of a type alias, allow the type alias to be
// referenced without generic arguments as well.
if (auto *aliasDecl = dyn_cast<TypeAliasDecl>(typeDecl)) {
for (auto *parentDC = fromDC; !parentDC->isModuleScopeContext();
parentDC = parentDC->getParentForLookup()) {
if (auto *ext = dyn_cast<ExtensionDecl>(parentDC)) {
auto extendedType = ext->getExtendedType();
if (auto *unboundGeneric =
dyn_cast<UnboundGenericType>(extendedType.getPointer())) {
if (auto *ugAliasDecl =
dyn_cast<TypeAliasDecl>(unboundGeneric->getAnyGeneric())) {
if (ugAliasDecl == aliasDecl) {
if (getStage() == TypeResolutionStage::Structural &&
aliasDecl->getUnderlyingTypeRepr() != nullptr) {
return aliasDecl->getStructuralType();
}
return aliasDecl->getDeclaredInterfaceType();
}
extendedType = unboundGeneric->getParent();
continue;
}
}
if (auto *aliasType =
dyn_cast<TypeAliasType>(extendedType.getPointer())) {
if (aliasType->getDecl() == aliasDecl) {
if (getStage() == TypeResolutionStage::Structural &&
aliasDecl->getUnderlyingTypeRepr() != nullptr) {
return aliasDecl->getStructuralType();
}
return aliasDecl->getDeclaredInterfaceType();
}
extendedType = aliasType->getParent();
continue;
}
}
}
}
}
// Simple case -- the type is not nested inside of another type.
// However, it might be nested inside another generic context, so
// we do want to write the type in terms of interface types or
// context archetypes, depending on the resolver given to us.
if (!typeDecl->getDeclContext()->isTypeContext()) {
if (auto *aliasDecl = dyn_cast<TypeAliasDecl>(typeDecl)) {
// For a generic typealias, return the unbound generic form of the type.
if (aliasDecl->getGenericParams())
return aliasDecl->getUnboundGenericType();
// Otherwise, return the appropriate type.
if (getStage() == TypeResolutionStage::Structural &&
aliasDecl->getUnderlyingTypeRepr() != nullptr) {
return aliasDecl->getStructuralType();
}
return aliasDecl->getDeclaredInterfaceType();
}
// When a nominal type used outside its context, return the unbound
// generic form of the type.
if (auto *nominalDecl = dyn_cast<NominalTypeDecl>(typeDecl))
return nominalDecl->getDeclaredType();
assert(isa<ModuleDecl>(typeDecl));
return typeDecl->getDeclaredInterfaceType();
}
assert(foundDC);
// selfType is the self type of the context, unless the
// context is a protocol type, in which case we might have
// to use the existential type or superclass bound as a
// parent type instead.
Type selfType;
if (isa<NominalTypeDecl>(typeDecl) &&
typeDecl->getDeclContext()->getSelfProtocolDecl()) {
// When looking up a nominal type declaration inside of a
// protocol extension, always use the nominal type and
// not the protocol 'Self' type.
if (!foundDC->getDeclaredInterfaceType())
return ErrorType::get(ctx);
selfType = foundDC->getDeclaredInterfaceType();
} else {
// Otherwise, we want the protocol 'Self' type for
// substituting into alias types and associated types.
selfType = foundDC->getSelfInterfaceType();
if (selfType->is<GenericTypeParamType>()) {
if (typeDecl->getDeclContext()->getSelfProtocolDecl()) {
if (isa<AssociatedTypeDecl>(typeDecl) ||
(isa<TypeAliasDecl>(typeDecl) &&
!cast<TypeAliasDecl>(typeDecl)->isGeneric())) {
if (getStage() == TypeResolutionStage::Structural) {
return DependentMemberType::get(selfType, typeDecl->getName());
} else if (auto assocType = dyn_cast<AssociatedTypeDecl>(typeDecl)) {
typeDecl = assocType->getAssociatedTypeAnchor();
}
}
}
if (typeDecl->getDeclContext()->getSelfClassDecl()) {
// We found a member of a class from a protocol or protocol
// extension.
//
// Get the superclass of the 'Self' type parameter.
auto sig = foundDC->getGenericSignatureOfContext();
if (!sig)
return ErrorType::get(ctx);
auto superclassType = sig->getSuperclassBound(selfType);
if (!superclassType)
return ErrorType::get(ctx);
selfType = superclassType;
}
}
}
// Finally, substitute the base type into the member type.
return TypeChecker::substMemberTypeWithBase(
fromDC->getParentModule(), typeDecl, selfType, /*useArchetypes=*/false);
}
static TypeResolutionOptions
adjustOptionsForGenericArgs(TypeResolutionOptions options) {
options.setContext(None);
options -= TypeResolutionFlags::SILType;
return options;
}
/// This function checks if a bound generic type is UnsafePointer<Void> or
/// UnsafeMutablePointer<Void>. For these two type representations, we should
/// warn users that they are deprecated and replace them with more handy
/// UnsafeRawPointer and UnsafeMutableRawPointer, respectively.
static bool isPointerToVoid(ASTContext &Ctx, Type Ty, bool &IsMutable) {
if (Ty.isNull())
return false;
auto *BGT = Ty->getAs<BoundGenericType>();
if (!BGT)
return false;
if (!BGT->isUnsafePointer() && !BGT->isUnsafeMutablePointer())
return false;
IsMutable = BGT->isUnsafeMutablePointer();
assert(BGT->getGenericArgs().size() == 1);
return BGT->getGenericArgs().front()->isVoid();
}
bool TypeChecker::checkContextualRequirements(GenericTypeDecl *decl,
Type parentTy, SourceLoc loc,
ModuleDecl *module,
GenericSignature contextSig) {
assert(parentTy && "expected a parent type");
if (parentTy->hasUnboundGenericType() || parentTy->hasTypeVariable()) {
return true;
}
SourceLoc noteLoc;
{
// We are interested in either a contextual where clause or
// a constrained extension context.
const auto ext = dyn_cast<ExtensionDecl>(decl->getDeclContext());
if (decl->getTrailingWhereClause())
noteLoc = decl->getLoc();
else if (ext && ext->isConstrainedExtension())
noteLoc = ext->getLoc();
else
return true;
if (noteLoc.isInvalid())
noteLoc = loc;
}
const auto subMap = parentTy->getContextSubstitutions(decl->getDeclContext());
const auto genericSig = decl->getGenericSignature();
const auto result =
TypeChecker::checkGenericArguments(
module, loc, noteLoc,
decl->getDeclaredInterfaceType(),
genericSig.getGenericParams(),
genericSig.getRequirements(),
[&](SubstitutableType *type) -> Type {
auto result = QueryTypeSubstitutionMap{subMap}(type);
if (result->hasTypeParameter()) {
if (contextSig) {
auto *genericEnv = contextSig.getGenericEnvironment();
return genericEnv->mapTypeIntoContext(result);
}
}
return result;
});
switch (result) {
case RequirementCheckResult::Failure:
case RequirementCheckResult::SubstitutionFailure:
return false;
case RequirementCheckResult::Success:
return true;
}
llvm_unreachable("invalid requirement check type");
}
static void diagnoseUnboundGenericType(Type ty, SourceLoc loc);
/// Apply generic arguments to the given type.
///
/// If the type is itself not generic, this does nothing.
///
/// This function emits diagnostics about an invalid type or the wrong number
/// of generic arguments, whereas
/// \c TypeResolution::applyUnboundGenericArguments requires this
/// to be in a correct and valid form.
///
/// \param type The generic type to which to apply arguments.
/// \param resolution The type resolution to perform.
/// \param silParams Used to look up generic parameters in SIL mode.
/// \param comp The arguments to apply with the angle bracket range for
/// diagnostics.
///
/// \returns A BoundGenericType bound to the given arguments, or null on
/// error.
///
/// \see TypeResolution::applyUnboundGenericArguments
static Type applyGenericArguments(Type type, TypeResolution resolution,
GenericParamList *silParams,
ComponentIdentTypeRepr *comp) {
const auto options = resolution.getOptions();
auto dc = resolution.getDeclContext();
auto loc = comp->getNameLoc().getBaseNameLoc();
auto *generic = dyn_cast<GenericIdentTypeRepr>(comp);
if (!generic) {
if (auto *const unboundTy = type->getAs<UnboundGenericType>()) {
if (!options.is(TypeResolverContext::TypeAliasDecl)) {
// If the resolution object carries an opener, attempt to open
// the unbound generic type.
// TODO: We should be able to just open the generic arguments as N
// different PlaceholderTypes.
if (const auto openerFn = resolution.getUnboundTypeOpener())
if (const auto boundTy = openerFn(unboundTy))
return boundTy;
return type;
}
}
if (resolution.getStage() == TypeResolutionStage::Structural)
return type;
GenericTypeDecl *decl;
Type parentTy;
if (auto *aliasTy = dyn_cast<TypeAliasType>(type.getPointer())) {
decl = aliasTy->getDecl();
parentTy = aliasTy->getParent();
} else if (auto *nominalTy = type->getAs<NominalType>()) {
decl = nominalTy->getDecl();
parentTy = nominalTy->getParent();
} else {
return type;
}
if (!parentTy) {
return type;
}
if (TypeChecker::checkContextualRequirements(
decl, parentTy, loc, dc->getParentModule(),
resolution.getGenericSignature()))
return type;
return ErrorType::get(resolution.getASTContext());
}
if (type->hasError()) {
generic->setInvalid();
return type;
}
auto &ctx = dc->getASTContext();
auto &diags = ctx.Diags;
if (ctx.LangOpts.EnableParameterizedProtocolTypes) {
if (auto *protoType = type->getAs<ProtocolType>()) {
// Build ParameterizedProtocolType if the protocol has a primary associated
// type and we're in a supported context (for now just generic requirements,
// inheritance clause, extension binding).
if (!resolution.getOptions().isParameterizedProtocolSupported()) {
diags.diagnose(loc, diag::parameterized_protocol_not_supported);
return ErrorType::get(ctx);
}
auto *protoDecl = protoType->getDecl();
auto assocTypes = protoDecl->getPrimaryAssociatedTypes();
if (assocTypes.empty()) {
diags.diagnose(loc, diag::protocol_does_not_have_primary_assoc_type,
protoType);
return ErrorType::get(ctx);
}
auto genericArgs = generic->getGenericArgs();
if (genericArgs.size() > assocTypes.size()) {
diags.diagnose(loc, diag::parameterized_protocol_too_many_type_arguments,
protoType, genericArgs.size(), assocTypes.size());
return ErrorType::get(ctx);
}
auto genericResolution =
resolution.withOptions(adjustOptionsForGenericArgs(options));
SmallVector<Type, 2> argTys;
for (auto *genericArg : genericArgs) {
Type argTy = genericResolution.resolveType(genericArg, silParams);
if (!argTy || argTy->hasError())
return ErrorType::get(ctx);
argTys.push_back(argTy);
}
return ParameterizedProtocolType::get(ctx, protoType, argTys);
}
}
// We must either have an unbound generic type, or a generic type alias.
if (!type->is<UnboundGenericType>()) {
if (!options.contains(TypeResolutionFlags::SilenceErrors)) {
auto diag = diags.diagnose(loc, diag::not_a_generic_type, type);
// Don't add fixit on module type; that isn't the right type regardless
// of whether it had generic arguments.
if (!type->is<ModuleType>()) {
// When turning a SourceRange into CharSourceRange the closing angle
// brackets on nested generics are lexed as one token.
SourceRange angles = generic->getAngleBrackets();
diag.fixItRemoveChars(angles.Start,
angles.End.getAdvancedLocOrInvalid(1));
}
generic->setInvalid();
}
return ErrorType::get(ctx);
}
auto *unboundType = type->castTo<UnboundGenericType>();
auto *decl = unboundType->getDecl();
// Make sure we have the right number of generic arguments.
//
// For generic types without type sequence parameters, we require
// the number of declared generic parameters match the number of
// arguments.
//
// For generic types with type sequence parameters, we only require
// that the number of arguments is enough to saturate the number of
// regular generic parameters. The type sequence parameter will absorb
// any excess parameters, or will have a substitution of `Void` if there
// is nothing to bind. This Void-binding behavior of type sequences
// also explains the offset of one that isn't otherwise present in
// the plain generic parameter case.
//
// struct Foo<Prefix, T..., Suffix> {}
// typealias X = Foo<String, Int, Float, Double> // Prefix -> String, Suffix
// -> Double, T... -> (Int, Float) typealias X = Foo<String, Int> // Prefix ->
// String, Suffix -> Int, T... -> Void typealias Y = Foo<String> // error: Not
// enough arguments to bind Suffix.
//
// FIXME: If we have fewer arguments than we need, that might be okay, if
// we're allowed to deduce the remaining arguments from context. The
// expression checker certainly only cares about the case where too many
// arguments are given.
auto genericArgs = generic->getGenericArgs();
auto genericParams = decl->getGenericParams();
auto hasTypeSequence = llvm::any_of(
*genericParams, [](const auto *GPT) { return GPT->isTypeSequence(); });
if ((!hasTypeSequence && genericArgs.size() != genericParams->size()) ||
(hasTypeSequence && genericArgs.size() < genericParams->size() - 1)) {
if (!options.contains(TypeResolutionFlags::SilenceErrors)) {
diags
.diagnose(loc, diag::type_parameter_count_mismatch, decl->getName(),
genericParams->size() - (hasTypeSequence ? 1 : 0),
genericArgs.size(),
genericArgs.size() < genericParams->size(), hasTypeSequence)
.highlight(generic->getAngleBrackets());
decl->diagnose(diag::kind_declname_declared_here,
DescriptiveDeclKind::GenericType, decl->getName());
}
return ErrorType::get(ctx);
}
// In SIL mode, Optional<T> interprets T as a SIL type.
if (options.contains(TypeResolutionFlags::SILType)) {
if (auto nominal = dyn_cast<NominalTypeDecl>(decl)) {
if (nominal->isOptionalDecl()) {
// Validate the generic argument.
Type objectType = resolution.resolveType(genericArgs[0], silParams);
if (objectType->hasError()) {
return ErrorType::get(ctx);
}
return BoundGenericType::get(nominal, /*parent*/ Type(), objectType);
}
}
}
// Resolve the types of the generic arguments.
auto genericResolution =
resolution.withOptions(adjustOptionsForGenericArgs(options));
SmallVector<Type, 2> args;
for (auto tyR : genericArgs) {
// Propagate failure.
Type substTy = genericResolution.resolveType(tyR, silParams);
if (!substTy || substTy->hasError())
return ErrorType::get(ctx);
args.push_back(substTy);
}
const auto result = resolution.applyUnboundGenericArguments(
decl, unboundType->getParent(), loc, args);
// Migration hack.
bool isMutablePointer;
if (isPointerToVoid(dc->getASTContext(), result, isMutablePointer)) {
if (isMutablePointer)
diags.diagnose(loc, diag::use_of_void_pointer, "Mutable").
fixItReplace(generic->getSourceRange(), "UnsafeMutableRawPointer");
else
diags.diagnose(loc, diag::use_of_void_pointer, "").
fixItReplace(generic->getSourceRange(), "UnsafeRawPointer");
}
if (auto clangDecl = decl->getClangDecl()) {
if (auto classTemplateDecl =
dyn_cast<clang::ClassTemplateDecl>(clangDecl)) {
SmallVector<Type, 2> typesOfGenericArgs;
for (auto typeRepr : generic->getGenericArgs()) {
typesOfGenericArgs.push_back(resolution.resolveType(typeRepr));
}
SmallVector<clang::TemplateArgument, 2> templateArguments;
std::unique_ptr<TemplateInstantiationError> error =
ctx.getClangTemplateArguments(
classTemplateDecl->getTemplateParameters(), typesOfGenericArgs,
templateArguments);
if (error) {
std::string failedTypesStr;
llvm::raw_string_ostream failedTypesStrStream(failedTypesStr);
llvm::interleaveComma(error->failedTypes, failedTypesStrStream);
// TODO: This error message should not reference implementation details.
// See: https://github.com/apple/swift/pull/33053#discussion_r477003350
ctx.Diags.diagnose(
loc, diag::unable_to_convert_generic_swift_types.ID,
{classTemplateDecl->getName(), StringRef(failedTypesStr)});
return ErrorType::get(ctx);
}
auto *clangModuleLoader = decl->getASTContext().getClangModuleLoader();
auto instantiatedDecl = clangModuleLoader->instantiateCXXClassTemplate(
const_cast<clang::ClassTemplateDecl *>(classTemplateDecl),
templateArguments);
if (instantiatedDecl) {
instantiatedDecl->setTemplateInstantiationType(result);
return instantiatedDecl->getDeclaredInterfaceType();
} else {
diags.diagnose(loc, diag::cxx_class_instantiation_failed);
return ErrorType::get(ctx);
}
}
}
return result;
}
/// Apply generic arguments to the given type.
Type TypeResolution::applyUnboundGenericArguments(
GenericTypeDecl *decl, Type parentTy, SourceLoc loc,
ArrayRef<Type> genericArgs) const {
const bool hasTypeSequence =
llvm::any_of(*decl->getGenericParams(),
[](const auto *GPT) { return GPT->isTypeSequence(); });
assert(
((!hasTypeSequence &&
genericArgs.size() == decl->getGenericParams()->size()) ||
(hasTypeSequence &&
genericArgs.size() >= decl->getGenericParams()->size() - 1)) &&
"invalid arguments, use applyGenericArguments for diagnostic emitting");
TypeSubstitutionMap subs;
// Get the interface type for the declaration. We will be substituting
// type parameters that appear inside this type with the provided
// generic arguments.
auto resultType = decl->getDeclaredInterfaceType();
// If types involved in requirements check have either type variables
// or unbound generics, let's skip the check here, and let the solver
// do it when missing types are deduced.
bool skipRequirementsCheck = false;
// Get the substitutions for outer generic parameters from the parent
// type.
if (parentTy) {
if (parentTy->hasUnboundGenericType()) {
// If we're working with a nominal type declaration, just construct
// a bound generic type without checking the generic arguments.
if (auto *nominalDecl = dyn_cast<NominalTypeDecl>(decl)) {
return BoundGenericType::get(nominalDecl, parentTy, genericArgs);
}
if (!resultType->hasTypeParameter())
return resultType;
auto genericSig = decl->getGenericSignature();
auto parentSig = decl->getDeclContext()->getGenericSignatureOfContext();
for (auto gp : parentSig.getGenericParams())
subs[gp->getCanonicalType()->castTo<GenericTypeParamType>()] =
genericSig->getConcreteType(gp);
} else {
subs = parentTy->getContextSubstitutions(decl->getDeclContext());
}
skipRequirementsCheck |= parentTy->hasTypeVariable();
} else if (auto parentSig =
decl->getDeclContext()->getGenericSignatureOfContext()) {
for (auto gp : parentSig.getGenericParams()) {
subs[gp->getCanonicalType()->castTo<GenericTypeParamType>()] = gp;
}
}
// Realize the types of the generic arguments and add them to the
// substitution map.
auto innerParams = decl->getGenericParams()->getParams();
for (unsigned i : indices(innerParams)) {
auto origTy = innerParams[i]->getDeclaredInterfaceType();
auto origGP = origTy->getCanonicalType()->castTo<GenericTypeParamType>();
if (!origGP->isTypeSequence()) {
auto substTy = genericArgs[i];
// Enter a substitution.
subs[origGP] = substTy;
skipRequirementsCheck |=
substTy->hasTypeVariable() || substTy->hasUnboundGenericType();
continue;
}
// Scan backwards to find the bounds of the longest run of
// types we can bind to this type sequence parameter.
unsigned tail;
for (tail = 1; tail <= innerParams.size(); ++tail) {
auto tailTy = innerParams[innerParams.size() - tail]
->getDeclaredInterfaceType();
auto tailGP = tailTy->getCanonicalType()->castTo<GenericTypeParamType>();
if (tailGP->isTypeSequence()) {
assert(tailGP->isEqual(origGP) &&
"Found multiple type sequence parameters!");
// Saturate the type sequence. Take care that if the prefix and suffix
// have bound all available arguments that we bind the type sequence
// parameter to `Void`.
const size_t sequenceLength = tail + i <= genericArgs.size()
? genericArgs.size() - tail - i + 1
: 0;
auto substTy = PackType::get(getASTContext(),
genericArgs.slice(i, sequenceLength));
// Enter a substitution.
subs[origGP] = substTy;
skipRequirementsCheck |=
substTy->hasTypeVariable() || substTy->hasUnboundGenericType();
break;
}
auto substTy = genericArgs[genericArgs.size() - tail];
// Enter a substitution.
subs[tailGP] = substTy;
skipRequirementsCheck |=
substTy->hasTypeVariable() || substTy->hasUnboundGenericType();
}
break;
}
// Check the generic arguments against the requirements of the declaration's
// generic signature.
auto *module = getDeclContext()->getParentModule();
if (!skipRequirementsCheck && getStage() == TypeResolutionStage::Interface) {
// Check the generic arguments against the requirements of the declaration's
// generic signature.
SourceLoc noteLoc = decl->getLoc();
if (noteLoc.isInvalid())
noteLoc = loc;
auto genericSig = decl->getGenericSignature();
auto result = TypeChecker::checkGenericArguments(
module, loc, noteLoc,
UnboundGenericType::get(decl, parentTy, getASTContext()),
genericSig.getGenericParams(), genericSig.getRequirements(),
[&](SubstitutableType *type) -> Type {
auto result = QueryTypeSubstitutionMap{subs}(type);
if (result->hasTypeParameter()) {
if (const auto contextSig = getGenericSignature()) {
auto *genericEnv = contextSig.getGenericEnvironment();
return genericEnv->mapTypeIntoContext(result);
}
}
return result;
});
switch (result) {
case RequirementCheckResult::Failure:
case RequirementCheckResult::SubstitutionFailure:
return ErrorType::get(getASTContext());
case RequirementCheckResult::Success:
break;
}
}
// For a typealias, use the underlying type. We'll wrap up the result
// later.
auto typealias = dyn_cast<TypeAliasDecl>(decl);
if (typealias) {
resultType = typealias->getUnderlyingType();
}
// Apply the substitution map to the interface type of the declaration.
resultType = resultType.subst(QueryTypeSubstitutionMap{subs},
LookUpConformanceInModule(module));
// Form a sugared typealias reference.
if (typealias && (!parentTy || !parentTy->isAnyExistentialType())) {
auto genericSig = typealias->getGenericSignature();
auto subMap = SubstitutionMap::get(genericSig,
QueryTypeSubstitutionMap{subs},
LookUpConformanceInModule(module));
resultType = TypeAliasType::get(typealias, parentTy, subMap, resultType);
}
return resultType;
}
/// Diagnose a use of an unbound generic type.
static void diagnoseUnboundGenericType(Type ty, SourceLoc loc) {
auto &ctx = ty->getASTContext();
if (auto unbound = ty->getAs<UnboundGenericType>()) {
auto *decl = unbound->getDecl();
{
// Compute the string before creating a new diagnostic, since
// getDefaultGenericArgumentsString() might emit its own
// diagnostics.
SmallString<64> genericArgsToAdd;
bool hasGenericArgsToAdd =
TypeChecker::getDefaultGenericArgumentsString(genericArgsToAdd,
decl);
auto diag = ctx.Diags.diagnose(loc,
diag::generic_type_requires_arguments, ty);
if (hasGenericArgsToAdd)
diag.fixItInsertAfter(loc, genericArgsToAdd);
}
decl->diagnose(diag::kind_declname_declared_here,
DescriptiveDeclKind::GenericType,
decl->getName());
} else {
ty.findIf([&](Type t) -> bool {
if (auto unbound = t->getAs<UnboundGenericType>()) {
ctx.Diags.diagnose(loc,
diag::generic_type_requires_arguments, t);
return true;
}
return false;
});
}
}
// Produce a diagnostic if the type we referenced was an
// associated type but the type itself was erroneous. We'll produce a
// diagnostic here if the diagnostic for the bad type witness would show up in
// a different context.
static void maybeDiagnoseBadConformanceRef(DeclContext *dc,
Type parentTy,
SourceLoc loc,
TypeDecl *typeDecl) {
auto protocol = dyn_cast<ProtocolDecl>(typeDecl->getDeclContext());
// If we weren't given a conformance, go look it up.
ProtocolConformance *conformance = nullptr;
if (protocol) {
auto conformanceRef = dc->getParentModule()->lookupConformance(
parentTy, protocol);
if (conformanceRef.isConcrete())
conformance = conformanceRef.getConcrete();
}
// If any errors have occurred, don't bother diagnosing this cross-file
// issue.
ASTContext &ctx = dc->getASTContext();
if (ctx.Diags.hadAnyError())
return;
auto diagCode =
(!protocol || (conformance && !conformance->getConditionalRequirementsIfAvailable()))
? diag::unsupported_recursion_in_associated_type_reference
: diag::broken_associated_type_witness;
ctx.Diags.diagnose(loc, diagCode, isa<TypeAliasDecl>(typeDecl),
typeDecl->getName(), parentTy);
}
/// Returns a valid type or ErrorType in case of an error.
static Type resolveTypeDecl(TypeDecl *typeDecl, DeclContext *foundDC,
TypeResolution resolution,
GenericParamList *silParams,
ComponentIdentTypeRepr *comp) {
// Resolve the type declaration to a specific type. How this occurs
// depends on the current context and where the type was found.
Type type = resolution.resolveTypeInContext(typeDecl, foundDC,
isa<GenericIdentTypeRepr>(comp));
if (type->hasError() && foundDC &&
(isa<AssociatedTypeDecl>(typeDecl) || isa<TypeAliasDecl>(typeDecl))) {
auto fromDC = resolution.getDeclContext();
assert(fromDC && "No declaration context for type resolution?");
maybeDiagnoseBadConformanceRef(fromDC, foundDC->getDeclaredInterfaceType(),
comp->getNameLoc().getBaseNameLoc(),
typeDecl);
}
return applyGenericArguments(type, resolution, silParams, comp);
}
static std::string getDeclNameFromContext(DeclContext *dc,
NominalTypeDecl *nominal) {
// We don't allow an unqualified reference to a type inside an
// extension if the type is itself nested inside another type,
// eg:
//
// extension A.B { ... B ... }
//
// Instead, you must write 'A.B'. Calculate the right name to use
// for fixits.
if (!isa<ExtensionDecl>(dc)) {
SmallVector<Identifier, 2> idents;
auto *parentNominal = nominal;
while (parentNominal != nullptr) {
idents.push_back(parentNominal->getName());
parentNominal = parentNominal->getDeclContext()->getSelfNominalTypeDecl();
}
std::reverse(idents.begin(), idents.end());
std::string result;
for (auto ident : idents) {
if (!result.empty())
result += ".";
result += ident.str();
}
return result;
} else {
return std::string(nominal->getName());
}
}
/// Diagnose a reference to an unknown type.
///
/// This routine diagnoses a reference to an unknown type, and
/// attempts to fix the reference via various means.
///
/// \returns either the corrected type, if possible, or an error type to
/// that correction failed.
static Type diagnoseUnknownType(TypeResolution resolution,
Type parentType,
SourceRange parentRange,
ComponentIdentTypeRepr *comp,
NameLookupOptions lookupOptions) {
auto dc = resolution.getDeclContext();
ASTContext &ctx = dc->getASTContext();
auto &diags = ctx.Diags;
// Unqualified lookup case.
if (parentType.isNull()) {
// Tailored diagnostic for custom attributes.
if (resolution.getOptions().is(TypeResolverContext::CustomAttr)) {
diags.diagnose(comp->getNameLoc(), diag::unknown_attribute,
comp->getNameRef().getBaseIdentifier().str());
return ErrorType::get(ctx);
}
if (comp->getNameRef().isSimpleName(ctx.Id_Self) &&
!isa<GenericIdentTypeRepr>(comp)) {
DeclContext *nominalDC = nullptr;
NominalTypeDecl *nominal = nullptr;
if ((nominalDC = dc->getInnermostTypeContext()) &&
(nominal = nominalDC->getSelfNominalTypeDecl())) {
if (isa<ClassDecl>(nominal)) {
// Attempt to refer to 'Self' within a non-protocol nominal
// type. Fix this by replacing 'Self' with the nominal type name.
// Produce a Fix-It replacing 'Self' with the nominal type name.
auto name = getDeclNameFromContext(dc, nominal);
diags.diagnose(comp->getNameLoc(), diag::dynamic_self_invalid, name)
.fixItReplace(comp->getNameLoc().getSourceRange(), name);
comp->overwriteNameRef(DeclNameRef(nominal->getName()));
comp->setValue(nominal, nominalDC->getParent());
return dc->getInnermostTypeContext()->getSelfInterfaceType();
} else {
diags.diagnose(comp->getNameLoc(), diag::cannot_find_type_in_scope,
comp->getNameRef());
return ErrorType::get(ctx);
}
}
// Attempt to refer to 'Self' from a free function.
diags.diagnose(comp->getNameLoc(), diag::dynamic_self_non_method,
dc->getParent()->isLocalContext());
return ErrorType::get(ctx);
}
// Try ignoring access control.
NameLookupOptions relookupOptions = lookupOptions;
relookupOptions |= NameLookupFlags::IgnoreAccessControl;
auto inaccessibleResults =
TypeChecker::lookupUnqualifiedType(dc, comp->getNameRef(),
comp->getLoc(), relookupOptions);
if (!inaccessibleResults.empty()) {
// FIXME: What if the unviable candidates have different levels of access?
auto first = cast<TypeDecl>(inaccessibleResults.front().getValueDecl());
diags.diagnose(comp->getNameLoc(), diag::candidate_inaccessible,
first->getBaseName(), first->getFormalAccess());
// FIXME: If any of the candidates (usually just one) are in the same
// module we could offer a fix-it.
for (auto lookupResult : inaccessibleResults)
lookupResult.getValueDecl()->diagnose(diag::kind_declared_here,
DescriptiveDeclKind::Type);
// Don't try to recover here; we'll get more access-related diagnostics
// downstream if we do.
return ErrorType::get(ctx);
}
// Fallback.
auto L = comp->getNameLoc();
SourceRange R = comp->getNameLoc().getSourceRange();
// Check if the unknown type is in the type remappings.
auto &Remapped = ctx.RemappedTypes;
auto TypeName = comp->getNameRef().getBaseIdentifier().str();
auto I = Remapped.find(TypeName);
if (I != Remapped.end()) {
auto RemappedTy = I->second->getString();
diags.diagnose(L, diag::cannot_find_type_in_scope_did_you_mean,
comp->getNameRef(), RemappedTy)
.highlight(R)
.fixItReplace(R, RemappedTy);
// Replace the computed type with the suggested type.
comp->overwriteNameRef(DeclNameRef(ctx.getIdentifier(RemappedTy)));
// HACK: 'NSUInteger' suggests both 'UInt' and 'Int'.
if (TypeName == ctx.getSwiftName(KnownFoundationEntity::NSUInteger)) {
diags.diagnose(L, diag::note_remapped_type, "UInt")
.fixItReplace(R, "UInt");
}
return I->second;
}
diags.diagnose(L, diag::cannot_find_type_in_scope, comp->getNameRef())
.highlight(R);
return ErrorType::get(ctx);
}
// Qualified lookup case.
if (!parentType->mayHaveMembers()) {
const auto kind = describeDeclOfType(parentType);
diags
.diagnose(comp->getNameLoc(), diag::invalid_member_type,
comp->getNameRef(), kind, parentType)
.highlight(parentRange);
return ErrorType::get(ctx);
}
// Try ignoring access control.
NameLookupOptions relookupOptions = lookupOptions;
relookupOptions |= NameLookupFlags::IgnoreAccessControl;
auto inaccessibleMembers =
TypeChecker::lookupMemberType(dc, parentType, comp->getNameRef(),
relookupOptions);
if (inaccessibleMembers) {
// FIXME: What if the unviable candidates have different levels of access?
const TypeDecl *first = inaccessibleMembers.front().Member;
diags.diagnose(comp->getNameLoc(), diag::candidate_inaccessible,
first->getBaseName(), first->getFormalAccess());
// FIXME: If any of the candidates (usually just one) are in the same module
// we could offer a fix-it.
for (auto lookupResult : inaccessibleMembers)
lookupResult.Member->diagnose(diag::kind_declared_here,
DescriptiveDeclKind::Type);
// Don't try to recover here; we'll get more access-related diagnostics
// downstream if we do.
return ErrorType::get(ctx);
}
// FIXME: Typo correction!
// Lookup into a type.
if (auto moduleType = parentType->getAs<ModuleType>()) {
diags.diagnose(comp->getNameLoc(), diag::no_module_type,
comp->getNameRef(), moduleType->getModule()->getName());
} else {
LookupResult memberLookup;
// Let's try to look any member of the parent type with the given name,
// even if it is not a type, allowing for a more precise diagnostic.
NLOptions memberLookupOptions = (NL_QualifiedDefault |
NL_IgnoreAccessControl);
SmallVector<ValueDecl *, 2> results;
dc->lookupQualified(parentType, comp->getNameRef(), memberLookupOptions,
results);
// Looks like this is not a member type, but simply a member of parent type.
if (!results.empty()) {
auto member = results[0];
diags.diagnose(comp->getNameLoc(), diag::invalid_member_reference,
member->getDescriptiveKind(), member->getName(),
parentType)
.highlight(parentRange);
} else {
const auto kind = describeDeclOfType(parentType);
diags
.diagnose(comp->getNameLoc(), diag::invalid_member_type,
comp->getNameRef(), kind, parentType)
.highlight(parentRange);
// Note where the type was defined, this can help diagnose if the user
// expected name lookup to find a module when there's a conflicting type.
if (auto typeDecl = parentType->getNominalOrBoundGenericNominal()) {
ctx.Diags.diagnose(typeDecl, diag::decl_declared_here,
typeDecl->getName());
}
}
}
return ErrorType::get(ctx);
}
enum class SelfTypeKind {
StaticSelf,
DynamicSelf,
InvalidSelf
};
static SelfTypeKind getSelfTypeKind(DeclContext *dc,
TypeResolutionOptions options) {
auto *typeDC = dc->getInnermostTypeContext();
// For protocols, skip this code path and find the 'Self' generic parameter.
if (typeDC->getSelfProtocolDecl())
return SelfTypeKind::InvalidSelf;
// In enums and structs, 'Self' is just a shorthand for the nominal type,
// and can be used anywhere.
if (!typeDC->getSelfClassDecl())
return SelfTypeKind::StaticSelf;
// In class methods, 'Self' is the DynamicSelfType and can only appear in
// the return type.
switch (options.getBaseContext()) {
case TypeResolverContext::FunctionResult:
case TypeResolverContext::PatternBindingDecl:
return SelfTypeKind::DynamicSelf;
case TypeResolverContext::AbstractFunctionDecl:
case TypeResolverContext::SubscriptDecl:
case TypeResolverContext::TypeAliasDecl:
case TypeResolverContext::GenericTypeAliasDecl:
// When checking a function or subscript parameter list, we have to go up
// one level to determine if we're in a local context or not.
if (dc->getParent()->isLocalContext())
return SelfTypeKind::DynamicSelf;
return SelfTypeKind::InvalidSelf;
default:
// In local functions inside classes, 'Self' is the DynamicSelfType and can
// be used anywhere.
if (dc->isLocalContext())
return SelfTypeKind::DynamicSelf;
return SelfTypeKind::InvalidSelf;
}
}
static void diagnoseGenericArgumentsOnSelf(TypeResolution resolution,
ComponentIdentTypeRepr *comp,
DeclContext *typeDC) {
ASTContext &ctx = resolution.getASTContext();
auto &diags = ctx.Diags;
auto *selfNominal = typeDC->getSelfNominalTypeDecl();
auto declaredType = selfNominal->getDeclaredType();
diags.diagnose(comp->getNameLoc(), diag::cannot_specialize_self);
if (selfNominal->isGeneric() && !isa<ProtocolDecl>(selfNominal)) {
diags.diagnose(comp->getNameLoc(), diag::specialize_explicit_type_instead,
declaredType)
.fixItReplace(comp->getNameLoc().getSourceRange(),
declaredType.getString());
}
}
/// Resolve the given identifier type representation as an unqualified type,
/// returning the type it references.
///
/// \returns Either the resolved type or a null type, the latter of
/// which indicates that some dependencies were unsatisfied.
static Type resolveTopLevelIdentTypeComponent(TypeResolution resolution,
GenericParamList *silParams,
ComponentIdentTypeRepr *comp) {
const auto options = resolution.getOptions();
ASTContext &ctx = resolution.getASTContext();
auto &diags = ctx.Diags;
// Short-circuiting.
if (comp->isInvalid()) return ErrorType::get(ctx);
// If the component has already been bound to a declaration, handle
// that now.
if (auto *typeDecl = comp->getBoundDecl()) {
// Resolve the type declaration within this context.
return resolveTypeDecl(typeDecl, comp->getDeclContext(), resolution,
silParams, comp);
}
// Resolve the first component, which is the only one that requires
// unqualified name lookup.
auto DC = resolution.getDeclContext();
auto id = comp->getNameRef();
// In SIL mode, we bind generic parameters here, since name lookup
// won't find them.
if (silParams != nullptr) {
auto name = id.getBaseIdentifier();
if (auto *paramDecl = silParams->lookUpGenericParam(name)) {
comp->setValue(paramDecl, DC);
return resolveTypeDecl(paramDecl, DC, resolution,
silParams, comp);
}
}
NameLookupOptions lookupOptions = defaultUnqualifiedLookupOptions;
if (options.contains(TypeResolutionFlags::AllowUsableFromInline))
lookupOptions |= NameLookupFlags::IncludeUsableFromInline;
auto globals = TypeChecker::lookupUnqualifiedType(DC, id, comp->getLoc(),
lookupOptions);
// Process the names we found.
Type current;
TypeDecl *currentDecl = nullptr;
DeclContext *currentDC = nullptr;
bool isAmbiguous = false;
for (const auto &entry : globals) {
auto *foundDC = entry.getDeclContext();
auto *typeDecl = cast<TypeDecl>(entry.getValueDecl());
Type type = resolveTypeDecl(typeDecl, foundDC, resolution, silParams, comp);
if (type->is<ErrorType>())
return type;
// If this is the first result we found, record it.
if (current.isNull()) {
current = type;
currentDecl = typeDecl;
currentDC = foundDC;
continue;
}
// Otherwise, check for an ambiguity.
if (!resolution.areSameType(current, type)) {
isAmbiguous = true;
break;
}
// We have a found multiple type aliases that refer to the same thing.
// Ignore the duplicate.
}
// Complain about any ambiguities we detected.
// FIXME: We could recover by looking at later components.
if (isAmbiguous) {
if (!options.contains(TypeResolutionFlags::SilenceErrors)) {
diags.diagnose(comp->getNameLoc(), diag::ambiguous_type_base,
comp->getNameRef())
.highlight(comp->getNameLoc().getSourceRange());
for (auto entry : globals) {
entry.getValueDecl()->diagnose(diag::found_candidate);
}
}
comp->setInvalid();
return ErrorType::get(ctx);
}
// If we found a type declaration with the given name, return it now.
if (current) {
comp->setValue(currentDecl, currentDC);
return current;
}
// 'Self' inside of a nominal type refers to that type.
if (id.isSimpleName(ctx.Id_Self)) {
if (auto *typeDC = DC->getInnermostTypeContext()) {
// FIXME: The passed-in TypeRepr should get 'typechecked' as well.
// The issue is though that ComponentIdentTypeRepr only accepts a ValueDecl
// while the 'Self' type is more than just a reference to a TypeDecl.
auto selfType = typeDC->getSelfInterfaceType();
// Check if we can reference 'Self' here, and if so, what kind of Self it is.
auto selfTypeKind = getSelfTypeKind(DC, options);
// We don't allow generic arguments on 'Self'.
if (selfTypeKind != SelfTypeKind::InvalidSelf &&
isa<GenericIdentTypeRepr>(comp)) {
diagnoseGenericArgumentsOnSelf(resolution, comp, typeDC);
}
switch (selfTypeKind) {
case SelfTypeKind::StaticSelf:
return selfType;
case SelfTypeKind::DynamicSelf:
return DynamicSelfType::get(selfType, ctx);
case SelfTypeKind::InvalidSelf:
break;
}
}
}
// If we're not allowed to complain, bail out.
if (options.contains(TypeResolutionFlags::SilenceErrors))
return ErrorType::get(ctx);
// Complain and give ourselves a chance to recover.
return diagnoseUnknownType(resolution, nullptr, SourceRange(), comp,
lookupOptions);
}
static void diagnoseAmbiguousMemberType(Type baseTy, SourceRange baseRange,
DeclNameRef name, DeclNameLoc nameLoc,
LookupTypeResult &lookup) {
ASTContext &ctx = baseTy->getASTContext();
auto &diags = ctx.Diags;
if (auto moduleTy = baseTy->getAs<ModuleType>()) {
diags.diagnose(nameLoc, diag::ambiguous_module_type, name,
moduleTy->getModule()->getName())
.highlight(baseRange);
} else {
diags.diagnose(nameLoc, diag::ambiguous_member_type, name, baseTy)
.highlight(baseRange);
}
for (const auto &member : lookup) {
member.Member->diagnose(diag::found_candidate_type, member.MemberType);
}
}
/// Resolve the given identifier type representation as a qualified
/// lookup within the given parent type, returning the type it
/// references.
/// \param silParams Used to look up generic parameters in SIL mode.
static Type resolveNestedIdentTypeComponent(TypeResolution resolution,
GenericParamList *silParams,
Type parentTy,
SourceRange parentRange,
ComponentIdentTypeRepr *comp) {
const auto options = resolution.getOptions();
auto DC = resolution.getDeclContext();
auto &ctx = DC->getASTContext();
auto &diags = ctx.Diags;
auto maybeDiagnoseBadMemberType = [&](TypeDecl *member, Type memberType,
AssociatedTypeDecl *inferredAssocType) {
bool hasUnboundOpener = !!resolution.getUnboundTypeOpener();
if (options.contains(TypeResolutionFlags::SilenceErrors)) {
if (TypeChecker::isUnsupportedMemberTypeAccess(parentTy, member,
hasUnboundOpener)
!= TypeChecker::UnsupportedMemberTypeAccessKind::None)
return ErrorType::get(ctx);
}
switch (TypeChecker::isUnsupportedMemberTypeAccess(parentTy, member,
hasUnboundOpener)) {
case TypeChecker::UnsupportedMemberTypeAccessKind::None:
break;
case TypeChecker::UnsupportedMemberTypeAccessKind::NominalTypeOfUnboundGeneric:
case TypeChecker::UnsupportedMemberTypeAccessKind::TypeAliasOfUnboundGeneric:
case TypeChecker::UnsupportedMemberTypeAccessKind::AssociatedTypeOfUnboundGeneric:
diagnoseUnboundGenericType(parentTy, parentRange.End);
return ErrorType::get(ctx);
case TypeChecker::UnsupportedMemberTypeAccessKind::TypeAliasOfExistential:
diags.diagnose(comp->getNameLoc(), diag::typealias_outside_of_protocol,
comp->getNameRef());
return ErrorType::get(ctx);
case TypeChecker::UnsupportedMemberTypeAccessKind::AssociatedTypeOfExistential:
diags.diagnose(comp->getNameLoc(), diag::assoc_type_outside_of_protocol,
comp->getNameRef());
return ErrorType::get(ctx);
}
// Only the last component of the underlying type of a type alias may
// be an unbound generic.
if (options.is(TypeResolverContext::TypeAliasDecl)) {
if (parentTy->is<UnboundGenericType>()) {
if (!options.contains(TypeResolutionFlags::SilenceErrors))
diagnoseUnboundGenericType(parentTy, parentRange.End);
return ErrorType::get(ctx);
}
}
// Diagnose a bad conformance reference if we need to.
if (!options.contains(TypeResolutionFlags::SilenceErrors) &&
inferredAssocType && memberType->hasError()) {
maybeDiagnoseBadConformanceRef(DC, parentTy, comp->getLoc(),
inferredAssocType);
}
// If there are generic arguments, apply them now.
return applyGenericArguments(memberType, resolution,
silParams, comp);
};
// Short-circuiting.
if (comp->isInvalid()) return ErrorType::get(ctx);
// If the parent is a type parameter, the member is a dependent member,
// and we skip much of the work below.
if (parentTy->isTypeParameter()) {
if (auto memberType = resolution.resolveDependentMemberType(
parentTy, DC, parentRange, comp)) {
// Hack -- if we haven't resolved this to a declaration yet, don't
// attempt to apply generic arguments, since this will emit a
// diagnostic, and its possible that this type will become a concrete
// type later on.
if (!memberType->is<DependentMemberType>() ||
memberType->castTo<DependentMemberType>()->getAssocType()) {
return applyGenericArguments(memberType, resolution, silParams, comp);
}
return memberType;
}
}
// Phase 2: If a declaration has already been bound, use it.
if (auto *typeDecl = comp->getBoundDecl()) {
auto memberType =
TypeChecker::substMemberTypeWithBase(DC->getParentModule(), typeDecl,
parentTy);
return maybeDiagnoseBadMemberType(typeDecl, memberType, nullptr);
}
// Phase 1: Find and bind the component decl.
// Look for member types with the given name.
NameLookupOptions lookupOptions = defaultMemberLookupOptions;
if (options.contains(TypeResolutionFlags::AllowUsableFromInline))
lookupOptions |= NameLookupFlags::IncludeUsableFromInline;
LookupTypeResult memberTypes;
if (parentTy->mayHaveMembers())
memberTypes = TypeChecker::lookupMemberType(
DC, parentTy, comp->getNameRef(), lookupOptions);
// Name lookup was ambiguous. Complain.
// FIXME: Could try to apply generic arguments first, and see whether
// that resolves things. But do we really want that to succeed?
if (memberTypes.size() > 1) {
if (!options.contains(TypeResolutionFlags::SilenceErrors))
diagnoseAmbiguousMemberType(parentTy, parentRange, comp->getNameRef(),
comp->getNameLoc(), memberTypes);
return ErrorType::get(ctx);
}
// If we didn't find anything, complain.
Type memberType;
TypeDecl *member = nullptr;
AssociatedTypeDecl *inferredAssocType = nullptr;
if (!memberTypes) {
// If we're not allowed to complain or we couldn't fix the
// source, bail out.
if (options.contains(TypeResolutionFlags::SilenceErrors))
return ErrorType::get(ctx);
memberType = diagnoseUnknownType(resolution, parentTy, parentRange, comp,
lookupOptions);
member = comp->getBoundDecl();
if (!member)
return ErrorType::get(ctx);
} else {
memberType = memberTypes.back().MemberType;
member = memberTypes.back().Member;
inferredAssocType = memberTypes.back().InferredAssociatedType;
comp->setValue(member, nullptr);
}
return maybeDiagnoseBadMemberType(member, memberType, inferredAssocType);
}
/// \param silParams Used to look up generic parameters in SIL mode.
static Type
resolveIdentTypeComponent(TypeResolution resolution,
GenericParamList *silParams,
ArrayRef<ComponentIdentTypeRepr *> components) {
// The first component uses unqualified lookup.
auto topLevelComp = components.front();
auto result = resolveTopLevelIdentTypeComponent(resolution, silParams,
topLevelComp);
if (result->hasError())
return ErrorType::get(result->getASTContext());
// Remaining components are resolved via iterated qualified lookups.
SourceRange parentRange(topLevelComp->getStartLoc(),
topLevelComp->getEndLoc());
for (auto nestedComp : components.drop_front()) {
result = resolveNestedIdentTypeComponent(resolution, silParams,
result, parentRange,
nestedComp);
if (result->hasError())
return ErrorType::get(result->getASTContext());
parentRange.End = nestedComp->getEndLoc();
}
// Diagnose an error if the last component's generic arguments are missing.
auto lastComp = components.back();
auto options = resolution.getOptions();
if (result->is<UnboundGenericType>() &&
!isa<GenericIdentTypeRepr>(lastComp) &&
!resolution.getUnboundTypeOpener() &&
!options.is(TypeResolverContext::TypeAliasDecl)) {
if (!options.contains(TypeResolutionFlags::SilenceErrors)) {
// Tailored diagnostic for custom attributes.
if (options.is(TypeResolverContext::CustomAttr)) {
auto &ctx = resolution.getASTContext();
ctx.Diags.diagnose(lastComp->getNameLoc(), diag::unknown_attribute,
lastComp->getNameRef().getBaseIdentifier().str());
return ErrorType::get(ctx);
}
diagnoseUnboundGenericType(result,
lastComp->getNameLoc().getBaseNameLoc());
}
return ErrorType::get(result->getASTContext());
}
return result;
}
// Hack to apply context-specific @escaping to an AST function type.
static Type applyNonEscapingIfNecessary(Type ty,
TypeResolutionOptions options) {
// Remember whether this is a function parameter.
bool defaultNoEscape = options.is(TypeResolverContext::FunctionInput) &&
!options.hasBase(TypeResolverContext::EnumElementDecl);
// Desugar here
auto *funcTy = ty->castTo<FunctionType>();
auto extInfo = funcTy->getExtInfo();
if (defaultNoEscape && !extInfo.isNoEscape()) {
extInfo = extInfo.withNoEscape();
// We lost the sugar to flip the isNoEscape bit.
//
// FIXME: It would be better to add a new AttributedType sugared type,
// which would wrap the TypeAliasType or ParenType, and apply the
// isNoEscape bit when de-sugaring.
// <https://bugs.swift.org/browse/SR-2520>
return FunctionType::get(funcTy->getParams(), funcTy->getResult(), extInfo);
}
// Note: original sugared type
return ty;
}
/// Validate whether type associated with @autoclosure attribute is correct,
/// it supposed to be a function type with no parameters.
/// \returns true if there was an error, false otherwise.
static bool validateAutoClosureAttr(DiagnosticEngine &Diags, const SourceLoc &loc,
Type paramType) {
if (auto *fnType = paramType->getAs<FunctionType>()) {
if (fnType->getNumParams() != 0) {
Diags.diagnose(loc, diag::autoclosure_function_input_nonunit);
return true;
}
// A function type with no parameters.
return false;
}
Diags.diagnose(loc, diag::autoclosure_function_type);
return true;
}
/// Check whether the type associated with particular source location
/// has `@autoclosure` attribute, and if so, validate that such use is correct.
/// \returns true if there was an error, false otherwise.
static bool validateAutoClosureAttributeUse(DiagnosticEngine &Diags,
const TypeRepr *TR,
Type type,
TypeResolutionOptions options) {
if (!TR || TR->isInvalid())
return false;
// If is a parameter declaration marked as @autoclosure.
if (options.is(TypeResolverContext::FunctionInput)) {
if (auto *ATR = dyn_cast<AttributedTypeRepr>(TR)) {
const auto attrLoc = ATR->getAttrs().getLoc(TAK_autoclosure);
if (attrLoc.isValid())
return validateAutoClosureAttr(Diags, attrLoc, type);
}
}
// Otherwise, let's dig into the type and see if there are any
// functions with parameters marked as @autoclosure,
// such would be a part of expressions like:
// `let _: (@autoclosure () -> Int) -> Void = ...`.
bool isValid = true;
type.visit([&](Type subType) {
if (auto *fnType = subType->getAs<FunctionType>()) {
isValid &= llvm::none_of(
fnType->getParams(), [&](const FunctionType::Param ¶m) {
return param.isAutoClosure() &&
validateAutoClosureAttr(Diags, TR->getLoc(),
param.getPlainType());
});
}
});
return !isValid;
}
namespace {
const auto DefaultParameterConvention = ParameterConvention::Direct_Unowned;
const auto DefaultResultConvention = ResultConvention::Unowned;
/// A wrapper that ensures that the returned type from
/// \c TypeResolver::resolveType is never the null \c Type. It otherwise
/// tries to behave like \c Type, so it provides the proper conversion and
/// arrow operators.
class NeverNullType final {
public:
/// Forbid default construction.
NeverNullType() = delete;
/// Forbid construction from \c nullptr.
NeverNullType(std::nullptr_t) = delete;
public:
/// Construct a never-null Type. If \p Ty is null, a fatal error is thrown.
NeverNullType(Type Ty) : WrappedTy(Ty) {
if (WrappedTy.isNull()) {
llvm::report_fatal_error("Resolved to null type!");
}
}
/// Construct a never-null Type. If \p TyB is null, a fatal error is thrown.
NeverNullType(TypeBase *TyB) : NeverNullType(Type(TyB)) {}
operator Type() const { return WrappedTy; }
Type get() const { return WrappedTy; }
TypeBase *operator->() const { return WrappedTy.operator->(); }
private:
Type WrappedTy;
};
class TypeResolver {
const TypeResolution &resolution;
/// Used in SIL mode.
GenericParamList *genericParams;
public:
explicit TypeResolver(const TypeResolution &resolution,
GenericParamList *genericParams = nullptr)
: resolution(resolution), genericParams(genericParams) {}
NeverNullType resolveType(TypeRepr *repr, TypeResolutionOptions options);
private:
ASTContext &getASTContext() const { return resolution.getASTContext(); }
DeclContext *getDeclContext() { return resolution.getDeclContext(); }
const DeclContext *getDeclContext() const {
return resolution.getDeclContext();
}
private:
template<typename ...ArgTypes>
InFlightDiagnostic diagnose(ArgTypes &&...Args) const {
auto &diags = getASTContext().Diags;
return diags.diagnose(std::forward<ArgTypes>(Args)...);
}
template <typename... ArgTypes>
InFlightDiagnostic diagnoseInvalid(TypeRepr *repr,
ArgTypes &&... Args) const {
auto &diags = getASTContext().Diags;
repr->setInvalid();
return diags.diagnose(std::forward<ArgTypes>(Args)...);
}
NeverNullType resolveAttributedType(AttributedTypeRepr *repr,
TypeResolutionOptions options);
NeverNullType resolveAttributedType(TypeAttributes &attrs, TypeRepr *repr,
TypeResolutionOptions options);
NeverNullType
resolveASTFunctionType(FunctionTypeRepr *repr,
TypeResolutionOptions options,
AnyFunctionType::Representation representation =
AnyFunctionType::Representation::Swift,
bool noescape = false,
bool concurrent = false,
const clang::Type *parsedClangFunctionType = nullptr,
DifferentiabilityKind diffKind =
DifferentiabilityKind::NonDifferentiable,
Type globalActor = Type());
SmallVector<AnyFunctionType::Param, 8>
resolveASTFunctionTypeParams(TupleTypeRepr *inputRepr,
TypeResolutionOptions options,
DifferentiabilityKind diffKind);
NeverNullType resolveSILFunctionType(
FunctionTypeRepr *repr, TypeResolutionOptions options,
SILCoroutineKind coroutineKind = SILCoroutineKind::None,
SILFunctionType::ExtInfoBuilder extInfoBuilder =
SILFunctionType::ExtInfoBuilder(),
ParameterConvention calleeConvention = DefaultParameterConvention,
TypeRepr *witnessmethodProtocol = nullptr);
SILParameterInfo resolveSILParameter(TypeRepr *repr,
TypeResolutionOptions options);
SILYieldInfo resolveSILYield(TypeAttributes &remainingAttrs,
TypeRepr *repr, TypeResolutionOptions options);
bool resolveSILResults(TypeRepr *repr, TypeResolutionOptions options,
SmallVectorImpl<SILYieldInfo> &yields,
SmallVectorImpl<SILResultInfo> &results,
Optional<SILResultInfo> &errorResult);
bool resolveSingleSILResult(TypeRepr *repr, TypeResolutionOptions options,
SmallVectorImpl<SILYieldInfo> &yields,
SmallVectorImpl<SILResultInfo> &results,
Optional<SILResultInfo> &errorResult);
NeverNullType resolveIdentifierType(IdentTypeRepr *IdType,
TypeResolutionOptions options);
NeverNullType resolveSpecifierTypeRepr(SpecifierTypeRepr *repr,
TypeResolutionOptions options);
NeverNullType resolveIsolatedTypeRepr(IsolatedTypeRepr *repr,
TypeResolutionOptions options);
NeverNullType resolveCompileTimeConstTypeRepr(CompileTimeConstTypeRepr *repr,
TypeResolutionOptions options);
NeverNullType resolveArrayType(ArrayTypeRepr *repr,
TypeResolutionOptions options);
NeverNullType resolveDictionaryType(DictionaryTypeRepr *repr,
TypeResolutionOptions options);
NeverNullType resolveOptionalType(OptionalTypeRepr *repr,
TypeResolutionOptions options);
NeverNullType resolveImplicitlyUnwrappedOptionalType(
ImplicitlyUnwrappedOptionalTypeRepr *repr,
TypeResolutionOptions options, bool isDirect);
NeverNullType resolveTupleType(TupleTypeRepr *repr,
TypeResolutionOptions options);
NeverNullType resolveCompositionType(CompositionTypeRepr *repr,
TypeResolutionOptions options);
NeverNullType resolveExistentialType(ExistentialTypeRepr *repr,
TypeResolutionOptions options);
NeverNullType resolveMetatypeType(MetatypeTypeRepr *repr,
TypeResolutionOptions options);
NeverNullType resolveProtocolType(ProtocolTypeRepr *repr,
TypeResolutionOptions options);
NeverNullType resolveSILBoxType(SILBoxTypeRepr *repr,
TypeResolutionOptions options);
NeverNullType
buildMetatypeType(MetatypeTypeRepr *repr, Type instanceType,
Optional<MetatypeRepresentation> storedRepr);
NeverNullType
buildProtocolType(ProtocolTypeRepr *repr, Type instanceType,
Optional<MetatypeRepresentation> storedRepr);
NeverNullType resolveOpaqueReturnType(TypeRepr *repr, StringRef mangledName,
unsigned ordinal,
TypeResolutionOptions options);
};
} // end anonymous namespace
Type TypeResolution::resolveContextualType(
TypeRepr *TyR, DeclContext *dc, TypeResolutionOptions opts,
OpenUnboundGenericTypeFn unboundTyOpener,
HandlePlaceholderTypeReprFn placeholderHandler,
GenericParamList *silParams) {
return resolveContextualType(TyR, dc, dc->getGenericEnvironmentOfContext(),
opts, unboundTyOpener, placeholderHandler);
}
Type TypeResolution::resolveContextualType(
TypeRepr *TyR, DeclContext *dc, GenericEnvironment *genericEnv,
TypeResolutionOptions opts, OpenUnboundGenericTypeFn unboundTyOpener,
HandlePlaceholderTypeReprFn placeholderHandler,
GenericParamList *silParams) {
const auto resolution = TypeResolution::forInterface(
dc, genericEnv, opts, unboundTyOpener, placeholderHandler);
const auto ty = resolution.resolveType(TyR, silParams);
return GenericEnvironment::mapTypeIntoContext(
resolution.getGenericSignature().getGenericEnvironment(), ty);
}
Type TypeResolution::resolveType(TypeRepr *TyR,
GenericParamList *silParams) const {
auto &ctx = getASTContext();
auto Ty =
evaluateOrDefault(ctx.evaluator,
ResolveTypeRequest{this, TyR, silParams}, Type());
if (!Ty)
return ErrorType::get(ctx);
return Ty;
}
Type ResolveTypeRequest::evaluate(Evaluator &evaluator,
const TypeResolution *resolution,
TypeRepr *TyR,
GenericParamList *silParams) const {
const auto options = resolution->getOptions();
auto &ctx = resolution->getASTContext();
auto result =
TypeResolver(*resolution, silParams)
.resolveType(TyR, resolution->getOptions());
// If we resolved down to an error, make sure to mark the typeRepr as invalid
// so we don't produce a redundant diagnostic.
if (result->hasError()) {
TyR->setInvalid();
return result;
}
auto loc = TyR->getLoc();
if (options.contains(TypeResolutionFlags::SILType)
&& !result->isLegalSILType()) {
ctx.Diags.diagnose(loc, diag::illegal_sil_type, result);
return ErrorType::get(ctx);
}
if (validateAutoClosureAttributeUse(ctx.Diags, TyR, result, options))
return ErrorType::get(ctx);
return result;
}
NeverNullType TypeResolver::resolveType(TypeRepr *repr,
TypeResolutionOptions options) {
assert(repr && "Cannot validate null TypeReprs!");
// If we know the type representation is invalid, just return an
// error type.
if (repr->isInvalid())
return ErrorType::get(getASTContext());
// Strip the "is function input" bits unless this is a type that knows about
// them.
if (options.is(TypeResolverContext::FunctionInput) &&
!isa<SpecifierTypeRepr>(repr) && !isa<TupleTypeRepr>(repr) &&
!isa<AttributedTypeRepr>(repr) && !isa<FunctionTypeRepr>(repr) &&
!isa<IdentTypeRepr>(repr) &&
!isa<ImplicitlyUnwrappedOptionalTypeRepr>(repr)) {
options.setContext(None);
}
bool isDirect = false;
if ((options & TypeResolutionFlags::Direct) && !isa<SpecifierTypeRepr>(repr)){
isDirect = true;
options -= TypeResolutionFlags::Direct;
}
switch (repr->getKind()) {
case TypeReprKind::Error:
return ErrorType::get(getASTContext());
case TypeReprKind::Attributed:
return resolveAttributedType(cast<AttributedTypeRepr>(repr), options);
case TypeReprKind::InOut:
case TypeReprKind::Shared:
case TypeReprKind::Owned:
return resolveSpecifierTypeRepr(cast<SpecifierTypeRepr>(repr), options);
case TypeReprKind::Isolated:
return resolveIsolatedTypeRepr(cast<IsolatedTypeRepr>(repr), options);
case TypeReprKind::CompileTimeConst:
return resolveCompileTimeConstTypeRepr(cast<CompileTimeConstTypeRepr>(repr),
options);
case TypeReprKind::SimpleIdent:
case TypeReprKind::GenericIdent:
case TypeReprKind::CompoundIdent:
return resolveIdentifierType(cast<IdentTypeRepr>(repr), options);
case TypeReprKind::Function: {
if (!(options & TypeResolutionFlags::SILType)) {
// Default non-escaping for closure parameters
auto result =
resolveASTFunctionType(cast<FunctionTypeRepr>(repr), options);
if (result->is<FunctionType>())
return applyNonEscapingIfNecessary(result, options);
return result;
}
return resolveSILFunctionType(cast<FunctionTypeRepr>(repr), options);
}
case TypeReprKind::SILBox:
assert((options & TypeResolutionFlags::SILType) && "SILBox repr in non-SIL type context?!");
return resolveSILBoxType(cast<SILBoxTypeRepr>(repr), options);
case TypeReprKind::Array:
return resolveArrayType(cast<ArrayTypeRepr>(repr), options);
case TypeReprKind::Dictionary:
return resolveDictionaryType(cast<DictionaryTypeRepr>(repr), options);
case TypeReprKind::Optional:
return resolveOptionalType(cast<OptionalTypeRepr>(repr), options);
case TypeReprKind::ImplicitlyUnwrappedOptional: {
auto iuoRepr = cast<ImplicitlyUnwrappedOptionalTypeRepr>(repr);
return resolveImplicitlyUnwrappedOptionalType(iuoRepr, options, isDirect);
}
case TypeReprKind::Tuple:
return resolveTupleType(cast<TupleTypeRepr>(repr), options);
case TypeReprKind::Composition:
return resolveCompositionType(cast<CompositionTypeRepr>(repr), options);
case TypeReprKind::Metatype:
return resolveMetatypeType(cast<MetatypeTypeRepr>(repr), options);
case TypeReprKind::Protocol:
return resolveProtocolType(cast<ProtocolTypeRepr>(repr), options);
case TypeReprKind::OpaqueReturn: {
// If the opaque type is in a valid position, e.g. part of a function return
// type, resolution should happen in the context of an `OpaqueTypeDecl`.
// This decl is implicit in the source and is created in such contexts by
// evaluation of an `OpaqueResultTypeRequest`.
auto opaqueRepr = cast<OpaqueReturnTypeRepr>(repr);
auto *DC = getDeclContext();
if (auto opaqueDecl = dyn_cast<OpaqueTypeDecl>(DC)) {
if (auto ordinal = opaqueDecl->getAnonymousOpaqueParamOrdinal(opaqueRepr))
return getIdentityOpaqueTypeArchetypeType(opaqueDecl, *ordinal);
}
// Check whether any of the generic parameters in the context represents
// this opaque type. If so, return that generic parameter.
if (auto declDC = DC->getAsDecl()) {
if (auto genericContext = declDC->getAsGenericContext()) {
if (auto genericParams = genericContext->getGenericParams()) {
for (auto genericParam : *genericParams) {
if (genericParam->getOpaqueTypeRepr() == opaqueRepr)
return genericParam->getDeclaredInterfaceType();
}
}
}
}
// We are not inside an `OpaqueTypeDecl`, so diagnose an error.
if (!(options & TypeResolutionFlags::SilenceErrors)) {
diagnose(opaqueRepr->getOpaqueLoc(),
diag::unsupported_opaque_type);
}
// Try to resolve the constraint upper bound type as a placeholder.
options |= TypeResolutionFlags::SilenceErrors;
auto constraintType = resolveType(opaqueRepr->getConstraint(),
options);
return !constraintType->hasError() ? ErrorType::get(constraintType)
: ErrorType::get(getASTContext());
}
case TypeReprKind::Existential: {
auto *existential = cast<ExistentialTypeRepr>(repr);
return resolveExistentialType(existential, options);
}
case TypeReprKind::NamedOpaqueReturn: {
// If the named opaque result type is in a valid position, resolution
// should happen in the context of an `OpaqueTypeDecl`. This decl is
// implicit in the source and is created in such contexts by evaluation of
// an `OpaqueResultTypeRequest`.
auto opaqueRepr = cast<NamedOpaqueReturnTypeRepr>(repr);
if (auto opaqueDecl = dyn_cast<OpaqueTypeDecl>(getDeclContext())) {
// Resolve the base type within this context.
// FIXME: Temporary hack to resolve an identifier type to one of the
// generic parameters of the opaque return type. This should be subsumed
// be proper name lookup, OF COURSE.
if (auto simpleIdent = dyn_cast<SimpleIdentTypeRepr>(
opaqueRepr->getBase())) {
Identifier name = simpleIdent->getComponentRange().front()
->getNameRef().getBaseIdentifier();
if (auto gpDecl = opaqueRepr->getGenericParams()
->lookUpGenericParam(name)) {
auto outerGenericSignature = opaqueDecl->getNamingDecl()
->getInnermostDeclContext()
->getGenericSignatureOfContext();
SubstitutionMap subs;
if (outerGenericSignature)
subs = outerGenericSignature->getIdentitySubstitutionMap();
return OpaqueTypeArchetypeType::get(
opaqueDecl, gpDecl->getDeclaredInterfaceType(), subs);
}
}
return resolveType(opaqueRepr->getBase(), options);
}
// We are not inside an `OpaqueTypeDecl`, so diagnose an error.
if (!(options & TypeResolutionFlags::SilenceErrors)) {
diagnose(repr->getStartLoc(), diag::unsupported_opaque_type);
}
return ErrorType::get(getASTContext());
}
case TypeReprKind::Placeholder: {
auto &ctx = getASTContext();
// Fill in the placeholder if there's an appropriate handler.
if (const auto handlerFn = resolution.getPlaceholderHandler())
if (const auto ty = handlerFn(ctx, cast<PlaceholderTypeRepr>(repr)))
return ty;
// Complain if we're allowed to and bail out with an error.
if (!options.contains(TypeResolutionFlags::SilenceErrors))
ctx.Diags.diagnose(repr->getLoc(),
diag::placeholder_type_not_allowed);
return ErrorType::get(resolution.getASTContext());
}
case TypeReprKind::Fixed:
return cast<FixedTypeRepr>(repr)->getType();
}
llvm_unreachable("all cases should be handled");
}
static Type rebuildWithDynamicSelf(ASTContext &Context, Type ty) {
if (auto metatypeTy = ty->getAs<MetatypeType>()) {
return MetatypeType::get(
rebuildWithDynamicSelf(Context, metatypeTy->getInstanceType()),
metatypeTy->getRepresentation());
} else if (auto optionalTy = ty->getOptionalObjectType()) {
return OptionalType::get(rebuildWithDynamicSelf(Context, optionalTy));
} else {
return DynamicSelfType::get(ty, Context);
}
}
NeverNullType
TypeResolver::resolveAttributedType(AttributedTypeRepr *repr,
TypeResolutionOptions options) {
// Copy the attributes, since we're about to start hacking on them.
TypeAttributes attrs = repr->getAttrs();
assert(!attrs.empty());
return resolveAttributedType(attrs, repr->getTypeRepr(), options);
}
NeverNullType
TypeResolver::resolveAttributedType(TypeAttributes &attrs, TypeRepr *repr,
TypeResolutionOptions options) {
// Convenience to grab the source range of a type attribute.
auto getTypeAttrRangeWithAt = [](ASTContext &ctx, SourceLoc attrLoc) {
return SourceRange(attrLoc, attrLoc.getAdvancedLoc(1));
};
// Remember whether this is a function parameter.
bool isParam = options.is(TypeResolverContext::FunctionInput);
// Remember whether this is a function result.
bool isResult = options.is(TypeResolverContext::FunctionResult);
// Remember whether this is a variadic function parameter.
bool isVariadicFunctionParam =
options.is(TypeResolverContext::VariadicFunctionInput) &&
!options.hasBase(TypeResolverContext::EnumElementDecl);
// Resolve global actor.
CustomAttr *globalActorAttr = nullptr;
Type globalActor;
if (isa<FunctionTypeRepr>(repr)) {
auto foundGlobalActor = checkGlobalActorAttributes(
repr->getLoc(), getDeclContext(),
std::vector<CustomAttr *>(
attrs.getCustomAttrs().begin(), attrs.getCustomAttrs().end()));
if (foundGlobalActor) {
globalActorAttr = foundGlobalActor->first;
globalActor = resolveType(globalActorAttr->getTypeRepr(), options);
if (globalActor->hasError())
globalActor = Type();
}
}
// Diagnose custom attributes that haven't been processed yet.
for (auto customAttr : attrs.getCustomAttrs()) {
// If this was the global actor we matched, ignore it.
if (globalActorAttr == customAttr)
continue;
// If this attribute was marked invalid, ignore it.
if (customAttr->isInvalid())
continue;
// Diagnose the attribute, because we don't yet handle custom type
// attributes.
std::string typeName;
if (auto typeRepr = customAttr->getTypeRepr()) {
llvm::raw_string_ostream out(typeName);
typeRepr->print(out);
} else {
typeName = customAttr->getType().getString();
}
diagnose(customAttr->getLocation(), diag::unknown_attribute, typeName);
customAttr->setInvalid();
}
// The type we're working with, in case we want to build it differently
// based on the attributes we see.
Type ty;
// If this is a reference to an opaque return type, resolve it.
if (auto &opaque = attrs.OpaqueReturnTypeOf) {
return resolveOpaqueReturnType(repr, opaque->mangledName, opaque->index,
options);
}
// In SIL *only*, allow @thin, @thick, or @objc_metatype to apply to
// a metatype.
if (attrs.has(TAK_thin) || attrs.has(TAK_thick) ||
attrs.has(TAK_objc_metatype)) {
if (auto SF = getDeclContext()->getParentSourceFile()) {
if (SF->Kind == SourceFileKind::SIL) {
TypeRepr *base;
if (auto metatypeRepr = dyn_cast<MetatypeTypeRepr>(repr)) {
base = metatypeRepr->getBase();
} else if (auto protocolRepr = dyn_cast<ProtocolTypeRepr>(repr)) {
base = protocolRepr->getBase();
} else {
base = nullptr;
}
if (base) {
Optional<MetatypeRepresentation> storedRepr;
// The instance type is not a SIL type.
auto instanceOptions = options;
TypeResolverContext context = TypeResolverContext::None;
if (isa<MetatypeTypeRepr>(repr)) {
context = TypeResolverContext::MetatypeBase;
} else if (isa<ProtocolTypeRepr>(repr)) {
context = TypeResolverContext::ProtocolMetatypeBase;
}
instanceOptions.setContext(context);
instanceOptions -= TypeResolutionFlags::SILType;
auto instanceTy = resolveType(base, instanceOptions);
if (instanceTy->hasError())
return instanceTy;
// Check for @thin.
if (attrs.has(TAK_thin)) {
storedRepr = MetatypeRepresentation::Thin;
attrs.clearAttribute(TAK_thin);
}
// Check for @thick.
if (attrs.has(TAK_thick)) {
if (storedRepr) {
diagnoseInvalid(repr, repr->getStartLoc(),
diag::sil_metatype_multiple_reprs);
}
storedRepr = MetatypeRepresentation::Thick;
attrs.clearAttribute(TAK_thick);
}
// Check for @objc_metatype.
if (attrs.has(TAK_objc_metatype)) {
if (storedRepr) {
diagnoseInvalid(repr, repr->getStartLoc(),
diag::sil_metatype_multiple_reprs);
}
storedRepr = MetatypeRepresentation::ObjC;
attrs.clearAttribute(TAK_objc_metatype);
}
if (instanceTy->hasError()) {
ty = instanceTy;
} else if (auto metatype = dyn_cast<MetatypeTypeRepr>(repr)) {
ty = buildMetatypeType(metatype, instanceTy, storedRepr);
} else {
ty = buildProtocolType(cast<ProtocolTypeRepr>(repr),
instanceTy, storedRepr);
}
}
}
}
}
// Pass down the variable function type attributes to the
// function-type creator.
static const TypeAttrKind FunctionAttrs[] = {
TAK_convention, TAK_pseudogeneric,
TAK_callee_owned, TAK_callee_guaranteed, TAK_noescape, TAK_autoclosure,
TAK_differentiable, TAK_escaping, TAK_Sendable,
TAK_yield_once, TAK_yield_many, TAK_async
};
auto checkUnsupportedAttr = [&](TypeAttrKind attr) {
if (attrs.has(attr)) {
diagnoseInvalid(repr, attrs.getLoc(attr), diag::unknown_attribute,
TypeAttributes::getAttrName(attr));
attrs.clearAttribute(attr);
}
};
// Some function representation attributes are not supported at source level;
// only SIL knows how to handle them. Reject them unless this is a SIL input.
if (!(options & TypeResolutionFlags::SILType)) {
for (auto silOnlyAttr : {TAK_pseudogeneric,
TAK_callee_owned,
TAK_callee_guaranteed,
TAK_noescape,
TAK_yield_once,
TAK_yield_many}) {
checkUnsupportedAttr(silOnlyAttr);
}
}
// Other function representation attributes are not normally supported at
// source level, but we want to support them there in SIL files.
auto SF = getDeclContext()->getParentSourceFile();
if (!SF || SF->Kind != SourceFileKind::SIL) {
for (auto silOnlyAttr : {TAK_thin, TAK_thick}) {
checkUnsupportedAttr(silOnlyAttr);
}
}
bool hasFunctionAttr = globalActor ||
llvm::any_of(FunctionAttrs, [&attrs](const TypeAttrKind &attr) {
return attrs.has(attr);
});
// Function attributes require a syntactic function type.
auto *fnRepr = dyn_cast<FunctionTypeRepr>(repr);
auto tryParseClangType = [this](TypeAttributes::Convention &conv,
bool hasConventionCOrBlock)
-> const clang::Type * {
if (conv.ClangType.Item.empty())
return nullptr;
if (!hasConventionCOrBlock) {
diagnose(conv.ClangType.Loc,
diag::unexpected_ctype_for_non_c_convention,
conv.Name, conv.ClangType.Item);
return nullptr;
}
const clang::Type *type =
getASTContext().getClangModuleLoader()->parseClangFunctionType(
conv.ClangType.Item, conv.ClangType.Loc);
if (!type)
diagnose(conv.ClangType.Loc, diag::unable_to_parse_c_function_type,
conv.ClangType.Item);
return type;
};
if (fnRepr && hasFunctionAttr) {
const clang::Type *parsedClangFunctionType = nullptr;
if (options & TypeResolutionFlags::SILType) {
SILFunctionType::Representation rep;
TypeRepr *witnessMethodProtocol = nullptr;
auto coroutineKind = SILCoroutineKind::None;
if (attrs.has(TAK_yield_once)) {
coroutineKind = SILCoroutineKind::YieldOnce;
} else if (attrs.has(TAK_yield_many)) {
coroutineKind = SILCoroutineKind::YieldMany;
}
auto calleeConvention = ParameterConvention::Direct_Unowned;
if (attrs.has(TAK_callee_owned)) {
if (attrs.has(TAK_callee_guaranteed)) {
diagnoseInvalid(repr, attrs.getLoc(TAK_callee_owned),
diag::sil_function_repeat_convention, /*callee*/ 2);
}
calleeConvention = ParameterConvention::Direct_Owned;
} else if (attrs.has(TAK_callee_guaranteed)) {
calleeConvention = ParameterConvention::Direct_Guaranteed;
}
if (!attrs.hasConvention()) {
rep = SILFunctionType::Representation::Thick;
} else {
auto convention = attrs.getConventionName();
// SIL exposes a greater number of conventions than Swift source.
auto parsedRep =
llvm::StringSwitch<Optional<SILFunctionType::Representation>>(
convention)
.Case("thick", SILFunctionType::Representation::Thick)
.Case("block", SILFunctionType::Representation::Block)
.Case("thin", SILFunctionType::Representation::Thin)
.Case("c", SILFunctionType::Representation::CFunctionPointer)
.Case("method", SILFunctionType::Representation::Method)
.Case("objc_method",
SILFunctionType::Representation::ObjCMethod)
.Case("witness_method",
SILFunctionType::Representation::WitnessMethod)
.Default(None);
if (!parsedRep) {
diagnoseInvalid(repr, attrs.getLoc(TAK_convention),
diag::unsupported_sil_convention,
attrs.getConventionName());
rep = SILFunctionType::Representation::Thin;
} else {
rep = *parsedRep;
parsedClangFunctionType = tryParseClangType(
attrs.ConventionArguments.getValue(), shouldStoreClangType(rep));
}
if (rep == SILFunctionType::Representation::WitnessMethod) {
auto protocolName =
attrs.ConventionArguments.getValue().WitnessMethodProtocol;
witnessMethodProtocol = new (getASTContext())
SimpleIdentTypeRepr(DeclNameLoc(), protocolName);
}
}
DifferentiabilityKind diffKind = DifferentiabilityKind::NonDifferentiable;
if (attrs.has(TAK_differentiable)) {
auto *SF = getDeclContext()->getParentSourceFile();
if (SF && isDifferentiableProgrammingEnabled(*SF)) {
diffKind = attrs.differentiabilityKind;
} else {
diagnoseInvalid(
repr, attrs.getLoc(TAK_differentiable),
diag::
differentiable_programming_attr_used_without_required_module,
TypeAttributes::getAttrName(TAK_differentiable),
getASTContext().Id_Differentiation);
}
}
auto extInfoBuilder = SILFunctionType::ExtInfoBuilder(
rep, attrs.has(TAK_pseudogeneric), attrs.has(TAK_noescape),
attrs.has(TAK_Sendable), attrs.has(TAK_async), diffKind,
parsedClangFunctionType);
ty =
resolveSILFunctionType(fnRepr, options, coroutineKind, extInfoBuilder,
calleeConvention, witnessMethodProtocol);
if (!ty || ty->hasError())
return ty;
} else {
FunctionType::Representation rep = FunctionType::Representation::Swift;
if (attrs.hasConvention()) {
auto parsedRep =
llvm::StringSwitch<Optional<FunctionType::Representation>>(
attrs.getConventionName())
.Case("swift", FunctionType::Representation::Swift)
.Case("block", FunctionType::Representation::Block)
.Case("thin", FunctionType::Representation::Thin)
.Case("c", FunctionType::Representation::CFunctionPointer)
.Default(None);
if (!parsedRep) {
diagnoseInvalid(repr, attrs.getLoc(TAK_convention),
diag::unsupported_convention,
attrs.getConventionName());
rep = FunctionType::Representation::Swift;
} else {
rep = *parsedRep;
parsedClangFunctionType = tryParseClangType(
attrs.ConventionArguments.getValue(), shouldStoreClangType(rep));
}
}
DifferentiabilityKind diffKind = DifferentiabilityKind::NonDifferentiable;
if (attrs.has(TAK_differentiable)) {
auto *SF = getDeclContext()->getParentSourceFile();
if (SF && isDifferentiableProgrammingEnabled(*SF)) {
diffKind = attrs.differentiabilityKind;
} else {
diagnoseInvalid(
repr, attrs.getLoc(TAK_differentiable),
diag::
differentiable_programming_attr_used_without_required_module,
TypeAttributes::getAttrName(TAK_differentiable),
getASTContext().Id_Differentiation);
}
}
bool concurrent = attrs.has(TAK_Sendable);
ty = resolveASTFunctionType(fnRepr, options, rep, /*noescape=*/false,
concurrent, parsedClangFunctionType,
diffKind, globalActor);
if (!ty || ty->hasError())
return ty;
}
}
// Validate use of @autoclosure
if (attrs.has(TAK_autoclosure)) {
bool didDiagnose = false;
if (attrs.hasConvention()) {
if (attrs.getConventionName() == "c" ||
attrs.getConventionName() == "block") {
diagnoseInvalid(repr, attrs.getLoc(TAK_convention),
diag::invalid_autoclosure_and_convention_attributes,
attrs.getConventionName());
attrs.clearAttribute(TAK_convention);
didDiagnose = true;
}
} else if (options.is(TypeResolverContext::VariadicFunctionInput) &&
!options.hasBase(TypeResolverContext::EnumElementDecl)) {
diagnoseInvalid(repr, attrs.getLoc(TAK_autoclosure),
diag::attr_not_on_variadic_parameters, "@autoclosure");
attrs.clearAttribute(TAK_autoclosure);
didDiagnose = true;
} else if (!options.is(TypeResolverContext::FunctionInput)) {
diagnoseInvalid(repr, attrs.getLoc(TAK_autoclosure),
diag::attr_only_on_parameters, "@autoclosure");
attrs.clearAttribute(TAK_autoclosure);
didDiagnose = true;
}
if (didDiagnose) {
ty = ErrorType::get(getASTContext());
}
}
if (attrs.has(TAK_unchecked)) {
ty = resolveType(repr, options);
if (!ty || ty->hasError()) return ty;
if (!options.is(TypeResolverContext::Inherited) ||
getDeclContext()->getSelfProtocolDecl()) {
diagnoseInvalid(repr, attrs.getLoc(TAK_unchecked),
diag::unchecked_not_inheritance_clause);
ty = ErrorType::get(getASTContext());
} else if (!ty->isConstraintType()) {
diagnoseInvalid(repr, attrs.getLoc(TAK_unchecked),
diag::unchecked_not_existential, ty);
ty = ErrorType::get(getASTContext());
}
// Nothing to record in the type. Just clear the attribute.
attrs.clearAttribute(TAK_unchecked);
}
auto instanceOptions = options;
instanceOptions.setContext(None);
// If we didn't build the type differently above, we might have
// a typealias pointing at a function type with the @escaping
// attribute. Resolve the type as if it were in non-parameter
// context, and then set isNoEscape if @escaping is not present.
if (!ty) ty = resolveType(repr, instanceOptions);
if (!ty || ty->hasError()) return ty;
// Type aliases inside protocols are not yet resolved in the structural
// stage of type resolution
if (ty->is<DependentMemberType>() &&
resolution.getStage() == TypeResolutionStage::Structural) {
return ty;
}
// Handle @escaping
if (ty->is<FunctionType>()) {
if (attrs.has(TAK_escaping)) {
// The attribute is meaningless except on non-variadic parameter types.
if (!isParam || options.getBaseContext() == TypeResolverContext::EnumElementDecl) {
auto loc = attrs.getLoc(TAK_escaping);
auto attrRange = getTypeAttrRangeWithAt(getASTContext(), loc);
// Try to find a better diagnostic based on how the type is being used
if (options.is(TypeResolverContext::ImmediateOptionalTypeArgument)) {
diagnoseInvalid(repr, repr->getLoc(),
diag::escaping_optional_type_argument)
.fixItRemove(attrRange);
} else {
diagnoseInvalid(repr, loc, diag::escaping_non_function_parameter)
.fixItRemove(attrRange);
}
ty = ErrorType::get(getASTContext());
}
attrs.clearAttribute(TAK_escaping);
} else {
// No attribute; set the isNoEscape bit if we're in parameter context.
ty = applyNonEscapingIfNecessary(ty, options);
}
}
if (attrs.has(TAK_autoclosure)) {
// If this is a situation where function type is wrapped
// into a number of parens, let's try to look through them,
// because parens are insignificant here e.g.:
//
// let _: (@autoclosure (() -> Void)) -> Void = { _ in }
if (!ty->is<FunctionType>()) {
// @autoclosure is going to be diagnosed when type of
// the parameter is validated, because that attribute
// applies to the declaration now.
repr->setInvalid();
}
attrs.clearAttribute(TAK_autoclosure);
}
if (hasFunctionAttr && !fnRepr) {
const auto diagnoseInvalidAttr = [&](TypeAttrKind kind) {
if (kind == TAK_escaping) {
Type optionalObjectType = ty->getOptionalObjectType();
if (optionalObjectType && optionalObjectType->is<AnyFunctionType>()) {
return diagnoseInvalid(repr, attrs.getLoc(kind),
diag::escaping_optional_type_argument);
}
}
return diagnoseInvalid(repr, attrs.getLoc(kind),
diag::attribute_requires_function_type,
TypeAttributes::getAttrName(kind));
};
for (auto i : FunctionAttrs) {
if (!attrs.has(i))
continue;
auto diag = diagnoseInvalidAttr(i);
// If we see @escaping among the attributes on this type, because it
// isn't a function type, we'll remove it.
if (i == TAK_escaping) {
diag.fixItRemove(getTypeAttrRangeWithAt(getASTContext(),
attrs.getLoc(TAK_escaping)));
}
attrs.clearAttribute(i);
}
} else if (hasFunctionAttr && fnRepr) {
// Remove the function attributes from the set so that we don't diagnose.
for (auto i : FunctionAttrs)
attrs.clearAttribute(i);
attrs.ConventionArguments = None;
}
if (attrs.has(TAK_noDerivative)) {
// @noDerivative is valid on function parameters (AST and SIL) or on
// function results (SIL-only).
bool isNoDerivativeAllowed =
isParam ||
options.is(TypeResolverContext::InoutFunctionInput) ||
(isResult && (options & TypeResolutionFlags::SILType));
auto *SF = getDeclContext()->getParentSourceFile();
if (SF && !isDifferentiableProgrammingEnabled(*SF)) {
diagnose(
attrs.getLoc(TAK_noDerivative),
diag::differentiable_programming_attr_used_without_required_module,
TypeAttributes::getAttrName(TAK_noDerivative),
getASTContext().Id_Differentiation);
} else if (!isNoDerivativeAllowed) {
diagnose(attrs.getLoc(TAK_noDerivative),
(isVariadicFunctionParam
? diag::attr_not_on_variadic_parameters
: diag::attr_only_on_parameters_of_differentiable),
"@noDerivative");
}
attrs.clearAttribute(TAK_noDerivative);
}
// In SIL, handle @opened (n), which creates an existential archetype.
if (attrs.has(TAK_opened)) {
if (!ty->isExistentialType()) {
diagnoseInvalid(repr, attrs.getLoc(TAK_opened), diag::opened_non_protocol,
ty);
} else {
ty = GenericEnvironment::mapTypeIntoContext(
resolution.getGenericSignature().getGenericEnvironment(), ty);
ty = OpenedArchetypeType::get(ty->getCanonicalType(), attrs.OpenedID);
}
attrs.clearAttribute(TAK_opened);
}
// In SIL files *only*, permit @weak and @unowned to apply directly to types.
if (attrs.hasOwnership()) {
if (auto SF = getDeclContext()->getParentSourceFile()) {
if (SF->Kind == SourceFileKind::SIL) {
if (((attrs.has(TAK_sil_weak) || attrs.has(TAK_sil_unmanaged)) &&
ty->getOptionalObjectType()) ||
(!attrs.has(TAK_sil_weak) &&
GenericEnvironment::mapTypeIntoContext(
resolution.getGenericSignature().getGenericEnvironment(), ty)
->hasReferenceSemantics())) {
ty = ReferenceStorageType::get(ty, attrs.getOwnership(),
getASTContext());
attrs.clearOwnership();
}
}
}
}
// In SIL *only*, allow @block_storage to specify a block storage type.
if ((options & TypeResolutionFlags::SILType) && attrs.has(TAK_block_storage)) {
ty = SILBlockStorageType::get(ty->getCanonicalType());
attrs.clearAttribute(TAK_block_storage);
}
// In SIL *only*, allow @box to specify a box type.
if ((options & TypeResolutionFlags::SILType) && attrs.has(TAK_box)) {
ty = SILBoxType::get(ty->getCanonicalType());
attrs.clearAttribute(TAK_box);
}
// In SIL *only*, allow @dynamic_self to specify a dynamic Self type.
if ((options & TypeResolutionFlags::SILMode) && attrs.has(TAK_dynamic_self)) {
ty = rebuildWithDynamicSelf(getASTContext(), ty);
attrs.clearAttribute(TAK_dynamic_self);
}
// In SIL *only*, allow @async to specify an async function
if ((options & TypeResolutionFlags::SILMode) && attrs.has(TAK_async)) {
if (fnRepr != nullptr) {
attrs.clearAttribute(TAK_async);
}
}
for (unsigned i = 0; i != TypeAttrKind::TAK_Count; ++i)
if (attrs.has((TypeAttrKind)i)) {
diagnoseInvalid(repr, attrs.getLoc((TypeAttrKind)i),
diag::attribute_does_not_apply_to_type);
}
return ty;
}
SmallVector<AnyFunctionType::Param, 8>
TypeResolver::resolveASTFunctionTypeParams(TupleTypeRepr *inputRepr,
TypeResolutionOptions options,
DifferentiabilityKind diffKind) {
SmallVector<AnyFunctionType::Param, 8> elements;
elements.reserve(inputRepr->getNumElements());
auto elementOptions = options.withoutContext(true);
elementOptions.setContext(TypeResolverContext::FunctionInput);
for (unsigned i = 0, end = inputRepr->getNumElements(); i != end; ++i) {
auto *eltTypeRepr = inputRepr->getElementType(i);
// If the element is a variadic parameter, resolve the parameter type as if
// it were in non-parameter position, since we want functions to be
// @escaping in this case.
auto thisElementOptions = elementOptions;
bool variadic = false;
if (inputRepr->hasEllipsis() &&
elements.size() == inputRepr->getEllipsisIndex()) {
thisElementOptions = elementOptions.withoutContext();
thisElementOptions.setContext(TypeResolverContext::VariadicFunctionInput);
variadic = true;
}
auto ty = resolveType(eltTypeRepr, thisElementOptions);
if (ty->hasError()) {
elements.emplace_back(ErrorType::get(getASTContext()));
continue;
}
bool autoclosure = false;
if (auto *ATR = dyn_cast<AttributedTypeRepr>(eltTypeRepr))
autoclosure = ATR->getAttrs().has(TAK_autoclosure);
ValueOwnership ownership = ValueOwnership::Default;
// Look through parens here; other than parens, specifiers
// must appear at the top level of a parameter type.
auto *nestedRepr = eltTypeRepr->getWithoutParens();
bool isolated = false;
bool compileTimeConst = false;
while (true) {
if (auto *specifierRepr = dyn_cast<SpecifierTypeRepr>(nestedRepr)) {
switch (specifierRepr->getKind()) {
case TypeReprKind::Shared:
ownership = ValueOwnership::Shared;
nestedRepr = specifierRepr->getBase();
continue;
case TypeReprKind::InOut:
ownership = ValueOwnership::InOut;
nestedRepr = specifierRepr->getBase();
continue;
case TypeReprKind::Owned:
ownership = ValueOwnership::Owned;
nestedRepr = specifierRepr->getBase();
continue;
case TypeReprKind::Isolated:
isolated = true;
nestedRepr = specifierRepr->getBase();
continue;
case TypeReprKind::CompileTimeConst:
compileTimeConst = true;
nestedRepr = specifierRepr->getBase();
continue;
default:
break;
}
}
break;
}
bool noDerivative = false;
if (auto *attrTypeRepr = dyn_cast<AttributedTypeRepr>(nestedRepr)) {
if (attrTypeRepr->getAttrs().has(TAK_noDerivative)) {
if (diffKind == DifferentiabilityKind::NonDifferentiable &&
isDifferentiableProgrammingEnabled(
*getDeclContext()->getParentSourceFile()))
diagnose(nestedRepr->getLoc(),
diag::attr_only_on_parameters_of_differentiable,
"@noDerivative")
.highlight(nestedRepr->getSourceRange());
else
noDerivative = true;
}
}
auto paramFlags = ParameterTypeFlags::fromParameterType(
ty, variadic, autoclosure, /*isNonEphemeral*/ false, ownership,
isolated, noDerivative, compileTimeConst);
elements.emplace_back(ty, Identifier(), paramFlags,
inputRepr->getElementName(i));
}
return elements;
}
NeverNullType
TypeResolver::resolveOpaqueReturnType(TypeRepr *repr, StringRef mangledName,
unsigned ordinal,
TypeResolutionOptions options) {
// The type repr should be a generic identifier type. We don't really use
// the identifier for anything, but we do resolve the generic arguments
// to instantiate the possibly-generic opaque type.
SmallVector<Type, 4> TypeArgsBuf;
if (auto generic = dyn_cast<GenericIdentTypeRepr>(repr)) {
for (auto argRepr : generic->getGenericArgs()) {
auto argTy = resolveType(argRepr, options);
// If we cannot resolve the generic parameter, propagate the error out.
if (argTy->hasError()) {
return ErrorType::get(getASTContext());
}
TypeArgsBuf.push_back(argTy);
}
}
// Use type reconstruction to summon the opaque type decl.
Demangler demangle;
auto definingDeclNode = demangle.demangleSymbol(mangledName);
if (!definingDeclNode) {
diagnose(repr->getLoc(), diag::no_opaque_return_type_of);
return ErrorType::get(getASTContext());
}
if (definingDeclNode->getKind() == Node::Kind::Global)
definingDeclNode = definingDeclNode->getChild(0);
ASTBuilder builder(getASTContext());
auto opaqueNode =
builder.getNodeFactory().createNode(Node::Kind::OpaqueReturnTypeOf);
opaqueNode->addChild(definingDeclNode, builder.getNodeFactory());
auto TypeArgs = ArrayRef<Type>(TypeArgsBuf);
auto ty = builder.resolveOpaqueType(opaqueNode, TypeArgs, ordinal);
if (!ty || ty->hasError()) {
diagnose(repr->getLoc(), diag::no_opaque_return_type_of);
return ErrorType::get(getASTContext());
}
return ty;
}
NeverNullType TypeResolver::resolveASTFunctionType(
FunctionTypeRepr *repr, TypeResolutionOptions parentOptions,
AnyFunctionType::Representation representation, bool noescape,
bool concurrent, const clang::Type *parsedClangFunctionType,
DifferentiabilityKind diffKind, Type globalActor) {
Optional<llvm::SaveAndRestore<GenericParamList *>> saveGenericParams;
if (auto *genericParams = repr->getGenericParams())
saveGenericParams.emplace(this->genericParams, genericParams);
// Diagnose a couple of things that we can parse in SIL mode but we don't
// allow in formal types.
if (auto patternParams = repr->getPatternGenericParams()) {
diagnose(patternParams->getLAngleLoc(),
diag::ast_subst_function_type);
return ErrorType::get(getASTContext());
} else if (!repr->getInvocationSubstitutions().empty()) {
diagnose(repr->getInvocationSubstitutions()[0]->getStartLoc(),
diag::ast_subst_function_type);
return ErrorType::get(getASTContext());
}
TypeResolutionOptions options = None;
options |= parentOptions.withoutContext().getFlags();
auto params =
resolveASTFunctionTypeParams(repr->getArgsTypeRepr(), options, diffKind);
auto resultOptions = options.withoutContext();
resultOptions.setContext(TypeResolverContext::FunctionResult);
auto outputTy = resolveType(repr->getResultTypeRepr(), resultOptions);
if (outputTy->hasError()) {
return ErrorType::get(getASTContext());
}
// If this is a function type without parens around the parameter list,
// diagnose this and produce a fixit to add them.
if (!repr->isWarnedAbout()) {
// If someone wrote (Void) -> () in Swift 3, they probably meant
// () -> (), but (Void) -> () is (()) -> () so emit a warning
// asking if they meant () -> ().
auto args = repr->getArgsTypeRepr();
if (args->getNumElements() == 1) {
if (const auto Void =
dyn_cast<SimpleIdentTypeRepr>(args->getElementType(0))) {
if (Void->getNameRef().isSimpleName(getASTContext().Id_Void)) {
diagnose(args->getStartLoc(), diag::paren_void_probably_void)
.fixItReplace(args->getSourceRange(), "()");
repr->setWarned();
}
}
}
}
FunctionType::ExtInfoBuilder extInfoBuilder(
FunctionTypeRepresentation::Swift, noescape, repr->isThrowing(), diffKind,
/*clangFunctionType*/ nullptr, Type());
const clang::Type *clangFnType = parsedClangFunctionType;
if (shouldStoreClangType(representation) && !clangFnType)
clangFnType =
getASTContext().getClangFunctionType(params, outputTy, representation);
auto extInfo = extInfoBuilder.withRepresentation(representation)
.withConcurrent(concurrent)
.withAsync(repr->isAsync())
.withClangFunctionType(clangFnType)
.withGlobalActor(globalActor)
.build();
// SIL uses polymorphic function types to resolve overloaded member functions.
if (auto genericEnv = repr->getGenericEnvironment()) {
return GenericFunctionType::get(genericEnv->getGenericSignature(),
params, outputTy, extInfo);
}
auto fnTy = FunctionType::get(params, outputTy, extInfo);
if (fnTy->hasError())
return fnTy;
if (TypeChecker::diagnoseInvalidFunctionType(fnTy, repr->getLoc(), repr,
getDeclContext(),
resolution.getStage()))
return ErrorType::get(fnTy);
return fnTy;
}
NeverNullType TypeResolver::resolveSILBoxType(SILBoxTypeRepr *repr,
TypeResolutionOptions options) {
// Resolve the field types.
SmallVector<SILField, 4> fields;
{
// Resolve field types using the box type's generic environment, if it
// has one. (TODO: Field types should never refer to generic parameters
// outside the box's own environment; we should really validate that...)
TypeResolution fieldResolution{resolution};
auto *genericEnv = repr->getGenericEnvironment();
auto *genericParams = repr->getGenericParams();
if (genericParams) {
fieldResolution =
TypeResolution::forInterface(getDeclContext(), genericEnv, options,
resolution.getUnboundTypeOpener(),
resolution.getPlaceholderHandler());
}
TypeResolver fieldResolver{fieldResolution,
genericParams};
for (auto &fieldRepr : repr->getFields()) {
auto fieldTy = fieldResolver.resolveType(fieldRepr.getFieldType(), options);
fields.push_back({fieldTy->getCanonicalType(), fieldRepr.isMutable()});
}
}
// Substitute out parsed context types into interface types.
CanGenericSignature genericSig;
if (auto *genericEnv = repr->getGenericEnvironment()) {
genericSig = genericEnv->getGenericSignature().getCanonicalSignature();
}
// Resolve the generic arguments.
// Start by building a TypeSubstitutionMap.
SubstitutionMap subMap;
if (genericSig) {
TypeSubstitutionMap genericArgMap;
auto params = genericSig.getGenericParams();
if (repr->getGenericArguments().size()
!= genericSig.getGenericParams().size()) {
diagnose(repr->getLoc(), diag::sil_box_arg_mismatch);
return ErrorType::get(getASTContext());
}
for (unsigned i : indices(params)) {
auto argTy = resolveType(repr->getGenericArguments()[i], options);
genericArgMap.insert({params[i], argTy->getCanonicalType()});
}
subMap = SubstitutionMap::get(
genericSig, QueryTypeSubstitutionMap{genericArgMap},
LookUpConformanceInModule(getDeclContext()->getParentModule()));
}
auto layout = SILLayout::get(getASTContext(), genericSig, fields);
return SILBoxType::get(getASTContext(), layout, subMap);
}
NeverNullType TypeResolver::resolveSILFunctionType(
FunctionTypeRepr *repr, TypeResolutionOptions options,
SILCoroutineKind coroutineKind,
SILFunctionType::ExtInfoBuilder extInfoBuilder, ParameterConvention callee,
TypeRepr *witnessMethodProtocol) {
options.setContext(None);
bool hasError = false;
// Resolve parameter and result types using the function's generic
// environment.
SmallVector<SILParameterInfo, 4> params;
SmallVector<SILYieldInfo, 4> yields;
SmallVector<SILResultInfo, 4> results;
Optional<SILResultInfo> errorResult;
// Resolve generic params in the pattern environment, if present, or
// else the function's generic environment, if it has one.
GenericParamList *genericParams = repr->getGenericParams();
if (genericParams == nullptr)
genericParams = this->genericParams;
GenericParamList *componentGenericParams = repr->getPatternGenericParams();
if (componentGenericParams == nullptr)
componentGenericParams = genericParams;
GenericEnvironment *genericEnv = repr->getGenericEnvironment();
GenericEnvironment *componentTypeEnv =
repr->getPatternGenericEnvironment()
? repr->getPatternGenericEnvironment()
: genericEnv;
{
auto argsTuple = repr->getArgsTypeRepr();
// SIL functions cannot be variadic.
if (argsTuple->hasEllipsis()) {
diagnose(argsTuple->getEllipsisLoc(), diag::sil_function_ellipsis);
}
// SIL functions cannot have parameter names.
for (auto &element : argsTuple->getElements()) {
if (element.UnderscoreLoc.isValid())
diagnose(element.UnderscoreLoc, diag::sil_function_input_label);
}
TypeResolution functionResolution{resolution};
if (componentTypeEnv) {
functionResolution = TypeResolution::forInterface(
getDeclContext(), componentTypeEnv, options,
resolution.getUnboundTypeOpener(),
resolution.getPlaceholderHandler());
}
TypeResolver silResolver{functionResolution, componentGenericParams};
for (auto elt : argsTuple->getElements()) {
auto elementOptions = options;
elementOptions.setContext(TypeResolverContext::FunctionInput);
auto param = silResolver.resolveSILParameter(elt.Type, elementOptions);
params.push_back(param);
if (!param.getInterfaceType() || param.getInterfaceType()->hasError())
hasError = true;
}
{
if (silResolver.resolveSILResults(repr->getResultTypeRepr(),
options, yields,
results, errorResult)) {
hasError = true;
}
// Diagnose non-coroutines that declare yields.
if (coroutineKind == SILCoroutineKind::None && !yields.empty()) {
diagnose(repr->getResultTypeRepr()->getLoc(),
diag::sil_non_coro_yields);
hasError = true;
}
}
}
auto resolveSubstitutions = [&](GenericEnvironment *env,
ArrayRef<TypeRepr*> args,
TypeResolver &¶meterResolver) {
auto sig = env->getGenericSignature().getCanonicalSignature();
TypeSubstitutionMap subsMap;
auto params = sig.getGenericParams();
for (unsigned i : indices(args)) {
auto resolved = parameterResolver.resolveType(args[i], options);
subsMap.insert({params[i], resolved->getCanonicalType()});
}
return SubstitutionMap::get(
sig, QueryTypeSubstitutionMap{subsMap},
LookUpConformanceInModule(getDeclContext()->getParentModule()))
.getCanonical();
};
// Resolve pattern substitutions in the invocation environment, if
// applicable.
SubstitutionMap patternSubs;
if (!repr->getPatternSubstitutions().empty()) {
if (genericEnv) {
auto resolveSILParameters =
TypeResolution::forInterface(getDeclContext(), genericEnv, options,
resolution.getUnboundTypeOpener(),
resolution.getPlaceholderHandler());
patternSubs = resolveSubstitutions(repr->getPatternGenericEnvironment(),
repr->getPatternSubstitutions(),
TypeResolver{resolveSILParameters,
genericParams});
} else {
patternSubs = resolveSubstitutions(repr->getPatternGenericEnvironment(),
repr->getPatternSubstitutions(),
TypeResolver{resolution,
genericParams});
}
}
// Resolve invocation substitutions if we have them.
SubstitutionMap invocationSubs;
if (!repr->getInvocationSubstitutions().empty()) {
invocationSubs = resolveSubstitutions(repr->getGenericEnvironment(),
repr->getInvocationSubstitutions(),
TypeResolver{resolution,
genericParams});
}
if (hasError) {
return ErrorType::get(getASTContext());
}
ProtocolConformanceRef witnessMethodConformance;
if (witnessMethodProtocol) {
auto resolved = resolveType(witnessMethodProtocol,
options.withContext(TypeResolverContext::GenericRequirement));
if (resolved->hasError())
return resolved;
auto protocolType = resolved->getAs<ProtocolType>();
if (!protocolType)
return ErrorType::get(getASTContext());
Type selfType = params.back().getInterfaceType();
if (patternSubs)
selfType = selfType.subst(patternSubs);
if (invocationSubs) {
selfType = selfType.subst(invocationSubs);
}
// Only once we've done all the necessary substitutions, map the type
// into the function's environment.
selfType = GenericEnvironment::mapTypeIntoContext(genericEnv, selfType);
// The Self type can be nested in a few layers of metatypes (etc.).
while (auto metatypeType = selfType->getAs<MetatypeType>()) {
auto next = metatypeType->getInstanceType();
if (next->isEqual(selfType))
break;
selfType = next;
}
witnessMethodConformance = TypeChecker::conformsToProtocol(
selfType, protocolType->getDecl(),
getDeclContext()->getParentModule());
assert(witnessMethodConformance &&
"found witness_method without matching conformance");
}
auto representation = extInfoBuilder.getRepresentation();
const clang::Type *clangFnType = extInfoBuilder.getClangTypeInfo().getType();
if (shouldStoreClangType(representation) && !clangFnType) {
assert(results.size() <= 1 && yields.size() == 0 &&
"C functions and blocks have at most 1 result and 0 yields.");
auto result = results.empty() ? Optional<SILResultInfo>() : results[0];
clangFnType = getASTContext().getCanonicalClangFunctionType(params, result,
representation);
extInfoBuilder = extInfoBuilder.withClangFunctionType(clangFnType);
}
CanGenericSignature genericSig =
genericEnv ? genericEnv->getGenericSignature().getCanonicalSignature()
: CanGenericSignature();
return SILFunctionType::get(genericSig, extInfoBuilder.build(), coroutineKind,
callee, params, yields, results, errorResult,
patternSubs, invocationSubs, getASTContext(),
witnessMethodConformance);
}
SILYieldInfo TypeResolver::resolveSILYield(TypeAttributes &attrs,
TypeRepr *repr,
TypeResolutionOptions options) {
AttributedTypeRepr attrRepr(attrs, repr);
options.setContext(TypeResolverContext::FunctionInput);
SILParameterInfo paramInfo = resolveSILParameter(&attrRepr, options);
return SILYieldInfo(paramInfo.getInterfaceType(), paramInfo.getConvention());
}
SILParameterInfo TypeResolver::resolveSILParameter(
TypeRepr *repr,
TypeResolutionOptions options) {
assert(options.is(TypeResolverContext::FunctionInput) &&
"Parameters should be marked as inputs");
auto convention = DefaultParameterConvention;
Type type;
bool hadError = false;
auto differentiability =
SILParameterDifferentiability::DifferentiableOrNotApplicable;
if (auto attrRepr = dyn_cast<AttributedTypeRepr>(repr)) {
auto attrs = attrRepr->getAttrs();
auto checkFor = [&](TypeAttrKind tak, ParameterConvention attrConv) {
if (!attrs.has(tak)) return;
if (convention != DefaultParameterConvention) {
diagnose(attrs.getLoc(tak), diag::sil_function_repeat_convention,
/*input*/ 0);
hadError = true;
}
attrs.clearAttribute(tak);
convention = attrConv;
};
checkFor(TypeAttrKind::TAK_in_guaranteed,
ParameterConvention::Indirect_In_Guaranteed);
checkFor(TypeAttrKind::TAK_in, ParameterConvention::Indirect_In);
checkFor(TypeAttrKind::TAK_in_constant,
ParameterConvention::Indirect_In_Constant);
checkFor(TypeAttrKind::TAK_inout, ParameterConvention::Indirect_Inout);
checkFor(TypeAttrKind::TAK_inout_aliasable,
ParameterConvention::Indirect_InoutAliasable);
checkFor(TypeAttrKind::TAK_owned, ParameterConvention::Direct_Owned);
checkFor(TypeAttrKind::TAK_guaranteed,
ParameterConvention::Direct_Guaranteed);
if (attrs.has(TAK_noDerivative)) {
attrs.clearAttribute(TAK_noDerivative);
differentiability = SILParameterDifferentiability::NotDifferentiable;
}
type = resolveAttributedType(attrs, attrRepr->getTypeRepr(), options);
} else {
type = resolveType(repr, options);
}
if (!type || type->hasError()) {
hadError = true;
// Diagnose types that are illegal in SIL.
} else if (!type->isLegalSILType()) {
diagnose(repr->getLoc(), diag::illegal_sil_type, type);
hadError = true;
}
if (hadError)
type = ErrorType::get(getASTContext());
return SILParameterInfo(type->getCanonicalType(), convention,
differentiability);
}
bool TypeResolver::resolveSingleSILResult(TypeRepr *repr,
TypeResolutionOptions options,
SmallVectorImpl<SILYieldInfo> &yields,
SmallVectorImpl<SILResultInfo> &ordinaryResults,
Optional<SILResultInfo> &errorResult) {
Type type;
auto convention = DefaultResultConvention;
bool isErrorResult = false;
auto differentiability =
SILResultDifferentiability::DifferentiableOrNotApplicable;
options.setContext(TypeResolverContext::FunctionResult);
if (auto attrRepr = dyn_cast<AttributedTypeRepr>(repr)) {
// Copy the attributes out; we're going to destructively modify them.
auto attrs = attrRepr->getAttrs();
// Recognize @yields.
if (attrs.has(TypeAttrKind::TAK_yields)) {
attrs.clearAttribute(TypeAttrKind::TAK_yields);
// The treatment from this point on is basically completely different.
auto yield = resolveSILYield(attrs, attrRepr->getTypeRepr(), options);
if (yield.getInterfaceType()->hasError())
return true;
yields.push_back(yield);
return false;
}
// Recognize @error.
if (attrs.has(TypeAttrKind::TAK_error)) {
attrs.clearAttribute(TypeAttrKind::TAK_error);
isErrorResult = true;
// Error results are always implicitly @owned.
convention = ResultConvention::Owned;
}
// Recognize `@noDerivative`.
if (attrs.has(TAK_noDerivative)) {
attrs.clearAttribute(TAK_noDerivative);
differentiability = SILResultDifferentiability::NotDifferentiable;
}
// Recognize result conventions.
bool hadError = false;
auto checkFor = [&](TypeAttrKind tak, ResultConvention attrConv) {
if (!attrs.has(tak)) return;
if (convention != DefaultResultConvention) {
diagnose(attrs.getLoc(tak), diag::sil_function_repeat_convention,
/*result*/ 1);
hadError = true;
}
attrs.clearAttribute(tak);
convention = attrConv;
};
checkFor(TypeAttrKind::TAK_out, ResultConvention::Indirect);
checkFor(TypeAttrKind::TAK_owned, ResultConvention::Owned);
checkFor(TypeAttrKind::TAK_unowned_inner_pointer,
ResultConvention::UnownedInnerPointer);
checkFor(TypeAttrKind::TAK_autoreleased, ResultConvention::Autoreleased);
if (hadError) return true;
type = resolveAttributedType(attrs, attrRepr->getTypeRepr(), options);
} else {
type = resolveType(repr, options);
}
// Propagate type-resolution errors out.
if (!type || type->hasError()) return true;
// Diagnose types that are illegal in SIL.
if (!type->isLegalSILType()) {
diagnose(repr->getStartLoc(), diag::illegal_sil_type, type);
return false;
}
assert(!isErrorResult || convention == ResultConvention::Owned);
SILResultInfo resolvedResult(type->getCanonicalType(), convention,
differentiability);
if (!isErrorResult) {
ordinaryResults.push_back(resolvedResult);
return false;
}
// Error result types must have pointer-like representation.
// FIXME: check that here?
// We don't expect to have a reason to support multiple independent
// error results. (Would this be disjunctive or conjunctive?)
if (errorResult.hasValue()) {
diagnose(repr->getStartLoc(),
diag::sil_function_multiple_error_results);
return true;
}
errorResult = resolvedResult;
return false;
}
bool TypeResolver::resolveSILResults(TypeRepr *repr,
TypeResolutionOptions options,
SmallVectorImpl<SILYieldInfo> &yields,
SmallVectorImpl<SILResultInfo> &ordinaryResults,
Optional<SILResultInfo> &errorResult) {
if (auto tuple = dyn_cast<TupleTypeRepr>(repr)) {
bool hadError = false;
for (auto &element : tuple->getElements()) {
if (element.UnderscoreLoc.isValid())
diagnose(element.UnderscoreLoc, diag::sil_function_output_label);
}
for (auto elt : tuple->getElements()) {
if (resolveSingleSILResult(elt.Type, options,
yields, ordinaryResults, errorResult))
hadError = true;
}
return hadError;
}
return resolveSingleSILResult(repr, options,
yields, ordinaryResults, errorResult);
}
NeverNullType
TypeResolver::resolveIdentifierType(IdentTypeRepr *IdType,
TypeResolutionOptions options) {
auto ComponentRange = IdType->getComponentRange();
auto Components = llvm::makeArrayRef(ComponentRange.begin(),
ComponentRange.end());
Type result = resolveIdentTypeComponent(resolution.withOptions(options),
genericParams, Components);
if (!result || result->hasError()) {
return ErrorType::get(getASTContext());
}
if (auto moduleTy = result->getAs<ModuleType>()) {
// Allow module types only if flag is specified.
if (options.contains(TypeResolutionFlags::AllowModule))
return moduleTy;
// Otherwise, emit an error.
if (!options.contains(TypeResolutionFlags::SilenceErrors)) {
auto moduleName = moduleTy->getModule()->getName();
diagnose(Components.back()->getNameLoc(),
diag::cannot_find_type_in_scope, DeclNameRef(moduleName));
diagnose(Components.back()->getNameLoc(),
diag::note_module_as_type, moduleName);
}
Components.back()->setInvalid();
return ErrorType::get(getASTContext());
}
if (result->isConstraintType() &&
options.isConstraintImplicitExistential()) {
return ExistentialType::get(result);
}
if (!options.isConstraintImplicitExistential()) {
// Imported existential typealiases, e.g. id<P>, can be
// used as constraints by extracting the underlying protocol
// types.
auto *typeAlias = dyn_cast<TypeAliasType>(result.getPointer());
if (typeAlias && typeAlias->is<ExistentialType>() &&
typeAlias->getDecl()->hasClangNode()) {
return typeAlias->getAs<ExistentialType>()->getConstraintType();
}
}
// Hack to apply context-specific @escaping to a typealias with an underlying
// function type.
if (result->is<FunctionType>())
result = applyNonEscapingIfNecessary(result, options);
return result;
}
NeverNullType
TypeResolver::resolveSpecifierTypeRepr(SpecifierTypeRepr *repr,
TypeResolutionOptions options) {
// inout is only valid for (non-Subscript and non-EnumCaseDecl)
// function parameters.
if (!options.is(TypeResolverContext::FunctionInput) ||
options.hasBase(TypeResolverContext::SubscriptDecl) ||
options.hasBase(TypeResolverContext::EnumElementDecl)) {
decltype(diag::attr_only_on_parameters) diagID;
if (options.getBaseContext() == TypeResolverContext::SubscriptDecl) {
diagID = diag::attr_not_on_subscript_parameters;
} else if (options.is(TypeResolverContext::VariadicFunctionInput)) {
diagID = diag::attr_not_on_variadic_parameters;
} else {
diagID = diag::attr_only_on_parameters;
}
StringRef name;
switch (repr->getKind()) {
case TypeReprKind::InOut:
name = "inout";
break;
case TypeReprKind::Shared:
name = "__shared";
break;
case TypeReprKind::Owned:
name = "__owned";
break;
default:
llvm_unreachable("unknown SpecifierTypeRepr kind");
}
diagnoseInvalid(repr, repr->getSpecifierLoc(), diagID, name);
return ErrorType::get(getASTContext());
}
if (isa<InOutTypeRepr>(repr)
&& !isa<ImplicitlyUnwrappedOptionalTypeRepr>(repr->getBase())) {
// Anything within an inout isn't a parameter anymore.
options.setContext(TypeResolverContext::InoutFunctionInput);
}
return resolveType(repr->getBase(), options);
}
NeverNullType
TypeResolver::resolveIsolatedTypeRepr(IsolatedTypeRepr *repr,
TypeResolutionOptions options) {
// isolated is only value for non-EnumCaseDecl parameters.
if (!options.is(TypeResolverContext::FunctionInput) ||
options.hasBase(TypeResolverContext::EnumElementDecl)) {
diagnoseInvalid(
repr, repr->getSpecifierLoc(), diag::attr_only_on_parameters,
"isolated");
return ErrorType::get(getASTContext());
}
Type type = resolveType(repr->getBase(), options);
// isolated parameters must be of actor type
if (!type->hasTypeParameter() && !type->isActorType() && !type->hasError()) {
diagnoseInvalid(
repr, repr->getSpecifierLoc(), diag::isolated_parameter_not_actor, type);
return ErrorType::get(type);
}
return type;
}
NeverNullType
TypeResolver::resolveCompileTimeConstTypeRepr(CompileTimeConstTypeRepr *repr,
TypeResolutionOptions options) {
// TODO: more diagnotics
return resolveType(repr->getBase(), options);
}
NeverNullType TypeResolver::resolveArrayType(ArrayTypeRepr *repr,
TypeResolutionOptions options) {
auto baseTy = resolveType(repr->getBase(), options.withoutContext());
if (baseTy->hasError()) {
return ErrorType::get(getASTContext());
}
ASTContext &ctx = getASTContext();
// If the standard library isn't loaded, we ought to let the user know
// something has gone terribly wrong, since the rest of the compiler is going
// to assume it can canonicalize [T] to Array<T>.
if (!ctx.getArrayDecl()) {
ctx.Diags.diagnose(repr->getBrackets().Start,
diag::sugar_type_not_found, 0);
return ErrorType::get(ctx);
}
return ArraySliceType::get(baseTy);
}
NeverNullType
TypeResolver::resolveDictionaryType(DictionaryTypeRepr *repr,
TypeResolutionOptions options) {
options = adjustOptionsForGenericArgs(options);
auto keyTy = resolveType(repr->getKey(), options.withoutContext());
if (keyTy->hasError()) {
return ErrorType::get(getASTContext());
}
auto valueTy = resolveType(repr->getValue(), options.withoutContext());
if (valueTy->hasError()) {
return ErrorType::get(getASTContext());
}
auto *const dictDecl = getASTContext().getDictionaryDecl();
if (!dictDecl) {
getASTContext().Diags.diagnose(repr->getBrackets().Start,
diag::sugar_type_not_found, 3);
return ErrorType::get(getASTContext());
}
if (!resolution.applyUnboundGenericArguments(
dictDecl, nullptr, repr->getStartLoc(), {keyTy, valueTy})) {
assert(getASTContext().Diags.hadAnyError());
return ErrorType::get(getASTContext());
}
return DictionaryType::get(keyTy, valueTy);
}
NeverNullType TypeResolver::resolveOptionalType(OptionalTypeRepr *repr,
TypeResolutionOptions options) {
TypeResolutionOptions elementOptions = options.withoutContext(true);
elementOptions.setContext(TypeResolverContext::ImmediateOptionalTypeArgument);
auto baseTy = resolveType(repr->getBase(), elementOptions);
if (baseTy->hasError()) {
return ErrorType::get(getASTContext());
}
auto optionalTy = TypeChecker::getOptionalType(repr->getQuestionLoc(),
baseTy);
if (optionalTy->hasError()) {
return ErrorType::get(getASTContext());
}
return optionalTy;
}
NeverNullType TypeResolver::resolveImplicitlyUnwrappedOptionalType(
ImplicitlyUnwrappedOptionalTypeRepr *repr, TypeResolutionOptions options,
bool isDirect) {
TypeResolutionFlags allowIUO = TypeResolutionFlags::SILType;
bool doDiag = false;
switch (options.getContext()) {
case TypeResolverContext::None:
case TypeResolverContext::InoutFunctionInput:
if (!isDirect || !(options & allowIUO))
doDiag = true;
break;
case TypeResolverContext::FunctionInput:
case TypeResolverContext::FunctionResult:
case TypeResolverContext::PatternBindingDecl:
doDiag = !isDirect;
break;
case TypeResolverContext::VariadicFunctionInput:
case TypeResolverContext::ForEachStmt:
case TypeResolverContext::ExtensionBinding:
case TypeResolverContext::ExplicitCastExpr:
case TypeResolverContext::SubscriptDecl:
case TypeResolverContext::EnumElementDecl:
case TypeResolverContext::EnumPatternPayload:
case TypeResolverContext::TypeAliasDecl:
case TypeResolverContext::GenericTypeAliasDecl:
case TypeResolverContext::GenericRequirement:
case TypeResolverContext::ExistentialConstraint:
case TypeResolverContext::SameTypeRequirement:
case TypeResolverContext::ProtocolMetatypeBase:
case TypeResolverContext::MetatypeBase:
case TypeResolverContext::ImmediateOptionalTypeArgument:
case TypeResolverContext::InExpression:
case TypeResolverContext::EditorPlaceholderExpr:
case TypeResolverContext::AbstractFunctionDecl:
case TypeResolverContext::ClosureExpr:
case TypeResolverContext::Inherited:
case TypeResolverContext::CustomAttr:
doDiag = true;
break;
}
if (doDiag && !options.contains(TypeResolutionFlags::SilenceErrors)) {
// Prior to Swift 5, we allow 'as T!' and turn it into a disjunction.
if (getASTContext().isSwiftVersionAtLeast(5)) {
diagnose(repr->getStartLoc(),
diag::implicitly_unwrapped_optional_in_illegal_position)
.fixItReplace(repr->getExclamationLoc(), "?");
} else if (options.is(TypeResolverContext::ExplicitCastExpr)) {
diagnose(
repr->getStartLoc(),
diag::implicitly_unwrapped_optional_deprecated_in_this_position);
} else {
diagnose(
repr->getStartLoc(),
diag::implicitly_unwrapped_optional_in_illegal_position_interpreted_as_optional)
.fixItReplace(repr->getExclamationLoc(), "?");
}
}
TypeResolutionOptions elementOptions = options.withoutContext(true);
elementOptions.setContext(TypeResolverContext::ImmediateOptionalTypeArgument);
auto baseTy = resolveType(repr->getBase(), elementOptions);
if (baseTy->hasError()) {
return ErrorType::get(getASTContext());
}
auto uncheckedOptionalTy =
TypeChecker::getOptionalType(repr->getExclamationLoc(), baseTy);
if (uncheckedOptionalTy->hasError()) {
return ErrorType::get(getASTContext());
}
return uncheckedOptionalTy;
}
NeverNullType TypeResolver::resolveTupleType(TupleTypeRepr *repr,
TypeResolutionOptions options) {
SmallVector<TupleTypeElt, 8> elements;
elements.reserve(repr->getNumElements());
llvm::SmallDenseSet<Identifier> seenEltNames;
seenEltNames.reserve(repr->getNumElements());
auto elementOptions = options;
if (!repr->isParenType()) {
elementOptions = elementOptions.withoutContext(true);
}
bool complained = false;
if (repr->hasEllipsis()) {
if (repr->getNumElements() == 1 && !repr->hasElementNames()) {
// This is probably a pack expansion. Try to resolve the pattern type.
auto patternTy = resolveType(repr->getElementType(0), elementOptions);
if (patternTy->hasError())
complained = true;
// If there's no reference to a variadic generic parameter, complain
// - the pack won't actually expand to anything meaningful.
if (!patternTy->hasTypeSequence())
diagnose(repr->getLoc(), diag::expansion_not_variadic, patternTy)
.highlight(repr->getParens());
return PackExpansionType::get(patternTy);
} else {
// Variadic tuples are not permitted.
//
// FIXME: We could probably make this work.
// (T, U, V...) is a reasonable pack expansion to support with a kind of
// "guaranteed bound" of at least two elements.
diagnose(repr->getEllipsisLoc(), diag::tuple_ellipsis);
repr->removeEllipsis();
complained = true;
}
}
bool hadError = false;
bool foundDupLabel = false;
for (unsigned i = 0, end = repr->getNumElements(); i != end; ++i) {
auto *tyR = repr->getElementType(i);
auto ty = resolveType(tyR, elementOptions);
if (ty->hasError())
hadError = true;
auto eltName = repr->getElementName(i);
elements.emplace_back(ty, eltName, ParameterTypeFlags());
if (eltName.empty())
continue;
if (seenEltNames.count(eltName) == 1) {
foundDupLabel = true;
}
seenEltNames.insert(eltName);
}
if (hadError)
return ErrorType::get(getASTContext());
// Single-element labeled tuples are not permitted outside of declarations
// or SIL, either.
if (elements.size() == 1 && elements[0].hasName()
&& !(options & TypeResolutionFlags::SILType)) {
if (!complained) {
diagnose(repr->getElementNameLoc(0), diag::tuple_single_element)
.fixItRemoveChars(repr->getElementNameLoc(0),
repr->getElementType(0)->getStartLoc());
}
elements[0] = TupleTypeElt(elements[0].getType());
}
// Tuples with duplicate element labels are not permitted
if (foundDupLabel) {
diagnose(repr->getLoc(), diag::tuple_duplicate_label);
}
return TupleType::get(elements, getASTContext());
}
NeverNullType
TypeResolver::resolveCompositionType(CompositionTypeRepr *repr,
TypeResolutionOptions options) {
// Note that the superclass type will appear as part of one of the
// types in 'Members', so it's not used when constructing the
// fully-realized type below -- but we just record it to make sure
// there is only one superclass.
Type SuperclassType;
SmallVector<Type, 4> Members;
// Whether we saw at least one protocol. A protocol composition
// must either be empty (in which case it is Any or AnyObject),
// or if it has a superclass constraint, have at least one protocol.
bool HasProtocol = false;
auto checkSuperclass = [&](SourceLoc loc, Type t) -> bool {
if (SuperclassType && !SuperclassType->isEqual(t)) {
diagnose(loc, diag::protocol_composition_one_class, t,
SuperclassType);
return true;
}
SuperclassType = t;
return false;
};
bool IsInvalid = false;
for (auto tyR : repr->getTypes()) {
auto ty = resolveType(tyR,
options.withContext(TypeResolverContext::GenericRequirement));
if (ty->hasError()) return ty;
auto nominalDecl = ty->getAnyNominal();
if (isa_and_nonnull<ClassDecl>(nominalDecl)) {
if (checkSuperclass(tyR->getStartLoc(), ty))
continue;
Members.push_back(ty);
continue;
}
// FIXME: Support compositions involving parameterized protocol types,
// like Collection<String> & Sendable, etc.
if (ty->isConstraintType() &&
!ty->is<ParameterizedProtocolType>()) {
auto layout = ty->getExistentialLayout();
if (auto superclass = layout.explicitSuperclass)
if (checkSuperclass(tyR->getStartLoc(), superclass))
continue;
if (!layout.getProtocols().empty())
HasProtocol = true;
Members.push_back(ty);
continue;
}
diagnose(tyR->getStartLoc(),
diag::invalid_protocol_composition_member,
ty);
IsInvalid = true;
}
if (IsInvalid) {
repr->setInvalid();
return ErrorType::get(getASTContext());
}
// Avoid confusing diagnostics ('MyClass' not convertible to 'MyClass',
// etc) by collapsing a composition consisting of a single class down
// to the class itself.
if (SuperclassType && !HasProtocol)
return SuperclassType;
// In user-written types, AnyObject constraints always refer to the
// AnyObject type in the standard library.
auto composition =
ProtocolCompositionType::get(getASTContext(), Members,
/*HasExplicitAnyObject=*/false);
if (options.isConstraintImplicitExistential()) {
return ExistentialType::get(composition);
}
return composition;
}
NeverNullType
TypeResolver::resolveExistentialType(ExistentialTypeRepr *repr,
TypeResolutionOptions options) {
auto constraintType = resolveType(repr->getConstraint(),
options.withContext(TypeResolverContext::ExistentialConstraint));
if (constraintType->is<ExistentialMetatypeType>())
return constraintType;
// If we already failed, don't diagnose again.
if (constraintType->hasError())
return ErrorType::get(getASTContext());
auto anyStart = repr->getAnyLoc();
auto anyEnd = Lexer::getLocForEndOfToken(getASTContext().SourceMgr, anyStart);
if (!constraintType->isExistentialType()) {
diagnose(repr->getLoc(), diag::any_not_existential,
constraintType->isTypeParameter(),
constraintType)
.fixItRemove({anyStart, anyEnd});
return constraintType;
}
return ExistentialType::get(constraintType);
}
NeverNullType TypeResolver::resolveMetatypeType(MetatypeTypeRepr *repr,
TypeResolutionOptions options) {
// The instance type of a metatype is always abstract, not SIL-lowered.
auto ty = resolveType(repr->getBase(),
options.withContext(TypeResolverContext::MetatypeBase));
if (ty->hasError()) {
return ErrorType::get(getASTContext());
}
Optional<MetatypeRepresentation> storedRepr;
// In SIL mode, a metatype must have a @thin, @thick, or
// @objc_metatype attribute, so metatypes should have been lowered
// in resolveAttributedType.
if (options & TypeResolutionFlags::SILType) {
diagnose(repr->getStartLoc(), diag::sil_metatype_without_repr);
storedRepr = MetatypeRepresentation::Thick;
}
return buildMetatypeType(repr, ty, storedRepr);
}
NeverNullType
TypeResolver::buildMetatypeType(MetatypeTypeRepr *repr, Type instanceType,
Optional<MetatypeRepresentation> storedRepr) {
if (instanceType->isAnyExistentialType() &&
!instanceType->is<ExistentialType>()) {
// TODO: diagnose invalid representations?
return ExistentialMetatypeType::get(instanceType, storedRepr);
} else {
return MetatypeType::get(instanceType, storedRepr);
}
}
NeverNullType TypeResolver::resolveProtocolType(ProtocolTypeRepr *repr,
TypeResolutionOptions options) {
// The instance type of a metatype is always abstract, not SIL-lowered.
auto ty = resolveType(repr->getBase(),
options.withContext(TypeResolverContext::ProtocolMetatypeBase));
if (ty->hasError()) {
return ErrorType::get(getASTContext());
}
Optional<MetatypeRepresentation> storedRepr;
// In SIL mode, a metatype must have a @thin, @thick, or
// @objc_metatype attribute, so metatypes should have been lowered
// in resolveAttributedType.
if (options & TypeResolutionFlags::SILType) {
diagnose(repr->getStartLoc(), diag::sil_metatype_without_repr);
storedRepr = MetatypeRepresentation::Thick;
}
return buildProtocolType(repr, ty, storedRepr);
}
NeverNullType
TypeResolver::buildProtocolType(ProtocolTypeRepr *repr, Type instanceType,
Optional<MetatypeRepresentation> storedRepr) {
if (!instanceType->isAnyExistentialType()) {
diagnose(repr->getProtocolLoc(), diag::dot_protocol_on_non_existential,
instanceType);
return ErrorType::get(getASTContext());
}
return MetatypeType::get(instanceType, storedRepr);
}
Type TypeChecker::substMemberTypeWithBase(ModuleDecl *module,
TypeDecl *member,
Type baseTy,
bool useArchetypes) {
Type sugaredBaseTy = baseTy;
// For type members of a base class, make sure we use the right
// derived class as the parent type. If the base type is an error
// type, we have an invalid extension, so do nothing.
if (!baseTy->is<ErrorType>()) {
if (auto *ownerClass = member->getDeclContext()->getSelfClassDecl()) {
baseTy = baseTy->getSuperclassForDecl(ownerClass, useArchetypes);
}
}
if (baseTy->is<ModuleType>()) {
baseTy = Type();
sugaredBaseTy = Type();
}
// The declared interface type for a generic type will have the type
// arguments; strip them off.
if (auto *nominalDecl = dyn_cast<NominalTypeDecl>(member)) {
// If the base type is not a nominal type, we might be looking up a
// nominal member of a generic parameter. This is not supported right
// now, but at least don't crash.
if (member->getDeclContext()->getSelfProtocolDecl())
return nominalDecl->getDeclaredType();
if (!isa<ProtocolDecl>(nominalDecl) &&
nominalDecl->getGenericParams()) {
return UnboundGenericType::get(
nominalDecl, baseTy,
nominalDecl->getASTContext());
}
if (baseTy && baseTy->is<ErrorType>())
return baseTy;
return NominalType::get(
nominalDecl, baseTy,
nominalDecl->getASTContext());
}
auto *aliasDecl = dyn_cast<TypeAliasDecl>(member);
if (aliasDecl) {
if (aliasDecl->getGenericParams()) {
return UnboundGenericType::get(
aliasDecl, baseTy,
aliasDecl->getASTContext());
}
}
Type resultType;
auto memberType = aliasDecl ? aliasDecl->getUnderlyingType()
: member->getDeclaredInterfaceType();
SubstitutionMap subs;
if (baseTy) {
// Cope with the presence of unbound generic types, which are ill-formed
// at this point but break the invariants of getContextSubstitutionMap().
if (baseTy->hasUnboundGenericType()) {
if (memberType->hasTypeParameter())
return ErrorType::get(memberType);
return memberType;
}
if (baseTy->is<ErrorType>())
return ErrorType::get(memberType);
subs = baseTy->getContextSubstitutionMap(module, member->getDeclContext());
resultType = memberType.subst(subs);
} else {
resultType = memberType;
}
// If we're referring to a typealias within a generic context, build
// a sugared alias type.
if (aliasDecl && (!sugaredBaseTy || !sugaredBaseTy->isAnyExistentialType())) {
resultType = TypeAliasType::get(aliasDecl, sugaredBaseTy, subs, resultType);
}
return resultType;
}
namespace {
class ExistentialTypeVisitor
: public TypeReprVisitor<ExistentialTypeVisitor>, public ASTWalker
{
ASTContext &Ctx;
bool checkStatements;
bool hitTopStmt;
public:
ExistentialTypeVisitor(ASTContext &ctx, bool checkStatements)
: Ctx(ctx), checkStatements(checkStatements), hitTopStmt(false) { }
bool walkToTypeReprPre(TypeRepr *T) override {
if (T->isInvalid())
return false;
if (auto compound = dyn_cast<CompoundIdentTypeRepr>(T)) {
// Only visit the last component to check, because nested typealiases in
// existentials are okay.
visit(compound->getComponentRange().back());
return false;
}
// Arbitrary protocol constraints are OK on opaque types.
if (isa<OpaqueReturnTypeRepr>(T))
return false;
// Arbitrary protocol constraints are okay for 'any' types.
if (isa<ExistentialTypeRepr>(T))
return false;
visit(T);
return true;
}
std::pair<bool, Stmt*> walkToStmtPre(Stmt *S) override {
if (checkStatements && !hitTopStmt) {
hitTopStmt = true;
return { true, S };
}
return { false, S };
}
bool walkToDeclPre(Decl *D) override {
return !checkStatements;
}
void visitTypeRepr(TypeRepr *T) {
// Do nothing for all TypeReprs except the ones listed below.
}
void visitIdentTypeRepr(IdentTypeRepr *T) {
if (T->isInvalid())
return;
auto comp = T->getComponentRange().back();
if (auto *proto = dyn_cast_or_null<ProtocolDecl>(comp->getBoundDecl())) {
if (proto->existentialRequiresAny()) {
Ctx.Diags.diagnose(comp->getNameLoc(),
diag::existential_requires_any,
proto->getDeclaredInterfaceType(),
/*isAlias=*/false)
.limitBehavior(DiagnosticBehavior::Warning);
}
} else if (auto *alias = dyn_cast_or_null<TypeAliasDecl>(comp->getBoundDecl())) {
auto type = Type(alias->getDeclaredInterfaceType()->getDesugaredType());
// If this is a type alias to a constraint type, the type
// alias name must be prefixed with 'any' to be used as an
// existential type.
if (type->isConstraintType()) {
auto layout = type->getExistentialLayout();
for (auto *proto : layout.getProtocols()) {
auto *protoDecl = proto->getDecl();
if (!protoDecl->existentialRequiresAny())
continue;
Ctx.Diags.diagnose(comp->getNameLoc(),
diag::existential_requires_any,
alias->getDeclaredInterfaceType(),
/*isAlias=*/true)
.limitBehavior(DiagnosticBehavior::Warning);
}
}
}
}
void visitRequirements(ArrayRef<RequirementRepr> reqts) {
for (auto reqt : reqts) {
if (reqt.getKind() == RequirementReprKind::SameType) {
if (auto *repr = reqt.getFirstTypeRepr())
repr->walk(*this);
if (auto *repr = reqt.getSecondTypeRepr())
repr->walk(*this);
}
}
}
};
} // end anonymous namespace
void TypeChecker::checkExistentialTypes(Decl *decl) {
if (!decl || decl->isInvalid())
return;
auto &ctx = decl->getASTContext();
if (auto *protocolDecl = dyn_cast<ProtocolDecl>(decl)) {
checkExistentialTypes(ctx, protocolDecl->getTrailingWhereClause());
} else if (auto *genericDecl = dyn_cast<GenericTypeDecl>(decl)) {
checkExistentialTypes(ctx, genericDecl->getGenericParams());
checkExistentialTypes(ctx, genericDecl->getTrailingWhereClause());
if (auto *typeAlias = dyn_cast<TypeAliasDecl>(decl)) {
checkExistentialTypes(ctx, typeAlias);
}
} else if (auto *assocType = dyn_cast<AssociatedTypeDecl>(decl)) {
checkExistentialTypes(ctx, assocType->getTrailingWhereClause());
} else if (auto *extDecl = dyn_cast<ExtensionDecl>(decl)) {
checkExistentialTypes(ctx, extDecl->getTrailingWhereClause());
} else if (auto *subscriptDecl = dyn_cast<SubscriptDecl>(decl)) {
checkExistentialTypes(ctx, subscriptDecl->getGenericParams());
checkExistentialTypes(ctx, subscriptDecl->getTrailingWhereClause());
} else if (auto *funcDecl = dyn_cast<AbstractFunctionDecl>(decl)) {
if (!isa<AccessorDecl>(funcDecl)) {
checkExistentialTypes(ctx, funcDecl->getGenericParams());
checkExistentialTypes(ctx, funcDecl->getTrailingWhereClause());
}
}
if (isa<TypeDecl>(decl) || isa<ExtensionDecl>(decl))
return;
ExistentialTypeVisitor visitor(ctx, /*checkStatements=*/false);
decl->walk(visitor);
}
void TypeChecker::checkExistentialTypes(ASTContext &ctx, Stmt *stmt) {
if (!stmt)
return;
ExistentialTypeVisitor visitor(ctx, /*checkStatements=*/true);
stmt->walk(visitor);
}
void TypeChecker::checkExistentialTypes(ASTContext &ctx,
TypeAliasDecl *typeAlias) {
if (!typeAlias || !typeAlias->getUnderlyingTypeRepr())
return;
// A type alias to a plain constraint type is allowed.
if (typeAlias->getUnderlyingType()->isConstraintType())
return;
ExistentialTypeVisitor visitor(ctx, /*checkStatements=*/true);
typeAlias->getUnderlyingTypeRepr()->walk(visitor);
}
void TypeChecker::checkExistentialTypes(
ASTContext &ctx, TrailingWhereClause *whereClause) {
if (whereClause == nullptr)
return;
ExistentialTypeVisitor visitor(ctx, /*checkStatements=*/false);
visitor.visitRequirements(whereClause->getRequirements());
}
void TypeChecker::checkExistentialTypes(
ASTContext &ctx, GenericParamList *genericParams) {
if (genericParams == nullptr)
return;
ExistentialTypeVisitor visitor(ctx, /*checkStatements=*/false);
visitor.visitRequirements(genericParams->getRequirements());
}
Type CustomAttrTypeRequest::evaluate(Evaluator &eval, CustomAttr *attr,
DeclContext *dc,
CustomAttrTypeKind typeKind) const {
const TypeResolutionOptions options(TypeResolverContext::PatternBindingDecl);
OpenUnboundGenericTypeFn unboundTyOpener = nullptr;
// Property delegates allow their type to be an unbound generic.
if (typeKind == CustomAttrTypeKind::PropertyWrapper) {
unboundTyOpener = [](auto unboundTy) {
// FIXME: Don't let unbound generic types
// escape type resolution. For now, just
// return the unbound generic type.
return unboundTy;
};
}
const auto type = TypeResolution::resolveContextualType(
attr->getTypeRepr(), dc, options, unboundTyOpener,
/*placeholderHandler*/ nullptr);
// We always require the type to resolve to a nominal type. If the type was
// not a nominal type, we should have already diagnosed an error via
// CustomAttrNominalRequest.
auto checkType = [](Type type) -> bool {
while (auto *genericDecl = type->getAnyGeneric()) {
if (isa<NominalTypeDecl>(genericDecl))
return true;
auto *aliasDecl = cast<TypeAliasDecl>(genericDecl);
type = aliasDecl->getUnderlyingType();
}
return false;
};
if (!checkType(type)) {
ASTContext &ctx = dc->getASTContext();
assert(ctx.Diags.hadAnyError());
return ErrorType::get(ctx);
}
return type;
}
|
// Copyright 2016 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 "base/task/thread_pool/thread_group_impl.h"
#include <stddef.h>
#include <algorithm>
#include <type_traits>
#include <utility>
#include "base/atomicops.h"
#include "base/auto_reset.h"
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/compiler_specific.h"
#include "base/containers/stack_container.h"
#include "base/feature_list.h"
#include "base/location.h"
#include "base/memory/ptr_util.h"
#include "base/metrics/histogram.h"
#include "base/numerics/clamped_math.h"
#include "base/optional.h"
#include "base/sequence_token.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/task/task_features.h"
#include "base/task/task_traits.h"
#include "base/task/thread_pool/task_tracker.h"
#include "base/threading/platform_thread.h"
#include "base/threading/scoped_blocking_call.h"
#include "base/threading/scoped_blocking_call_internal.h"
#include "base/threading/thread_checker.h"
#include "base/threading/thread_restrictions.h"
#include "base/time/time_override.h"
#include "build/build_config.h"
#if defined(OS_WIN)
#include "base/win/scoped_com_initializer.h"
#include "base/win/scoped_windows_thread_environment.h"
#include "base/win/scoped_winrt_initializer.h"
#include "base/win/windows_version.h"
#endif // defined(OS_WIN)
namespace base {
namespace internal {
namespace {
constexpr char kDetachDurationHistogramPrefix[] = "ThreadPool.DetachDuration.";
constexpr char kNumTasksBeforeDetachHistogramPrefix[] =
"ThreadPool.NumTasksBeforeDetach.";
constexpr char kNumWorkersHistogramPrefix[] = "ThreadPool.NumWorkers.";
constexpr char kNumActiveWorkersHistogramPrefix[] =
"ThreadPool.NumActiveWorkers.";
constexpr size_t kMaxNumberOfWorkers = 256;
// In a background thread group:
// - Blocking calls take more time than in a foreground thread group.
// - We want to minimize impact on foreground work, not maximize execution
// throughput.
// For these reasons, the timeout to increase the maximum number of concurrent
// tasks when there is a MAY_BLOCK ScopedBlockingCall is *long*. It is not
// infinite because execution throughput should not be reduced forever if a task
// blocks forever.
//
// TODO(fdoray): On platforms without background thread groups, blocking in a
// BEST_EFFORT task should:
// 1. Increment the maximum number of concurrent tasks after a *short* timeout,
// to allow scheduling of USER_VISIBLE/USER_BLOCKING tasks.
// 2. Increment the maximum number of concurrent BEST_EFFORT tasks after a
// *long* timeout, because we only want to allow more BEST_EFFORT tasks to be
// be scheduled concurrently when we believe that a BEST_EFFORT task is
// blocked forever.
// Currently, only 1. is true as the configuration is per thread group.
// TODO(https://crbug.com/927755): Fix racy condition when MayBlockThreshold ==
// BlockedWorkersPoll.
constexpr TimeDelta kForegroundMayBlockThreshold =
TimeDelta::FromMilliseconds(1000);
constexpr TimeDelta kForegroundBlockedWorkersPoll =
TimeDelta::FromMilliseconds(1200);
constexpr TimeDelta kBackgroundMayBlockThreshold = TimeDelta::FromSeconds(10);
constexpr TimeDelta kBackgroundBlockedWorkersPoll = TimeDelta::FromSeconds(12);
// Only used in DCHECKs.
bool ContainsWorker(const std::vector<scoped_refptr<WorkerThread>>& workers,
const WorkerThread* worker) {
auto it = std::find_if(workers.begin(), workers.end(),
[worker](const scoped_refptr<WorkerThread>& i) {
return i.get() == worker;
});
return it != workers.end();
}
} // namespace
// Upon destruction, executes actions that control the number of active workers.
// Useful to satisfy locking requirements of these actions.
class ThreadGroupImpl::ScopedCommandsExecutor
: public ThreadGroup::BaseScopedCommandsExecutor {
public:
ScopedCommandsExecutor(ThreadGroupImpl* outer) : outer_(outer) {}
~ScopedCommandsExecutor() { FlushImpl(); }
void ScheduleWakeUp(scoped_refptr<WorkerThread> worker) {
workers_to_wake_up_.AddWorker(std::move(worker));
}
void ScheduleStart(scoped_refptr<WorkerThread> worker) {
workers_to_start_.AddWorker(std::move(worker));
}
void FlushWorkerCreation(CheckedLock* held_lock) {
if (workers_to_wake_up_.empty() && workers_to_start_.empty())
return;
CheckedAutoUnlock auto_unlock(*held_lock);
FlushImpl();
workers_to_wake_up_.clear();
workers_to_start_.clear();
must_schedule_adjust_max_tasks_ = false;
}
void ScheduleAdjustMaxTasks() {
DCHECK(!must_schedule_adjust_max_tasks_);
must_schedule_adjust_max_tasks_ = true;
}
void ScheduleAddHistogramSample(HistogramBase* histogram,
HistogramBase::Sample sample) {
scheduled_histogram_samples_->emplace_back(histogram, sample);
}
private:
class WorkerContainer {
public:
WorkerContainer() = default;
void AddWorker(scoped_refptr<WorkerThread> worker) {
if (!worker)
return;
if (!first_worker_)
first_worker_ = std::move(worker);
else
additional_workers_.push_back(std::move(worker));
}
template <typename Action>
void ForEachWorker(Action action) {
if (first_worker_) {
action(first_worker_.get());
for (scoped_refptr<WorkerThread> worker : additional_workers_)
action(worker.get());
} else {
DCHECK(additional_workers_.empty());
}
}
bool empty() const { return first_worker_ == nullptr; }
void clear() {
first_worker_.reset();
additional_workers_.clear();
}
private:
// The purpose of |first_worker| is to avoid a heap allocation by the vector
// in the case where there is only one worker in the container.
scoped_refptr<WorkerThread> first_worker_;
std::vector<scoped_refptr<WorkerThread>> additional_workers_;
DISALLOW_COPY_AND_ASSIGN(WorkerContainer);
};
void FlushImpl() {
CheckedLock::AssertNoLockHeldOnCurrentThread();
// Wake up workers.
workers_to_wake_up_.ForEachWorker(
[](WorkerThread* worker) { worker->WakeUp(); });
// Start workers. Happens after wake ups to prevent the case where a worker
// enters its main function, is descheduled because it wasn't woken up yet,
// and is woken up immediately after.
workers_to_start_.ForEachWorker([&](WorkerThread* worker) {
worker->Start(outer_->after_start().worker_thread_observer);
if (outer_->worker_started_for_testing_)
outer_->worker_started_for_testing_->Wait();
});
if (must_schedule_adjust_max_tasks_)
outer_->ScheduleAdjustMaxTasks();
if (!scheduled_histogram_samples_->empty()) {
DCHECK_LE(scheduled_histogram_samples_->size(),
kHistogramSampleStackSize);
for (auto& scheduled_sample : scheduled_histogram_samples_)
scheduled_sample.first->Add(scheduled_sample.second);
scheduled_histogram_samples_->clear();
}
}
ThreadGroupImpl* const outer_;
WorkerContainer workers_to_wake_up_;
WorkerContainer workers_to_start_;
bool must_schedule_adjust_max_tasks_ = false;
// StackVector rather than std::vector avoid heap allocations; size should be
// high enough to store the maximum number of histogram samples added to a
// given ScopedCommandsExecutor instance.
static constexpr size_t kHistogramSampleStackSize = 5;
StackVector<std::pair<HistogramBase*, HistogramBase::Sample>,
kHistogramSampleStackSize>
scheduled_histogram_samples_;
DISALLOW_COPY_AND_ASSIGN(ScopedCommandsExecutor);
};
// static
constexpr size_t
ThreadGroupImpl::ScopedCommandsExecutor::kHistogramSampleStackSize;
class ThreadGroupImpl::WorkerThreadDelegateImpl : public WorkerThread::Delegate,
public BlockingObserver {
public:
// |outer| owns the worker for which this delegate is constructed.
WorkerThreadDelegateImpl(TrackedRef<ThreadGroupImpl> outer);
~WorkerThreadDelegateImpl() override;
// WorkerThread::Delegate:
WorkerThread::ThreadLabel GetThreadLabel() const override;
void OnMainEntry(const WorkerThread* worker) override;
RegisteredTaskSource GetWork(WorkerThread* worker) override;
void DidProcessTask(RegisteredTaskSource task_source) override;
TimeDelta GetSleepTimeout() override;
void OnMainExit(WorkerThread* worker) override;
// BlockingObserver:
void BlockingStarted(BlockingType blocking_type) override;
void BlockingTypeUpgraded() override;
void BlockingEnded() override;
void MayBlockEntered();
void WillBlockEntered();
// Returns true iff the worker can get work. Cleans up the worker or puts it
// on the idle stack if it can't get work.
bool CanGetWorkLockRequired(ScopedCommandsExecutor* executor,
WorkerThread* worker)
EXCLUSIVE_LOCKS_REQUIRED(outer_->lock_);
// Returns true iff this worker has been within a MAY_BLOCK ScopedBlockingCall
// for more than |may_block_threshold|. The max tasks must be
// incremented if this returns true.
bool MustIncrementMaxTasksLockRequired()
EXCLUSIVE_LOCKS_REQUIRED(outer_->lock_);
TaskPriority current_task_priority_lock_required() const
EXCLUSIVE_LOCKS_REQUIRED(outer_->lock_) {
return *read_any().current_task_priority;
}
// Exposed for AnnotateCheckedLockAcquired in
// ThreadGroupImpl::AdjustMaxTasks()
const CheckedLock& lock() const LOCK_RETURNED(outer_->lock_) {
return outer_->lock_;
}
private:
// Returns true if |worker| is allowed to cleanup and remove itself from the
// thread group. Called from GetWork() when no work is available.
bool CanCleanupLockRequired(const WorkerThread* worker) const
EXCLUSIVE_LOCKS_REQUIRED(outer_->lock_);
// Calls cleanup on |worker| and removes it from the thread group. Called from
// GetWork() when no work is available and CanCleanupLockRequired() returns
// true.
void CleanupLockRequired(ScopedCommandsExecutor* executor,
WorkerThread* worker)
EXCLUSIVE_LOCKS_REQUIRED(outer_->lock_);
// Called in GetWork() when a worker becomes idle.
void OnWorkerBecomesIdleLockRequired(WorkerThread* worker)
EXCLUSIVE_LOCKS_REQUIRED(outer_->lock_);
// Accessed only from the worker thread.
struct WorkerOnly {
// Number of tasks executed since the last time the
// ThreadPool.NumTasksBeforeDetach histogram was recorded.
size_t num_tasks_since_last_detach = 0;
// Whether the worker is currently running a task (i.e. GetWork() has
// returned a non-empty task source and DidProcessTask() hasn't been called
// yet).
bool is_running_task = false;
#if defined(OS_WIN)
std::unique_ptr<win::ScopedWindowsThreadEnvironment> win_thread_environment;
#endif // defined(OS_WIN)
} worker_only_;
// Writes from the worker thread protected by |outer_->lock_|. Reads from any
// thread, protected by |outer_->lock_| when not on the worker thread.
struct WriteWorkerReadAny {
// The priority of the task the worker is currently running if any.
base::Optional<TaskPriority> current_task_priority;
// Time when MayBlockScopeEntered() was last called. Reset when
// BlockingScopeExited() is called.
TimeTicks may_block_start_time;
} write_worker_read_any_;
WorkerOnly& worker_only() {
DCHECK_CALLED_ON_VALID_THREAD(worker_thread_checker_);
return worker_only_;
}
WriteWorkerReadAny& write_worker() EXCLUSIVE_LOCKS_REQUIRED(outer_->lock_) {
DCHECK_CALLED_ON_VALID_THREAD(worker_thread_checker_);
return write_worker_read_any_;
}
const WriteWorkerReadAny& read_any() const
EXCLUSIVE_LOCKS_REQUIRED(outer_->lock_) {
return write_worker_read_any_;
}
const WriteWorkerReadAny& read_worker() const {
DCHECK_CALLED_ON_VALID_THREAD(worker_thread_checker_);
return write_worker_read_any_;
}
const TrackedRef<ThreadGroupImpl> outer_;
// Whether |outer_->max_tasks_| was incremented due to a ScopedBlockingCall on
// the thread.
bool incremented_max_tasks_since_blocked_ GUARDED_BY(outer_->lock_) = false;
// Verifies that specific calls are always made from the worker thread.
THREAD_CHECKER(worker_thread_checker_);
DISALLOW_COPY_AND_ASSIGN(WorkerThreadDelegateImpl);
};
ThreadGroupImpl::ThreadGroupImpl(StringPiece histogram_label,
StringPiece thread_group_label,
ThreadPriority priority_hint,
TrackedRef<TaskTracker> task_tracker,
TrackedRef<Delegate> delegate)
: ThreadGroup(std::move(task_tracker), std::move(delegate)),
thread_group_label_(thread_group_label.as_string()),
priority_hint_(priority_hint),
idle_workers_stack_cv_for_testing_(lock_.CreateConditionVariable()),
// Mimics the UMA_HISTOGRAM_LONG_TIMES macro.
detach_duration_histogram_(
histogram_label.empty()
? nullptr
: Histogram::FactoryTimeGet(
JoinString(
{kDetachDurationHistogramPrefix, histogram_label},
""),
TimeDelta::FromMilliseconds(1),
TimeDelta::FromHours(1),
50,
HistogramBase::kUmaTargetedHistogramFlag)),
// Mimics the UMA_HISTOGRAM_COUNTS_1000 macro. When a worker runs more
// than 1000 tasks before detaching, there is no need to know the exact
// number of tasks that ran.
num_tasks_before_detach_histogram_(
histogram_label.empty()
? nullptr
: Histogram::FactoryGet(
JoinString(
{kNumTasksBeforeDetachHistogramPrefix, histogram_label},
""),
1,
1000,
50,
HistogramBase::kUmaTargetedHistogramFlag)),
// Mimics the UMA_HISTOGRAM_COUNTS_100 macro. A ThreadGroup is
// expected to run between zero and a few tens of workers.
// When it runs more than 100 worker, there is no need to know the exact
// number of workers that ran.
num_workers_histogram_(
histogram_label.empty()
? nullptr
: Histogram::FactoryGet(
JoinString({kNumWorkersHistogramPrefix, histogram_label},
""),
1,
100,
50,
HistogramBase::kUmaTargetedHistogramFlag)),
num_active_workers_histogram_(
histogram_label.empty()
? nullptr
: Histogram::FactoryGet(
JoinString(
{kNumActiveWorkersHistogramPrefix, histogram_label},
""),
1,
100,
50,
HistogramBase::kUmaTargetedHistogramFlag)),
tracked_ref_factory_(this) {
DCHECK(!thread_group_label_.empty());
}
void ThreadGroupImpl::Start(
int max_tasks,
int max_best_effort_tasks,
TimeDelta suggested_reclaim_time,
scoped_refptr<SequencedTaskRunner> service_thread_task_runner,
WorkerThreadObserver* worker_thread_observer,
WorkerEnvironment worker_environment,
bool synchronous_thread_start_for_testing,
Optional<TimeDelta> may_block_threshold) {
DCHECK(!replacement_thread_group_);
in_start().may_block_without_delay =
FeatureList::IsEnabled(kMayBlockWithoutDelay);
in_start().fixed_max_best_effort_tasks =
FeatureList::IsEnabled(kFixedMaxBestEffortTasks);
in_start().may_block_threshold =
may_block_threshold ? may_block_threshold.value()
: (priority_hint_ == ThreadPriority::NORMAL
? kForegroundMayBlockThreshold
: kBackgroundMayBlockThreshold);
in_start().blocked_workers_poll_period =
priority_hint_ == ThreadPriority::NORMAL ? kForegroundBlockedWorkersPoll
: kBackgroundBlockedWorkersPoll;
ScopedCommandsExecutor executor(this);
CheckedAutoLock auto_lock(lock_);
DCHECK(workers_.empty());
max_tasks_ = max_tasks;
DCHECK_GE(max_tasks_, 1U);
in_start().initial_max_tasks = max_tasks_;
DCHECK_LE(in_start().initial_max_tasks, kMaxNumberOfWorkers);
max_best_effort_tasks_ = max_best_effort_tasks;
in_start().suggested_reclaim_time = suggested_reclaim_time;
in_start().worker_environment = worker_environment;
in_start().service_thread_task_runner = std::move(service_thread_task_runner);
in_start().worker_thread_observer = worker_thread_observer;
#if DCHECK_IS_ON()
in_start().initialized = true;
#endif
if (synchronous_thread_start_for_testing) {
worker_started_for_testing_.emplace(WaitableEvent::ResetPolicy::AUTOMATIC);
// Don't emit a ScopedBlockingCallWithBaseSyncPrimitives from this
// WaitableEvent or it defeats the purpose of having threads start without
// externally visible side-effects.
worker_started_for_testing_->declare_only_used_while_idle();
}
EnsureEnoughWorkersLockRequired(&executor);
}
ThreadGroupImpl::~ThreadGroupImpl() {
// ThreadGroup should only ever be deleted:
// 1) In tests, after JoinForTesting().
// 2) In production, iff initialization failed.
// In both cases |workers_| should be empty.
DCHECK(workers_.empty());
}
void ThreadGroupImpl::UpdateSortKey(TaskSource::Transaction transaction) {
ScopedCommandsExecutor executor(this);
UpdateSortKeyImpl(&executor, std::move(transaction));
}
void ThreadGroupImpl::PushTaskSourceAndWakeUpWorkers(
TransactionWithRegisteredTaskSource transaction_with_task_source) {
ScopedCommandsExecutor executor(this);
PushTaskSourceAndWakeUpWorkersImpl(&executor,
std::move(transaction_with_task_source));
}
size_t ThreadGroupImpl::GetMaxConcurrentNonBlockedTasksDeprecated() const {
#if DCHECK_IS_ON()
CheckedAutoLock auto_lock(lock_);
DCHECK_NE(after_start().initial_max_tasks, 0U)
<< "GetMaxConcurrentTasksDeprecated() should only be called after the "
<< "thread group has started.";
#endif
return after_start().initial_max_tasks;
}
void ThreadGroupImpl::WaitForWorkersIdleForTesting(size_t n) {
CheckedAutoLock auto_lock(lock_);
#if DCHECK_IS_ON()
DCHECK(!some_workers_cleaned_up_for_testing_)
<< "Workers detached prior to waiting for a specific number of idle "
"workers. Doing the wait under such conditions is flaky. Consider "
"setting the suggested reclaim time to TimeDelta::Max() in Start().";
#endif
WaitForWorkersIdleLockRequiredForTesting(n);
}
void ThreadGroupImpl::WaitForAllWorkersIdleForTesting() {
CheckedAutoLock auto_lock(lock_);
WaitForWorkersIdleLockRequiredForTesting(workers_.size());
}
void ThreadGroupImpl::WaitForWorkersCleanedUpForTesting(size_t n) {
CheckedAutoLock auto_lock(lock_);
if (!num_workers_cleaned_up_for_testing_cv_)
num_workers_cleaned_up_for_testing_cv_ = lock_.CreateConditionVariable();
while (num_workers_cleaned_up_for_testing_ < n)
num_workers_cleaned_up_for_testing_cv_->Wait();
num_workers_cleaned_up_for_testing_ = 0;
}
void ThreadGroupImpl::JoinForTesting() {
decltype(workers_) workers_copy;
{
CheckedAutoLock auto_lock(lock_);
priority_queue_.EnableFlushTaskSourcesOnDestroyForTesting();
DCHECK_GT(workers_.size(), size_t(0))
<< "Joined an unstarted thread group.";
join_for_testing_started_ = true;
// Ensure WorkerThreads in |workers_| do not attempt to cleanup while
// being joined.
worker_cleanup_disallowed_for_testing_ = true;
// Make a copy of the WorkerThreads so that we can call
// WorkerThread::JoinForTesting() without holding |lock_| since
// WorkerThreads may need to access |workers_|.
workers_copy = workers_;
}
for (const auto& worker : workers_copy)
worker->JoinForTesting();
CheckedAutoLock auto_lock(lock_);
DCHECK(workers_ == workers_copy);
// Release |workers_| to clear their TrackedRef against |this|.
workers_.clear();
}
size_t ThreadGroupImpl::NumberOfWorkersForTesting() const {
CheckedAutoLock auto_lock(lock_);
return workers_.size();
}
size_t ThreadGroupImpl::GetMaxTasksForTesting() const {
CheckedAutoLock auto_lock(lock_);
return max_tasks_;
}
size_t ThreadGroupImpl::NumberOfIdleWorkersForTesting() const {
CheckedAutoLock auto_lock(lock_);
return idle_workers_stack_.Size();
}
void ThreadGroupImpl::ReportHeartbeatMetrics() const {
HistogramBase::Sample num_workers_sample;
HistogramBase::Sample num_active_workers_sample;
// Increase histogram counts while |lock_| isn't being held,
// in case histogram code triggers PostTasks in callbacks.
{
CheckedAutoLock auto_lock(lock_);
num_workers_sample = workers_.size();
num_active_workers_sample = workers_.size() - idle_workers_stack_.Size();
}
if (num_workers_histogram_)
num_workers_histogram_->Add(num_workers_sample);
if (num_active_workers_histogram_)
num_active_workers_histogram_->Add(num_active_workers_sample);
}
ThreadGroupImpl::WorkerThreadDelegateImpl::WorkerThreadDelegateImpl(
TrackedRef<ThreadGroupImpl> outer)
: outer_(std::move(outer)) {
// Bound in OnMainEntry().
DETACH_FROM_THREAD(worker_thread_checker_);
}
// OnMainExit() handles the thread-affine cleanup; WorkerThreadDelegateImpl
// can thereafter safely be deleted from any thread.
ThreadGroupImpl::WorkerThreadDelegateImpl::~WorkerThreadDelegateImpl() =
default;
WorkerThread::ThreadLabel
ThreadGroupImpl::WorkerThreadDelegateImpl::GetThreadLabel() const {
return WorkerThread::ThreadLabel::POOLED;
}
void ThreadGroupImpl::WorkerThreadDelegateImpl::OnMainEntry(
const WorkerThread* worker) {
DCHECK_CALLED_ON_VALID_THREAD(worker_thread_checker_);
{
#if DCHECK_IS_ON()
CheckedAutoLock auto_lock(outer_->lock_);
DCHECK(ContainsWorker(outer_->workers_, worker));
#endif
}
#if defined(OS_WIN)
worker_only().win_thread_environment = GetScopedWindowsThreadEnvironment(
outer_->after_start().worker_environment);
#endif // defined(OS_WIN)
PlatformThread::SetName(
StringPrintf("ThreadPool%sWorker", outer_->thread_group_label_.c_str()));
outer_->BindToCurrentThread();
SetBlockingObserverForCurrentThread(this);
if (outer_->worker_started_for_testing_) {
// When |worker_started_for_testing_| is set, the thread that starts workers
// should wait for a worker to have started before starting the next one,
// and there should only be one thread that wakes up workers at a time.
DCHECK(!outer_->worker_started_for_testing_->IsSignaled());
outer_->worker_started_for_testing_->Signal();
}
}
RegisteredTaskSource ThreadGroupImpl::WorkerThreadDelegateImpl::GetWork(
WorkerThread* worker) {
DCHECK_CALLED_ON_VALID_THREAD(worker_thread_checker_);
DCHECK(!worker_only().is_running_task);
ScopedCommandsExecutor executor(outer_.get());
CheckedAutoLock auto_lock(outer_->lock_);
DCHECK(ContainsWorker(outer_->workers_, worker));
// Use this opportunity, before assigning work to this worker, to create/wake
// additional workers if needed (doing this here allows us to reduce
// potentially expensive create/wake directly on PostTask()).
outer_->EnsureEnoughWorkersLockRequired(&executor);
executor.FlushWorkerCreation(&outer_->lock_);
if (!CanGetWorkLockRequired(&executor, worker))
return nullptr;
RegisteredTaskSource task_source;
TaskPriority priority;
while (!task_source && !outer_->priority_queue_.IsEmpty()) {
// Enforce the CanRunPolicy and that no more than |max_best_effort_tasks_|
// BEST_EFFORT tasks run concurrently.
priority = outer_->priority_queue_.PeekSortKey().priority();
if (!outer_->task_tracker_->CanRunPriority(priority) ||
(priority == TaskPriority::BEST_EFFORT &&
outer_->num_running_best_effort_tasks_ >=
outer_->max_best_effort_tasks_)) {
break;
}
task_source = outer_->TakeRegisteredTaskSource(&executor);
}
if (!task_source) {
OnWorkerBecomesIdleLockRequired(worker);
return nullptr;
}
// Running task bookkeeping.
worker_only().is_running_task = true;
outer_->IncrementTasksRunningLockRequired(priority);
DCHECK(!outer_->idle_workers_stack_.Contains(worker));
write_worker().current_task_priority = priority;
return task_source;
}
void ThreadGroupImpl::WorkerThreadDelegateImpl::DidProcessTask(
RegisteredTaskSource task_source) {
DCHECK_CALLED_ON_VALID_THREAD(worker_thread_checker_);
DCHECK(worker_only().is_running_task);
DCHECK(read_worker().may_block_start_time.is_null());
++worker_only().num_tasks_since_last_detach;
// A transaction to the TaskSource to reenqueue, if any. Instantiated here as
// |TaskSource::lock_| is a UniversalPredecessor and must always be acquired
// prior to acquiring a second lock
Optional<TransactionWithRegisteredTaskSource> transaction_with_task_source;
if (task_source) {
transaction_with_task_source.emplace(
TransactionWithRegisteredTaskSource::FromTaskSource(
std::move(task_source)));
}
ScopedCommandsExecutor workers_executor(outer_.get());
ScopedReenqueueExecutor reenqueue_executor;
CheckedAutoLock auto_lock(outer_->lock_);
DCHECK(!incremented_max_tasks_since_blocked_);
// Running task bookkeeping.
outer_->DecrementTasksRunningLockRequired(
*read_worker().current_task_priority);
worker_only().is_running_task = false;
if (transaction_with_task_source) {
outer_->ReEnqueueTaskSourceLockRequired(
&workers_executor, &reenqueue_executor,
std::move(transaction_with_task_source.value()));
}
}
TimeDelta ThreadGroupImpl::WorkerThreadDelegateImpl::GetSleepTimeout() {
DCHECK_CALLED_ON_VALID_THREAD(worker_thread_checker_);
// Sleep for an extra 10% to avoid the following pathological case:
// 0) A task is running on a timer which matches
// |after_start().suggested_reclaim_time|.
// 1) The timer fires and this worker is created by
// MaintainAtLeastOneIdleWorkerLockRequired() because the last idle
// worker was assigned the task.
// 2) This worker begins sleeping |after_start().suggested_reclaim_time| (on
// top of the idle stack).
// 3) The task assigned to the other worker completes and the worker goes
// back on the idle stack (this worker is now second on the idle stack;
// its GetLastUsedTime() is set to Now()).
// 4) The sleep in (2) expires. Since (3) was fast this worker is likely to
// have been second on the idle stack long enough for
// CanCleanupLockRequired() to be satisfied in which case this worker is
// cleaned up.
// 5) The timer fires at roughly the same time and we're back to (1) if (4)
// resulted in a clean up; causing thread churn.
//
// Sleeping 10% longer in (2) makes it much less likely that (4) occurs
// before (5). In that case (5) will cause (3) and refresh this worker's
// GetLastUsedTime(), making CanCleanupLockRequired() return false in (4)
// and avoiding churn.
//
// Of course the same problem arises if in (0) the timer matches
// |after_start().suggested_reclaim_time * 1.1| but it's expected that any
// timer slower than |after_start().suggested_reclaim_time| will cause such
// churn during long idle periods. If this is a problem in practice, the
// standby thread configuration and algorithm should be revisited.
return outer_->after_start().suggested_reclaim_time * 1.1;
}
bool ThreadGroupImpl::WorkerThreadDelegateImpl::CanCleanupLockRequired(
const WorkerThread* worker) const {
DCHECK_CALLED_ON_VALID_THREAD(worker_thread_checker_);
const TimeTicks last_used_time = worker->GetLastUsedTime();
return !last_used_time.is_null() &&
subtle::TimeTicksNowIgnoringOverride() - last_used_time >=
outer_->after_start().suggested_reclaim_time &&
(outer_->workers_.size() > outer_->after_start().initial_max_tasks ||
!FeatureList::IsEnabled(kNoDetachBelowInitialCapacity)) &&
LIKELY(!outer_->worker_cleanup_disallowed_for_testing_);
}
void ThreadGroupImpl::WorkerThreadDelegateImpl::CleanupLockRequired(
ScopedCommandsExecutor* executor,
WorkerThread* worker) {
DCHECK(!outer_->join_for_testing_started_);
DCHECK_CALLED_ON_VALID_THREAD(worker_thread_checker_);
if (outer_->num_tasks_before_detach_histogram_) {
executor->ScheduleAddHistogramSample(
outer_->num_tasks_before_detach_histogram_,
worker_only().num_tasks_since_last_detach);
}
outer_->cleanup_timestamps_.push(subtle::TimeTicksNowIgnoringOverride());
worker->Cleanup();
outer_->idle_workers_stack_.Remove(worker);
// Remove the worker from |workers_|.
auto worker_iter =
std::find(outer_->workers_.begin(), outer_->workers_.end(), worker);
DCHECK(worker_iter != outer_->workers_.end());
outer_->workers_.erase(worker_iter);
}
void ThreadGroupImpl::WorkerThreadDelegateImpl::OnWorkerBecomesIdleLockRequired(
WorkerThread* worker) {
DCHECK_CALLED_ON_VALID_THREAD(worker_thread_checker_);
// Add the worker to the idle stack.
DCHECK(!outer_->idle_workers_stack_.Contains(worker));
outer_->idle_workers_stack_.Push(worker);
DCHECK_LE(outer_->idle_workers_stack_.Size(), outer_->workers_.size());
outer_->idle_workers_stack_cv_for_testing_->Broadcast();
}
void ThreadGroupImpl::WorkerThreadDelegateImpl::OnMainExit(
WorkerThread* worker) {
DCHECK_CALLED_ON_VALID_THREAD(worker_thread_checker_);
#if DCHECK_IS_ON()
{
bool shutdown_complete = outer_->task_tracker_->IsShutdownComplete();
CheckedAutoLock auto_lock(outer_->lock_);
// |worker| should already have been removed from the idle workers stack and
// |workers_| by the time the thread is about to exit. (except in the cases
// where the thread group is no longer going to be used - in which case,
// it's fine for there to be invalid workers in the thread group.
if (!shutdown_complete && !outer_->join_for_testing_started_) {
DCHECK(!outer_->idle_workers_stack_.Contains(worker));
DCHECK(!ContainsWorker(outer_->workers_, worker));
}
}
#endif
#if defined(OS_WIN)
worker_only().win_thread_environment.reset();
#endif // defined(OS_WIN)
// Count cleaned up workers for tests. It's important to do this here instead
// of at the end of CleanupLockRequired() because some side-effects of
// cleaning up happen outside the lock (e.g. recording histograms) and
// resuming from tests must happen-after that point or checks on the main
// thread will be flaky (crbug.com/1047733).
CheckedAutoLock auto_lock(outer_->lock_);
++outer_->num_workers_cleaned_up_for_testing_;
#if DCHECK_IS_ON()
outer_->some_workers_cleaned_up_for_testing_ = true;
#endif
if (outer_->num_workers_cleaned_up_for_testing_cv_)
outer_->num_workers_cleaned_up_for_testing_cv_->Signal();
}
void ThreadGroupImpl::WorkerThreadDelegateImpl::BlockingStarted(
BlockingType blocking_type) {
DCHECK_CALLED_ON_VALID_THREAD(worker_thread_checker_);
DCHECK(worker_only().is_running_task);
// MayBlock with no delay reuses WillBlock implementation.
// WillBlock is always used when time overrides is active. crbug.com/1038867
if (outer_->after_start().may_block_without_delay ||
base::subtle::ScopedTimeClockOverrides::overrides_active()) {
blocking_type = BlockingType::WILL_BLOCK;
}
switch (blocking_type) {
case BlockingType::MAY_BLOCK:
MayBlockEntered();
break;
case BlockingType::WILL_BLOCK:
WillBlockEntered();
break;
}
}
void ThreadGroupImpl::WorkerThreadDelegateImpl::BlockingTypeUpgraded() {
DCHECK_CALLED_ON_VALID_THREAD(worker_thread_checker_);
DCHECK(worker_only().is_running_task);
// The blocking type always being WILL_BLOCK in this experiment and with time
// overrides, it should never be considered "upgraded".
if (outer_->after_start().may_block_without_delay ||
base::subtle::ScopedTimeClockOverrides::overrides_active()) {
return;
}
{
CheckedAutoLock auto_lock(outer_->lock_);
// Don't do anything if a MAY_BLOCK ScopedBlockingCall instantiated in the
// same scope already caused the max tasks to be incremented.
if (incremented_max_tasks_since_blocked_)
return;
// Cancel the effect of a MAY_BLOCK ScopedBlockingCall instantiated in the
// same scope.
if (!read_worker().may_block_start_time.is_null()) {
write_worker().may_block_start_time = TimeTicks();
--outer_->num_unresolved_may_block_;
if (*read_worker().current_task_priority == TaskPriority::BEST_EFFORT)
--outer_->num_unresolved_best_effort_may_block_;
}
}
WillBlockEntered();
}
void ThreadGroupImpl::WorkerThreadDelegateImpl::BlockingEnded() {
DCHECK_CALLED_ON_VALID_THREAD(worker_thread_checker_);
DCHECK(worker_only().is_running_task);
CheckedAutoLock auto_lock(outer_->lock_);
if (incremented_max_tasks_since_blocked_) {
outer_->DecrementMaxTasksLockRequired(*read_worker().current_task_priority);
} else {
DCHECK(!read_worker().may_block_start_time.is_null());
--outer_->num_unresolved_may_block_;
if (*read_worker().current_task_priority == TaskPriority::BEST_EFFORT)
--outer_->num_unresolved_best_effort_may_block_;
}
incremented_max_tasks_since_blocked_ = false;
write_worker().may_block_start_time = TimeTicks();
}
void ThreadGroupImpl::WorkerThreadDelegateImpl::MayBlockEntered() {
DCHECK_CALLED_ON_VALID_THREAD(worker_thread_checker_);
DCHECK(worker_only().is_running_task);
ScopedCommandsExecutor executor(outer_.get());
CheckedAutoLock auto_lock(outer_->lock_);
DCHECK(!incremented_max_tasks_since_blocked_);
DCHECK(read_worker().may_block_start_time.is_null());
write_worker().may_block_start_time = subtle::TimeTicksNowIgnoringOverride();
++outer_->num_unresolved_may_block_;
if (*read_worker().current_task_priority == TaskPriority::BEST_EFFORT)
++outer_->num_unresolved_best_effort_may_block_;
outer_->MaybeScheduleAdjustMaxTasksLockRequired(&executor);
}
void ThreadGroupImpl::WorkerThreadDelegateImpl::WillBlockEntered() {
DCHECK_CALLED_ON_VALID_THREAD(worker_thread_checker_);
DCHECK(worker_only().is_running_task);
ScopedCommandsExecutor executor(outer_.get());
CheckedAutoLock auto_lock(outer_->lock_);
DCHECK(!incremented_max_tasks_since_blocked_);
DCHECK(read_worker().may_block_start_time.is_null());
incremented_max_tasks_since_blocked_ = true;
outer_->IncrementMaxTasksLockRequired(*read_worker().current_task_priority);
outer_->EnsureEnoughWorkersLockRequired(&executor);
}
bool ThreadGroupImpl::WorkerThreadDelegateImpl::CanGetWorkLockRequired(
ScopedCommandsExecutor* executor,
WorkerThread* worker) {
// To avoid searching through the idle stack : use GetLastUsedTime() not being
// null (or being directly on top of the idle stack) as a proxy for being on
// the idle stack.
const bool is_on_idle_workers_stack =
outer_->idle_workers_stack_.Peek() == worker ||
!worker->GetLastUsedTime().is_null();
DCHECK_EQ(is_on_idle_workers_stack,
outer_->idle_workers_stack_.Contains(worker));
if (is_on_idle_workers_stack) {
if (CanCleanupLockRequired(worker))
CleanupLockRequired(executor, worker);
return false;
}
// Excess workers should not get work, until they are no longer excess (i.e.
// max tasks increases). This ensures that if we have excess workers in the
// thread group, they get a chance to no longer be excess before being cleaned
// up.
if (outer_->GetNumAwakeWorkersLockRequired() >
outer_->GetDesiredNumAwakeWorkersLockRequired()) {
OnWorkerBecomesIdleLockRequired(worker);
return false;
}
return true;
}
bool ThreadGroupImpl::WorkerThreadDelegateImpl::
MustIncrementMaxTasksLockRequired() {
if (!incremented_max_tasks_since_blocked_ &&
!read_any().may_block_start_time.is_null() &&
subtle::TimeTicksNowIgnoringOverride() -
read_any().may_block_start_time >=
outer_->after_start().may_block_threshold) {
incremented_max_tasks_since_blocked_ = true;
--outer_->num_unresolved_may_block_;
if (*read_any().current_task_priority == TaskPriority::BEST_EFFORT)
--outer_->num_unresolved_best_effort_may_block_;
return true;
}
return false;
}
void ThreadGroupImpl::WaitForWorkersIdleLockRequiredForTesting(size_t n) {
// Make sure workers do not cleanup while watching the idle count.
AutoReset<bool> ban_cleanups(&worker_cleanup_disallowed_for_testing_, true);
while (idle_workers_stack_.Size() < n)
idle_workers_stack_cv_for_testing_->Wait();
}
void ThreadGroupImpl::MaintainAtLeastOneIdleWorkerLockRequired(
ScopedCommandsExecutor* executor) {
if (workers_.size() == kMaxNumberOfWorkers)
return;
DCHECK_LT(workers_.size(), kMaxNumberOfWorkers);
if (!idle_workers_stack_.IsEmpty())
return;
if (workers_.size() >= max_tasks_)
return;
scoped_refptr<WorkerThread> new_worker =
CreateAndRegisterWorkerLockRequired(executor);
DCHECK(new_worker);
idle_workers_stack_.Push(new_worker.get());
}
scoped_refptr<WorkerThread>
ThreadGroupImpl::CreateAndRegisterWorkerLockRequired(
ScopedCommandsExecutor* executor) {
DCHECK(!join_for_testing_started_);
DCHECK_LT(workers_.size(), max_tasks_);
DCHECK_LT(workers_.size(), kMaxNumberOfWorkers);
DCHECK(idle_workers_stack_.IsEmpty());
// WorkerThread needs |lock_| as a predecessor for its thread lock
// because in WakeUpOneWorker, |lock_| is first acquired and then
// the thread lock is acquired when WakeUp is called on the worker.
scoped_refptr<WorkerThread> worker =
MakeRefCounted<WorkerThread>(priority_hint_,
std::make_unique<WorkerThreadDelegateImpl>(
tracked_ref_factory_.GetTrackedRef()),
task_tracker_, &lock_);
workers_.push_back(worker);
executor->ScheduleStart(worker);
DCHECK_LE(workers_.size(), max_tasks_);
if (!cleanup_timestamps_.empty()) {
if (detach_duration_histogram_) {
executor->ScheduleAddHistogramSample(
detach_duration_histogram_,
(subtle::TimeTicksNowIgnoringOverride() - cleanup_timestamps_.top())
.InMilliseconds());
}
cleanup_timestamps_.pop();
}
return worker;
}
size_t ThreadGroupImpl::GetNumAwakeWorkersLockRequired() const {
DCHECK_GE(workers_.size(), idle_workers_stack_.Size());
size_t num_awake_workers = workers_.size() - idle_workers_stack_.Size();
DCHECK_GE(num_awake_workers, num_running_tasks_);
return num_awake_workers;
}
size_t ThreadGroupImpl::GetDesiredNumAwakeWorkersLockRequired() const {
// Number of BEST_EFFORT task sources that are running or queued and allowed
// to run by the CanRunPolicy.
const size_t num_running_or_queued_can_run_best_effort_task_sources =
num_running_best_effort_tasks_ +
GetNumAdditionalWorkersForBestEffortTaskSourcesLockRequired();
const size_t workers_for_best_effort_task_sources =
std::max(std::min(num_running_or_queued_can_run_best_effort_task_sources,
max_best_effort_tasks_),
num_running_best_effort_tasks_);
// Number of USER_{VISIBLE|BLOCKING} task sources that are running or queued.
const size_t num_running_or_queued_foreground_task_sources =
(num_running_tasks_ - num_running_best_effort_tasks_) +
GetNumAdditionalWorkersForForegroundTaskSourcesLockRequired();
const size_t workers_for_foreground_task_sources =
num_running_or_queued_foreground_task_sources;
return std::min({workers_for_best_effort_task_sources +
workers_for_foreground_task_sources,
max_tasks_, kMaxNumberOfWorkers});
}
void ThreadGroupImpl::DidUpdateCanRunPolicy() {
ScopedCommandsExecutor executor(this);
CheckedAutoLock auto_lock(lock_);
EnsureEnoughWorkersLockRequired(&executor);
}
void ThreadGroupImpl::EnsureEnoughWorkersLockRequired(
BaseScopedCommandsExecutor* base_executor) {
// Don't do anything if the thread group isn't started.
if (max_tasks_ == 0 || UNLIKELY(join_for_testing_started_))
return;
ScopedCommandsExecutor* executor =
static_cast<ScopedCommandsExecutor*>(base_executor);
const size_t desired_num_awake_workers =
GetDesiredNumAwakeWorkersLockRequired();
const size_t num_awake_workers = GetNumAwakeWorkersLockRequired();
size_t num_workers_to_wake_up =
ClampSub(desired_num_awake_workers, num_awake_workers);
num_workers_to_wake_up = std::min(num_workers_to_wake_up, size_t(2U));
// Wake up the appropriate number of workers.
for (size_t i = 0; i < num_workers_to_wake_up; ++i) {
MaintainAtLeastOneIdleWorkerLockRequired(executor);
WorkerThread* worker_to_wakeup = idle_workers_stack_.Pop();
DCHECK(worker_to_wakeup);
executor->ScheduleWakeUp(worker_to_wakeup);
}
// In the case where the loop above didn't wake up any worker and we don't
// have excess workers, the idle worker should be maintained. This happens
// when called from the last worker awake, or a recent increase in |max_tasks|
// now makes it possible to keep an idle worker.
if (desired_num_awake_workers == num_awake_workers)
MaintainAtLeastOneIdleWorkerLockRequired(executor);
// This function is called every time a task source is (re-)enqueued,
// hence the minimum priority needs to be updated.
UpdateMinAllowedPriorityLockRequired();
// Ensure that the number of workers is periodically adjusted if needed.
MaybeScheduleAdjustMaxTasksLockRequired(executor);
}
void ThreadGroupImpl::AdjustMaxTasks() {
DCHECK(
after_start().service_thread_task_runner->RunsTasksInCurrentSequence());
ScopedCommandsExecutor executor(this);
CheckedAutoLock auto_lock(lock_);
DCHECK(adjust_max_tasks_posted_);
adjust_max_tasks_posted_ = false;
// Increment max tasks for each worker that has been within a MAY_BLOCK
// ScopedBlockingCall for more than may_block_threshold.
for (scoped_refptr<WorkerThread> worker : workers_) {
// The delegates of workers inside a ThreadGroupImpl should be
// WorkerThreadDelegateImpls.
WorkerThreadDelegateImpl* delegate =
static_cast<WorkerThreadDelegateImpl*>(worker->delegate());
AnnotateAcquiredLockAlias annotate(lock_, delegate->lock());
if (delegate->MustIncrementMaxTasksLockRequired()) {
IncrementMaxTasksLockRequired(
delegate->current_task_priority_lock_required());
}
}
// Wake up workers according to the updated |max_tasks_|. This will also
// reschedule AdjustMaxTasks() if necessary.
EnsureEnoughWorkersLockRequired(&executor);
}
void ThreadGroupImpl::ScheduleAdjustMaxTasks() {
// |adjust_max_tasks_posted_| can't change before the task posted below runs.
// Skip check on NaCl to avoid unsafe reference acquisition warning.
#if !defined(OS_NACL)
DCHECK(TS_UNCHECKED_READ(adjust_max_tasks_posted_));
#endif
after_start().service_thread_task_runner->PostDelayedTask(
FROM_HERE, BindOnce(&ThreadGroupImpl::AdjustMaxTasks, Unretained(this)),
after_start().blocked_workers_poll_period);
}
void ThreadGroupImpl::MaybeScheduleAdjustMaxTasksLockRequired(
ScopedCommandsExecutor* executor) {
if (!adjust_max_tasks_posted_ &&
ShouldPeriodicallyAdjustMaxTasksLockRequired()) {
executor->ScheduleAdjustMaxTasks();
adjust_max_tasks_posted_ = true;
}
}
bool ThreadGroupImpl::ShouldPeriodicallyAdjustMaxTasksLockRequired() {
// AdjustMaxTasks() should be scheduled to periodically adjust |max_tasks_|
// and |max_best_effort_tasks_| when (1) the concurrency limits are not large
// enough to accommodate all queued and running task sources and an idle
// worker and (2) there are unresolved MAY_BLOCK ScopedBlockingCalls.
// - When (1) is false: No worker would be created or woken up if the
// concurrency limits were increased, so there is no hurry to increase them.
// - When (2) is false: The concurrency limits could not be increased by
// AdjustMaxTasks().
const size_t num_running_or_queued_best_effort_task_sources =
num_running_best_effort_tasks_ +
GetNumAdditionalWorkersForBestEffortTaskSourcesLockRequired();
if (num_running_or_queued_best_effort_task_sources > max_best_effort_tasks_ &&
num_unresolved_best_effort_may_block_ > 0) {
return true;
}
const size_t num_running_or_queued_task_sources =
num_running_tasks_ +
GetNumAdditionalWorkersForBestEffortTaskSourcesLockRequired() +
GetNumAdditionalWorkersForForegroundTaskSourcesLockRequired();
constexpr size_t kIdleWorker = 1;
return num_running_or_queued_task_sources + kIdleWorker > max_tasks_ &&
num_unresolved_may_block_ > 0;
}
void ThreadGroupImpl::UpdateMinAllowedPriorityLockRequired() {
if (priority_queue_.IsEmpty() || num_running_tasks_ < max_tasks_) {
min_allowed_priority_.store(TaskPriority::BEST_EFFORT,
std::memory_order_relaxed);
} else {
min_allowed_priority_.store(priority_queue_.PeekSortKey().priority(),
std::memory_order_relaxed);
}
}
void ThreadGroupImpl::DecrementTasksRunningLockRequired(TaskPriority priority) {
DCHECK_GT(num_running_tasks_, 0U);
--num_running_tasks_;
if (priority == TaskPriority::BEST_EFFORT) {
DCHECK_GT(num_running_best_effort_tasks_, 0U);
--num_running_best_effort_tasks_;
}
UpdateMinAllowedPriorityLockRequired();
}
void ThreadGroupImpl::IncrementTasksRunningLockRequired(TaskPriority priority) {
++num_running_tasks_;
DCHECK_LE(num_running_tasks_, max_tasks_);
DCHECK_LE(num_running_tasks_, kMaxNumberOfWorkers);
if (priority == TaskPriority::BEST_EFFORT) {
++num_running_best_effort_tasks_;
DCHECK_LE(num_running_best_effort_tasks_, num_running_tasks_);
DCHECK_LE(num_running_best_effort_tasks_, max_best_effort_tasks_);
}
UpdateMinAllowedPriorityLockRequired();
}
void ThreadGroupImpl::DecrementMaxTasksLockRequired(TaskPriority priority) {
DCHECK_GT(num_running_tasks_, 0U);
DCHECK_GT(max_tasks_, 0U);
--max_tasks_;
if (priority == TaskPriority::BEST_EFFORT &&
!after_start().fixed_max_best_effort_tasks) {
--max_best_effort_tasks_;
}
UpdateMinAllowedPriorityLockRequired();
}
void ThreadGroupImpl::IncrementMaxTasksLockRequired(TaskPriority priority) {
DCHECK_GT(num_running_tasks_, 0U);
++max_tasks_;
if (priority == TaskPriority::BEST_EFFORT &&
!after_start().fixed_max_best_effort_tasks) {
++max_best_effort_tasks_;
}
UpdateMinAllowedPriorityLockRequired();
}
ThreadGroupImpl::InitializedInStart::InitializedInStart() = default;
ThreadGroupImpl::InitializedInStart::~InitializedInStart() = default;
} // namespace internal
} // namespace base
|
/* Project Euler Problem 2: Even Fibonacci numbers
* Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
* 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
* By considering the terms in the Fibonaci sequence whose values do not exceed four million, find the sum of the even-valued terms.
*/
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<long> fib;
fib.push_back(1);
fib.push_back(2);
int n;
long next,sum=0;
while(1)
{
n=fib.size();
next=fib[n-1]+fib[n-2];
if(next>4000000)
{
break;
}
else
{
fib.push_back(next);
}
}
for(int i=0;i<n;i++)
{
if(fib[i]%2==0)
{
sum+=fib[i];
}
}
cout<<sum<<endl;
return 0;
}
|
// Copyright 2013 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.
#include "src/v8.h"
#if V8_TARGET_ARCH_ARM64
#include "src/bootstrapper.h"
#include "src/codegen.h"
#include "src/cpu-profiler.h"
#include "src/debug.h"
#include "src/isolate-inl.h"
#include "src/runtime.h"
namespace v8 {
namespace internal {
// Define a fake double underscore to use with the ASM_UNIMPLEMENTED macros.
#define __
MacroAssembler::MacroAssembler(Isolate* arg_isolate,
byte * buffer,
unsigned buffer_size)
: Assembler(arg_isolate, buffer, buffer_size),
generating_stub_(false),
#if DEBUG
allow_macro_instructions_(true),
#endif
has_frame_(false),
use_real_aborts_(true),
sp_(jssp),
tmp_list_(DefaultTmpList()),
fptmp_list_(DefaultFPTmpList()) {
if (isolate() != NULL) {
code_object_ = Handle<Object>(isolate()->heap()->undefined_value(),
isolate());
}
}
CPURegList MacroAssembler::DefaultTmpList() {
return CPURegList(ip0, ip1);
}
CPURegList MacroAssembler::DefaultFPTmpList() {
return CPURegList(fp_scratch1, fp_scratch2);
}
void MacroAssembler::LogicalMacro(const Register& rd,
const Register& rn,
const Operand& operand,
LogicalOp op) {
UseScratchRegisterScope temps(this);
if (operand.NeedsRelocation(this)) {
Register temp = temps.AcquireX();
Ldr(temp, operand.immediate());
Logical(rd, rn, temp, op);
} else if (operand.IsImmediate()) {
int64_t immediate = operand.ImmediateValue();
unsigned reg_size = rd.SizeInBits();
// If the operation is NOT, invert the operation and immediate.
if ((op & NOT) == NOT) {
op = static_cast<LogicalOp>(op & ~NOT);
immediate = ~immediate;
}
// Ignore the top 32 bits of an immediate if we're moving to a W register.
if (rd.Is32Bits()) {
// Check that the top 32 bits are consistent.
ASSERT(((immediate >> kWRegSizeInBits) == 0) ||
((immediate >> kWRegSizeInBits) == -1));
immediate &= kWRegMask;
}
ASSERT(rd.Is64Bits() || is_uint32(immediate));
// Special cases for all set or all clear immediates.
if (immediate == 0) {
switch (op) {
case AND:
Mov(rd, 0);
return;
case ORR: // Fall through.
case EOR:
Mov(rd, rn);
return;
case ANDS: // Fall through.
case BICS:
break;
default:
UNREACHABLE();
}
} else if ((rd.Is64Bits() && (immediate == -1L)) ||
(rd.Is32Bits() && (immediate == 0xffffffffL))) {
switch (op) {
case AND:
Mov(rd, rn);
return;
case ORR:
Mov(rd, immediate);
return;
case EOR:
Mvn(rd, rn);
return;
case ANDS: // Fall through.
case BICS:
break;
default:
UNREACHABLE();
}
}
unsigned n, imm_s, imm_r;
if (IsImmLogical(immediate, reg_size, &n, &imm_s, &imm_r)) {
// Immediate can be encoded in the instruction.
LogicalImmediate(rd, rn, n, imm_s, imm_r, op);
} else {
// Immediate can't be encoded: synthesize using move immediate.
Register temp = temps.AcquireSameSizeAs(rn);
Operand imm_operand = MoveImmediateForShiftedOp(temp, immediate);
if (rd.Is(csp)) {
// If rd is the stack pointer we cannot use it as the destination
// register so we use the temp register as an intermediate again.
Logical(temp, rn, imm_operand, op);
Mov(csp, temp);
AssertStackConsistency();
} else {
Logical(rd, rn, imm_operand, op);
}
}
} else if (operand.IsExtendedRegister()) {
ASSERT(operand.reg().SizeInBits() <= rd.SizeInBits());
// Add/sub extended supports shift <= 4. We want to support exactly the
// same modes here.
ASSERT(operand.shift_amount() <= 4);
ASSERT(operand.reg().Is64Bits() ||
((operand.extend() != UXTX) && (operand.extend() != SXTX)));
Register temp = temps.AcquireSameSizeAs(rn);
EmitExtendShift(temp, operand.reg(), operand.extend(),
operand.shift_amount());
Logical(rd, rn, temp, op);
} else {
// The operand can be encoded in the instruction.
ASSERT(operand.IsShiftedRegister());
Logical(rd, rn, operand, op);
}
}
void MacroAssembler::Mov(const Register& rd, uint64_t imm) {
ASSERT(allow_macro_instructions_);
ASSERT(is_uint32(imm) || is_int32(imm) || rd.Is64Bits());
ASSERT(!rd.IsZero());
// TODO(all) extend to support more immediates.
//
// Immediates on Aarch64 can be produced using an initial value, and zero to
// three move keep operations.
//
// Initial values can be generated with:
// 1. 64-bit move zero (movz).
// 2. 32-bit move inverted (movn).
// 3. 64-bit move inverted.
// 4. 32-bit orr immediate.
// 5. 64-bit orr immediate.
// Move-keep may then be used to modify each of the 16-bit half-words.
//
// The code below supports all five initial value generators, and
// applying move-keep operations to move-zero and move-inverted initial
// values.
// Try to move the immediate in one instruction, and if that fails, switch to
// using multiple instructions.
if (!TryOneInstrMoveImmediate(rd, imm)) {
unsigned reg_size = rd.SizeInBits();
// Generic immediate case. Imm will be represented by
// [imm3, imm2, imm1, imm0], where each imm is 16 bits.
// A move-zero or move-inverted is generated for the first non-zero or
// non-0xffff immX, and a move-keep for subsequent non-zero immX.
uint64_t ignored_halfword = 0;
bool invert_move = false;
// If the number of 0xffff halfwords is greater than the number of 0x0000
// halfwords, it's more efficient to use move-inverted.
if (CountClearHalfWords(~imm, reg_size) >
CountClearHalfWords(imm, reg_size)) {
ignored_halfword = 0xffffL;
invert_move = true;
}
// Mov instructions can't move immediate values into the stack pointer, so
// set up a temporary register, if needed.
UseScratchRegisterScope temps(this);
Register temp = rd.IsSP() ? temps.AcquireSameSizeAs(rd) : rd;
// Iterate through the halfwords. Use movn/movz for the first non-ignored
// halfword, and movk for subsequent halfwords.
ASSERT((reg_size % 16) == 0);
bool first_mov_done = false;
for (unsigned i = 0; i < (rd.SizeInBits() / 16); i++) {
uint64_t imm16 = (imm >> (16 * i)) & 0xffffL;
if (imm16 != ignored_halfword) {
if (!first_mov_done) {
if (invert_move) {
movn(temp, (~imm16) & 0xffffL, 16 * i);
} else {
movz(temp, imm16, 16 * i);
}
first_mov_done = true;
} else {
// Construct a wider constant.
movk(temp, imm16, 16 * i);
}
}
}
ASSERT(first_mov_done);
// Move the temporary if the original destination register was the stack
// pointer.
if (rd.IsSP()) {
mov(rd, temp);
AssertStackConsistency();
}
}
}
void MacroAssembler::Mov(const Register& rd,
const Operand& operand,
DiscardMoveMode discard_mode) {
ASSERT(allow_macro_instructions_);
ASSERT(!rd.IsZero());
// Provide a swap register for instructions that need to write into the
// system stack pointer (and can't do this inherently).
UseScratchRegisterScope temps(this);
Register dst = (rd.IsSP()) ? temps.AcquireSameSizeAs(rd) : rd;
if (operand.NeedsRelocation(this)) {
Ldr(dst, operand.immediate());
} else if (operand.IsImmediate()) {
// Call the macro assembler for generic immediates.
Mov(dst, operand.ImmediateValue());
} else if (operand.IsShiftedRegister() && (operand.shift_amount() != 0)) {
// Emit a shift instruction if moving a shifted register. This operation
// could also be achieved using an orr instruction (like orn used by Mvn),
// but using a shift instruction makes the disassembly clearer.
EmitShift(dst, operand.reg(), operand.shift(), operand.shift_amount());
} else if (operand.IsExtendedRegister()) {
// Emit an extend instruction if moving an extended register. This handles
// extend with post-shift operations, too.
EmitExtendShift(dst, operand.reg(), operand.extend(),
operand.shift_amount());
} else {
// Otherwise, emit a register move only if the registers are distinct, or
// if they are not X registers.
//
// Note that mov(w0, w0) is not a no-op because it clears the top word of
// x0. A flag is provided (kDiscardForSameWReg) if a move between the same W
// registers is not required to clear the top word of the X register. In
// this case, the instruction is discarded.
//
// If csp is an operand, add #0 is emitted, otherwise, orr #0.
if (!rd.Is(operand.reg()) || (rd.Is32Bits() &&
(discard_mode == kDontDiscardForSameWReg))) {
Assembler::mov(rd, operand.reg());
}
// This case can handle writes into the system stack pointer directly.
dst = rd;
}
// Copy the result to the system stack pointer.
if (!dst.Is(rd)) {
ASSERT(rd.IsSP());
Assembler::mov(rd, dst);
}
}
void MacroAssembler::Mvn(const Register& rd, const Operand& operand) {
ASSERT(allow_macro_instructions_);
if (operand.NeedsRelocation(this)) {
Ldr(rd, operand.immediate());
mvn(rd, rd);
} else if (operand.IsImmediate()) {
// Call the macro assembler for generic immediates.
Mov(rd, ~operand.ImmediateValue());
} else if (operand.IsExtendedRegister()) {
// Emit two instructions for the extend case. This differs from Mov, as
// the extend and invert can't be achieved in one instruction.
EmitExtendShift(rd, operand.reg(), operand.extend(),
operand.shift_amount());
mvn(rd, rd);
} else {
mvn(rd, operand);
}
}
unsigned MacroAssembler::CountClearHalfWords(uint64_t imm, unsigned reg_size) {
ASSERT((reg_size % 8) == 0);
int count = 0;
for (unsigned i = 0; i < (reg_size / 16); i++) {
if ((imm & 0xffff) == 0) {
count++;
}
imm >>= 16;
}
return count;
}
// The movz instruction can generate immediates containing an arbitrary 16-bit
// half-word, with remaining bits clear, eg. 0x00001234, 0x0000123400000000.
bool MacroAssembler::IsImmMovz(uint64_t imm, unsigned reg_size) {
ASSERT((reg_size == kXRegSizeInBits) || (reg_size == kWRegSizeInBits));
return CountClearHalfWords(imm, reg_size) >= ((reg_size / 16) - 1);
}
// The movn instruction can generate immediates containing an arbitrary 16-bit
// half-word, with remaining bits set, eg. 0xffff1234, 0xffff1234ffffffff.
bool MacroAssembler::IsImmMovn(uint64_t imm, unsigned reg_size) {
return IsImmMovz(~imm, reg_size);
}
void MacroAssembler::ConditionalCompareMacro(const Register& rn,
const Operand& operand,
StatusFlags nzcv,
Condition cond,
ConditionalCompareOp op) {
ASSERT((cond != al) && (cond != nv));
if (operand.NeedsRelocation(this)) {
UseScratchRegisterScope temps(this);
Register temp = temps.AcquireX();
Ldr(temp, operand.immediate());
ConditionalCompareMacro(rn, temp, nzcv, cond, op);
} else if ((operand.IsShiftedRegister() && (operand.shift_amount() == 0)) ||
(operand.IsImmediate() &&
IsImmConditionalCompare(operand.ImmediateValue()))) {
// The immediate can be encoded in the instruction, or the operand is an
// unshifted register: call the assembler.
ConditionalCompare(rn, operand, nzcv, cond, op);
} else {
// The operand isn't directly supported by the instruction: perform the
// operation on a temporary register.
UseScratchRegisterScope temps(this);
Register temp = temps.AcquireSameSizeAs(rn);
Mov(temp, operand);
ConditionalCompare(rn, temp, nzcv, cond, op);
}
}
void MacroAssembler::Csel(const Register& rd,
const Register& rn,
const Operand& operand,
Condition cond) {
ASSERT(allow_macro_instructions_);
ASSERT(!rd.IsZero());
ASSERT((cond != al) && (cond != nv));
if (operand.IsImmediate()) {
// Immediate argument. Handle special cases of 0, 1 and -1 using zero
// register.
int64_t imm = operand.ImmediateValue();
Register zr = AppropriateZeroRegFor(rn);
if (imm == 0) {
csel(rd, rn, zr, cond);
} else if (imm == 1) {
csinc(rd, rn, zr, cond);
} else if (imm == -1) {
csinv(rd, rn, zr, cond);
} else {
UseScratchRegisterScope temps(this);
Register temp = temps.AcquireSameSizeAs(rn);
Mov(temp, imm);
csel(rd, rn, temp, cond);
}
} else if (operand.IsShiftedRegister() && (operand.shift_amount() == 0)) {
// Unshifted register argument.
csel(rd, rn, operand.reg(), cond);
} else {
// All other arguments.
UseScratchRegisterScope temps(this);
Register temp = temps.AcquireSameSizeAs(rn);
Mov(temp, operand);
csel(rd, rn, temp, cond);
}
}
bool MacroAssembler::TryOneInstrMoveImmediate(const Register& dst,
int64_t imm) {
unsigned n, imm_s, imm_r;
int reg_size = dst.SizeInBits();
if (IsImmMovz(imm, reg_size) && !dst.IsSP()) {
// Immediate can be represented in a move zero instruction. Movz can't write
// to the stack pointer.
movz(dst, imm);
return true;
} else if (IsImmMovn(imm, reg_size) && !dst.IsSP()) {
// Immediate can be represented in a move not instruction. Movn can't write
// to the stack pointer.
movn(dst, dst.Is64Bits() ? ~imm : (~imm & kWRegMask));
return true;
} else if (IsImmLogical(imm, reg_size, &n, &imm_s, &imm_r)) {
// Immediate can be represented in a logical orr instruction.
LogicalImmediate(dst, AppropriateZeroRegFor(dst), n, imm_s, imm_r, ORR);
return true;
}
return false;
}
Operand MacroAssembler::MoveImmediateForShiftedOp(const Register& dst,
int64_t imm) {
int reg_size = dst.SizeInBits();
// Encode the immediate in a single move instruction, if possible.
if (TryOneInstrMoveImmediate(dst, imm)) {
// The move was successful; nothing to do here.
} else {
// Pre-shift the immediate to the least-significant bits of the register.
int shift_low = CountTrailingZeros(imm, reg_size);
int64_t imm_low = imm >> shift_low;
// Pre-shift the immediate to the most-significant bits of the register. We
// insert set bits in the least-significant bits, as this creates a
// different immediate that may be encodable using movn or orr-immediate.
// If this new immediate is encodable, the set bits will be eliminated by
// the post shift on the following instruction.
int shift_high = CountLeadingZeros(imm, reg_size);
int64_t imm_high = (imm << shift_high) | ((1 << shift_high) - 1);
if (TryOneInstrMoveImmediate(dst, imm_low)) {
// The new immediate has been moved into the destination's low bits:
// return a new leftward-shifting operand.
return Operand(dst, LSL, shift_low);
} else if (TryOneInstrMoveImmediate(dst, imm_high)) {
// The new immediate has been moved into the destination's high bits:
// return a new rightward-shifting operand.
return Operand(dst, LSR, shift_high);
} else {
// Use the generic move operation to set up the immediate.
Mov(dst, imm);
}
}
return Operand(dst);
}
void MacroAssembler::AddSubMacro(const Register& rd,
const Register& rn,
const Operand& operand,
FlagsUpdate S,
AddSubOp op) {
if (operand.IsZero() && rd.Is(rn) && rd.Is64Bits() && rn.Is64Bits() &&
!operand.NeedsRelocation(this) && (S == LeaveFlags)) {
// The instruction would be a nop. Avoid generating useless code.
return;
}
if (operand.NeedsRelocation(this)) {
UseScratchRegisterScope temps(this);
Register temp = temps.AcquireX();
Ldr(temp, operand.immediate());
AddSubMacro(rd, rn, temp, S, op);
} else if ((operand.IsImmediate() &&
!IsImmAddSub(operand.ImmediateValue())) ||
(rn.IsZero() && !operand.IsShiftedRegister()) ||
(operand.IsShiftedRegister() && (operand.shift() == ROR))) {
UseScratchRegisterScope temps(this);
Register temp = temps.AcquireSameSizeAs(rn);
if (operand.IsImmediate()) {
Operand imm_operand =
MoveImmediateForShiftedOp(temp, operand.ImmediateValue());
AddSub(rd, rn, imm_operand, S, op);
} else {
Mov(temp, operand);
AddSub(rd, rn, temp, S, op);
}
} else {
AddSub(rd, rn, operand, S, op);
}
}
void MacroAssembler::AddSubWithCarryMacro(const Register& rd,
const Register& rn,
const Operand& operand,
FlagsUpdate S,
AddSubWithCarryOp op) {
ASSERT(rd.SizeInBits() == rn.SizeInBits());
UseScratchRegisterScope temps(this);
if (operand.NeedsRelocation(this)) {
Register temp = temps.AcquireX();
Ldr(temp, operand.immediate());
AddSubWithCarryMacro(rd, rn, temp, S, op);
} else if (operand.IsImmediate() ||
(operand.IsShiftedRegister() && (operand.shift() == ROR))) {
// Add/sub with carry (immediate or ROR shifted register.)
Register temp = temps.AcquireSameSizeAs(rn);
Mov(temp, operand);
AddSubWithCarry(rd, rn, temp, S, op);
} else if (operand.IsShiftedRegister() && (operand.shift_amount() != 0)) {
// Add/sub with carry (shifted register).
ASSERT(operand.reg().SizeInBits() == rd.SizeInBits());
ASSERT(operand.shift() != ROR);
ASSERT(is_uintn(operand.shift_amount(),
rd.SizeInBits() == kXRegSizeInBits ? kXRegSizeInBitsLog2
: kWRegSizeInBitsLog2));
Register temp = temps.AcquireSameSizeAs(rn);
EmitShift(temp, operand.reg(), operand.shift(), operand.shift_amount());
AddSubWithCarry(rd, rn, temp, S, op);
} else if (operand.IsExtendedRegister()) {
// Add/sub with carry (extended register).
ASSERT(operand.reg().SizeInBits() <= rd.SizeInBits());
// Add/sub extended supports a shift <= 4. We want to support exactly the
// same modes.
ASSERT(operand.shift_amount() <= 4);
ASSERT(operand.reg().Is64Bits() ||
((operand.extend() != UXTX) && (operand.extend() != SXTX)));
Register temp = temps.AcquireSameSizeAs(rn);
EmitExtendShift(temp, operand.reg(), operand.extend(),
operand.shift_amount());
AddSubWithCarry(rd, rn, temp, S, op);
} else {
// The addressing mode is directly supported by the instruction.
AddSubWithCarry(rd, rn, operand, S, op);
}
}
void MacroAssembler::LoadStoreMacro(const CPURegister& rt,
const MemOperand& addr,
LoadStoreOp op) {
int64_t offset = addr.offset();
LSDataSize size = CalcLSDataSize(op);
// Check if an immediate offset fits in the immediate field of the
// appropriate instruction. If not, emit two instructions to perform
// the operation.
if (addr.IsImmediateOffset() && !IsImmLSScaled(offset, size) &&
!IsImmLSUnscaled(offset)) {
// Immediate offset that can't be encoded using unsigned or unscaled
// addressing modes.
UseScratchRegisterScope temps(this);
Register temp = temps.AcquireSameSizeAs(addr.base());
Mov(temp, addr.offset());
LoadStore(rt, MemOperand(addr.base(), temp), op);
} else if (addr.IsPostIndex() && !IsImmLSUnscaled(offset)) {
// Post-index beyond unscaled addressing range.
LoadStore(rt, MemOperand(addr.base()), op);
add(addr.base(), addr.base(), offset);
} else if (addr.IsPreIndex() && !IsImmLSUnscaled(offset)) {
// Pre-index beyond unscaled addressing range.
add(addr.base(), addr.base(), offset);
LoadStore(rt, MemOperand(addr.base()), op);
} else {
// Encodable in one load/store instruction.
LoadStore(rt, addr, op);
}
}
void MacroAssembler::Load(const Register& rt,
const MemOperand& addr,
Representation r) {
ASSERT(!r.IsDouble());
if (r.IsInteger8()) {
Ldrsb(rt, addr);
} else if (r.IsUInteger8()) {
Ldrb(rt, addr);
} else if (r.IsInteger16()) {
Ldrsh(rt, addr);
} else if (r.IsUInteger16()) {
Ldrh(rt, addr);
} else if (r.IsInteger32()) {
Ldr(rt.W(), addr);
} else {
ASSERT(rt.Is64Bits());
Ldr(rt, addr);
}
}
void MacroAssembler::Store(const Register& rt,
const MemOperand& addr,
Representation r) {
ASSERT(!r.IsDouble());
if (r.IsInteger8() || r.IsUInteger8()) {
Strb(rt, addr);
} else if (r.IsInteger16() || r.IsUInteger16()) {
Strh(rt, addr);
} else if (r.IsInteger32()) {
Str(rt.W(), addr);
} else {
ASSERT(rt.Is64Bits());
if (r.IsHeapObject()) {
AssertNotSmi(rt);
} else if (r.IsSmi()) {
AssertSmi(rt);
}
Str(rt, addr);
}
}
bool MacroAssembler::NeedExtraInstructionsOrRegisterBranch(
Label *label, ImmBranchType b_type) {
bool need_longer_range = false;
// There are two situations in which we care about the offset being out of
// range:
// - The label is bound but too far away.
// - The label is not bound but linked, and the previous branch
// instruction in the chain is too far away.
if (label->is_bound() || label->is_linked()) {
need_longer_range =
!Instruction::IsValidImmPCOffset(b_type, label->pos() - pc_offset());
}
if (!need_longer_range && !label->is_bound()) {
int max_reachable_pc = pc_offset() + Instruction::ImmBranchRange(b_type);
unresolved_branches_.insert(
std::pair<int, FarBranchInfo>(max_reachable_pc,
FarBranchInfo(pc_offset(), label)));
// Also maintain the next pool check.
next_veneer_pool_check_ =
Min(next_veneer_pool_check_,
max_reachable_pc - kVeneerDistanceCheckMargin);
}
return need_longer_range;
}
void MacroAssembler::Adr(const Register& rd, Label* label, AdrHint hint) {
ASSERT(allow_macro_instructions_);
ASSERT(!rd.IsZero());
if (hint == kAdrNear) {
adr(rd, label);
return;
}
ASSERT(hint == kAdrFar);
if (label->is_bound()) {
int label_offset = label->pos() - pc_offset();
if (Instruction::IsValidPCRelOffset(label_offset)) {
adr(rd, label);
} else {
ASSERT(label_offset <= 0);
int min_adr_offset = -(1 << (Instruction::ImmPCRelRangeBitwidth - 1));
adr(rd, min_adr_offset);
Add(rd, rd, label_offset - min_adr_offset);
}
} else {
UseScratchRegisterScope temps(this);
Register scratch = temps.AcquireX();
InstructionAccurateScope scope(
this, PatchingAssembler::kAdrFarPatchableNInstrs);
adr(rd, label);
for (int i = 0; i < PatchingAssembler::kAdrFarPatchableNNops; ++i) {
nop(ADR_FAR_NOP);
}
movz(scratch, 0);
}
}
void MacroAssembler::B(Label* label, BranchType type, Register reg, int bit) {
ASSERT((reg.Is(NoReg) || type >= kBranchTypeFirstUsingReg) &&
(bit == -1 || type >= kBranchTypeFirstUsingBit));
if (kBranchTypeFirstCondition <= type && type <= kBranchTypeLastCondition) {
B(static_cast<Condition>(type), label);
} else {
switch (type) {
case always: B(label); break;
case never: break;
case reg_zero: Cbz(reg, label); break;
case reg_not_zero: Cbnz(reg, label); break;
case reg_bit_clear: Tbz(reg, bit, label); break;
case reg_bit_set: Tbnz(reg, bit, label); break;
default:
UNREACHABLE();
}
}
}
void MacroAssembler::B(Label* label, Condition cond) {
ASSERT(allow_macro_instructions_);
ASSERT((cond != al) && (cond != nv));
Label done;
bool need_extra_instructions =
NeedExtraInstructionsOrRegisterBranch(label, CondBranchType);
if (need_extra_instructions) {
b(&done, NegateCondition(cond));
B(label);
} else {
b(label, cond);
}
bind(&done);
}
void MacroAssembler::Tbnz(const Register& rt, unsigned bit_pos, Label* label) {
ASSERT(allow_macro_instructions_);
Label done;
bool need_extra_instructions =
NeedExtraInstructionsOrRegisterBranch(label, TestBranchType);
if (need_extra_instructions) {
tbz(rt, bit_pos, &done);
B(label);
} else {
tbnz(rt, bit_pos, label);
}
bind(&done);
}
void MacroAssembler::Tbz(const Register& rt, unsigned bit_pos, Label* label) {
ASSERT(allow_macro_instructions_);
Label done;
bool need_extra_instructions =
NeedExtraInstructionsOrRegisterBranch(label, TestBranchType);
if (need_extra_instructions) {
tbnz(rt, bit_pos, &done);
B(label);
} else {
tbz(rt, bit_pos, label);
}
bind(&done);
}
void MacroAssembler::Cbnz(const Register& rt, Label* label) {
ASSERT(allow_macro_instructions_);
Label done;
bool need_extra_instructions =
NeedExtraInstructionsOrRegisterBranch(label, CompareBranchType);
if (need_extra_instructions) {
cbz(rt, &done);
B(label);
} else {
cbnz(rt, label);
}
bind(&done);
}
void MacroAssembler::Cbz(const Register& rt, Label* label) {
ASSERT(allow_macro_instructions_);
Label done;
bool need_extra_instructions =
NeedExtraInstructionsOrRegisterBranch(label, CompareBranchType);
if (need_extra_instructions) {
cbnz(rt, &done);
B(label);
} else {
cbz(rt, label);
}
bind(&done);
}
// Pseudo-instructions.
void MacroAssembler::Abs(const Register& rd, const Register& rm,
Label* is_not_representable,
Label* is_representable) {
ASSERT(allow_macro_instructions_);
ASSERT(AreSameSizeAndType(rd, rm));
Cmp(rm, 1);
Cneg(rd, rm, lt);
// If the comparison sets the v flag, the input was the smallest value
// representable by rm, and the mathematical result of abs(rm) is not
// representable using two's complement.
if ((is_not_representable != NULL) && (is_representable != NULL)) {
B(is_not_representable, vs);
B(is_representable);
} else if (is_not_representable != NULL) {
B(is_not_representable, vs);
} else if (is_representable != NULL) {
B(is_representable, vc);
}
}
// Abstracted stack operations.
void MacroAssembler::Push(const CPURegister& src0, const CPURegister& src1,
const CPURegister& src2, const CPURegister& src3) {
ASSERT(AreSameSizeAndType(src0, src1, src2, src3));
int count = 1 + src1.IsValid() + src2.IsValid() + src3.IsValid();
int size = src0.SizeInBytes();
PushPreamble(count, size);
PushHelper(count, size, src0, src1, src2, src3);
}
void MacroAssembler::Push(const CPURegister& src0, const CPURegister& src1,
const CPURegister& src2, const CPURegister& src3,
const CPURegister& src4, const CPURegister& src5,
const CPURegister& src6, const CPURegister& src7) {
ASSERT(AreSameSizeAndType(src0, src1, src2, src3, src4, src5, src6, src7));
int count = 5 + src5.IsValid() + src6.IsValid() + src6.IsValid();
int size = src0.SizeInBytes();
PushPreamble(count, size);
PushHelper(4, size, src0, src1, src2, src3);
PushHelper(count - 4, size, src4, src5, src6, src7);
}
void MacroAssembler::Pop(const CPURegister& dst0, const CPURegister& dst1,
const CPURegister& dst2, const CPURegister& dst3) {
// It is not valid to pop into the same register more than once in one
// instruction, not even into the zero register.
ASSERT(!AreAliased(dst0, dst1, dst2, dst3));
ASSERT(AreSameSizeAndType(dst0, dst1, dst2, dst3));
ASSERT(dst0.IsValid());
int count = 1 + dst1.IsValid() + dst2.IsValid() + dst3.IsValid();
int size = dst0.SizeInBytes();
PopHelper(count, size, dst0, dst1, dst2, dst3);
PopPostamble(count, size);
}
void MacroAssembler::Push(const Register& src0, const FPRegister& src1) {
int size = src0.SizeInBytes() + src1.SizeInBytes();
PushPreamble(size);
// Reserve room for src0 and push src1.
str(src1, MemOperand(StackPointer(), -size, PreIndex));
// Fill the gap with src0.
str(src0, MemOperand(StackPointer(), src1.SizeInBytes()));
}
void MacroAssembler::PushPopQueue::PushQueued(
PreambleDirective preamble_directive) {
if (queued_.empty()) return;
if (preamble_directive == WITH_PREAMBLE) {
masm_->PushPreamble(size_);
}
int count = queued_.size();
int index = 0;
while (index < count) {
// PushHelper can only handle registers with the same size and type, and it
// can handle only four at a time. Batch them up accordingly.
CPURegister batch[4] = {NoReg, NoReg, NoReg, NoReg};
int batch_index = 0;
do {
batch[batch_index++] = queued_[index++];
} while ((batch_index < 4) && (index < count) &&
batch[0].IsSameSizeAndType(queued_[index]));
masm_->PushHelper(batch_index, batch[0].SizeInBytes(),
batch[0], batch[1], batch[2], batch[3]);
}
queued_.clear();
}
void MacroAssembler::PushPopQueue::PopQueued() {
if (queued_.empty()) return;
int count = queued_.size();
int index = 0;
while (index < count) {
// PopHelper can only handle registers with the same size and type, and it
// can handle only four at a time. Batch them up accordingly.
CPURegister batch[4] = {NoReg, NoReg, NoReg, NoReg};
int batch_index = 0;
do {
batch[batch_index++] = queued_[index++];
} while ((batch_index < 4) && (index < count) &&
batch[0].IsSameSizeAndType(queued_[index]));
masm_->PopHelper(batch_index, batch[0].SizeInBytes(),
batch[0], batch[1], batch[2], batch[3]);
}
masm_->PopPostamble(size_);
queued_.clear();
}
void MacroAssembler::PushCPURegList(CPURegList registers) {
int size = registers.RegisterSizeInBytes();
PushPreamble(registers.Count(), size);
// Push up to four registers at a time because if the current stack pointer is
// csp and reg_size is 32, registers must be pushed in blocks of four in order
// to maintain the 16-byte alignment for csp.
while (!registers.IsEmpty()) {
int count_before = registers.Count();
const CPURegister& src0 = registers.PopHighestIndex();
const CPURegister& src1 = registers.PopHighestIndex();
const CPURegister& src2 = registers.PopHighestIndex();
const CPURegister& src3 = registers.PopHighestIndex();
int count = count_before - registers.Count();
PushHelper(count, size, src0, src1, src2, src3);
}
}
void MacroAssembler::PopCPURegList(CPURegList registers) {
int size = registers.RegisterSizeInBytes();
// Pop up to four registers at a time because if the current stack pointer is
// csp and reg_size is 32, registers must be pushed in blocks of four in
// order to maintain the 16-byte alignment for csp.
while (!registers.IsEmpty()) {
int count_before = registers.Count();
const CPURegister& dst0 = registers.PopLowestIndex();
const CPURegister& dst1 = registers.PopLowestIndex();
const CPURegister& dst2 = registers.PopLowestIndex();
const CPURegister& dst3 = registers.PopLowestIndex();
int count = count_before - registers.Count();
PopHelper(count, size, dst0, dst1, dst2, dst3);
}
PopPostamble(registers.Count(), size);
}
void MacroAssembler::PushMultipleTimes(CPURegister src, int count) {
int size = src.SizeInBytes();
PushPreamble(count, size);
if (FLAG_optimize_for_size && count > 8) {
UseScratchRegisterScope temps(this);
Register temp = temps.AcquireX();
Label loop;
__ Mov(temp, count / 2);
__ Bind(&loop);
PushHelper(2, size, src, src, NoReg, NoReg);
__ Subs(temp, temp, 1);
__ B(ne, &loop);
count %= 2;
}
// Push up to four registers at a time if possible because if the current
// stack pointer is csp and the register size is 32, registers must be pushed
// in blocks of four in order to maintain the 16-byte alignment for csp.
while (count >= 4) {
PushHelper(4, size, src, src, src, src);
count -= 4;
}
if (count >= 2) {
PushHelper(2, size, src, src, NoReg, NoReg);
count -= 2;
}
if (count == 1) {
PushHelper(1, size, src, NoReg, NoReg, NoReg);
count -= 1;
}
ASSERT(count == 0);
}
void MacroAssembler::PushMultipleTimes(CPURegister src, Register count) {
PushPreamble(Operand(count, UXTW, WhichPowerOf2(src.SizeInBytes())));
UseScratchRegisterScope temps(this);
Register temp = temps.AcquireSameSizeAs(count);
if (FLAG_optimize_for_size) {
Label loop, done;
Subs(temp, count, 1);
B(mi, &done);
// Push all registers individually, to save code size.
Bind(&loop);
Subs(temp, temp, 1);
PushHelper(1, src.SizeInBytes(), src, NoReg, NoReg, NoReg);
B(pl, &loop);
Bind(&done);
} else {
Label loop, leftover2, leftover1, done;
Subs(temp, count, 4);
B(mi, &leftover2);
// Push groups of four first.
Bind(&loop);
Subs(temp, temp, 4);
PushHelper(4, src.SizeInBytes(), src, src, src, src);
B(pl, &loop);
// Push groups of two.
Bind(&leftover2);
Tbz(count, 1, &leftover1);
PushHelper(2, src.SizeInBytes(), src, src, NoReg, NoReg);
// Push the last one (if required).
Bind(&leftover1);
Tbz(count, 0, &done);
PushHelper(1, src.SizeInBytes(), src, NoReg, NoReg, NoReg);
Bind(&done);
}
}
void MacroAssembler::PushHelper(int count, int size,
const CPURegister& src0,
const CPURegister& src1,
const CPURegister& src2,
const CPURegister& src3) {
// Ensure that we don't unintentially modify scratch or debug registers.
InstructionAccurateScope scope(this);
ASSERT(AreSameSizeAndType(src0, src1, src2, src3));
ASSERT(size == src0.SizeInBytes());
// When pushing multiple registers, the store order is chosen such that
// Push(a, b) is equivalent to Push(a) followed by Push(b).
switch (count) {
case 1:
ASSERT(src1.IsNone() && src2.IsNone() && src3.IsNone());
str(src0, MemOperand(StackPointer(), -1 * size, PreIndex));
break;
case 2:
ASSERT(src2.IsNone() && src3.IsNone());
stp(src1, src0, MemOperand(StackPointer(), -2 * size, PreIndex));
break;
case 3:
ASSERT(src3.IsNone());
stp(src2, src1, MemOperand(StackPointer(), -3 * size, PreIndex));
str(src0, MemOperand(StackPointer(), 2 * size));
break;
case 4:
// Skip over 4 * size, then fill in the gap. This allows four W registers
// to be pushed using csp, whilst maintaining 16-byte alignment for csp
// at all times.
stp(src3, src2, MemOperand(StackPointer(), -4 * size, PreIndex));
stp(src1, src0, MemOperand(StackPointer(), 2 * size));
break;
default:
UNREACHABLE();
}
}
void MacroAssembler::PopHelper(int count, int size,
const CPURegister& dst0,
const CPURegister& dst1,
const CPURegister& dst2,
const CPURegister& dst3) {
// Ensure that we don't unintentially modify scratch or debug registers.
InstructionAccurateScope scope(this);
ASSERT(AreSameSizeAndType(dst0, dst1, dst2, dst3));
ASSERT(size == dst0.SizeInBytes());
// When popping multiple registers, the load order is chosen such that
// Pop(a, b) is equivalent to Pop(a) followed by Pop(b).
switch (count) {
case 1:
ASSERT(dst1.IsNone() && dst2.IsNone() && dst3.IsNone());
ldr(dst0, MemOperand(StackPointer(), 1 * size, PostIndex));
break;
case 2:
ASSERT(dst2.IsNone() && dst3.IsNone());
ldp(dst0, dst1, MemOperand(StackPointer(), 2 * size, PostIndex));
break;
case 3:
ASSERT(dst3.IsNone());
ldr(dst2, MemOperand(StackPointer(), 2 * size));
ldp(dst0, dst1, MemOperand(StackPointer(), 3 * size, PostIndex));
break;
case 4:
// Load the higher addresses first, then load the lower addresses and
// skip the whole block in the second instruction. This allows four W
// registers to be popped using csp, whilst maintaining 16-byte alignment
// for csp at all times.
ldp(dst2, dst3, MemOperand(StackPointer(), 2 * size));
ldp(dst0, dst1, MemOperand(StackPointer(), 4 * size, PostIndex));
break;
default:
UNREACHABLE();
}
}
void MacroAssembler::PushPreamble(Operand total_size) {
if (csp.Is(StackPointer())) {
// If the current stack pointer is csp, then it must be aligned to 16 bytes
// on entry and the total size of the specified registers must also be a
// multiple of 16 bytes.
if (total_size.IsImmediate()) {
ASSERT((total_size.ImmediateValue() % 16) == 0);
}
// Don't check access size for non-immediate sizes. It's difficult to do
// well, and it will be caught by hardware (or the simulator) anyway.
} else {
// Even if the current stack pointer is not the system stack pointer (csp),
// the system stack pointer will still be modified in order to comply with
// ABI rules about accessing memory below the system stack pointer.
BumpSystemStackPointer(total_size);
}
}
void MacroAssembler::PopPostamble(Operand total_size) {
if (csp.Is(StackPointer())) {
// If the current stack pointer is csp, then it must be aligned to 16 bytes
// on entry and the total size of the specified registers must also be a
// multiple of 16 bytes.
if (total_size.IsImmediate()) {
ASSERT((total_size.ImmediateValue() % 16) == 0);
}
// Don't check access size for non-immediate sizes. It's difficult to do
// well, and it will be caught by hardware (or the simulator) anyway.
} else if (emit_debug_code()) {
// It is safe to leave csp where it is when unwinding the JavaScript stack,
// but if we keep it matching StackPointer, the simulator can detect memory
// accesses in the now-free part of the stack.
SyncSystemStackPointer();
}
}
void MacroAssembler::Poke(const CPURegister& src, const Operand& offset) {
if (offset.IsImmediate()) {
ASSERT(offset.ImmediateValue() >= 0);
} else if (emit_debug_code()) {
Cmp(xzr, offset);
Check(le, kStackAccessBelowStackPointer);
}
Str(src, MemOperand(StackPointer(), offset));
}
void MacroAssembler::Peek(const CPURegister& dst, const Operand& offset) {
if (offset.IsImmediate()) {
ASSERT(offset.ImmediateValue() >= 0);
} else if (emit_debug_code()) {
Cmp(xzr, offset);
Check(le, kStackAccessBelowStackPointer);
}
Ldr(dst, MemOperand(StackPointer(), offset));
}
void MacroAssembler::PokePair(const CPURegister& src1,
const CPURegister& src2,
int offset) {
ASSERT(AreSameSizeAndType(src1, src2));
ASSERT((offset >= 0) && ((offset % src1.SizeInBytes()) == 0));
Stp(src1, src2, MemOperand(StackPointer(), offset));
}
void MacroAssembler::PeekPair(const CPURegister& dst1,
const CPURegister& dst2,
int offset) {
ASSERT(AreSameSizeAndType(dst1, dst2));
ASSERT((offset >= 0) && ((offset % dst1.SizeInBytes()) == 0));
Ldp(dst1, dst2, MemOperand(StackPointer(), offset));
}
void MacroAssembler::PushCalleeSavedRegisters() {
// Ensure that the macro-assembler doesn't use any scratch registers.
InstructionAccurateScope scope(this);
// This method must not be called unless the current stack pointer is the
// system stack pointer (csp).
ASSERT(csp.Is(StackPointer()));
MemOperand tos(csp, -2 * kXRegSize, PreIndex);
stp(d14, d15, tos);
stp(d12, d13, tos);
stp(d10, d11, tos);
stp(d8, d9, tos);
stp(x29, x30, tos);
stp(x27, x28, tos); // x28 = jssp
stp(x25, x26, tos);
stp(x23, x24, tos);
stp(x21, x22, tos);
stp(x19, x20, tos);
}
void MacroAssembler::PopCalleeSavedRegisters() {
// Ensure that the macro-assembler doesn't use any scratch registers.
InstructionAccurateScope scope(this);
// This method must not be called unless the current stack pointer is the
// system stack pointer (csp).
ASSERT(csp.Is(StackPointer()));
MemOperand tos(csp, 2 * kXRegSize, PostIndex);
ldp(x19, x20, tos);
ldp(x21, x22, tos);
ldp(x23, x24, tos);
ldp(x25, x26, tos);
ldp(x27, x28, tos); // x28 = jssp
ldp(x29, x30, tos);
ldp(d8, d9, tos);
ldp(d10, d11, tos);
ldp(d12, d13, tos);
ldp(d14, d15, tos);
}
void MacroAssembler::AssertStackConsistency() {
// Avoid emitting code when !use_real_abort() since non-real aborts cause too
// much code to be generated.
if (emit_debug_code() && use_real_aborts()) {
if (csp.Is(StackPointer()) || CpuFeatures::IsSupported(ALWAYS_ALIGN_CSP)) {
// Always check the alignment of csp if ALWAYS_ALIGN_CSP is true. We
// can't check the alignment of csp without using a scratch register (or
// clobbering the flags), but the processor (or simulator) will abort if
// it is not properly aligned during a load.
ldr(xzr, MemOperand(csp, 0));
}
if (FLAG_enable_slow_asserts && !csp.Is(StackPointer())) {
Label ok;
// Check that csp <= StackPointer(), preserving all registers and NZCV.
sub(StackPointer(), csp, StackPointer());
cbz(StackPointer(), &ok); // Ok if csp == StackPointer().
tbnz(StackPointer(), kXSignBit, &ok); // Ok if csp < StackPointer().
// Avoid generating AssertStackConsistency checks for the Push in Abort.
{ DontEmitDebugCodeScope dont_emit_debug_code_scope(this);
Abort(kTheCurrentStackPointerIsBelowCsp);
}
bind(&ok);
// Restore StackPointer().
sub(StackPointer(), csp, StackPointer());
}
}
}
void MacroAssembler::AssertFPCRState(Register fpcr) {
if (emit_debug_code()) {
Label unexpected_mode, done;
UseScratchRegisterScope temps(this);
if (fpcr.IsNone()) {
fpcr = temps.AcquireX();
Mrs(fpcr, FPCR);
}
// Settings overridden by ConfiugreFPCR():
// - Assert that default-NaN mode is set.
Tbz(fpcr, DN_offset, &unexpected_mode);
// Settings left to their default values:
// - Assert that flush-to-zero is not set.
Tbnz(fpcr, FZ_offset, &unexpected_mode);
// - Assert that the rounding mode is nearest-with-ties-to-even.
STATIC_ASSERT(FPTieEven == 0);
Tst(fpcr, RMode_mask);
B(eq, &done);
Bind(&unexpected_mode);
Abort(kUnexpectedFPCRMode);
Bind(&done);
}
}
void MacroAssembler::ConfigureFPCR() {
UseScratchRegisterScope temps(this);
Register fpcr = temps.AcquireX();
Mrs(fpcr, FPCR);
// If necessary, enable default-NaN mode. The default values of the other FPCR
// options should be suitable, and AssertFPCRState will verify that.
Label no_write_required;
Tbnz(fpcr, DN_offset, &no_write_required);
Orr(fpcr, fpcr, DN_mask);
Msr(FPCR, fpcr);
Bind(&no_write_required);
AssertFPCRState(fpcr);
}
void MacroAssembler::CanonicalizeNaN(const FPRegister& dst,
const FPRegister& src) {
AssertFPCRState();
// With DN=1 and RMode=FPTieEven, subtracting 0.0 preserves all inputs except
// for NaNs, which become the default NaN. We use fsub rather than fadd
// because sub preserves -0.0 inputs: -0.0 + 0.0 = 0.0, but -0.0 - 0.0 = -0.0.
Fsub(dst, src, fp_zero);
}
void MacroAssembler::LoadRoot(CPURegister destination,
Heap::RootListIndex index) {
// TODO(jbramley): Most root values are constants, and can be synthesized
// without a load. Refer to the ARM back end for details.
Ldr(destination, MemOperand(root, index << kPointerSizeLog2));
}
void MacroAssembler::StoreRoot(Register source,
Heap::RootListIndex index) {
Str(source, MemOperand(root, index << kPointerSizeLog2));
}
void MacroAssembler::LoadTrueFalseRoots(Register true_root,
Register false_root) {
STATIC_ASSERT((Heap::kTrueValueRootIndex + 1) == Heap::kFalseValueRootIndex);
Ldp(true_root, false_root,
MemOperand(root, Heap::kTrueValueRootIndex << kPointerSizeLog2));
}
void MacroAssembler::LoadHeapObject(Register result,
Handle<HeapObject> object) {
AllowDeferredHandleDereference using_raw_address;
if (isolate()->heap()->InNewSpace(*object)) {
Handle<Cell> cell = isolate()->factory()->NewCell(object);
Mov(result, Operand(cell));
Ldr(result, FieldMemOperand(result, Cell::kValueOffset));
} else {
Mov(result, Operand(object));
}
}
void MacroAssembler::LoadInstanceDescriptors(Register map,
Register descriptors) {
Ldr(descriptors, FieldMemOperand(map, Map::kDescriptorsOffset));
}
void MacroAssembler::NumberOfOwnDescriptors(Register dst, Register map) {
Ldr(dst, FieldMemOperand(map, Map::kBitField3Offset));
DecodeField<Map::NumberOfOwnDescriptorsBits>(dst);
}
void MacroAssembler::EnumLengthUntagged(Register dst, Register map) {
STATIC_ASSERT(Map::EnumLengthBits::kShift == 0);
Ldrsw(dst, FieldMemOperand(map, Map::kBitField3Offset));
And(dst, dst, Map::EnumLengthBits::kMask);
}
void MacroAssembler::EnumLengthSmi(Register dst, Register map) {
EnumLengthUntagged(dst, map);
SmiTag(dst, dst);
}
void MacroAssembler::CheckEnumCache(Register object,
Register null_value,
Register scratch0,
Register scratch1,
Register scratch2,
Register scratch3,
Label* call_runtime) {
ASSERT(!AreAliased(object, null_value, scratch0, scratch1, scratch2,
scratch3));
Register empty_fixed_array_value = scratch0;
Register current_object = scratch1;
LoadRoot(empty_fixed_array_value, Heap::kEmptyFixedArrayRootIndex);
Label next, start;
Mov(current_object, object);
// Check if the enum length field is properly initialized, indicating that
// there is an enum cache.
Register map = scratch2;
Register enum_length = scratch3;
Ldr(map, FieldMemOperand(current_object, HeapObject::kMapOffset));
EnumLengthUntagged(enum_length, map);
Cmp(enum_length, kInvalidEnumCacheSentinel);
B(eq, call_runtime);
B(&start);
Bind(&next);
Ldr(map, FieldMemOperand(current_object, HeapObject::kMapOffset));
// For all objects but the receiver, check that the cache is empty.
EnumLengthUntagged(enum_length, map);
Cbnz(enum_length, call_runtime);
Bind(&start);
// Check that there are no elements. Register current_object contains the
// current JS object we've reached through the prototype chain.
Label no_elements;
Ldr(current_object, FieldMemOperand(current_object,
JSObject::kElementsOffset));
Cmp(current_object, empty_fixed_array_value);
B(eq, &no_elements);
// Second chance, the object may be using the empty slow element dictionary.
CompareRoot(current_object, Heap::kEmptySlowElementDictionaryRootIndex);
B(ne, call_runtime);
Bind(&no_elements);
Ldr(current_object, FieldMemOperand(map, Map::kPrototypeOffset));
Cmp(current_object, null_value);
B(ne, &next);
}
void MacroAssembler::TestJSArrayForAllocationMemento(Register receiver,
Register scratch1,
Register scratch2,
Label* no_memento_found) {
ExternalReference new_space_start =
ExternalReference::new_space_start(isolate());
ExternalReference new_space_allocation_top =
ExternalReference::new_space_allocation_top_address(isolate());
Add(scratch1, receiver,
JSArray::kSize + AllocationMemento::kSize - kHeapObjectTag);
Cmp(scratch1, new_space_start);
B(lt, no_memento_found);
Mov(scratch2, new_space_allocation_top);
Ldr(scratch2, MemOperand(scratch2));
Cmp(scratch1, scratch2);
B(gt, no_memento_found);
Ldr(scratch1, MemOperand(scratch1, -AllocationMemento::kSize));
Cmp(scratch1,
Operand(isolate()->factory()->allocation_memento_map()));
}
void MacroAssembler::JumpToHandlerEntry(Register exception,
Register object,
Register state,
Register scratch1,
Register scratch2) {
// Handler expects argument in x0.
ASSERT(exception.Is(x0));
// Compute the handler entry address and jump to it. The handler table is
// a fixed array of (smi-tagged) code offsets.
Ldr(scratch1, FieldMemOperand(object, Code::kHandlerTableOffset));
Add(scratch1, scratch1, FixedArray::kHeaderSize - kHeapObjectTag);
STATIC_ASSERT(StackHandler::kKindWidth < kPointerSizeLog2);
Lsr(scratch2, state, StackHandler::kKindWidth);
Ldr(scratch2, MemOperand(scratch1, scratch2, LSL, kPointerSizeLog2));
Add(scratch1, object, Code::kHeaderSize - kHeapObjectTag);
Add(scratch1, scratch1, Operand::UntagSmi(scratch2));
Br(scratch1);
}
void MacroAssembler::InNewSpace(Register object,
Condition cond,
Label* branch) {
ASSERT(cond == eq || cond == ne);
UseScratchRegisterScope temps(this);
Register temp = temps.AcquireX();
And(temp, object, ExternalReference::new_space_mask(isolate()));
Cmp(temp, ExternalReference::new_space_start(isolate()));
B(cond, branch);
}
void MacroAssembler::Throw(Register value,
Register scratch1,
Register scratch2,
Register scratch3,
Register scratch4) {
// Adjust this code if not the case.
STATIC_ASSERT(StackHandlerConstants::kSize == 5 * kPointerSize);
STATIC_ASSERT(StackHandlerConstants::kNextOffset == 0);
STATIC_ASSERT(StackHandlerConstants::kCodeOffset == 1 * kPointerSize);
STATIC_ASSERT(StackHandlerConstants::kStateOffset == 2 * kPointerSize);
STATIC_ASSERT(StackHandlerConstants::kContextOffset == 3 * kPointerSize);
STATIC_ASSERT(StackHandlerConstants::kFPOffset == 4 * kPointerSize);
// The handler expects the exception in x0.
ASSERT(value.Is(x0));
// Drop the stack pointer to the top of the top handler.
ASSERT(jssp.Is(StackPointer()));
Mov(scratch1, Operand(ExternalReference(Isolate::kHandlerAddress,
isolate())));
Ldr(jssp, MemOperand(scratch1));
// Restore the next handler.
Pop(scratch2);
Str(scratch2, MemOperand(scratch1));
// Get the code object and state. Restore the context and frame pointer.
Register object = scratch1;
Register state = scratch2;
Pop(object, state, cp, fp);
// If the handler is a JS frame, restore the context to the frame.
// (kind == ENTRY) == (fp == 0) == (cp == 0), so we could test either fp
// or cp.
Label not_js_frame;
Cbz(cp, ¬_js_frame);
Str(cp, MemOperand(fp, StandardFrameConstants::kContextOffset));
Bind(¬_js_frame);
JumpToHandlerEntry(value, object, state, scratch3, scratch4);
}
void MacroAssembler::ThrowUncatchable(Register value,
Register scratch1,
Register scratch2,
Register scratch3,
Register scratch4) {
// Adjust this code if not the case.
STATIC_ASSERT(StackHandlerConstants::kSize == 5 * kPointerSize);
STATIC_ASSERT(StackHandlerConstants::kNextOffset == 0 * kPointerSize);
STATIC_ASSERT(StackHandlerConstants::kCodeOffset == 1 * kPointerSize);
STATIC_ASSERT(StackHandlerConstants::kStateOffset == 2 * kPointerSize);
STATIC_ASSERT(StackHandlerConstants::kContextOffset == 3 * kPointerSize);
STATIC_ASSERT(StackHandlerConstants::kFPOffset == 4 * kPointerSize);
// The handler expects the exception in x0.
ASSERT(value.Is(x0));
// Drop the stack pointer to the top of the top stack handler.
ASSERT(jssp.Is(StackPointer()));
Mov(scratch1, Operand(ExternalReference(Isolate::kHandlerAddress,
isolate())));
Ldr(jssp, MemOperand(scratch1));
// Unwind the handlers until the ENTRY handler is found.
Label fetch_next, check_kind;
B(&check_kind);
Bind(&fetch_next);
Peek(jssp, StackHandlerConstants::kNextOffset);
Bind(&check_kind);
STATIC_ASSERT(StackHandler::JS_ENTRY == 0);
Peek(scratch2, StackHandlerConstants::kStateOffset);
TestAndBranchIfAnySet(scratch2, StackHandler::KindField::kMask, &fetch_next);
// Set the top handler address to next handler past the top ENTRY handler.
Pop(scratch2);
Str(scratch2, MemOperand(scratch1));
// Get the code object and state. Clear the context and frame pointer (0 was
// saved in the handler).
Register object = scratch1;
Register state = scratch2;
Pop(object, state, cp, fp);
JumpToHandlerEntry(value, object, state, scratch3, scratch4);
}
void MacroAssembler::SmiAbs(const Register& smi, Label* slow) {
ASSERT(smi.Is64Bits());
Abs(smi, smi, slow);
}
void MacroAssembler::AssertSmi(Register object, BailoutReason reason) {
if (emit_debug_code()) {
STATIC_ASSERT(kSmiTag == 0);
Tst(object, kSmiTagMask);
Check(eq, reason);
}
}
void MacroAssembler::AssertNotSmi(Register object, BailoutReason reason) {
if (emit_debug_code()) {
STATIC_ASSERT(kSmiTag == 0);
Tst(object, kSmiTagMask);
Check(ne, reason);
}
}
void MacroAssembler::AssertName(Register object) {
if (emit_debug_code()) {
AssertNotSmi(object, kOperandIsASmiAndNotAName);
UseScratchRegisterScope temps(this);
Register temp = temps.AcquireX();
Ldr(temp, FieldMemOperand(object, HeapObject::kMapOffset));
CompareInstanceType(temp, temp, LAST_NAME_TYPE);
Check(ls, kOperandIsNotAName);
}
}
void MacroAssembler::AssertUndefinedOrAllocationSite(Register object,
Register scratch) {
if (emit_debug_code()) {
Label done_checking;
AssertNotSmi(object);
JumpIfRoot(object, Heap::kUndefinedValueRootIndex, &done_checking);
Ldr(scratch, FieldMemOperand(object, HeapObject::kMapOffset));
CompareRoot(scratch, Heap::kAllocationSiteMapRootIndex);
Assert(eq, kExpectedUndefinedOrCell);
Bind(&done_checking);
}
}
void MacroAssembler::AssertString(Register object) {
if (emit_debug_code()) {
UseScratchRegisterScope temps(this);
Register temp = temps.AcquireX();
STATIC_ASSERT(kSmiTag == 0);
Tst(object, kSmiTagMask);
Check(ne, kOperandIsASmiAndNotAString);
Ldr(temp, FieldMemOperand(object, HeapObject::kMapOffset));
CompareInstanceType(temp, temp, FIRST_NONSTRING_TYPE);
Check(lo, kOperandIsNotAString);
}
}
void MacroAssembler::CallStub(CodeStub* stub, TypeFeedbackId ast_id) {
ASSERT(AllowThisStubCall(stub)); // Stub calls are not allowed in some stubs.
Call(stub->GetCode(), RelocInfo::CODE_TARGET, ast_id);
}
void MacroAssembler::TailCallStub(CodeStub* stub) {
Jump(stub->GetCode(), RelocInfo::CODE_TARGET);
}
void MacroAssembler::CallRuntime(const Runtime::Function* f,
int num_arguments,
SaveFPRegsMode save_doubles) {
// All arguments must be on the stack before this function is called.
// x0 holds the return value after the call.
// Check that the number of arguments matches what the function expects.
// If f->nargs is -1, the function can accept a variable number of arguments.
CHECK(f->nargs < 0 || f->nargs == num_arguments);
// Place the necessary arguments.
Mov(x0, num_arguments);
Mov(x1, ExternalReference(f, isolate()));
CEntryStub stub(isolate(), 1, save_doubles);
CallStub(&stub);
}
static int AddressOffset(ExternalReference ref0, ExternalReference ref1) {
return ref0.address() - ref1.address();
}
void MacroAssembler::CallApiFunctionAndReturn(
Register function_address,
ExternalReference thunk_ref,
int stack_space,
int spill_offset,
MemOperand return_value_operand,
MemOperand* context_restore_operand) {
ASM_LOCATION("CallApiFunctionAndReturn");
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);
ASSERT(function_address.is(x1) || function_address.is(x2));
Label profiler_disabled;
Label end_profiler_check;
Mov(x10, ExternalReference::is_profiling_address(isolate()));
Ldrb(w10, MemOperand(x10));
Cbz(w10, &profiler_disabled);
Mov(x3, thunk_ref);
B(&end_profiler_check);
Bind(&profiler_disabled);
Mov(x3, function_address);
Bind(&end_profiler_check);
// Save the callee-save registers we are going to use.
// TODO(all): Is this necessary? ARM doesn't do it.
STATIC_ASSERT(kCallApiFunctionSpillSpace == 4);
Poke(x19, (spill_offset + 0) * kXRegSize);
Poke(x20, (spill_offset + 1) * kXRegSize);
Poke(x21, (spill_offset + 2) * kXRegSize);
Poke(x22, (spill_offset + 3) * kXRegSize);
// Allocate HandleScope in callee-save registers.
// We will need to restore the HandleScope after the call to the API function,
// by allocating it in callee-save registers they will be preserved by C code.
Register handle_scope_base = x22;
Register next_address_reg = x19;
Register limit_reg = x20;
Register level_reg = w21;
Mov(handle_scope_base, next_address);
Ldr(next_address_reg, MemOperand(handle_scope_base, kNextOffset));
Ldr(limit_reg, MemOperand(handle_scope_base, kLimitOffset));
Ldr(level_reg, MemOperand(handle_scope_base, kLevelOffset));
Add(level_reg, level_reg, 1);
Str(level_reg, MemOperand(handle_scope_base, kLevelOffset));
if (FLAG_log_timer_events) {
FrameScope frame(this, StackFrame::MANUAL);
PushSafepointRegisters();
Mov(x0, ExternalReference::isolate_address(isolate()));
CallCFunction(ExternalReference::log_enter_external_function(isolate()), 1);
PopSafepointRegisters();
}
// Native call returns to the DirectCEntry stub which redirects to the
// return address pushed on stack (could have moved after GC).
// DirectCEntry stub itself is generated early and never moves.
DirectCEntryStub stub(isolate());
stub.GenerateCall(this, x3);
if (FLAG_log_timer_events) {
FrameScope frame(this, StackFrame::MANUAL);
PushSafepointRegisters();
Mov(x0, ExternalReference::isolate_address(isolate()));
CallCFunction(ExternalReference::log_leave_external_function(isolate()), 1);
PopSafepointRegisters();
}
Label promote_scheduled_exception;
Label exception_handled;
Label delete_allocated_handles;
Label leave_exit_frame;
Label return_value_loaded;
// Load value from ReturnValue.
Ldr(x0, return_value_operand);
Bind(&return_value_loaded);
// No more valid handles (the result handle was the last one). Restore
// previous handle scope.
Str(next_address_reg, MemOperand(handle_scope_base, kNextOffset));
if (emit_debug_code()) {
Ldr(w1, MemOperand(handle_scope_base, kLevelOffset));
Cmp(w1, level_reg);
Check(eq, kUnexpectedLevelAfterReturnFromApiCall);
}
Sub(level_reg, level_reg, 1);
Str(level_reg, MemOperand(handle_scope_base, kLevelOffset));
Ldr(x1, MemOperand(handle_scope_base, kLimitOffset));
Cmp(limit_reg, x1);
B(ne, &delete_allocated_handles);
Bind(&leave_exit_frame);
// Restore callee-saved registers.
Peek(x19, (spill_offset + 0) * kXRegSize);
Peek(x20, (spill_offset + 1) * kXRegSize);
Peek(x21, (spill_offset + 2) * kXRegSize);
Peek(x22, (spill_offset + 3) * kXRegSize);
// Check if the function scheduled an exception.
Mov(x5, ExternalReference::scheduled_exception_address(isolate()));
Ldr(x5, MemOperand(x5));
JumpIfNotRoot(x5, Heap::kTheHoleValueRootIndex, &promote_scheduled_exception);
Bind(&exception_handled);
bool restore_context = context_restore_operand != NULL;
if (restore_context) {
Ldr(cp, *context_restore_operand);
}
LeaveExitFrame(false, x1, !restore_context);
Drop(stack_space);
Ret();
Bind(&promote_scheduled_exception);
{
FrameScope frame(this, StackFrame::INTERNAL);
CallExternalReference(
ExternalReference(
Runtime::kPromoteScheduledException, isolate()), 0);
}
B(&exception_handled);
// HandleScope limit has changed. Delete allocated extensions.
Bind(&delete_allocated_handles);
Str(limit_reg, MemOperand(handle_scope_base, kLimitOffset));
// Save the return value in a callee-save register.
Register saved_result = x19;
Mov(saved_result, x0);
Mov(x0, ExternalReference::isolate_address(isolate()));
CallCFunction(
ExternalReference::delete_handle_scope_extensions(isolate()), 1);
Mov(x0, saved_result);
B(&leave_exit_frame);
}
void MacroAssembler::CallExternalReference(const ExternalReference& ext,
int num_arguments) {
Mov(x0, num_arguments);
Mov(x1, ext);
CEntryStub stub(isolate(), 1);
CallStub(&stub);
}
void MacroAssembler::JumpToExternalReference(const ExternalReference& builtin) {
Mov(x1, builtin);
CEntryStub stub(isolate(), 1);
Jump(stub.GetCode(), RelocInfo::CODE_TARGET);
}
void MacroAssembler::GetBuiltinFunction(Register target,
Builtins::JavaScript id) {
// Load the builtins object into target register.
Ldr(target, GlobalObjectMemOperand());
Ldr(target, FieldMemOperand(target, GlobalObject::kBuiltinsOffset));
// Load the JavaScript builtin function from the builtins object.
Ldr(target, FieldMemOperand(target,
JSBuiltinsObject::OffsetOfFunctionWithId(id)));
}
void MacroAssembler::GetBuiltinEntry(Register target,
Register function,
Builtins::JavaScript id) {
ASSERT(!AreAliased(target, function));
GetBuiltinFunction(function, id);
// Load the code entry point from the builtins object.
Ldr(target, FieldMemOperand(function, JSFunction::kCodeEntryOffset));
}
void MacroAssembler::InvokeBuiltin(Builtins::JavaScript id,
InvokeFlag flag,
const CallWrapper& call_wrapper) {
ASM_LOCATION("MacroAssembler::InvokeBuiltin");
// You can't call a builtin without a valid frame.
ASSERT(flag == JUMP_FUNCTION || has_frame());
// Get the builtin entry in x2 and setup the function object in x1.
GetBuiltinEntry(x2, x1, id);
if (flag == CALL_FUNCTION) {
call_wrapper.BeforeCall(CallSize(x2));
Call(x2);
call_wrapper.AfterCall();
} else {
ASSERT(flag == JUMP_FUNCTION);
Jump(x2);
}
}
void MacroAssembler::TailCallExternalReference(const ExternalReference& ext,
int num_arguments,
int result_size) {
// TODO(1236192): Most runtime routines don't need the number of
// arguments passed in because it is constant. At some point we
// should remove this need and make the runtime routine entry code
// smarter.
Mov(x0, num_arguments);
JumpToExternalReference(ext);
}
void MacroAssembler::TailCallRuntime(Runtime::FunctionId fid,
int num_arguments,
int result_size) {
TailCallExternalReference(ExternalReference(fid, isolate()),
num_arguments,
result_size);
}
void MacroAssembler::InitializeNewString(Register string,
Register length,
Heap::RootListIndex map_index,
Register scratch1,
Register scratch2) {
ASSERT(!AreAliased(string, length, scratch1, scratch2));
LoadRoot(scratch2, map_index);
SmiTag(scratch1, length);
Str(scratch2, FieldMemOperand(string, HeapObject::kMapOffset));
Mov(scratch2, String::kEmptyHashField);
Str(scratch1, FieldMemOperand(string, String::kLengthOffset));
Str(scratch2, FieldMemOperand(string, String::kHashFieldOffset));
}
int MacroAssembler::ActivationFrameAlignment() {
#if V8_HOST_ARCH_ARM64
// Running on the real platform. Use the alignment as mandated by the local
// environment.
// Note: This will break if we ever start generating snapshots on one ARM
// platform for another ARM platform with a different alignment.
return base::OS::ActivationFrameAlignment();
#else // V8_HOST_ARCH_ARM64
// If we are using the simulator then we should always align to the expected
// alignment. As the simulator is used to generate snapshots we do not know
// if the target platform will need alignment, so this is controlled from a
// flag.
return FLAG_sim_stack_alignment;
#endif // V8_HOST_ARCH_ARM64
}
void MacroAssembler::CallCFunction(ExternalReference function,
int num_of_reg_args) {
CallCFunction(function, num_of_reg_args, 0);
}
void MacroAssembler::CallCFunction(ExternalReference function,
int num_of_reg_args,
int num_of_double_args) {
UseScratchRegisterScope temps(this);
Register temp = temps.AcquireX();
Mov(temp, function);
CallCFunction(temp, num_of_reg_args, num_of_double_args);
}
void MacroAssembler::CallCFunction(Register function,
int num_of_reg_args,
int num_of_double_args) {
ASSERT(has_frame());
// We can pass 8 integer arguments in registers. If we need to pass more than
// that, we'll need to implement support for passing them on the stack.
ASSERT(num_of_reg_args <= 8);
// If we're passing doubles, we're limited to the following prototypes
// (defined by ExternalReference::Type):
// BUILTIN_COMPARE_CALL: int f(double, double)
// BUILTIN_FP_FP_CALL: double f(double, double)
// BUILTIN_FP_CALL: double f(double)
// BUILTIN_FP_INT_CALL: double f(double, int)
if (num_of_double_args > 0) {
ASSERT(num_of_reg_args <= 1);
ASSERT((num_of_double_args + num_of_reg_args) <= 2);
}
// If the stack pointer is not csp, we need to derive an aligned csp from the
// current stack pointer.
const Register old_stack_pointer = StackPointer();
if (!csp.Is(old_stack_pointer)) {
AssertStackConsistency();
int sp_alignment = ActivationFrameAlignment();
// The ABI mandates at least 16-byte alignment.
ASSERT(sp_alignment >= 16);
ASSERT(IsPowerOf2(sp_alignment));
// The current stack pointer is a callee saved register, and is preserved
// across the call.
ASSERT(kCalleeSaved.IncludesAliasOf(old_stack_pointer));
// Align and synchronize the system stack pointer with jssp.
Bic(csp, old_stack_pointer, sp_alignment - 1);
SetStackPointer(csp);
}
// Call directly. The function called cannot cause a GC, or allow preemption,
// so the return address in the link register stays correct.
Call(function);
if (!csp.Is(old_stack_pointer)) {
if (emit_debug_code()) {
// Because the stack pointer must be aligned on a 16-byte boundary, the
// aligned csp can be up to 12 bytes below the jssp. This is the case
// where we only pushed one W register on top of an aligned jssp.
UseScratchRegisterScope temps(this);
Register temp = temps.AcquireX();
ASSERT(ActivationFrameAlignment() == 16);
Sub(temp, csp, old_stack_pointer);
// We want temp <= 0 && temp >= -12.
Cmp(temp, 0);
Ccmp(temp, -12, NFlag, le);
Check(ge, kTheStackWasCorruptedByMacroAssemblerCall);
}
SetStackPointer(old_stack_pointer);
}
}
void MacroAssembler::Jump(Register target) {
Br(target);
}
void MacroAssembler::Jump(intptr_t target, RelocInfo::Mode rmode) {
UseScratchRegisterScope temps(this);
Register temp = temps.AcquireX();
Mov(temp, Operand(target, rmode));
Br(temp);
}
void MacroAssembler::Jump(Address target, RelocInfo::Mode rmode) {
ASSERT(!RelocInfo::IsCodeTarget(rmode));
Jump(reinterpret_cast<intptr_t>(target), rmode);
}
void MacroAssembler::Jump(Handle<Code> code, RelocInfo::Mode rmode) {
ASSERT(RelocInfo::IsCodeTarget(rmode));
AllowDeferredHandleDereference embedding_raw_address;
Jump(reinterpret_cast<intptr_t>(code.location()), rmode);
}
void MacroAssembler::Call(Register target) {
BlockPoolsScope scope(this);
#ifdef DEBUG
Label start_call;
Bind(&start_call);
#endif
Blr(target);
#ifdef DEBUG
AssertSizeOfCodeGeneratedSince(&start_call, CallSize(target));
#endif
}
void MacroAssembler::Call(Label* target) {
BlockPoolsScope scope(this);
#ifdef DEBUG
Label start_call;
Bind(&start_call);
#endif
Bl(target);
#ifdef DEBUG
AssertSizeOfCodeGeneratedSince(&start_call, CallSize(target));
#endif
}
// MacroAssembler::CallSize is sensitive to changes in this function, as it
// requires to know how many instructions are used to branch to the target.
void MacroAssembler::Call(Address target, RelocInfo::Mode rmode) {
BlockPoolsScope scope(this);
#ifdef DEBUG
Label start_call;
Bind(&start_call);
#endif
// Statement positions are expected to be recorded when the target
// address is loaded.
positions_recorder()->WriteRecordedPositions();
// Addresses always have 64 bits, so we shouldn't encounter NONE32.
ASSERT(rmode != RelocInfo::NONE32);
UseScratchRegisterScope temps(this);
Register temp = temps.AcquireX();
if (rmode == RelocInfo::NONE64) {
// Addresses are 48 bits so we never need to load the upper 16 bits.
uint64_t imm = reinterpret_cast<uint64_t>(target);
// If we don't use ARM tagged addresses, the 16 higher bits must be 0.
ASSERT(((imm >> 48) & 0xffff) == 0);
movz(temp, (imm >> 0) & 0xffff, 0);
movk(temp, (imm >> 16) & 0xffff, 16);
movk(temp, (imm >> 32) & 0xffff, 32);
} else {
Ldr(temp, Immediate(reinterpret_cast<intptr_t>(target), rmode));
}
Blr(temp);
#ifdef DEBUG
AssertSizeOfCodeGeneratedSince(&start_call, CallSize(target, rmode));
#endif
}
void MacroAssembler::Call(Handle<Code> code,
RelocInfo::Mode rmode,
TypeFeedbackId ast_id) {
#ifdef DEBUG
Label start_call;
Bind(&start_call);
#endif
if ((rmode == RelocInfo::CODE_TARGET) && (!ast_id.IsNone())) {
SetRecordedAstId(ast_id);
rmode = RelocInfo::CODE_TARGET_WITH_ID;
}
AllowDeferredHandleDereference embedding_raw_address;
Call(reinterpret_cast<Address>(code.location()), rmode);
#ifdef DEBUG
// Check the size of the code generated.
AssertSizeOfCodeGeneratedSince(&start_call, CallSize(code, rmode, ast_id));
#endif
}
int MacroAssembler::CallSize(Register target) {
USE(target);
return kInstructionSize;
}
int MacroAssembler::CallSize(Label* target) {
USE(target);
return kInstructionSize;
}
int MacroAssembler::CallSize(Address target, RelocInfo::Mode rmode) {
USE(target);
// Addresses always have 64 bits, so we shouldn't encounter NONE32.
ASSERT(rmode != RelocInfo::NONE32);
if (rmode == RelocInfo::NONE64) {
return kCallSizeWithoutRelocation;
} else {
return kCallSizeWithRelocation;
}
}
int MacroAssembler::CallSize(Handle<Code> code,
RelocInfo::Mode rmode,
TypeFeedbackId ast_id) {
USE(code);
USE(ast_id);
// Addresses always have 64 bits, so we shouldn't encounter NONE32.
ASSERT(rmode != RelocInfo::NONE32);
if (rmode == RelocInfo::NONE64) {
return kCallSizeWithoutRelocation;
} else {
return kCallSizeWithRelocation;
}
}
void MacroAssembler::JumpForHeapNumber(Register object,
Register heap_number_map,
Label* on_heap_number,
Label* on_not_heap_number) {
ASSERT(on_heap_number || on_not_heap_number);
AssertNotSmi(object);
UseScratchRegisterScope temps(this);
Register temp = temps.AcquireX();
// Load the HeapNumber map if it is not passed.
if (heap_number_map.Is(NoReg)) {
heap_number_map = temps.AcquireX();
LoadRoot(heap_number_map, Heap::kHeapNumberMapRootIndex);
} else {
AssertRegisterIsRoot(heap_number_map, Heap::kHeapNumberMapRootIndex);
}
ASSERT(!AreAliased(temp, heap_number_map));
Ldr(temp, FieldMemOperand(object, HeapObject::kMapOffset));
Cmp(temp, heap_number_map);
if (on_heap_number) {
B(eq, on_heap_number);
}
if (on_not_heap_number) {
B(ne, on_not_heap_number);
}
}
void MacroAssembler::JumpIfHeapNumber(Register object,
Label* on_heap_number,
Register heap_number_map) {
JumpForHeapNumber(object,
heap_number_map,
on_heap_number,
NULL);
}
void MacroAssembler::JumpIfNotHeapNumber(Register object,
Label* on_not_heap_number,
Register heap_number_map) {
JumpForHeapNumber(object,
heap_number_map,
NULL,
on_not_heap_number);
}
void MacroAssembler::LookupNumberStringCache(Register object,
Register result,
Register scratch1,
Register scratch2,
Register scratch3,
Label* not_found) {
ASSERT(!AreAliased(object, result, scratch1, scratch2, scratch3));
// Use of registers. Register result is used as a temporary.
Register number_string_cache = result;
Register mask = scratch3;
// Load the number string cache.
LoadRoot(number_string_cache, Heap::kNumberStringCacheRootIndex);
// Make the hash mask from the length of the number string cache. It
// contains two elements (number and string) for each cache entry.
Ldrsw(mask, UntagSmiFieldMemOperand(number_string_cache,
FixedArray::kLengthOffset));
Asr(mask, mask, 1); // Divide length by two.
Sub(mask, mask, 1); // Make mask.
// Calculate the entry in the number string cache. The hash value in the
// number string cache for smis is just the smi value, and the hash for
// doubles is the xor of the upper and lower words. See
// Heap::GetNumberStringCache.
Label is_smi;
Label load_result_from_cache;
JumpIfSmi(object, &is_smi);
CheckMap(object, scratch1, Heap::kHeapNumberMapRootIndex, not_found,
DONT_DO_SMI_CHECK);
STATIC_ASSERT(kDoubleSize == (kWRegSize * 2));
Add(scratch1, object, HeapNumber::kValueOffset - kHeapObjectTag);
Ldp(scratch1.W(), scratch2.W(), MemOperand(scratch1));
Eor(scratch1, scratch1, scratch2);
And(scratch1, scratch1, mask);
// Calculate address of entry in string cache: each entry consists of two
// pointer sized fields.
Add(scratch1, number_string_cache,
Operand(scratch1, LSL, kPointerSizeLog2 + 1));
Register probe = mask;
Ldr(probe, FieldMemOperand(scratch1, FixedArray::kHeaderSize));
JumpIfSmi(probe, not_found);
Ldr(d0, FieldMemOperand(object, HeapNumber::kValueOffset));
Ldr(d1, FieldMemOperand(probe, HeapNumber::kValueOffset));
Fcmp(d0, d1);
B(ne, not_found);
B(&load_result_from_cache);
Bind(&is_smi);
Register scratch = scratch1;
And(scratch, mask, Operand::UntagSmi(object));
// Calculate address of entry in string cache: each entry consists
// of two pointer sized fields.
Add(scratch, number_string_cache,
Operand(scratch, LSL, kPointerSizeLog2 + 1));
// Check if the entry is the smi we are looking for.
Ldr(probe, FieldMemOperand(scratch, FixedArray::kHeaderSize));
Cmp(object, probe);
B(ne, not_found);
// Get the result from the cache.
Bind(&load_result_from_cache);
Ldr(result, FieldMemOperand(scratch, FixedArray::kHeaderSize + kPointerSize));
IncrementCounter(isolate()->counters()->number_to_string_native(), 1,
scratch1, scratch2);
}
void MacroAssembler::TryRepresentDoubleAsInt(Register as_int,
FPRegister value,
FPRegister scratch_d,
Label* on_successful_conversion,
Label* on_failed_conversion) {
// Convert to an int and back again, then compare with the original value.
Fcvtzs(as_int, value);
Scvtf(scratch_d, as_int);
Fcmp(value, scratch_d);
if (on_successful_conversion) {
B(on_successful_conversion, eq);
}
if (on_failed_conversion) {
B(on_failed_conversion, ne);
}
}
void MacroAssembler::TestForMinusZero(DoubleRegister input) {
UseScratchRegisterScope temps(this);
Register temp = temps.AcquireX();
// Floating point -0.0 is kMinInt as an integer, so subtracting 1 (cmp) will
// cause overflow.
Fmov(temp, input);
Cmp(temp, 1);
}
void MacroAssembler::JumpIfMinusZero(DoubleRegister input,
Label* on_negative_zero) {
TestForMinusZero(input);
B(vs, on_negative_zero);
}
void MacroAssembler::JumpIfMinusZero(Register input,
Label* on_negative_zero) {
ASSERT(input.Is64Bits());
// Floating point value is in an integer register. Detect -0.0 by subtracting
// 1 (cmp), which will cause overflow.
Cmp(input, 1);
B(vs, on_negative_zero);
}
void MacroAssembler::ClampInt32ToUint8(Register output, Register input) {
// Clamp the value to [0..255].
Cmp(input.W(), Operand(input.W(), UXTB));
// If input < input & 0xff, it must be < 0, so saturate to 0.
Csel(output.W(), wzr, input.W(), lt);
// If input <= input & 0xff, it must be <= 255. Otherwise, saturate to 255.
Csel(output.W(), output.W(), 255, le);
}
void MacroAssembler::ClampInt32ToUint8(Register in_out) {
ClampInt32ToUint8(in_out, in_out);
}
void MacroAssembler::ClampDoubleToUint8(Register output,
DoubleRegister input,
DoubleRegister dbl_scratch) {
// This conversion follows the WebIDL "[Clamp]" rules for PIXEL types:
// - Inputs lower than 0 (including -infinity) produce 0.
// - Inputs higher than 255 (including +infinity) produce 255.
// Also, it seems that PIXEL types use round-to-nearest rather than
// round-towards-zero.
// Squash +infinity before the conversion, since Fcvtnu will normally
// convert it to 0.
Fmov(dbl_scratch, 255);
Fmin(dbl_scratch, dbl_scratch, input);
// Convert double to unsigned integer. Values less than zero become zero.
// Values greater than 255 have already been clamped to 255.
Fcvtnu(output, dbl_scratch);
}
void MacroAssembler::CopyFieldsLoopPairsHelper(Register dst,
Register src,
unsigned count,
Register scratch1,
Register scratch2,
Register scratch3,
Register scratch4,
Register scratch5) {
// Untag src and dst into scratch registers.
// Copy src->dst in a tight loop.
ASSERT(!AreAliased(dst, src,
scratch1, scratch2, scratch3, scratch4, scratch5));
ASSERT(count >= 2);
const Register& remaining = scratch3;
Mov(remaining, count / 2);
const Register& dst_untagged = scratch1;
const Register& src_untagged = scratch2;
Sub(dst_untagged, dst, kHeapObjectTag);
Sub(src_untagged, src, kHeapObjectTag);
// Copy fields in pairs.
Label loop;
Bind(&loop);
Ldp(scratch4, scratch5,
MemOperand(src_untagged, kXRegSize* 2, PostIndex));
Stp(scratch4, scratch5,
MemOperand(dst_untagged, kXRegSize* 2, PostIndex));
Sub(remaining, remaining, 1);
Cbnz(remaining, &loop);
// Handle the leftovers.
if (count & 1) {
Ldr(scratch4, MemOperand(src_untagged));
Str(scratch4, MemOperand(dst_untagged));
}
}
void MacroAssembler::CopyFieldsUnrolledPairsHelper(Register dst,
Register src,
unsigned count,
Register scratch1,
Register scratch2,
Register scratch3,
Register scratch4) {
// Untag src and dst into scratch registers.
// Copy src->dst in an unrolled loop.
ASSERT(!AreAliased(dst, src, scratch1, scratch2, scratch3, scratch4));
const Register& dst_untagged = scratch1;
const Register& src_untagged = scratch2;
sub(dst_untagged, dst, kHeapObjectTag);
sub(src_untagged, src, kHeapObjectTag);
// Copy fields in pairs.
for (unsigned i = 0; i < count / 2; i++) {
Ldp(scratch3, scratch4, MemOperand(src_untagged, kXRegSize * 2, PostIndex));
Stp(scratch3, scratch4, MemOperand(dst_untagged, kXRegSize * 2, PostIndex));
}
// Handle the leftovers.
if (count & 1) {
Ldr(scratch3, MemOperand(src_untagged));
Str(scratch3, MemOperand(dst_untagged));
}
}
void MacroAssembler::CopyFieldsUnrolledHelper(Register dst,
Register src,
unsigned count,
Register scratch1,
Register scratch2,
Register scratch3) {
// Untag src and dst into scratch registers.
// Copy src->dst in an unrolled loop.
ASSERT(!AreAliased(dst, src, scratch1, scratch2, scratch3));
const Register& dst_untagged = scratch1;
const Register& src_untagged = scratch2;
Sub(dst_untagged, dst, kHeapObjectTag);
Sub(src_untagged, src, kHeapObjectTag);
// Copy fields one by one.
for (unsigned i = 0; i < count; i++) {
Ldr(scratch3, MemOperand(src_untagged, kXRegSize, PostIndex));
Str(scratch3, MemOperand(dst_untagged, kXRegSize, PostIndex));
}
}
void MacroAssembler::CopyFields(Register dst, Register src, CPURegList temps,
unsigned count) {
// One of two methods is used:
//
// For high 'count' values where many scratch registers are available:
// Untag src and dst into scratch registers.
// Copy src->dst in a tight loop.
//
// For low 'count' values or where few scratch registers are available:
// Untag src and dst into scratch registers.
// Copy src->dst in an unrolled loop.
//
// In both cases, fields are copied in pairs if possible, and left-overs are
// handled separately.
ASSERT(!AreAliased(dst, src));
ASSERT(!temps.IncludesAliasOf(dst));
ASSERT(!temps.IncludesAliasOf(src));
ASSERT(!temps.IncludesAliasOf(xzr));
if (emit_debug_code()) {
Cmp(dst, src);
Check(ne, kTheSourceAndDestinationAreTheSame);
}
// The value of 'count' at which a loop will be generated (if there are
// enough scratch registers).
static const unsigned kLoopThreshold = 8;
UseScratchRegisterScope masm_temps(this);
if ((temps.Count() >= 3) && (count >= kLoopThreshold)) {
CopyFieldsLoopPairsHelper(dst, src, count,
Register(temps.PopLowestIndex()),
Register(temps.PopLowestIndex()),
Register(temps.PopLowestIndex()),
masm_temps.AcquireX(),
masm_temps.AcquireX());
} else if (temps.Count() >= 2) {
CopyFieldsUnrolledPairsHelper(dst, src, count,
Register(temps.PopLowestIndex()),
Register(temps.PopLowestIndex()),
masm_temps.AcquireX(),
masm_temps.AcquireX());
} else if (temps.Count() == 1) {
CopyFieldsUnrolledHelper(dst, src, count,
Register(temps.PopLowestIndex()),
masm_temps.AcquireX(),
masm_temps.AcquireX());
} else {
UNREACHABLE();
}
}
void MacroAssembler::CopyBytes(Register dst,
Register src,
Register length,
Register scratch,
CopyHint hint) {
UseScratchRegisterScope temps(this);
Register tmp1 = temps.AcquireX();
Register tmp2 = temps.AcquireX();
ASSERT(!AreAliased(src, dst, length, scratch, tmp1, tmp2));
ASSERT(!AreAliased(src, dst, csp));
if (emit_debug_code()) {
// Check copy length.
Cmp(length, 0);
Assert(ge, kUnexpectedNegativeValue);
// Check src and dst buffers don't overlap.
Add(scratch, src, length); // Calculate end of src buffer.
Cmp(scratch, dst);
Add(scratch, dst, length); // Calculate end of dst buffer.
Ccmp(scratch, src, ZFlag, gt);
Assert(le, kCopyBuffersOverlap);
}
Label short_copy, short_loop, bulk_loop, done;
if ((hint == kCopyLong || hint == kCopyUnknown) && !FLAG_optimize_for_size) {
Register bulk_length = scratch;
int pair_size = 2 * kXRegSize;
int pair_mask = pair_size - 1;
Bic(bulk_length, length, pair_mask);
Cbz(bulk_length, &short_copy);
Bind(&bulk_loop);
Sub(bulk_length, bulk_length, pair_size);
Ldp(tmp1, tmp2, MemOperand(src, pair_size, PostIndex));
Stp(tmp1, tmp2, MemOperand(dst, pair_size, PostIndex));
Cbnz(bulk_length, &bulk_loop);
And(length, length, pair_mask);
}
Bind(&short_copy);
Cbz(length, &done);
Bind(&short_loop);
Sub(length, length, 1);
Ldrb(tmp1, MemOperand(src, 1, PostIndex));
Strb(tmp1, MemOperand(dst, 1, PostIndex));
Cbnz(length, &short_loop);
Bind(&done);
}
void MacroAssembler::FillFields(Register dst,
Register field_count,
Register filler) {
ASSERT(!dst.Is(csp));
UseScratchRegisterScope temps(this);
Register field_ptr = temps.AcquireX();
Register counter = temps.AcquireX();
Label done;
// Decrement count. If the result < zero, count was zero, and there's nothing
// to do. If count was one, flags are set to fail the gt condition at the end
// of the pairs loop.
Subs(counter, field_count, 1);
B(lt, &done);
// There's at least one field to fill, so do this unconditionally.
Str(filler, MemOperand(dst, kPointerSize, PostIndex));
// If the bottom bit of counter is set, there are an even number of fields to
// fill, so pull the start pointer back by one field, allowing the pairs loop
// to overwrite the field that was stored above.
And(field_ptr, counter, 1);
Sub(field_ptr, dst, Operand(field_ptr, LSL, kPointerSizeLog2));
// Store filler to memory in pairs.
Label entry, loop;
B(&entry);
Bind(&loop);
Stp(filler, filler, MemOperand(field_ptr, 2 * kPointerSize, PostIndex));
Subs(counter, counter, 2);
Bind(&entry);
B(gt, &loop);
Bind(&done);
}
void MacroAssembler::JumpIfEitherIsNotSequentialAsciiStrings(
Register first,
Register second,
Register scratch1,
Register scratch2,
Label* failure,
SmiCheckType smi_check) {
if (smi_check == DO_SMI_CHECK) {
JumpIfEitherSmi(first, second, failure);
} else if (emit_debug_code()) {
ASSERT(smi_check == DONT_DO_SMI_CHECK);
Label not_smi;
JumpIfEitherSmi(first, second, NULL, ¬_smi);
// At least one input is a smi, but the flags indicated a smi check wasn't
// needed.
Abort(kUnexpectedSmi);
Bind(¬_smi);
}
// Test that both first and second are sequential ASCII strings.
Ldr(scratch1, FieldMemOperand(first, HeapObject::kMapOffset));
Ldr(scratch2, FieldMemOperand(second, HeapObject::kMapOffset));
Ldrb(scratch1, FieldMemOperand(scratch1, Map::kInstanceTypeOffset));
Ldrb(scratch2, FieldMemOperand(scratch2, Map::kInstanceTypeOffset));
JumpIfEitherInstanceTypeIsNotSequentialAscii(scratch1,
scratch2,
scratch1,
scratch2,
failure);
}
void MacroAssembler::JumpIfEitherInstanceTypeIsNotSequentialAscii(
Register first,
Register second,
Register scratch1,
Register scratch2,
Label* failure) {
ASSERT(!AreAliased(scratch1, second));
ASSERT(!AreAliased(scratch1, scratch2));
static const int kFlatAsciiStringMask =
kIsNotStringMask | kStringEncodingMask | kStringRepresentationMask;
static const int kFlatAsciiStringTag = ASCII_STRING_TYPE;
And(scratch1, first, kFlatAsciiStringMask);
And(scratch2, second, kFlatAsciiStringMask);
Cmp(scratch1, kFlatAsciiStringTag);
Ccmp(scratch2, kFlatAsciiStringTag, NoFlag, eq);
B(ne, failure);
}
void MacroAssembler::JumpIfInstanceTypeIsNotSequentialAscii(Register type,
Register scratch,
Label* failure) {
const int kFlatAsciiStringMask =
kIsNotStringMask | kStringEncodingMask | kStringRepresentationMask;
const int kFlatAsciiStringTag =
kStringTag | kOneByteStringTag | kSeqStringTag;
And(scratch, type, kFlatAsciiStringMask);
Cmp(scratch, kFlatAsciiStringTag);
B(ne, failure);
}
void MacroAssembler::JumpIfBothInstanceTypesAreNotSequentialAscii(
Register first,
Register second,
Register scratch1,
Register scratch2,
Label* failure) {
ASSERT(!AreAliased(first, second, scratch1, scratch2));
const int kFlatAsciiStringMask =
kIsNotStringMask | kStringEncodingMask | kStringRepresentationMask;
const int kFlatAsciiStringTag =
kStringTag | kOneByteStringTag | kSeqStringTag;
And(scratch1, first, kFlatAsciiStringMask);
And(scratch2, second, kFlatAsciiStringMask);
Cmp(scratch1, kFlatAsciiStringTag);
Ccmp(scratch2, kFlatAsciiStringTag, NoFlag, eq);
B(ne, failure);
}
void MacroAssembler::JumpIfNotUniqueName(Register type,
Label* not_unique_name) {
STATIC_ASSERT((kInternalizedTag == 0) && (kStringTag == 0));
// if ((type is string && type is internalized) || type == SYMBOL_TYPE) {
// continue
// } else {
// goto not_unique_name
// }
Tst(type, kIsNotStringMask | kIsNotInternalizedMask);
Ccmp(type, SYMBOL_TYPE, ZFlag, ne);
B(ne, not_unique_name);
}
void MacroAssembler::InvokePrologue(const ParameterCount& expected,
const ParameterCount& actual,
Handle<Code> code_constant,
Register code_reg,
Label* done,
InvokeFlag flag,
bool* definitely_mismatches,
const CallWrapper& call_wrapper) {
bool definitely_matches = false;
*definitely_mismatches = false;
Label regular_invoke;
// Check whether the expected and actual arguments count match. If not,
// setup registers according to contract with ArgumentsAdaptorTrampoline:
// x0: actual arguments count.
// x1: function (passed through to callee).
// x2: expected arguments count.
// The code below is made a lot easier because the calling code already sets
// up actual and expected registers according to the contract if values are
// passed in registers.
ASSERT(actual.is_immediate() || actual.reg().is(x0));
ASSERT(expected.is_immediate() || expected.reg().is(x2));
ASSERT((!code_constant.is_null() && code_reg.is(no_reg)) || code_reg.is(x3));
if (expected.is_immediate()) {
ASSERT(actual.is_immediate());
if (expected.immediate() == actual.immediate()) {
definitely_matches = true;
} else {
Mov(x0, actual.immediate());
if (expected.immediate() ==
SharedFunctionInfo::kDontAdaptArgumentsSentinel) {
// Don't worry about adapting arguments for builtins that
// don't want that done. Skip adaption code by making it look
// like we have a match between expected and actual number of
// arguments.
definitely_matches = true;
} else {
*definitely_mismatches = true;
// Set up x2 for the argument adaptor.
Mov(x2, expected.immediate());
}
}
} else { // expected is a register.
Operand actual_op = actual.is_immediate() ? Operand(actual.immediate())
: Operand(actual.reg());
// If actual == expected perform a regular invocation.
Cmp(expected.reg(), actual_op);
B(eq, ®ular_invoke);
// Otherwise set up x0 for the argument adaptor.
Mov(x0, actual_op);
}
// If the argument counts may mismatch, generate a call to the argument
// adaptor.
if (!definitely_matches) {
if (!code_constant.is_null()) {
Mov(x3, Operand(code_constant));
Add(x3, x3, Code::kHeaderSize - kHeapObjectTag);
}
Handle<Code> adaptor =
isolate()->builtins()->ArgumentsAdaptorTrampoline();
if (flag == CALL_FUNCTION) {
call_wrapper.BeforeCall(CallSize(adaptor));
Call(adaptor);
call_wrapper.AfterCall();
if (!*definitely_mismatches) {
// If the arg counts don't match, no extra code is emitted by
// MAsm::InvokeCode and we can just fall through.
B(done);
}
} else {
Jump(adaptor, RelocInfo::CODE_TARGET);
}
}
Bind(®ular_invoke);
}
void MacroAssembler::InvokeCode(Register code,
const ParameterCount& expected,
const ParameterCount& actual,
InvokeFlag flag,
const CallWrapper& call_wrapper) {
// You can't call a function without a valid frame.
ASSERT(flag == JUMP_FUNCTION || has_frame());
Label done;
bool definitely_mismatches = false;
InvokePrologue(expected, actual, Handle<Code>::null(), code, &done, flag,
&definitely_mismatches, call_wrapper);
// If we are certain that actual != expected, then we know InvokePrologue will
// have handled the call through the argument adaptor mechanism.
// The called function expects the call kind in x5.
if (!definitely_mismatches) {
if (flag == CALL_FUNCTION) {
call_wrapper.BeforeCall(CallSize(code));
Call(code);
call_wrapper.AfterCall();
} else {
ASSERT(flag == JUMP_FUNCTION);
Jump(code);
}
}
// Continue here if InvokePrologue does handle the invocation due to
// mismatched parameter counts.
Bind(&done);
}
void MacroAssembler::InvokeFunction(Register function,
const ParameterCount& actual,
InvokeFlag flag,
const CallWrapper& call_wrapper) {
// You can't call a function without a valid frame.
ASSERT(flag == JUMP_FUNCTION || has_frame());
// Contract with called JS functions requires that function is passed in x1.
// (See FullCodeGenerator::Generate().)
ASSERT(function.is(x1));
Register expected_reg = x2;
Register code_reg = x3;
Ldr(cp, FieldMemOperand(function, JSFunction::kContextOffset));
// The number of arguments is stored as an int32_t, and -1 is a marker
// (SharedFunctionInfo::kDontAdaptArgumentsSentinel), so we need sign
// extension to correctly handle it.
Ldr(expected_reg, FieldMemOperand(function,
JSFunction::kSharedFunctionInfoOffset));
Ldrsw(expected_reg,
FieldMemOperand(expected_reg,
SharedFunctionInfo::kFormalParameterCountOffset));
Ldr(code_reg,
FieldMemOperand(function, JSFunction::kCodeEntryOffset));
ParameterCount expected(expected_reg);
InvokeCode(code_reg, expected, actual, flag, call_wrapper);
}
void MacroAssembler::InvokeFunction(Register function,
const ParameterCount& expected,
const ParameterCount& actual,
InvokeFlag flag,
const CallWrapper& call_wrapper) {
// You can't call a function without a valid frame.
ASSERT(flag == JUMP_FUNCTION || has_frame());
// Contract with called JS functions requires that function is passed in x1.
// (See FullCodeGenerator::Generate().)
ASSERT(function.Is(x1));
Register code_reg = x3;
// Set up the context.
Ldr(cp, FieldMemOperand(function, JSFunction::kContextOffset));
// We call indirectly through the code field in the function to
// allow recompilation to take effect without changing any of the
// call sites.
Ldr(code_reg, FieldMemOperand(function, JSFunction::kCodeEntryOffset));
InvokeCode(code_reg, expected, actual, flag, call_wrapper);
}
void MacroAssembler::InvokeFunction(Handle<JSFunction> function,
const ParameterCount& expected,
const ParameterCount& actual,
InvokeFlag flag,
const CallWrapper& call_wrapper) {
// Contract with called JS functions requires that function is passed in x1.
// (See FullCodeGenerator::Generate().)
__ LoadObject(x1, function);
InvokeFunction(x1, expected, actual, flag, call_wrapper);
}
void MacroAssembler::TryConvertDoubleToInt64(Register result,
DoubleRegister double_input,
Label* done) {
// Try to convert with an FPU convert instruction. It's trivial to compute
// the modulo operation on an integer register so we convert to a 64-bit
// integer.
//
// Fcvtzs will saturate to INT64_MIN (0x800...00) or INT64_MAX (0x7ff...ff)
// when the double is out of range. NaNs and infinities will be converted to 0
// (as ECMA-262 requires).
Fcvtzs(result.X(), double_input);
// The values INT64_MIN (0x800...00) or INT64_MAX (0x7ff...ff) are not
// representable using a double, so if the result is one of those then we know
// that saturation occured, and we need to manually handle the conversion.
//
// It is easy to detect INT64_MIN and INT64_MAX because adding or subtracting
// 1 will cause signed overflow.
Cmp(result.X(), 1);
Ccmp(result.X(), -1, VFlag, vc);
B(vc, done);
}
void MacroAssembler::TruncateDoubleToI(Register result,
DoubleRegister double_input) {
Label done;
ASSERT(jssp.Is(StackPointer()));
// Try to convert the double to an int64. If successful, the bottom 32 bits
// contain our truncated int32 result.
TryConvertDoubleToInt64(result, double_input, &done);
// If we fell through then inline version didn't succeed - call stub instead.
Push(lr, double_input);
DoubleToIStub stub(isolate(),
jssp,
result,
0,
true, // is_truncating
true); // skip_fastpath
CallStub(&stub); // DoubleToIStub preserves any registers it needs to clobber
Drop(1, kDoubleSize); // Drop the double input on the stack.
Pop(lr);
Bind(&done);
}
void MacroAssembler::TruncateHeapNumberToI(Register result,
Register object) {
Label done;
ASSERT(!result.is(object));
ASSERT(jssp.Is(StackPointer()));
Ldr(fp_scratch, FieldMemOperand(object, HeapNumber::kValueOffset));
// Try to convert the double to an int64. If successful, the bottom 32 bits
// contain our truncated int32 result.
TryConvertDoubleToInt64(result, fp_scratch, &done);
// If we fell through then inline version didn't succeed - call stub instead.
Push(lr);
DoubleToIStub stub(isolate(),
object,
result,
HeapNumber::kValueOffset - kHeapObjectTag,
true, // is_truncating
true); // skip_fastpath
CallStub(&stub); // DoubleToIStub preserves any registers it needs to clobber
Pop(lr);
Bind(&done);
}
void MacroAssembler::StubPrologue() {
ASSERT(StackPointer().Is(jssp));
UseScratchRegisterScope temps(this);
Register temp = temps.AcquireX();
__ Mov(temp, Smi::FromInt(StackFrame::STUB));
// Compiled stubs don't age, and so they don't need the predictable code
// ageing sequence.
__ Push(lr, fp, cp, temp);
__ Add(fp, jssp, StandardFrameConstants::kFixedFrameSizeFromFp);
}
void MacroAssembler::Prologue(bool code_pre_aging) {
if (code_pre_aging) {
Code* stub = Code::GetPreAgedCodeAgeStub(isolate());
__ EmitCodeAgeSequence(stub);
} else {
__ EmitFrameSetupForCodeAgePatching();
}
}
void MacroAssembler::EnterFrame(StackFrame::Type type) {
ASSERT(jssp.Is(StackPointer()));
UseScratchRegisterScope temps(this);
Register type_reg = temps.AcquireX();
Register code_reg = temps.AcquireX();
Push(lr, fp, cp);
Mov(type_reg, Smi::FromInt(type));
Mov(code_reg, Operand(CodeObject()));
Push(type_reg, code_reg);
// jssp[4] : lr
// jssp[3] : fp
// jssp[2] : cp
// jssp[1] : type
// jssp[0] : code object
// Adjust FP to point to saved FP.
Add(fp, jssp, StandardFrameConstants::kFixedFrameSizeFromFp + kPointerSize);
}
void MacroAssembler::LeaveFrame(StackFrame::Type type) {
ASSERT(jssp.Is(StackPointer()));
// Drop the execution stack down to the frame pointer and restore
// the caller frame pointer and return address.
Mov(jssp, fp);
AssertStackConsistency();
Pop(fp, lr);
}
void MacroAssembler::ExitFramePreserveFPRegs() {
PushCPURegList(kCallerSavedFP);
}
void MacroAssembler::ExitFrameRestoreFPRegs() {
// Read the registers from the stack without popping them. The stack pointer
// will be reset as part of the unwinding process.
CPURegList saved_fp_regs = kCallerSavedFP;
ASSERT(saved_fp_regs.Count() % 2 == 0);
int offset = ExitFrameConstants::kLastExitFrameField;
while (!saved_fp_regs.IsEmpty()) {
const CPURegister& dst0 = saved_fp_regs.PopHighestIndex();
const CPURegister& dst1 = saved_fp_regs.PopHighestIndex();
offset -= 2 * kDRegSize;
Ldp(dst1, dst0, MemOperand(fp, offset));
}
}
void MacroAssembler::EnterExitFrame(bool save_doubles,
const Register& scratch,
int extra_space) {
ASSERT(jssp.Is(StackPointer()));
// Set up the new stack frame.
Mov(scratch, Operand(CodeObject()));
Push(lr, fp);
Mov(fp, StackPointer());
Push(xzr, scratch);
// fp[8]: CallerPC (lr)
// fp -> fp[0]: CallerFP (old fp)
// fp[-8]: Space reserved for SPOffset.
// jssp -> fp[-16]: CodeObject()
STATIC_ASSERT((2 * kPointerSize) ==
ExitFrameConstants::kCallerSPDisplacement);
STATIC_ASSERT((1 * kPointerSize) == ExitFrameConstants::kCallerPCOffset);
STATIC_ASSERT((0 * kPointerSize) == ExitFrameConstants::kCallerFPOffset);
STATIC_ASSERT((-1 * kPointerSize) == ExitFrameConstants::kSPOffset);
STATIC_ASSERT((-2 * kPointerSize) == ExitFrameConstants::kCodeOffset);
// Save the frame pointer and context pointer in the top frame.
Mov(scratch, Operand(ExternalReference(Isolate::kCEntryFPAddress,
isolate())));
Str(fp, MemOperand(scratch));
Mov(scratch, Operand(ExternalReference(Isolate::kContextAddress,
isolate())));
Str(cp, MemOperand(scratch));
STATIC_ASSERT((-2 * kPointerSize) ==
ExitFrameConstants::kLastExitFrameField);
if (save_doubles) {
ExitFramePreserveFPRegs();
}
// Reserve space for the return address and for user requested memory.
// We do this before aligning to make sure that we end up correctly
// aligned with the minimum of wasted space.
Claim(extra_space + 1, kXRegSize);
// fp[8]: CallerPC (lr)
// fp -> fp[0]: CallerFP (old fp)
// fp[-8]: Space reserved for SPOffset.
// fp[-16]: CodeObject()
// fp[-16 - fp_size]: Saved doubles (if save_doubles is true).
// jssp[8]: Extra space reserved for caller (if extra_space != 0).
// jssp -> jssp[0]: Space reserved for the return address.
// Align and synchronize the system stack pointer with jssp.
AlignAndSetCSPForFrame();
ASSERT(csp.Is(StackPointer()));
// fp[8]: CallerPC (lr)
// fp -> fp[0]: CallerFP (old fp)
// fp[-8]: Space reserved for SPOffset.
// fp[-16]: CodeObject()
// fp[-16 - fp_size]: Saved doubles (if save_doubles is true).
// csp[8]: Memory reserved for the caller if extra_space != 0.
// Alignment padding, if necessary.
// csp -> csp[0]: Space reserved for the return address.
// ExitFrame::GetStateForFramePointer expects to find the return address at
// the memory address immediately below the pointer stored in SPOffset.
// It is not safe to derive much else from SPOffset, because the size of the
// padding can vary.
Add(scratch, csp, kXRegSize);
Str(scratch, MemOperand(fp, ExitFrameConstants::kSPOffset));
}
// Leave the current exit frame.
void MacroAssembler::LeaveExitFrame(bool restore_doubles,
const Register& scratch,
bool restore_context) {
ASSERT(csp.Is(StackPointer()));
if (restore_doubles) {
ExitFrameRestoreFPRegs();
}
// Restore the context pointer from the top frame.
if (restore_context) {
Mov(scratch, Operand(ExternalReference(Isolate::kContextAddress,
isolate())));
Ldr(cp, MemOperand(scratch));
}
if (emit_debug_code()) {
// Also emit debug code to clear the cp in the top frame.
Mov(scratch, Operand(ExternalReference(Isolate::kContextAddress,
isolate())));
Str(xzr, MemOperand(scratch));
}
// Clear the frame pointer from the top frame.
Mov(scratch, Operand(ExternalReference(Isolate::kCEntryFPAddress,
isolate())));
Str(xzr, MemOperand(scratch));
// Pop the exit frame.
// fp[8]: CallerPC (lr)
// fp -> fp[0]: CallerFP (old fp)
// fp[...]: The rest of the frame.
Mov(jssp, fp);
SetStackPointer(jssp);
AssertStackConsistency();
Pop(fp, lr);
}
void MacroAssembler::SetCounter(StatsCounter* counter, int value,
Register scratch1, Register scratch2) {
if (FLAG_native_code_counters && counter->Enabled()) {
Mov(scratch1, value);
Mov(scratch2, ExternalReference(counter));
Str(scratch1, MemOperand(scratch2));
}
}
void MacroAssembler::IncrementCounter(StatsCounter* counter, int value,
Register scratch1, Register scratch2) {
ASSERT(value != 0);
if (FLAG_native_code_counters && counter->Enabled()) {
Mov(scratch2, ExternalReference(counter));
Ldr(scratch1, MemOperand(scratch2));
Add(scratch1, scratch1, value);
Str(scratch1, MemOperand(scratch2));
}
}
void MacroAssembler::DecrementCounter(StatsCounter* counter, int value,
Register scratch1, Register scratch2) {
IncrementCounter(counter, -value, scratch1, scratch2);
}
void MacroAssembler::LoadContext(Register dst, int context_chain_length) {
if (context_chain_length > 0) {
// Move up the chain of contexts to the context containing the slot.
Ldr(dst, MemOperand(cp, Context::SlotOffset(Context::PREVIOUS_INDEX)));
for (int i = 1; i < context_chain_length; i++) {
Ldr(dst, MemOperand(dst, Context::SlotOffset(Context::PREVIOUS_INDEX)));
}
} else {
// Slot is in the current function context. Move it into the
// destination register in case we store into it (the write barrier
// cannot be allowed to destroy the context in cp).
Mov(dst, cp);
}
}
void MacroAssembler::DebugBreak() {
Mov(x0, 0);
Mov(x1, ExternalReference(Runtime::kDebugBreak, isolate()));
CEntryStub ces(isolate(), 1);
ASSERT(AllowThisStubCall(&ces));
Call(ces.GetCode(), RelocInfo::DEBUG_BREAK);
}
void MacroAssembler::PushTryHandler(StackHandler::Kind kind,
int handler_index) {
ASSERT(jssp.Is(StackPointer()));
// Adjust this code if the asserts don't hold.
STATIC_ASSERT(StackHandlerConstants::kSize == 5 * kPointerSize);
STATIC_ASSERT(StackHandlerConstants::kNextOffset == 0 * kPointerSize);
STATIC_ASSERT(StackHandlerConstants::kCodeOffset == 1 * kPointerSize);
STATIC_ASSERT(StackHandlerConstants::kStateOffset == 2 * kPointerSize);
STATIC_ASSERT(StackHandlerConstants::kContextOffset == 3 * kPointerSize);
STATIC_ASSERT(StackHandlerConstants::kFPOffset == 4 * kPointerSize);
// For the JSEntry handler, we must preserve the live registers x0-x4.
// (See JSEntryStub::GenerateBody().)
unsigned state =
StackHandler::IndexField::encode(handler_index) |
StackHandler::KindField::encode(kind);
// Set up the code object and the state for pushing.
Mov(x10, Operand(CodeObject()));
Mov(x11, state);
// Push the frame pointer, context, state, and code object.
if (kind == StackHandler::JS_ENTRY) {
ASSERT(Smi::FromInt(0) == 0);
Push(xzr, xzr, x11, x10);
} else {
Push(fp, cp, x11, x10);
}
// Link the current handler as the next handler.
Mov(x11, ExternalReference(Isolate::kHandlerAddress, isolate()));
Ldr(x10, MemOperand(x11));
Push(x10);
// Set this new handler as the current one.
Str(jssp, MemOperand(x11));
}
void MacroAssembler::PopTryHandler() {
STATIC_ASSERT(StackHandlerConstants::kNextOffset == 0);
Pop(x10);
Mov(x11, ExternalReference(Isolate::kHandlerAddress, isolate()));
Drop(StackHandlerConstants::kSize - kXRegSize, kByteSizeInBytes);
Str(x10, MemOperand(x11));
}
void MacroAssembler::Allocate(int object_size,
Register result,
Register scratch1,
Register scratch2,
Label* gc_required,
AllocationFlags flags) {
ASSERT(object_size <= Page::kMaxRegularHeapObjectSize);
if (!FLAG_inline_new) {
if (emit_debug_code()) {
// Trash the registers to simulate an allocation failure.
// We apply salt to the original zap value to easily spot the values.
Mov(result, (kDebugZapValue & ~0xffL) | 0x11L);
Mov(scratch1, (kDebugZapValue & ~0xffL) | 0x21L);
Mov(scratch2, (kDebugZapValue & ~0xffL) | 0x21L);
}
B(gc_required);
return;
}
UseScratchRegisterScope temps(this);
Register scratch3 = temps.AcquireX();
ASSERT(!AreAliased(result, scratch1, scratch2, scratch3));
ASSERT(result.Is64Bits() && scratch1.Is64Bits() && scratch2.Is64Bits());
// Make object size into bytes.
if ((flags & SIZE_IN_WORDS) != 0) {
object_size *= kPointerSize;
}
ASSERT(0 == (object_size & kObjectAlignmentMask));
// Check relative positions of allocation top and limit addresses.
// The values must be adjacent in memory to allow the use of LDP.
ExternalReference heap_allocation_top =
AllocationUtils::GetAllocationTopReference(isolate(), flags);
ExternalReference heap_allocation_limit =
AllocationUtils::GetAllocationLimitReference(isolate(), flags);
intptr_t top = reinterpret_cast<intptr_t>(heap_allocation_top.address());
intptr_t limit = reinterpret_cast<intptr_t>(heap_allocation_limit.address());
ASSERT((limit - top) == kPointerSize);
// Set up allocation top address and object size registers.
Register top_address = scratch1;
Register allocation_limit = scratch2;
Mov(top_address, Operand(heap_allocation_top));
if ((flags & RESULT_CONTAINS_TOP) == 0) {
// Load allocation top into result and the allocation limit.
Ldp(result, allocation_limit, MemOperand(top_address));
} else {
if (emit_debug_code()) {
// Assert that result actually contains top on entry.
Ldr(scratch3, MemOperand(top_address));
Cmp(result, scratch3);
Check(eq, kUnexpectedAllocationTop);
}
// Load the allocation limit. 'result' already contains the allocation top.
Ldr(allocation_limit, MemOperand(top_address, limit - top));
}
// We can ignore DOUBLE_ALIGNMENT flags here because doubles and pointers have
// the same alignment on ARM64.
STATIC_ASSERT(kPointerAlignment == kDoubleAlignment);
// Calculate new top and bail out if new space is exhausted.
Adds(scratch3, result, object_size);
Ccmp(scratch3, allocation_limit, CFlag, cc);
B(hi, gc_required);
Str(scratch3, MemOperand(top_address));
// Tag the object if requested.
if ((flags & TAG_OBJECT) != 0) {
ObjectTag(result, result);
}
}
void MacroAssembler::Allocate(Register object_size,
Register result,
Register scratch1,
Register scratch2,
Label* gc_required,
AllocationFlags flags) {
if (!FLAG_inline_new) {
if (emit_debug_code()) {
// Trash the registers to simulate an allocation failure.
// We apply salt to the original zap value to easily spot the values.
Mov(result, (kDebugZapValue & ~0xffL) | 0x11L);
Mov(scratch1, (kDebugZapValue & ~0xffL) | 0x21L);
Mov(scratch2, (kDebugZapValue & ~0xffL) | 0x21L);
}
B(gc_required);
return;
}
UseScratchRegisterScope temps(this);
Register scratch3 = temps.AcquireX();
ASSERT(!AreAliased(object_size, result, scratch1, scratch2, scratch3));
ASSERT(object_size.Is64Bits() && result.Is64Bits() &&
scratch1.Is64Bits() && scratch2.Is64Bits());
// Check relative positions of allocation top and limit addresses.
// The values must be adjacent in memory to allow the use of LDP.
ExternalReference heap_allocation_top =
AllocationUtils::GetAllocationTopReference(isolate(), flags);
ExternalReference heap_allocation_limit =
AllocationUtils::GetAllocationLimitReference(isolate(), flags);
intptr_t top = reinterpret_cast<intptr_t>(heap_allocation_top.address());
intptr_t limit = reinterpret_cast<intptr_t>(heap_allocation_limit.address());
ASSERT((limit - top) == kPointerSize);
// Set up allocation top address and object size registers.
Register top_address = scratch1;
Register allocation_limit = scratch2;
Mov(top_address, heap_allocation_top);
if ((flags & RESULT_CONTAINS_TOP) == 0) {
// Load allocation top into result and the allocation limit.
Ldp(result, allocation_limit, MemOperand(top_address));
} else {
if (emit_debug_code()) {
// Assert that result actually contains top on entry.
Ldr(scratch3, MemOperand(top_address));
Cmp(result, scratch3);
Check(eq, kUnexpectedAllocationTop);
}
// Load the allocation limit. 'result' already contains the allocation top.
Ldr(allocation_limit, MemOperand(top_address, limit - top));
}
// We can ignore DOUBLE_ALIGNMENT flags here because doubles and pointers have
// the same alignment on ARM64.
STATIC_ASSERT(kPointerAlignment == kDoubleAlignment);
// Calculate new top and bail out if new space is exhausted
if ((flags & SIZE_IN_WORDS) != 0) {
Adds(scratch3, result, Operand(object_size, LSL, kPointerSizeLog2));
} else {
Adds(scratch3, result, object_size);
}
if (emit_debug_code()) {
Tst(scratch3, kObjectAlignmentMask);
Check(eq, kUnalignedAllocationInNewSpace);
}
Ccmp(scratch3, allocation_limit, CFlag, cc);
B(hi, gc_required);
Str(scratch3, MemOperand(top_address));
// Tag the object if requested.
if ((flags & TAG_OBJECT) != 0) {
ObjectTag(result, result);
}
}
void MacroAssembler::UndoAllocationInNewSpace(Register object,
Register scratch) {
ExternalReference new_space_allocation_top =
ExternalReference::new_space_allocation_top_address(isolate());
// Make sure the object has no tag before resetting top.
Bic(object, object, kHeapObjectTagMask);
#ifdef DEBUG
// Check that the object un-allocated is below the current top.
Mov(scratch, new_space_allocation_top);
Ldr(scratch, MemOperand(scratch));
Cmp(object, scratch);
Check(lt, kUndoAllocationOfNonAllocatedMemory);
#endif
// Write the address of the object to un-allocate as the current top.
Mov(scratch, new_space_allocation_top);
Str(object, MemOperand(scratch));
}
void MacroAssembler::AllocateTwoByteString(Register result,
Register length,
Register scratch1,
Register scratch2,
Register scratch3,
Label* gc_required) {
ASSERT(!AreAliased(result, length, scratch1, scratch2, scratch3));
// Calculate the number of bytes needed for the characters in the string while
// observing object alignment.
STATIC_ASSERT((SeqTwoByteString::kHeaderSize & kObjectAlignmentMask) == 0);
Add(scratch1, length, length); // Length in bytes, not chars.
Add(scratch1, scratch1, kObjectAlignmentMask + SeqTwoByteString::kHeaderSize);
Bic(scratch1, scratch1, kObjectAlignmentMask);
// Allocate two-byte string in new space.
Allocate(scratch1,
result,
scratch2,
scratch3,
gc_required,
TAG_OBJECT);
// Set the map, length and hash field.
InitializeNewString(result,
length,
Heap::kStringMapRootIndex,
scratch1,
scratch2);
}
void MacroAssembler::AllocateAsciiString(Register result,
Register length,
Register scratch1,
Register scratch2,
Register scratch3,
Label* gc_required) {
ASSERT(!AreAliased(result, length, scratch1, scratch2, scratch3));
// Calculate the number of bytes needed for the characters in the string while
// observing object alignment.
STATIC_ASSERT((SeqOneByteString::kHeaderSize & kObjectAlignmentMask) == 0);
STATIC_ASSERT(kCharSize == 1);
Add(scratch1, length, kObjectAlignmentMask + SeqOneByteString::kHeaderSize);
Bic(scratch1, scratch1, kObjectAlignmentMask);
// Allocate ASCII string in new space.
Allocate(scratch1,
result,
scratch2,
scratch3,
gc_required,
TAG_OBJECT);
// Set the map, length and hash field.
InitializeNewString(result,
length,
Heap::kAsciiStringMapRootIndex,
scratch1,
scratch2);
}
void MacroAssembler::AllocateTwoByteConsString(Register result,
Register length,
Register scratch1,
Register scratch2,
Label* gc_required) {
Allocate(ConsString::kSize, result, scratch1, scratch2, gc_required,
TAG_OBJECT);
InitializeNewString(result,
length,
Heap::kConsStringMapRootIndex,
scratch1,
scratch2);
}
void MacroAssembler::AllocateAsciiConsString(Register result,
Register length,
Register scratch1,
Register scratch2,
Label* gc_required) {
Allocate(ConsString::kSize,
result,
scratch1,
scratch2,
gc_required,
TAG_OBJECT);
InitializeNewString(result,
length,
Heap::kConsAsciiStringMapRootIndex,
scratch1,
scratch2);
}
void MacroAssembler::AllocateTwoByteSlicedString(Register result,
Register length,
Register scratch1,
Register scratch2,
Label* gc_required) {
ASSERT(!AreAliased(result, length, scratch1, scratch2));
Allocate(SlicedString::kSize, result, scratch1, scratch2, gc_required,
TAG_OBJECT);
InitializeNewString(result,
length,
Heap::kSlicedStringMapRootIndex,
scratch1,
scratch2);
}
void MacroAssembler::AllocateAsciiSlicedString(Register result,
Register length,
Register scratch1,
Register scratch2,
Label* gc_required) {
ASSERT(!AreAliased(result, length, scratch1, scratch2));
Allocate(SlicedString::kSize, result, scratch1, scratch2, gc_required,
TAG_OBJECT);
InitializeNewString(result,
length,
Heap::kSlicedAsciiStringMapRootIndex,
scratch1,
scratch2);
}
// Allocates a heap number or jumps to the need_gc label if the young space
// is full and a scavenge is needed.
void MacroAssembler::AllocateHeapNumber(Register result,
Label* gc_required,
Register scratch1,
Register scratch2,
CPURegister value,
CPURegister heap_number_map,
MutableMode mode) {
ASSERT(!value.IsValid() || value.Is64Bits());
UseScratchRegisterScope temps(this);
// Allocate an object in the heap for the heap number and tag it as a heap
// object.
Allocate(HeapNumber::kSize, result, scratch1, scratch2, gc_required,
NO_ALLOCATION_FLAGS);
Heap::RootListIndex map_index = mode == MUTABLE
? Heap::kMutableHeapNumberMapRootIndex
: Heap::kHeapNumberMapRootIndex;
// Prepare the heap number map.
if (!heap_number_map.IsValid()) {
// If we have a valid value register, use the same type of register to store
// the map so we can use STP to store both in one instruction.
if (value.IsValid() && value.IsFPRegister()) {
heap_number_map = temps.AcquireD();
} else {
heap_number_map = scratch1;
}
LoadRoot(heap_number_map, map_index);
}
if (emit_debug_code()) {
Register map;
if (heap_number_map.IsFPRegister()) {
map = scratch1;
Fmov(map, DoubleRegister(heap_number_map));
} else {
map = Register(heap_number_map);
}
AssertRegisterIsRoot(map, map_index);
}
// Store the heap number map and the value in the allocated object.
if (value.IsSameSizeAndType(heap_number_map)) {
STATIC_ASSERT(HeapObject::kMapOffset + kPointerSize ==
HeapNumber::kValueOffset);
Stp(heap_number_map, value, MemOperand(result, HeapObject::kMapOffset));
} else {
Str(heap_number_map, MemOperand(result, HeapObject::kMapOffset));
if (value.IsValid()) {
Str(value, MemOperand(result, HeapNumber::kValueOffset));
}
}
ObjectTag(result, result);
}
void MacroAssembler::JumpIfObjectType(Register object,
Register map,
Register type_reg,
InstanceType type,
Label* if_cond_pass,
Condition cond) {
CompareObjectType(object, map, type_reg, type);
B(cond, if_cond_pass);
}
void MacroAssembler::JumpIfNotObjectType(Register object,
Register map,
Register type_reg,
InstanceType type,
Label* if_not_object) {
JumpIfObjectType(object, map, type_reg, type, if_not_object, ne);
}
// Sets condition flags based on comparison, and returns type in type_reg.
void MacroAssembler::CompareObjectType(Register object,
Register map,
Register type_reg,
InstanceType type) {
Ldr(map, FieldMemOperand(object, HeapObject::kMapOffset));
CompareInstanceType(map, type_reg, type);
}
// Sets condition flags based on comparison, and returns type in type_reg.
void MacroAssembler::CompareInstanceType(Register map,
Register type_reg,
InstanceType type) {
Ldrb(type_reg, FieldMemOperand(map, Map::kInstanceTypeOffset));
Cmp(type_reg, type);
}
void MacroAssembler::CompareMap(Register obj,
Register scratch,
Handle<Map> map) {
Ldr(scratch, FieldMemOperand(obj, HeapObject::kMapOffset));
CompareMap(scratch, map);
}
void MacroAssembler::CompareMap(Register obj_map,
Handle<Map> map) {
Cmp(obj_map, Operand(map));
}
void MacroAssembler::CheckMap(Register obj,
Register scratch,
Handle<Map> map,
Label* fail,
SmiCheckType smi_check_type) {
if (smi_check_type == DO_SMI_CHECK) {
JumpIfSmi(obj, fail);
}
CompareMap(obj, scratch, map);
B(ne, fail);
}
void MacroAssembler::CheckMap(Register obj,
Register scratch,
Heap::RootListIndex index,
Label* fail,
SmiCheckType smi_check_type) {
if (smi_check_type == DO_SMI_CHECK) {
JumpIfSmi(obj, fail);
}
Ldr(scratch, FieldMemOperand(obj, HeapObject::kMapOffset));
JumpIfNotRoot(scratch, index, fail);
}
void MacroAssembler::CheckMap(Register obj_map,
Handle<Map> map,
Label* fail,
SmiCheckType smi_check_type) {
if (smi_check_type == DO_SMI_CHECK) {
JumpIfSmi(obj_map, fail);
}
CompareMap(obj_map, map);
B(ne, fail);
}
void MacroAssembler::DispatchMap(Register obj,
Register scratch,
Handle<Map> map,
Handle<Code> success,
SmiCheckType smi_check_type) {
Label fail;
if (smi_check_type == DO_SMI_CHECK) {
JumpIfSmi(obj, &fail);
}
Ldr(scratch, FieldMemOperand(obj, HeapObject::kMapOffset));
Cmp(scratch, Operand(map));
B(ne, &fail);
Jump(success, RelocInfo::CODE_TARGET);
Bind(&fail);
}
void MacroAssembler::TestMapBitfield(Register object, uint64_t mask) {
UseScratchRegisterScope temps(this);
Register temp = temps.AcquireX();
Ldr(temp, FieldMemOperand(object, HeapObject::kMapOffset));
Ldrb(temp, FieldMemOperand(temp, Map::kBitFieldOffset));
Tst(temp, mask);
}
void MacroAssembler::LoadElementsKindFromMap(Register result, Register map) {
// Load the map's "bit field 2".
__ Ldrb(result, FieldMemOperand(map, Map::kBitField2Offset));
// Retrieve elements_kind from bit field 2.
DecodeField<Map::ElementsKindBits>(result);
}
void MacroAssembler::TryGetFunctionPrototype(Register function,
Register result,
Register scratch,
Label* miss,
BoundFunctionAction action) {
ASSERT(!AreAliased(function, result, scratch));
// Check that the receiver isn't a smi.
JumpIfSmi(function, miss);
// Check that the function really is a function. Load map into result reg.
JumpIfNotObjectType(function, result, scratch, JS_FUNCTION_TYPE, miss);
if (action == kMissOnBoundFunction) {
Register scratch_w = scratch.W();
Ldr(scratch,
FieldMemOperand(function, JSFunction::kSharedFunctionInfoOffset));
// On 64-bit platforms, compiler hints field is not a smi. See definition of
// kCompilerHintsOffset in src/objects.h.
Ldr(scratch_w,
FieldMemOperand(scratch, SharedFunctionInfo::kCompilerHintsOffset));
Tbnz(scratch, SharedFunctionInfo::kBoundFunction, miss);
}
// Make sure that the function has an instance prototype.
Label non_instance;
Ldrb(scratch, FieldMemOperand(result, Map::kBitFieldOffset));
Tbnz(scratch, Map::kHasNonInstancePrototype, &non_instance);
// Get the prototype or initial map from the function.
Ldr(result,
FieldMemOperand(function, JSFunction::kPrototypeOrInitialMapOffset));
// If the prototype or initial map is the hole, don't return it and simply
// miss the cache instead. This will allow us to allocate a prototype object
// on-demand in the runtime system.
JumpIfRoot(result, Heap::kTheHoleValueRootIndex, miss);
// If the function does not have an initial map, we're done.
Label done;
JumpIfNotObjectType(result, scratch, scratch, MAP_TYPE, &done);
// Get the prototype from the initial map.
Ldr(result, FieldMemOperand(result, Map::kPrototypeOffset));
B(&done);
// Non-instance prototype: fetch prototype from constructor field in initial
// map.
Bind(&non_instance);
Ldr(result, FieldMemOperand(result, Map::kConstructorOffset));
// All done.
Bind(&done);
}
void MacroAssembler::CompareRoot(const Register& obj,
Heap::RootListIndex index) {
UseScratchRegisterScope temps(this);
Register temp = temps.AcquireX();
ASSERT(!AreAliased(obj, temp));
LoadRoot(temp, index);
Cmp(obj, temp);
}
void MacroAssembler::JumpIfRoot(const Register& obj,
Heap::RootListIndex index,
Label* if_equal) {
CompareRoot(obj, index);
B(eq, if_equal);
}
void MacroAssembler::JumpIfNotRoot(const Register& obj,
Heap::RootListIndex index,
Label* if_not_equal) {
CompareRoot(obj, index);
B(ne, if_not_equal);
}
void MacroAssembler::CompareAndSplit(const Register& lhs,
const Operand& rhs,
Condition cond,
Label* if_true,
Label* if_false,
Label* fall_through) {
if ((if_true == if_false) && (if_false == fall_through)) {
// Fall through.
} else if (if_true == if_false) {
B(if_true);
} else if (if_false == fall_through) {
CompareAndBranch(lhs, rhs, cond, if_true);
} else if (if_true == fall_through) {
CompareAndBranch(lhs, rhs, NegateCondition(cond), if_false);
} else {
CompareAndBranch(lhs, rhs, cond, if_true);
B(if_false);
}
}
void MacroAssembler::TestAndSplit(const Register& reg,
uint64_t bit_pattern,
Label* if_all_clear,
Label* if_any_set,
Label* fall_through) {
if ((if_all_clear == if_any_set) && (if_any_set == fall_through)) {
// Fall through.
} else if (if_all_clear == if_any_set) {
B(if_all_clear);
} else if (if_all_clear == fall_through) {
TestAndBranchIfAnySet(reg, bit_pattern, if_any_set);
} else if (if_any_set == fall_through) {
TestAndBranchIfAllClear(reg, bit_pattern, if_all_clear);
} else {
TestAndBranchIfAnySet(reg, bit_pattern, if_any_set);
B(if_all_clear);
}
}
void MacroAssembler::CheckFastElements(Register map,
Register scratch,
Label* fail) {
STATIC_ASSERT(FAST_SMI_ELEMENTS == 0);
STATIC_ASSERT(FAST_HOLEY_SMI_ELEMENTS == 1);
STATIC_ASSERT(FAST_ELEMENTS == 2);
STATIC_ASSERT(FAST_HOLEY_ELEMENTS == 3);
Ldrb(scratch, FieldMemOperand(map, Map::kBitField2Offset));
Cmp(scratch, Map::kMaximumBitField2FastHoleyElementValue);
B(hi, fail);
}
void MacroAssembler::CheckFastObjectElements(Register map,
Register scratch,
Label* fail) {
STATIC_ASSERT(FAST_SMI_ELEMENTS == 0);
STATIC_ASSERT(FAST_HOLEY_SMI_ELEMENTS == 1);
STATIC_ASSERT(FAST_ELEMENTS == 2);
STATIC_ASSERT(FAST_HOLEY_ELEMENTS == 3);
Ldrb(scratch, FieldMemOperand(map, Map::kBitField2Offset));
Cmp(scratch, Operand(Map::kMaximumBitField2FastHoleySmiElementValue));
// If cond==ls, set cond=hi, otherwise compare.
Ccmp(scratch,
Operand(Map::kMaximumBitField2FastHoleyElementValue), CFlag, hi);
B(hi, fail);
}
// Note: The ARM version of this clobbers elements_reg, but this version does
// not. Some uses of this in ARM64 assume that elements_reg will be preserved.
void MacroAssembler::StoreNumberToDoubleElements(Register value_reg,
Register key_reg,
Register elements_reg,
Register scratch1,
FPRegister fpscratch1,
Label* fail,
int elements_offset) {
ASSERT(!AreAliased(value_reg, key_reg, elements_reg, scratch1));
Label store_num;
// Speculatively convert the smi to a double - all smis can be exactly
// represented as a double.
SmiUntagToDouble(fpscratch1, value_reg, kSpeculativeUntag);
// If value_reg is a smi, we're done.
JumpIfSmi(value_reg, &store_num);
// Ensure that the object is a heap number.
CheckMap(value_reg, scratch1, isolate()->factory()->heap_number_map(),
fail, DONT_DO_SMI_CHECK);
Ldr(fpscratch1, FieldMemOperand(value_reg, HeapNumber::kValueOffset));
// Canonicalize NaNs.
CanonicalizeNaN(fpscratch1);
// Store the result.
Bind(&store_num);
Add(scratch1, elements_reg,
Operand::UntagSmiAndScale(key_reg, kDoubleSizeLog2));
Str(fpscratch1,
FieldMemOperand(scratch1,
FixedDoubleArray::kHeaderSize - elements_offset));
}
bool MacroAssembler::AllowThisStubCall(CodeStub* stub) {
return has_frame_ || !stub->SometimesSetsUpAFrame();
}
void MacroAssembler::IndexFromHash(Register hash, Register index) {
// If the hash field contains an array index pick it out. The assert checks
// that the constants for the maximum number of digits for an array index
// cached in the hash field and the number of bits reserved for it does not
// conflict.
ASSERT(TenToThe(String::kMaxCachedArrayIndexLength) <
(1 << String::kArrayIndexValueBits));
DecodeField<String::ArrayIndexValueBits>(index, hash);
SmiTag(index, index);
}
void MacroAssembler::EmitSeqStringSetCharCheck(
Register string,
Register index,
SeqStringSetCharCheckIndexType index_type,
Register scratch,
uint32_t encoding_mask) {
ASSERT(!AreAliased(string, index, scratch));
if (index_type == kIndexIsSmi) {
AssertSmi(index);
}
// Check that string is an object.
AssertNotSmi(string, kNonObject);
// Check that string has an appropriate map.
Ldr(scratch, FieldMemOperand(string, HeapObject::kMapOffset));
Ldrb(scratch, FieldMemOperand(scratch, Map::kInstanceTypeOffset));
And(scratch, scratch, kStringRepresentationMask | kStringEncodingMask);
Cmp(scratch, encoding_mask);
Check(eq, kUnexpectedStringType);
Ldr(scratch, FieldMemOperand(string, String::kLengthOffset));
Cmp(index, index_type == kIndexIsSmi ? scratch : Operand::UntagSmi(scratch));
Check(lt, kIndexIsTooLarge);
ASSERT_EQ(0, Smi::FromInt(0));
Cmp(index, 0);
Check(ge, kIndexIsNegative);
}
void MacroAssembler::CheckAccessGlobalProxy(Register holder_reg,
Register scratch1,
Register scratch2,
Label* miss) {
ASSERT(!AreAliased(holder_reg, scratch1, scratch2));
Label same_contexts;
// Load current lexical context from the stack frame.
Ldr(scratch1, MemOperand(fp, StandardFrameConstants::kContextOffset));
// In debug mode, make sure the lexical context is set.
#ifdef DEBUG
Cmp(scratch1, 0);
Check(ne, kWeShouldNotHaveAnEmptyLexicalContext);
#endif
// Load the native context of the current context.
int offset =
Context::kHeaderSize + Context::GLOBAL_OBJECT_INDEX * kPointerSize;
Ldr(scratch1, FieldMemOperand(scratch1, offset));
Ldr(scratch1, FieldMemOperand(scratch1, GlobalObject::kNativeContextOffset));
// Check the context is a native context.
if (emit_debug_code()) {
// Read the first word and compare to the global_context_map.
Ldr(scratch2, FieldMemOperand(scratch1, HeapObject::kMapOffset));
CompareRoot(scratch2, Heap::kNativeContextMapRootIndex);
Check(eq, kExpectedNativeContext);
}
// Check if both contexts are the same.
Ldr(scratch2, FieldMemOperand(holder_reg,
JSGlobalProxy::kNativeContextOffset));
Cmp(scratch1, scratch2);
B(&same_contexts, eq);
// Check the context is a native context.
if (emit_debug_code()) {
// We're short on scratch registers here, so use holder_reg as a scratch.
Push(holder_reg);
Register scratch3 = holder_reg;
CompareRoot(scratch2, Heap::kNullValueRootIndex);
Check(ne, kExpectedNonNullContext);
Ldr(scratch3, FieldMemOperand(scratch2, HeapObject::kMapOffset));
CompareRoot(scratch3, Heap::kNativeContextMapRootIndex);
Check(eq, kExpectedNativeContext);
Pop(holder_reg);
}
// Check that the security token in the calling global object is
// compatible with the security token in the receiving global
// object.
int token_offset = Context::kHeaderSize +
Context::SECURITY_TOKEN_INDEX * kPointerSize;
Ldr(scratch1, FieldMemOperand(scratch1, token_offset));
Ldr(scratch2, FieldMemOperand(scratch2, token_offset));
Cmp(scratch1, scratch2);
B(miss, ne);
Bind(&same_contexts);
}
// Compute the hash code from the untagged key. This must be kept in sync with
// ComputeIntegerHash in utils.h and KeyedLoadGenericElementStub in
// code-stub-hydrogen.cc
void MacroAssembler::GetNumberHash(Register key, Register scratch) {
ASSERT(!AreAliased(key, scratch));
// Xor original key with a seed.
LoadRoot(scratch, Heap::kHashSeedRootIndex);
Eor(key, key, Operand::UntagSmi(scratch));
// The algorithm uses 32-bit integer values.
key = key.W();
scratch = scratch.W();
// Compute the hash code from the untagged key. This must be kept in sync
// with ComputeIntegerHash in utils.h.
//
// hash = ~hash + (hash <<1 15);
Mvn(scratch, key);
Add(key, scratch, Operand(key, LSL, 15));
// hash = hash ^ (hash >> 12);
Eor(key, key, Operand(key, LSR, 12));
// hash = hash + (hash << 2);
Add(key, key, Operand(key, LSL, 2));
// hash = hash ^ (hash >> 4);
Eor(key, key, Operand(key, LSR, 4));
// hash = hash * 2057;
Mov(scratch, Operand(key, LSL, 11));
Add(key, key, Operand(key, LSL, 3));
Add(key, key, scratch);
// hash = hash ^ (hash >> 16);
Eor(key, key, Operand(key, LSR, 16));
}
void MacroAssembler::LoadFromNumberDictionary(Label* miss,
Register elements,
Register key,
Register result,
Register scratch0,
Register scratch1,
Register scratch2,
Register scratch3) {
ASSERT(!AreAliased(elements, key, scratch0, scratch1, scratch2, scratch3));
Label done;
SmiUntag(scratch0, key);
GetNumberHash(scratch0, scratch1);
// Compute the capacity mask.
Ldrsw(scratch1,
UntagSmiFieldMemOperand(elements,
SeededNumberDictionary::kCapacityOffset));
Sub(scratch1, scratch1, 1);
// Generate an unrolled loop that performs a few probes before giving up.
for (int i = 0; i < kNumberDictionaryProbes; i++) {
// Compute the masked index: (hash + i + i * i) & mask.
if (i > 0) {
Add(scratch2, scratch0, SeededNumberDictionary::GetProbeOffset(i));
} else {
Mov(scratch2, scratch0);
}
And(scratch2, scratch2, scratch1);
// Scale the index by multiplying by the element size.
ASSERT(SeededNumberDictionary::kEntrySize == 3);
Add(scratch2, scratch2, Operand(scratch2, LSL, 1));
// Check if the key is identical to the name.
Add(scratch2, elements, Operand(scratch2, LSL, kPointerSizeLog2));
Ldr(scratch3,
FieldMemOperand(scratch2,
SeededNumberDictionary::kElementsStartOffset));
Cmp(key, scratch3);
if (i != (kNumberDictionaryProbes - 1)) {
B(eq, &done);
} else {
B(ne, miss);
}
}
Bind(&done);
// Check that the value is a normal property.
const int kDetailsOffset =
SeededNumberDictionary::kElementsStartOffset + 2 * kPointerSize;
Ldrsw(scratch1, UntagSmiFieldMemOperand(scratch2, kDetailsOffset));
TestAndBranchIfAnySet(scratch1, PropertyDetails::TypeField::kMask, miss);
// Get the value at the masked, scaled index and return.
const int kValueOffset =
SeededNumberDictionary::kElementsStartOffset + kPointerSize;
Ldr(result, FieldMemOperand(scratch2, kValueOffset));
}
void MacroAssembler::RememberedSetHelper(Register object, // For debug tests.
Register address,
Register scratch1,
SaveFPRegsMode fp_mode,
RememberedSetFinalAction and_then) {
ASSERT(!AreAliased(object, address, scratch1));
Label done, store_buffer_overflow;
if (emit_debug_code()) {
Label ok;
JumpIfNotInNewSpace(object, &ok);
Abort(kRememberedSetPointerInNewSpace);
bind(&ok);
}
UseScratchRegisterScope temps(this);
Register scratch2 = temps.AcquireX();
// Load store buffer top.
Mov(scratch2, ExternalReference::store_buffer_top(isolate()));
Ldr(scratch1, MemOperand(scratch2));
// Store pointer to buffer and increment buffer top.
Str(address, MemOperand(scratch1, kPointerSize, PostIndex));
// Write back new top of buffer.
Str(scratch1, MemOperand(scratch2));
// Call stub on end of buffer.
// Check for end of buffer.
ASSERT(StoreBuffer::kStoreBufferOverflowBit ==
(1 << (14 + kPointerSizeLog2)));
if (and_then == kFallThroughAtEnd) {
Tbz(scratch1, (14 + kPointerSizeLog2), &done);
} else {
ASSERT(and_then == kReturnAtEnd);
Tbnz(scratch1, (14 + kPointerSizeLog2), &store_buffer_overflow);
Ret();
}
Bind(&store_buffer_overflow);
Push(lr);
StoreBufferOverflowStub store_buffer_overflow_stub =
StoreBufferOverflowStub(isolate(), fp_mode);
CallStub(&store_buffer_overflow_stub);
Pop(lr);
Bind(&done);
if (and_then == kReturnAtEnd) {
Ret();
}
}
void MacroAssembler::PopSafepointRegisters() {
const int num_unsaved = kNumSafepointRegisters - kNumSafepointSavedRegisters;
PopXRegList(kSafepointSavedRegisters);
Drop(num_unsaved);
}
void MacroAssembler::PushSafepointRegisters() {
// Safepoints expect a block of kNumSafepointRegisters values on the stack, so
// adjust the stack for unsaved registers.
const int num_unsaved = kNumSafepointRegisters - kNumSafepointSavedRegisters;
ASSERT(num_unsaved >= 0);
Claim(num_unsaved);
PushXRegList(kSafepointSavedRegisters);
}
void MacroAssembler::PushSafepointRegistersAndDoubles() {
PushSafepointRegisters();
PushCPURegList(CPURegList(CPURegister::kFPRegister, kDRegSizeInBits,
FPRegister::kAllocatableFPRegisters));
}
void MacroAssembler::PopSafepointRegistersAndDoubles() {
PopCPURegList(CPURegList(CPURegister::kFPRegister, kDRegSizeInBits,
FPRegister::kAllocatableFPRegisters));
PopSafepointRegisters();
}
int MacroAssembler::SafepointRegisterStackIndex(int reg_code) {
// Make sure the safepoint registers list is what we expect.
ASSERT(CPURegList::GetSafepointSavedRegisters().list() == 0x6ffcffff);
// Safepoint registers are stored contiguously on the stack, but not all the
// registers are saved. The following registers are excluded:
// - x16 and x17 (ip0 and ip1) because they shouldn't be preserved outside of
// the macro assembler.
// - x28 (jssp) because JS stack pointer doesn't need to be included in
// safepoint registers.
// - x31 (csp) because the system stack pointer doesn't need to be included
// in safepoint registers.
//
// This function implements the mapping of register code to index into the
// safepoint register slots.
if ((reg_code >= 0) && (reg_code <= 15)) {
return reg_code;
} else if ((reg_code >= 18) && (reg_code <= 27)) {
// Skip ip0 and ip1.
return reg_code - 2;
} else if ((reg_code == 29) || (reg_code == 30)) {
// Also skip jssp.
return reg_code - 3;
} else {
// This register has no safepoint register slot.
UNREACHABLE();
return -1;
}
}
void MacroAssembler::CheckPageFlagSet(const Register& object,
const Register& scratch,
int mask,
Label* if_any_set) {
And(scratch, object, ~Page::kPageAlignmentMask);
Ldr(scratch, MemOperand(scratch, MemoryChunk::kFlagsOffset));
TestAndBranchIfAnySet(scratch, mask, if_any_set);
}
void MacroAssembler::CheckPageFlagClear(const Register& object,
const Register& scratch,
int mask,
Label* if_all_clear) {
And(scratch, object, ~Page::kPageAlignmentMask);
Ldr(scratch, MemOperand(scratch, MemoryChunk::kFlagsOffset));
TestAndBranchIfAllClear(scratch, mask, if_all_clear);
}
void MacroAssembler::RecordWriteField(
Register object,
int offset,
Register value,
Register scratch,
LinkRegisterStatus lr_status,
SaveFPRegsMode save_fp,
RememberedSetAction remembered_set_action,
SmiCheck smi_check,
PointersToHereCheck pointers_to_here_check_for_value) {
// First, check if a write barrier is even needed. The tests below
// catch stores of Smis.
Label done;
// Skip the barrier if writing a smi.
if (smi_check == INLINE_SMI_CHECK) {
JumpIfSmi(value, &done);
}
// Although the object register is tagged, the offset is relative to the start
// of the object, so offset must be a multiple of kPointerSize.
ASSERT(IsAligned(offset, kPointerSize));
Add(scratch, object, offset - kHeapObjectTag);
if (emit_debug_code()) {
Label ok;
Tst(scratch, (1 << kPointerSizeLog2) - 1);
B(eq, &ok);
Abort(kUnalignedCellInWriteBarrier);
Bind(&ok);
}
RecordWrite(object,
scratch,
value,
lr_status,
save_fp,
remembered_set_action,
OMIT_SMI_CHECK,
pointers_to_here_check_for_value);
Bind(&done);
// Clobber clobbered input registers when running with the debug-code flag
// turned on to provoke errors.
if (emit_debug_code()) {
Mov(value, Operand(BitCast<int64_t>(kZapValue + 4)));
Mov(scratch, Operand(BitCast<int64_t>(kZapValue + 8)));
}
}
// Will clobber: object, map, dst.
// If lr_status is kLRHasBeenSaved, lr will also be clobbered.
void MacroAssembler::RecordWriteForMap(Register object,
Register map,
Register dst,
LinkRegisterStatus lr_status,
SaveFPRegsMode fp_mode) {
ASM_LOCATION("MacroAssembler::RecordWrite");
ASSERT(!AreAliased(object, map));
if (emit_debug_code()) {
UseScratchRegisterScope temps(this);
Register temp = temps.AcquireX();
CompareMap(map, temp, isolate()->factory()->meta_map());
Check(eq, kWrongAddressOrValuePassedToRecordWrite);
}
if (!FLAG_incremental_marking) {
return;
}
if (emit_debug_code()) {
UseScratchRegisterScope temps(this);
Register temp = temps.AcquireX();
Ldr(temp, FieldMemOperand(object, HeapObject::kMapOffset));
Cmp(temp, map);
Check(eq, kWrongAddressOrValuePassedToRecordWrite);
}
// Count number of write barriers in generated code.
isolate()->counters()->write_barriers_static()->Increment();
// TODO(mstarzinger): Dynamic counter missing.
// First, check if a write barrier is even needed. The tests below
// catch stores of smis and stores into the young generation.
Label done;
// A single check of the map's pages interesting flag suffices, since it is
// only set during incremental collection, and then it's also guaranteed that
// the from object's page's interesting flag is also set. This optimization
// relies on the fact that maps can never be in new space.
CheckPageFlagClear(map,
map, // Used as scratch.
MemoryChunk::kPointersToHereAreInterestingMask,
&done);
// Record the actual write.
if (lr_status == kLRHasNotBeenSaved) {
Push(lr);
}
Add(dst, object, HeapObject::kMapOffset - kHeapObjectTag);
RecordWriteStub stub(isolate(), object, map, dst, OMIT_REMEMBERED_SET,
fp_mode);
CallStub(&stub);
if (lr_status == kLRHasNotBeenSaved) {
Pop(lr);
}
Bind(&done);
// Clobber clobbered registers when running with the debug-code flag
// turned on to provoke errors.
if (emit_debug_code()) {
Mov(dst, Operand(BitCast<int64_t>(kZapValue + 12)));
Mov(map, Operand(BitCast<int64_t>(kZapValue + 16)));
}
}
// Will clobber: object, address, value.
// If lr_status is kLRHasBeenSaved, lr will also be clobbered.
//
// The register 'object' contains a heap object pointer. The heap object tag is
// shifted away.
void MacroAssembler::RecordWrite(
Register object,
Register address,
Register value,
LinkRegisterStatus lr_status,
SaveFPRegsMode fp_mode,
RememberedSetAction remembered_set_action,
SmiCheck smi_check,
PointersToHereCheck pointers_to_here_check_for_value) {
ASM_LOCATION("MacroAssembler::RecordWrite");
ASSERT(!AreAliased(object, value));
if (emit_debug_code()) {
UseScratchRegisterScope temps(this);
Register temp = temps.AcquireX();
Ldr(temp, MemOperand(address));
Cmp(temp, value);
Check(eq, kWrongAddressOrValuePassedToRecordWrite);
}
// Count number of write barriers in generated code.
isolate()->counters()->write_barriers_static()->Increment();
// TODO(mstarzinger): Dynamic counter missing.
// First, check if a write barrier is even needed. The tests below
// catch stores of smis and stores into the young generation.
Label done;
if (smi_check == INLINE_SMI_CHECK) {
ASSERT_EQ(0, kSmiTag);
JumpIfSmi(value, &done);
}
if (pointers_to_here_check_for_value != kPointersToHereAreAlwaysInteresting) {
CheckPageFlagClear(value,
value, // Used as scratch.
MemoryChunk::kPointersToHereAreInterestingMask,
&done);
}
CheckPageFlagClear(object,
value, // Used as scratch.
MemoryChunk::kPointersFromHereAreInterestingMask,
&done);
// Record the actual write.
if (lr_status == kLRHasNotBeenSaved) {
Push(lr);
}
RecordWriteStub stub(isolate(), object, value, address, remembered_set_action,
fp_mode);
CallStub(&stub);
if (lr_status == kLRHasNotBeenSaved) {
Pop(lr);
}
Bind(&done);
// Clobber clobbered registers when running with the debug-code flag
// turned on to provoke errors.
if (emit_debug_code()) {
Mov(address, Operand(BitCast<int64_t>(kZapValue + 12)));
Mov(value, Operand(BitCast<int64_t>(kZapValue + 16)));
}
}
void MacroAssembler::AssertHasValidColor(const Register& reg) {
if (emit_debug_code()) {
// The bit sequence is backward. The first character in the string
// represents the least significant bit.
ASSERT(strcmp(Marking::kImpossibleBitPattern, "01") == 0);
Label color_is_valid;
Tbnz(reg, 0, &color_is_valid);
Tbz(reg, 1, &color_is_valid);
Abort(kUnexpectedColorFound);
Bind(&color_is_valid);
}
}
void MacroAssembler::GetMarkBits(Register addr_reg,
Register bitmap_reg,
Register shift_reg) {
ASSERT(!AreAliased(addr_reg, bitmap_reg, shift_reg));
ASSERT(addr_reg.Is64Bits() && bitmap_reg.Is64Bits() && shift_reg.Is64Bits());
// addr_reg is divided into fields:
// |63 page base 20|19 high 8|7 shift 3|2 0|
// 'high' gives the index of the cell holding color bits for the object.
// 'shift' gives the offset in the cell for this object's color.
const int kShiftBits = kPointerSizeLog2 + Bitmap::kBitsPerCellLog2;
UseScratchRegisterScope temps(this);
Register temp = temps.AcquireX();
Ubfx(temp, addr_reg, kShiftBits, kPageSizeBits - kShiftBits);
Bic(bitmap_reg, addr_reg, Page::kPageAlignmentMask);
Add(bitmap_reg, bitmap_reg, Operand(temp, LSL, Bitmap::kBytesPerCellLog2));
// bitmap_reg:
// |63 page base 20|19 zeros 15|14 high 3|2 0|
Ubfx(shift_reg, addr_reg, kPointerSizeLog2, Bitmap::kBitsPerCellLog2);
}
void MacroAssembler::HasColor(Register object,
Register bitmap_scratch,
Register shift_scratch,
Label* has_color,
int first_bit,
int second_bit) {
// See mark-compact.h for color definitions.
ASSERT(!AreAliased(object, bitmap_scratch, shift_scratch));
GetMarkBits(object, bitmap_scratch, shift_scratch);
Ldr(bitmap_scratch, MemOperand(bitmap_scratch, MemoryChunk::kHeaderSize));
// Shift the bitmap down to get the color of the object in bits [1:0].
Lsr(bitmap_scratch, bitmap_scratch, shift_scratch);
AssertHasValidColor(bitmap_scratch);
// These bit sequences are backwards. The first character in the string
// represents the least significant bit.
ASSERT(strcmp(Marking::kWhiteBitPattern, "00") == 0);
ASSERT(strcmp(Marking::kBlackBitPattern, "10") == 0);
ASSERT(strcmp(Marking::kGreyBitPattern, "11") == 0);
// Check for the color.
if (first_bit == 0) {
// Checking for white.
ASSERT(second_bit == 0);
// We only need to test the first bit.
Tbz(bitmap_scratch, 0, has_color);
} else {
Label other_color;
// Checking for grey or black.
Tbz(bitmap_scratch, 0, &other_color);
if (second_bit == 0) {
Tbz(bitmap_scratch, 1, has_color);
} else {
Tbnz(bitmap_scratch, 1, has_color);
}
Bind(&other_color);
}
// Fall through if it does not have the right color.
}
void MacroAssembler::CheckMapDeprecated(Handle<Map> map,
Register scratch,
Label* if_deprecated) {
if (map->CanBeDeprecated()) {
Mov(scratch, Operand(map));
Ldrsw(scratch, FieldMemOperand(scratch, Map::kBitField3Offset));
TestAndBranchIfAnySet(scratch, Map::Deprecated::kMask, if_deprecated);
}
}
void MacroAssembler::JumpIfBlack(Register object,
Register scratch0,
Register scratch1,
Label* on_black) {
ASSERT(strcmp(Marking::kBlackBitPattern, "10") == 0);
HasColor(object, scratch0, scratch1, on_black, 1, 0); // kBlackBitPattern.
}
void MacroAssembler::JumpIfDictionaryInPrototypeChain(
Register object,
Register scratch0,
Register scratch1,
Label* found) {
ASSERT(!AreAliased(object, scratch0, scratch1));
Factory* factory = isolate()->factory();
Register current = scratch0;
Label loop_again;
// Scratch contains elements pointer.
Mov(current, object);
// Loop based on the map going up the prototype chain.
Bind(&loop_again);
Ldr(current, FieldMemOperand(current, HeapObject::kMapOffset));
Ldrb(scratch1, FieldMemOperand(current, Map::kBitField2Offset));
DecodeField<Map::ElementsKindBits>(scratch1);
CompareAndBranch(scratch1, DICTIONARY_ELEMENTS, eq, found);
Ldr(current, FieldMemOperand(current, Map::kPrototypeOffset));
CompareAndBranch(current, Operand(factory->null_value()), ne, &loop_again);
}
void MacroAssembler::GetRelocatedValueLocation(Register ldr_location,
Register result) {
ASSERT(!result.Is(ldr_location));
const uint32_t kLdrLitOffset_lsb = 5;
const uint32_t kLdrLitOffset_width = 19;
Ldr(result, MemOperand(ldr_location));
if (emit_debug_code()) {
And(result, result, LoadLiteralFMask);
Cmp(result, LoadLiteralFixed);
Check(eq, kTheInstructionToPatchShouldBeAnLdrLiteral);
// The instruction was clobbered. Reload it.
Ldr(result, MemOperand(ldr_location));
}
Sbfx(result, result, kLdrLitOffset_lsb, kLdrLitOffset_width);
Add(result, ldr_location, Operand(result, LSL, kWordSizeInBytesLog2));
}
void MacroAssembler::EnsureNotWhite(
Register value,
Register bitmap_scratch,
Register shift_scratch,
Register load_scratch,
Register length_scratch,
Label* value_is_white_and_not_data) {
ASSERT(!AreAliased(
value, bitmap_scratch, shift_scratch, load_scratch, length_scratch));
// These bit sequences are backwards. The first character in the string
// represents the least significant bit.
ASSERT(strcmp(Marking::kWhiteBitPattern, "00") == 0);
ASSERT(strcmp(Marking::kBlackBitPattern, "10") == 0);
ASSERT(strcmp(Marking::kGreyBitPattern, "11") == 0);
GetMarkBits(value, bitmap_scratch, shift_scratch);
Ldr(load_scratch, MemOperand(bitmap_scratch, MemoryChunk::kHeaderSize));
Lsr(load_scratch, load_scratch, shift_scratch);
AssertHasValidColor(load_scratch);
// If the value is black or grey we don't need to do anything.
// Since both black and grey have a 1 in the first position and white does
// not have a 1 there we only need to check one bit.
Label done;
Tbnz(load_scratch, 0, &done);
// Value is white. We check whether it is data that doesn't need scanning.
Register map = load_scratch; // Holds map while checking type.
Label is_data_object;
// Check for heap-number.
Ldr(map, FieldMemOperand(value, HeapObject::kMapOffset));
Mov(length_scratch, HeapNumber::kSize);
JumpIfRoot(map, Heap::kHeapNumberMapRootIndex, &is_data_object);
// Check for strings.
ASSERT(kIsIndirectStringTag == 1 && kIsIndirectStringMask == 1);
ASSERT(kNotStringTag == 0x80 && kIsNotStringMask == 0x80);
// If it's a string and it's not a cons string then it's an object containing
// no GC pointers.
Register instance_type = load_scratch;
Ldrb(instance_type, FieldMemOperand(map, Map::kInstanceTypeOffset));
TestAndBranchIfAnySet(instance_type,
kIsIndirectStringMask | kIsNotStringMask,
value_is_white_and_not_data);
// It's a non-indirect (non-cons and non-slice) string.
// If it's external, the length is just ExternalString::kSize.
// Otherwise it's String::kHeaderSize + string->length() * (1 or 2).
// External strings are the only ones with the kExternalStringTag bit
// set.
ASSERT_EQ(0, kSeqStringTag & kExternalStringTag);
ASSERT_EQ(0, kConsStringTag & kExternalStringTag);
Mov(length_scratch, ExternalString::kSize);
TestAndBranchIfAnySet(instance_type, kExternalStringTag, &is_data_object);
// Sequential string, either ASCII or UC16.
// For ASCII (char-size of 1) we shift the smi tag away to get the length.
// For UC16 (char-size of 2) we just leave the smi tag in place, thereby
// getting the length multiplied by 2.
ASSERT(kOneByteStringTag == 4 && kStringEncodingMask == 4);
Ldrsw(length_scratch, UntagSmiFieldMemOperand(value,
String::kLengthOffset));
Tst(instance_type, kStringEncodingMask);
Cset(load_scratch, eq);
Lsl(length_scratch, length_scratch, load_scratch);
Add(length_scratch,
length_scratch,
SeqString::kHeaderSize + kObjectAlignmentMask);
Bic(length_scratch, length_scratch, kObjectAlignmentMask);
Bind(&is_data_object);
// Value is a data object, and it is white. Mark it black. Since we know
// that the object is white we can make it black by flipping one bit.
Register mask = shift_scratch;
Mov(load_scratch, 1);
Lsl(mask, load_scratch, shift_scratch);
Ldr(load_scratch, MemOperand(bitmap_scratch, MemoryChunk::kHeaderSize));
Orr(load_scratch, load_scratch, mask);
Str(load_scratch, MemOperand(bitmap_scratch, MemoryChunk::kHeaderSize));
Bic(bitmap_scratch, bitmap_scratch, Page::kPageAlignmentMask);
Ldr(load_scratch, MemOperand(bitmap_scratch, MemoryChunk::kLiveBytesOffset));
Add(load_scratch, load_scratch, length_scratch);
Str(load_scratch, MemOperand(bitmap_scratch, MemoryChunk::kLiveBytesOffset));
Bind(&done);
}
void MacroAssembler::Assert(Condition cond, BailoutReason reason) {
if (emit_debug_code()) {
Check(cond, reason);
}
}
void MacroAssembler::AssertRegisterIsClear(Register reg, BailoutReason reason) {
if (emit_debug_code()) {
CheckRegisterIsClear(reg, reason);
}
}
void MacroAssembler::AssertRegisterIsRoot(Register reg,
Heap::RootListIndex index,
BailoutReason reason) {
if (emit_debug_code()) {
CompareRoot(reg, index);
Check(eq, reason);
}
}
void MacroAssembler::AssertFastElements(Register elements) {
if (emit_debug_code()) {
UseScratchRegisterScope temps(this);
Register temp = temps.AcquireX();
Label ok;
Ldr(temp, FieldMemOperand(elements, HeapObject::kMapOffset));
JumpIfRoot(temp, Heap::kFixedArrayMapRootIndex, &ok);
JumpIfRoot(temp, Heap::kFixedDoubleArrayMapRootIndex, &ok);
JumpIfRoot(temp, Heap::kFixedCOWArrayMapRootIndex, &ok);
Abort(kJSObjectWithFastElementsMapHasSlowElements);
Bind(&ok);
}
}
void MacroAssembler::AssertIsString(const Register& object) {
if (emit_debug_code()) {
UseScratchRegisterScope temps(this);
Register temp = temps.AcquireX();
STATIC_ASSERT(kSmiTag == 0);
Tst(object, kSmiTagMask);
Check(ne, kOperandIsNotAString);
Ldr(temp, FieldMemOperand(object, HeapObject::kMapOffset));
CompareInstanceType(temp, temp, FIRST_NONSTRING_TYPE);
Check(lo, kOperandIsNotAString);
}
}
void MacroAssembler::Check(Condition cond, BailoutReason reason) {
Label ok;
B(cond, &ok);
Abort(reason);
// Will not return here.
Bind(&ok);
}
void MacroAssembler::CheckRegisterIsClear(Register reg, BailoutReason reason) {
Label ok;
Cbz(reg, &ok);
Abort(reason);
// Will not return here.
Bind(&ok);
}
void MacroAssembler::Abort(BailoutReason reason) {
#ifdef DEBUG
RecordComment("Abort message: ");
RecordComment(GetBailoutReason(reason));
if (FLAG_trap_on_abort) {
Brk(0);
return;
}
#endif
// Abort is used in some contexts where csp is the stack pointer. In order to
// simplify the CallRuntime code, make sure that jssp is the stack pointer.
// There is no risk of register corruption here because Abort doesn't return.
Register old_stack_pointer = StackPointer();
SetStackPointer(jssp);
Mov(jssp, old_stack_pointer);
// We need some scratch registers for the MacroAssembler, so make sure we have
// some. This is safe here because Abort never returns.
RegList old_tmp_list = TmpList()->list();
TmpList()->Combine(MacroAssembler::DefaultTmpList());
if (use_real_aborts()) {
// Avoid infinite recursion; Push contains some assertions that use Abort.
NoUseRealAbortsScope no_real_aborts(this);
Mov(x0, Smi::FromInt(reason));
Push(x0);
if (!has_frame_) {
// We don't actually want to generate a pile of code for this, so just
// claim there is a stack frame, without generating one.
FrameScope scope(this, StackFrame::NONE);
CallRuntime(Runtime::kAbort, 1);
} else {
CallRuntime(Runtime::kAbort, 1);
}
} else {
// Load the string to pass to Printf.
Label msg_address;
Adr(x0, &msg_address);
// Call Printf directly to report the error.
CallPrintf();
// We need a way to stop execution on both the simulator and real hardware,
// and Unreachable() is the best option.
Unreachable();
// Emit the message string directly in the instruction stream.
{
BlockPoolsScope scope(this);
Bind(&msg_address);
EmitStringData(GetBailoutReason(reason));
}
}
SetStackPointer(old_stack_pointer);
TmpList()->set_list(old_tmp_list);
}
void MacroAssembler::LoadTransitionedArrayMapConditional(
ElementsKind expected_kind,
ElementsKind transitioned_kind,
Register map_in_out,
Register scratch1,
Register scratch2,
Label* no_map_match) {
// Load the global or builtins object from the current context.
Ldr(scratch1, GlobalObjectMemOperand());
Ldr(scratch1, FieldMemOperand(scratch1, GlobalObject::kNativeContextOffset));
// Check that the function's map is the same as the expected cached map.
Ldr(scratch1, ContextMemOperand(scratch1, Context::JS_ARRAY_MAPS_INDEX));
size_t offset = (expected_kind * kPointerSize) + FixedArrayBase::kHeaderSize;
Ldr(scratch2, FieldMemOperand(scratch1, offset));
Cmp(map_in_out, scratch2);
B(ne, no_map_match);
// Use the transitioned cached map.
offset = (transitioned_kind * kPointerSize) + FixedArrayBase::kHeaderSize;
Ldr(map_in_out, FieldMemOperand(scratch1, offset));
}
void MacroAssembler::LoadGlobalFunction(int index, Register function) {
// Load the global or builtins object from the current context.
Ldr(function, GlobalObjectMemOperand());
// Load the native context from the global or builtins object.
Ldr(function, FieldMemOperand(function,
GlobalObject::kNativeContextOffset));
// Load the function from the native context.
Ldr(function, ContextMemOperand(function, index));
}
void MacroAssembler::LoadGlobalFunctionInitialMap(Register function,
Register map,
Register scratch) {
// Load the initial map. The global functions all have initial maps.
Ldr(map, FieldMemOperand(function, JSFunction::kPrototypeOrInitialMapOffset));
if (emit_debug_code()) {
Label ok, fail;
CheckMap(map, scratch, Heap::kMetaMapRootIndex, &fail, DO_SMI_CHECK);
B(&ok);
Bind(&fail);
Abort(kGlobalFunctionsMustHaveInitialMap);
Bind(&ok);
}
}
// This is the main Printf implementation. All other Printf variants call
// PrintfNoPreserve after setting up one or more PreserveRegisterScopes.
void MacroAssembler::PrintfNoPreserve(const char * format,
const CPURegister& arg0,
const CPURegister& arg1,
const CPURegister& arg2,
const CPURegister& arg3) {
// We cannot handle a caller-saved stack pointer. It doesn't make much sense
// in most cases anyway, so this restriction shouldn't be too serious.
ASSERT(!kCallerSaved.IncludesAliasOf(__ StackPointer()));
// The provided arguments, and their proper procedure-call standard registers.
CPURegister args[kPrintfMaxArgCount] = {arg0, arg1, arg2, arg3};
CPURegister pcs[kPrintfMaxArgCount] = {NoReg, NoReg, NoReg, NoReg};
int arg_count = kPrintfMaxArgCount;
// The PCS varargs registers for printf. Note that x0 is used for the printf
// format string.
static const CPURegList kPCSVarargs =
CPURegList(CPURegister::kRegister, kXRegSizeInBits, 1, arg_count);
static const CPURegList kPCSVarargsFP =
CPURegList(CPURegister::kFPRegister, kDRegSizeInBits, 0, arg_count - 1);
// We can use caller-saved registers as scratch values, except for the
// arguments and the PCS registers where they might need to go.
CPURegList tmp_list = kCallerSaved;
tmp_list.Remove(x0); // Used to pass the format string.
tmp_list.Remove(kPCSVarargs);
tmp_list.Remove(arg0, arg1, arg2, arg3);
CPURegList fp_tmp_list = kCallerSavedFP;
fp_tmp_list.Remove(kPCSVarargsFP);
fp_tmp_list.Remove(arg0, arg1, arg2, arg3);
// Override the MacroAssembler's scratch register list. The lists will be
// reset automatically at the end of the UseScratchRegisterScope.
UseScratchRegisterScope temps(this);
TmpList()->set_list(tmp_list.list());
FPTmpList()->set_list(fp_tmp_list.list());
// Copies of the printf vararg registers that we can pop from.
CPURegList pcs_varargs = kPCSVarargs;
CPURegList pcs_varargs_fp = kPCSVarargsFP;
// Place the arguments. There are lots of clever tricks and optimizations we
// could use here, but Printf is a debug tool so instead we just try to keep
// it simple: Move each input that isn't already in the right place to a
// scratch register, then move everything back.
for (unsigned i = 0; i < kPrintfMaxArgCount; i++) {
// Work out the proper PCS register for this argument.
if (args[i].IsRegister()) {
pcs[i] = pcs_varargs.PopLowestIndex().X();
// We might only need a W register here. We need to know the size of the
// argument so we can properly encode it for the simulator call.
if (args[i].Is32Bits()) pcs[i] = pcs[i].W();
} else if (args[i].IsFPRegister()) {
// In C, floats are always cast to doubles for varargs calls.
pcs[i] = pcs_varargs_fp.PopLowestIndex().D();
} else {
ASSERT(args[i].IsNone());
arg_count = i;
break;
}
// If the argument is already in the right place, leave it where it is.
if (args[i].Aliases(pcs[i])) continue;
// Otherwise, if the argument is in a PCS argument register, allocate an
// appropriate scratch register and then move it out of the way.
if (kPCSVarargs.IncludesAliasOf(args[i]) ||
kPCSVarargsFP.IncludesAliasOf(args[i])) {
if (args[i].IsRegister()) {
Register old_arg = Register(args[i]);
Register new_arg = temps.AcquireSameSizeAs(old_arg);
Mov(new_arg, old_arg);
args[i] = new_arg;
} else {
FPRegister old_arg = FPRegister(args[i]);
FPRegister new_arg = temps.AcquireSameSizeAs(old_arg);
Fmov(new_arg, old_arg);
args[i] = new_arg;
}
}
}
// Do a second pass to move values into their final positions and perform any
// conversions that may be required.
for (int i = 0; i < arg_count; i++) {
ASSERT(pcs[i].type() == args[i].type());
if (pcs[i].IsRegister()) {
Mov(Register(pcs[i]), Register(args[i]), kDiscardForSameWReg);
} else {
ASSERT(pcs[i].IsFPRegister());
if (pcs[i].SizeInBytes() == args[i].SizeInBytes()) {
Fmov(FPRegister(pcs[i]), FPRegister(args[i]));
} else {
Fcvt(FPRegister(pcs[i]), FPRegister(args[i]));
}
}
}
// Load the format string into x0, as per the procedure-call standard.
//
// To make the code as portable as possible, the format string is encoded
// directly in the instruction stream. It might be cleaner to encode it in a
// literal pool, but since Printf is usually used for debugging, it is
// beneficial for it to be minimally dependent on other features.
Label format_address;
Adr(x0, &format_address);
// Emit the format string directly in the instruction stream.
{ BlockPoolsScope scope(this);
Label after_data;
B(&after_data);
Bind(&format_address);
EmitStringData(format);
Unreachable();
Bind(&after_data);
}
// We don't pass any arguments on the stack, but we still need to align the C
// stack pointer to a 16-byte boundary for PCS compliance.
if (!csp.Is(StackPointer())) {
Bic(csp, StackPointer(), 0xf);
}
CallPrintf(arg_count, pcs);
}
void MacroAssembler::CallPrintf(int arg_count, const CPURegister * args) {
// A call to printf needs special handling for the simulator, since the system
// printf function will use a different instruction set and the procedure-call
// standard will not be compatible.
#ifdef USE_SIMULATOR
{ InstructionAccurateScope scope(this, kPrintfLength / kInstructionSize);
hlt(kImmExceptionIsPrintf);
dc32(arg_count); // kPrintfArgCountOffset
// Determine the argument pattern.
uint32_t arg_pattern_list = 0;
for (int i = 0; i < arg_count; i++) {
uint32_t arg_pattern;
if (args[i].IsRegister()) {
arg_pattern = args[i].Is32Bits() ? kPrintfArgW : kPrintfArgX;
} else {
ASSERT(args[i].Is64Bits());
arg_pattern = kPrintfArgD;
}
ASSERT(arg_pattern < (1 << kPrintfArgPatternBits));
arg_pattern_list |= (arg_pattern << (kPrintfArgPatternBits * i));
}
dc32(arg_pattern_list); // kPrintfArgPatternListOffset
}
#else
Call(FUNCTION_ADDR(printf), RelocInfo::EXTERNAL_REFERENCE);
#endif
}
void MacroAssembler::Printf(const char * format,
CPURegister arg0,
CPURegister arg1,
CPURegister arg2,
CPURegister arg3) {
// We can only print sp if it is the current stack pointer.
if (!csp.Is(StackPointer())) {
ASSERT(!csp.Aliases(arg0));
ASSERT(!csp.Aliases(arg1));
ASSERT(!csp.Aliases(arg2));
ASSERT(!csp.Aliases(arg3));
}
// Printf is expected to preserve all registers, so make sure that none are
// available as scratch registers until we've preserved them.
RegList old_tmp_list = TmpList()->list();
RegList old_fp_tmp_list = FPTmpList()->list();
TmpList()->set_list(0);
FPTmpList()->set_list(0);
// Preserve all caller-saved registers as well as NZCV.
// If csp is the stack pointer, PushCPURegList asserts that the size of each
// list is a multiple of 16 bytes.
PushCPURegList(kCallerSaved);
PushCPURegList(kCallerSavedFP);
// We can use caller-saved registers as scratch values (except for argN).
CPURegList tmp_list = kCallerSaved;
CPURegList fp_tmp_list = kCallerSavedFP;
tmp_list.Remove(arg0, arg1, arg2, arg3);
fp_tmp_list.Remove(arg0, arg1, arg2, arg3);
TmpList()->set_list(tmp_list.list());
FPTmpList()->set_list(fp_tmp_list.list());
{ UseScratchRegisterScope temps(this);
// If any of the arguments are the current stack pointer, allocate a new
// register for them, and adjust the value to compensate for pushing the
// caller-saved registers.
bool arg0_sp = StackPointer().Aliases(arg0);
bool arg1_sp = StackPointer().Aliases(arg1);
bool arg2_sp = StackPointer().Aliases(arg2);
bool arg3_sp = StackPointer().Aliases(arg3);
if (arg0_sp || arg1_sp || arg2_sp || arg3_sp) {
// Allocate a register to hold the original stack pointer value, to pass
// to PrintfNoPreserve as an argument.
Register arg_sp = temps.AcquireX();
Add(arg_sp, StackPointer(),
kCallerSaved.TotalSizeInBytes() + kCallerSavedFP.TotalSizeInBytes());
if (arg0_sp) arg0 = Register::Create(arg_sp.code(), arg0.SizeInBits());
if (arg1_sp) arg1 = Register::Create(arg_sp.code(), arg1.SizeInBits());
if (arg2_sp) arg2 = Register::Create(arg_sp.code(), arg2.SizeInBits());
if (arg3_sp) arg3 = Register::Create(arg_sp.code(), arg3.SizeInBits());
}
// Preserve NZCV.
{ UseScratchRegisterScope temps(this);
Register tmp = temps.AcquireX();
Mrs(tmp, NZCV);
Push(tmp, xzr);
}
PrintfNoPreserve(format, arg0, arg1, arg2, arg3);
// Restore NZCV.
{ UseScratchRegisterScope temps(this);
Register tmp = temps.AcquireX();
Pop(xzr, tmp);
Msr(NZCV, tmp);
}
}
PopCPURegList(kCallerSavedFP);
PopCPURegList(kCallerSaved);
TmpList()->set_list(old_tmp_list);
FPTmpList()->set_list(old_fp_tmp_list);
}
void MacroAssembler::EmitFrameSetupForCodeAgePatching() {
// TODO(jbramley): Other architectures use the internal memcpy to copy the
// sequence. If this is a performance bottleneck, we should consider caching
// the sequence and copying it in the same way.
InstructionAccurateScope scope(this,
kNoCodeAgeSequenceLength / kInstructionSize);
ASSERT(jssp.Is(StackPointer()));
EmitFrameSetupForCodeAgePatching(this);
}
void MacroAssembler::EmitCodeAgeSequence(Code* stub) {
InstructionAccurateScope scope(this,
kNoCodeAgeSequenceLength / kInstructionSize);
ASSERT(jssp.Is(StackPointer()));
EmitCodeAgeSequence(this, stub);
}
#undef __
#define __ assm->
void MacroAssembler::EmitFrameSetupForCodeAgePatching(Assembler * assm) {
Label start;
__ bind(&start);
// We can do this sequence using four instructions, but the code ageing
// sequence that patches it needs five, so we use the extra space to try to
// simplify some addressing modes and remove some dependencies (compared to
// using two stp instructions with write-back).
__ sub(jssp, jssp, 4 * kXRegSize);
__ sub(csp, csp, 4 * kXRegSize);
__ stp(x1, cp, MemOperand(jssp, 0 * kXRegSize));
__ stp(fp, lr, MemOperand(jssp, 2 * kXRegSize));
__ add(fp, jssp, StandardFrameConstants::kFixedFrameSizeFromFp);
__ AssertSizeOfCodeGeneratedSince(&start, kNoCodeAgeSequenceLength);
}
void MacroAssembler::EmitCodeAgeSequence(Assembler * assm,
Code * stub) {
Label start;
__ bind(&start);
// When the stub is called, the sequence is replaced with the young sequence
// (as in EmitFrameSetupForCodeAgePatching). After the code is replaced, the
// stub jumps to &start, stored in x0. The young sequence does not call the
// stub so there is no infinite loop here.
//
// A branch (br) is used rather than a call (blr) because this code replaces
// the frame setup code that would normally preserve lr.
__ ldr_pcrel(ip0, kCodeAgeStubEntryOffset >> kLoadLiteralScaleLog2);
__ adr(x0, &start);
__ br(ip0);
// IsCodeAgeSequence in codegen-arm64.cc assumes that the code generated up
// until now (kCodeAgeStubEntryOffset) is the same for all code age sequences.
__ AssertSizeOfCodeGeneratedSince(&start, kCodeAgeStubEntryOffset);
if (stub) {
__ dc64(reinterpret_cast<uint64_t>(stub->instruction_start()));
__ AssertSizeOfCodeGeneratedSince(&start, kNoCodeAgeSequenceLength);
}
}
bool MacroAssembler::IsYoungSequence(Isolate* isolate, byte* sequence) {
bool is_young = isolate->code_aging_helper()->IsYoung(sequence);
ASSERT(is_young ||
isolate->code_aging_helper()->IsOld(sequence));
return is_young;
}
void MacroAssembler::TruncatingDiv(Register result,
Register dividend,
int32_t divisor) {
ASSERT(!AreAliased(result, dividend));
ASSERT(result.Is32Bits() && dividend.Is32Bits());
MultiplierAndShift ms(divisor);
Mov(result, ms.multiplier());
Smull(result.X(), dividend, result);
Asr(result.X(), result.X(), 32);
if (divisor > 0 && ms.multiplier() < 0) Add(result, result, dividend);
if (divisor < 0 && ms.multiplier() > 0) Sub(result, result, dividend);
if (ms.shift() > 0) Asr(result, result, ms.shift());
Add(result, result, Operand(dividend, LSR, 31));
}
#undef __
UseScratchRegisterScope::~UseScratchRegisterScope() {
available_->set_list(old_available_);
availablefp_->set_list(old_availablefp_);
}
Register UseScratchRegisterScope::AcquireSameSizeAs(const Register& reg) {
int code = AcquireNextAvailable(available_).code();
return Register::Create(code, reg.SizeInBits());
}
FPRegister UseScratchRegisterScope::AcquireSameSizeAs(const FPRegister& reg) {
int code = AcquireNextAvailable(availablefp_).code();
return FPRegister::Create(code, reg.SizeInBits());
}
CPURegister UseScratchRegisterScope::AcquireNextAvailable(
CPURegList* available) {
CHECK(!available->IsEmpty());
CPURegister result = available->PopLowestIndex();
ASSERT(!AreAliased(result, xzr, csp));
return result;
}
CPURegister UseScratchRegisterScope::UnsafeAcquire(CPURegList* available,
const CPURegister& reg) {
ASSERT(available->IncludesAliasOf(reg));
available->Remove(reg);
return reg;
}
#define __ masm->
void InlineSmiCheckInfo::Emit(MacroAssembler* masm, const Register& reg,
const Label* smi_check) {
Assembler::BlockPoolsScope scope(masm);
if (reg.IsValid()) {
ASSERT(smi_check->is_bound());
ASSERT(reg.Is64Bits());
// Encode the register (x0-x30) in the lowest 5 bits, then the offset to
// 'check' in the other bits. The possible offset is limited in that we
// use BitField to pack the data, and the underlying data type is a
// uint32_t.
uint32_t delta = __ InstructionsGeneratedSince(smi_check);
__ InlineData(RegisterBits::encode(reg.code()) | DeltaBits::encode(delta));
} else {
ASSERT(!smi_check->is_bound());
// An offset of 0 indicates that there is no patch site.
__ InlineData(0);
}
}
InlineSmiCheckInfo::InlineSmiCheckInfo(Address info)
: reg_(NoReg), smi_check_(NULL) {
InstructionSequence* inline_data = InstructionSequence::At(info);
ASSERT(inline_data->IsInlineData());
if (inline_data->IsInlineData()) {
uint64_t payload = inline_data->InlineData();
// We use BitField to decode the payload, and BitField can only handle
// 32-bit values.
ASSERT(is_uint32(payload));
if (payload != 0) {
int reg_code = RegisterBits::decode(payload);
reg_ = Register::XRegFromCode(reg_code);
uint64_t smi_check_delta = DeltaBits::decode(payload);
ASSERT(smi_check_delta != 0);
smi_check_ = inline_data->preceding(smi_check_delta);
}
}
}
#undef __
} } // namespace v8::internal
#endif // V8_TARGET_ARCH_ARM64
|
/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2015-2018 Inviwo Foundation
* 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.
*
* 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.
*
*********************************************************************************/
#include <inviwo/core/util/volumesampler.h>
namespace inviwo {
template <>
Vector<1, double> VolumeDoubleSampler<1>::getVoxel(const size3_t &pos) const {
auto p = glm::clamp(pos, size3_t(0), dims_ - size3_t(1));
return ram_->getAsDouble(p);
}
template <>
Vector<2, double> VolumeDoubleSampler<2>::getVoxel(const size3_t &pos) const {
auto p = glm::clamp(pos, size3_t(0), dims_ - size3_t(1));
return ram_->getAsDVec2(p);
}
template <>
Vector<3, double> VolumeDoubleSampler<3>::getVoxel(const size3_t &pos) const {
auto p = glm::clamp(pos, size3_t(0), dims_ - size3_t(1));
return ram_->getAsDVec3(p);
}
template <>
Vector<4, double> VolumeDoubleSampler<4>::getVoxel(const size3_t &pos) const {
auto p = glm::clamp(pos, size3_t(0), dims_ - size3_t(1));
return ram_->getAsDVec4(p);
}
} // namespace inviwo
|
#include "message.h"
#include <QDataStream>
Message::Message() :
mSpeedX(0)
, mSpeedY(0)
, mSpeedR(0)
, mSpeedDribbler(0)
, mDribblerEnable(0)
, mKickerVoltageLevel(0)
, mKickerChargeEnable(0)
, mKickUp(0)
, mKickForward(0)
, mBeep(0)
, mAutoKick(0)
{}
void Message::setSpeedX(int speedX)
{
mSpeedX = speedX;
}
void Message::setSpeedY(int speedY)
{
mSpeedY = speedY;
}
void Message::setSpeedR(int speedR)
{
mSpeedR = speedR;
}
void Message::setSpeedDribbler(int speedDribbler)
{
mSpeedDribbler = speedDribbler;
}
void Message::setDribblerEnable(int dribblerEnable)
{
mDribblerEnable = dribblerEnable;
}
void Message::setKickVoltageLevel(int kickerVoltageLevel)
{
mKickerVoltageLevel = kickerVoltageLevel;
}
void Message::setKickerChargeEnable(int kickerChargeEnable)
{
mKickerChargeEnable = kickerChargeEnable;
}
void Message::setKickUp(int kickUp)
{
mKickUp = kickUp;
}
void Message::setKickForward(int kickForward)
{
mKickForward = kickForward;
}
void Message::setRobotNumber(int number)
{
mRobotNumber = number;
}
void Message::setBeep(int beep)
{
mBeep = beep;
}
void Message::setAutoKick(int autoKick)
{
mAutoKick = autoKick;
}
QByteArray Message::generateByteArray()
{
QByteArray ba;
QDataStream ds(&ba, QIODevice::WriteOnly);
ds.setByteOrder(QDataStream::LittleEndian);
quint8 opcode = 1;
ds << opcode;
ds << (quint8)mRobotNumber;
ds << (qint8)mSpeedY;
ds << (qint8)mSpeedX;
ds << (qint8)mSpeedR;
ds << (quint8)mSpeedDribbler;
ds << (quint8)mKickerVoltageLevel;
ds << (quint8)mKickUp;
ds << (quint8)mKickForward;
ds << (quint8)mBeep;
ds << (quint8)mDribblerEnable;
ds << (quint8)mKickerChargeEnable;
ds << (quint8)mAutoKick;
return ba;
}
|
#include <td.hpp>
int main()
{
Td game;
game.Run();
return 0;
}
|
// ======================================================================
// \title TestTlm/test/ut/TesterBase.cpp
// \author Auto-generated
// \brief cpp file for TestTlm component test harness base class
//
// \copyright
// Copyright 2009-2016, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include <stdlib.h>
#include <string.h>
#include "TesterBase.hpp"
namespace Tlm {
// ----------------------------------------------------------------------
// Construction, initialization, and destruction
// ----------------------------------------------------------------------
TestTlmTesterBase ::
TestTlmTesterBase(
#if FW_OBJECT_NAMES == 1
const char *const compName,
const U32 maxHistorySize
#else
const U32 maxHistorySize
#endif
) :
#if FW_OBJECT_NAMES == 1
Fw::PassiveComponentBase(compName)
#else
Fw::PassiveComponentBase()
#endif
{
// Initialize telemetry histories
this->tlmHistory_somechan =
new History<TlmEntry_somechan>(maxHistorySize);
this->tlmHistory_enumchan =
new History<TlmEntry_enumchan>(maxHistorySize);
this->tlmHistory_quatchan =
new History<TlmEntry_quatchan>(maxHistorySize);
this->tlmHistory_stringchan =
new History<TlmEntry_stringchan>(maxHistorySize);
// Clear history
this->clearHistory();
}
TestTlmTesterBase ::
~TestTlmTesterBase(void)
{
// Destroy telemetry histories
delete this->tlmHistory_somechan;
delete this->tlmHistory_enumchan;
delete this->tlmHistory_quatchan;
delete this->tlmHistory_stringchan;
}
void TestTlmTesterBase ::
init(
const NATIVE_INT_TYPE instance
)
{
// Initialize base class
Fw::PassiveComponentBase::init(instance);
// Attach input port Tlm
for (
NATIVE_INT_TYPE _port = 0;
_port < this->getNum_from_Tlm();
++_port
) {
this->m_from_Tlm[_port].init();
this->m_from_Tlm[_port].addCallComp(
this,
from_Tlm_static
);
this->m_from_Tlm[_port].setPortNum(_port);
#if FW_OBJECT_NAMES == 1
char _portName[80];
(void) snprintf(
_portName,
sizeof(_portName),
"%s_from_Tlm[%d]",
this->m_objName,
_port
);
this->m_from_Tlm[_port].setObjName(_portName);
#endif
}
// Attach input port Time
for (
NATIVE_INT_TYPE _port = 0;
_port < this->getNum_from_Time();
++_port
) {
this->m_from_Time[_port].init();
this->m_from_Time[_port].addCallComp(
this,
from_Time_static
);
this->m_from_Time[_port].setPortNum(_port);
#if FW_OBJECT_NAMES == 1
char _portName[80];
(void) snprintf(
_portName,
sizeof(_portName),
"%s_from_Time[%d]",
this->m_objName,
_port
);
this->m_from_Time[_port].setObjName(_portName);
#endif
}
// Initialize output port aport
for (
NATIVE_INT_TYPE _port = 0;
_port < this->getNum_to_aport();
++_port
) {
this->m_to_aport[_port].init();
#if FW_OBJECT_NAMES == 1
char _portName[80];
snprintf(
_portName,
sizeof(_portName),
"%s_to_aport[%d]",
this->m_objName,
_port
);
this->m_to_aport[_port].setObjName(_portName);
#endif
}
}
// ----------------------------------------------------------------------
// Getters for port counts
// ----------------------------------------------------------------------
NATIVE_INT_TYPE TestTlmTesterBase ::
getNum_to_aport(void) const
{
return (NATIVE_INT_TYPE) FW_NUM_ARRAY_ELEMENTS(this->m_to_aport);
}
NATIVE_INT_TYPE TestTlmTesterBase ::
getNum_from_Tlm(void) const
{
return (NATIVE_INT_TYPE) FW_NUM_ARRAY_ELEMENTS(this->m_from_Tlm);
}
NATIVE_INT_TYPE TestTlmTesterBase ::
getNum_from_Time(void) const
{
return (NATIVE_INT_TYPE) FW_NUM_ARRAY_ELEMENTS(this->m_from_Time);
}
// ----------------------------------------------------------------------
// Connectors for to ports
// ----------------------------------------------------------------------
void TestTlmTesterBase ::
connect_to_aport(
const NATIVE_INT_TYPE portNum,
Another::InputTestPort *const aport
)
{
FW_ASSERT(portNum < this->getNum_to_aport(),static_cast<AssertArg>(portNum));
this->m_to_aport[portNum].addCallPort(aport);
}
// ----------------------------------------------------------------------
// Invocation functions for to ports
// ----------------------------------------------------------------------
void TestTlmTesterBase ::
invoke_to_aport(
const NATIVE_INT_TYPE portNum,
I32 arg4,
F32 arg5,
U8 arg6
)
{
FW_ASSERT(portNum < this->getNum_to_aport(),static_cast<AssertArg>(portNum));
FW_ASSERT(portNum < this->getNum_to_aport(),static_cast<AssertArg>(portNum));
this->m_to_aport[portNum].invoke(
arg4, arg5, arg6
);
}
// ----------------------------------------------------------------------
// Connection status for to ports
// ----------------------------------------------------------------------
bool TestTlmTesterBase ::
isConnected_to_aport(const NATIVE_INT_TYPE portNum)
{
FW_ASSERT(portNum < this->getNum_to_aport(), static_cast<AssertArg>(portNum));
return this->m_to_aport[portNum].isConnected();
}
// ----------------------------------------------------------------------
// Getters for from ports
// ----------------------------------------------------------------------
Fw::InputTlmPort *TestTlmTesterBase ::
get_from_Tlm(const NATIVE_INT_TYPE portNum)
{
FW_ASSERT(portNum < this->getNum_from_Tlm(),static_cast<AssertArg>(portNum));
return &this->m_from_Tlm[portNum];
}
Fw::InputTimePort *TestTlmTesterBase ::
get_from_Time(const NATIVE_INT_TYPE portNum)
{
FW_ASSERT(portNum < this->getNum_from_Time(),static_cast<AssertArg>(portNum));
return &this->m_from_Time[portNum];
}
// ----------------------------------------------------------------------
// Static functions for from ports
// ----------------------------------------------------------------------
void TestTlmTesterBase ::
from_Tlm_static(
Fw::PassiveComponentBase *const component,
NATIVE_INT_TYPE portNum,
FwChanIdType id,
Fw::Time &timeTag,
Fw::TlmBuffer &val
)
{
TestTlmTesterBase* _testerBase =
static_cast<TestTlmTesterBase*>(component);
_testerBase->dispatchTlm(id, timeTag, val);
}
void TestTlmTesterBase ::
from_Time_static(
Fw::PassiveComponentBase *const component,
const NATIVE_INT_TYPE portNum,
Fw::Time& time
)
{
TestTlmTesterBase* _testerBase =
static_cast<TestTlmTesterBase*>(component);
time = _testerBase->m_testTime;
}
// ----------------------------------------------------------------------
// History
// ----------------------------------------------------------------------
void TestTlmTesterBase ::
clearHistory()
{
this->clearTlm();
}
// ----------------------------------------------------------------------
// Time
// ----------------------------------------------------------------------
void TestTlmTesterBase ::
setTestTime(const Fw::Time& time)
{
this->m_testTime = time;
}
// ----------------------------------------------------------------------
// Telemetry dispatch
// ----------------------------------------------------------------------
void TestTlmTesterBase ::
dispatchTlm(
const FwChanIdType id,
const Fw::Time &timeTag,
Fw::TlmBuffer &val
)
{
val.resetDeser();
const U32 idBase = this->getIdBase();
FW_ASSERT(id >= idBase, id, idBase);
switch (id - idBase) {
case TestTlmComponentBase::CHANNELID_SOMECHAN:
{
U32 arg;
const Fw::SerializeStatus _status = val.deserialize(arg);
if (_status != Fw::FW_SERIALIZE_OK) {
printf("Error deserializing somechan: %d\n", _status);
return;
}
this->tlmInput_somechan(timeTag, arg);
break;
}
case TestTlmComponentBase::CHANNELID_ENUMCHAN:
{
FwEnumStoreType enumchanarg;
const Fw::SerializeStatus _status = val.deserialize(enumchanarg);
if (_status != Fw::FW_SERIALIZE_OK) {
printf("Error deserializing enumchan: %d\n", _status);
return;
}
TestTlmComponentBase::SomeEnum arg =
static_cast<TestTlmComponentBase::SomeEnum>(enumchanarg);
this->tlmInput_enumchan(timeTag, arg);
break;
}
case TestTlmComponentBase::CHANNELID_QUATCHAN:
{
U32 arg;
const Fw::SerializeStatus _status = val.deserialize(arg);
if (_status != Fw::FW_SERIALIZE_OK) {
printf("Error deserializing quatchan: %d\n", _status);
return;
}
this->tlmInput_quatchan(timeTag, arg);
break;
}
case TestTlmComponentBase::CHANNELID_STRINGCHAN:
{
U32 arg;
const Fw::SerializeStatus _status = val.deserialize(arg);
if (_status != Fw::FW_SERIALIZE_OK) {
printf("Error deserializing stringchan: %d\n", _status);
return;
}
this->tlmInput_stringchan(timeTag, arg);
break;
}
default: {
FW_ASSERT(0, id);
break;
}
}
}
void TestTlmTesterBase ::
clearTlm(void)
{
this->tlmSize = 0;
this->tlmHistory_somechan->clear();
this->tlmHistory_enumchan->clear();
this->tlmHistory_quatchan->clear();
this->tlmHistory_stringchan->clear();
}
// ----------------------------------------------------------------------
// Channel: somechan
// ----------------------------------------------------------------------
void TestTlmTesterBase ::
tlmInput_somechan(
const Fw::Time& timeTag,
const U32& val
)
{
TlmEntry_somechan e = { timeTag, val };
this->tlmHistory_somechan->push_back(e);
++this->tlmSize;
}
// ----------------------------------------------------------------------
// Channel: enumchan
// ----------------------------------------------------------------------
void TestTlmTesterBase ::
tlmInput_enumchan(
const Fw::Time& timeTag,
const TestTlmComponentBase::SomeEnum& val
)
{
TlmEntry_enumchan e = { timeTag, val };
this->tlmHistory_enumchan->push_back(e);
++this->tlmSize;
}
// ----------------------------------------------------------------------
// Channel: quatchan
// ----------------------------------------------------------------------
void TestTlmTesterBase ::
tlmInput_quatchan(
const Fw::Time& timeTag,
const U32& val
)
{
TlmEntry_quatchan e = { timeTag, val };
this->tlmHistory_quatchan->push_back(e);
++this->tlmSize;
}
// ----------------------------------------------------------------------
// Channel: stringchan
// ----------------------------------------------------------------------
void TestTlmTesterBase ::
tlmInput_stringchan(
const Fw::Time& timeTag,
const U32& val
)
{
TlmEntry_stringchan e = { timeTag, val };
this->tlmHistory_stringchan->push_back(e);
++this->tlmSize;
}
} // end namespace Tlm
|
#include <iostream>
#include "Types.hpp"
#include "Parser.hpp"
#include "Formatter.hpp"
int main() {
glgen::EnumInfo d;
d.name = "GL_VERSION_NAME_STRING";
std::cout << "==================\n";
auto versions = glgen::Parser::parse("gl.xml");
glgen::Formatter formatter;
formatter.setClassNamespace("OpenGL");
formatter.generate(versions, "./glout");
std::cout << "==================\n";
return 0;
}
|
// Copyright (c) 2014-2016 The Dash developers
// Copyright (c) 2016-2017 The PIVX developers
// Copyright (c) 2017-2020 The Verizon Core developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "spork.h"
#include "base58.h"
#include "key.h"
#include "main.h"
#include "masternode-budget.h"
#include "net.h"
#include "protocol.h"
#include "sync.h"
#include "util.h"
#include <boost/lexical_cast.hpp>
using namespace std;
using namespace boost;
class CSporkMessage;
class CSporkManager;
CSporkManager sporkManager;
std::map<uint256, CSporkMessage> mapSporks;
std::map<int, CSporkMessage> mapSporksActive;
void ProcessSpork(CNode* pfrom, std::string& strCommand, CDataStream& vRecv)
{
if (fLiteMode) return; //disable all privatesend/masternode related functionality
if (strCommand == "spork") {
//LogPrintf("ProcessSpork::spork\n");
CDataStream vMsg(vRecv);
CSporkMessage spork;
vRecv >> spork;
if (chainActive.Tip() == NULL) return;
uint256 hash = spork.GetHash();
if (mapSporksActive.count(spork.nSporkID)) {
if (mapSporksActive[spork.nSporkID].nTimeSigned >= spork.nTimeSigned) {
if (fDebug) LogPrintf("spork - seen %s block %d \n", hash.ToString(), chainActive.Tip()->nHeight);
return;
} else {
if (fDebug) LogPrintf("spork - got updated spork %s block %d \n", hash.ToString(), chainActive.Tip()->nHeight);
}
}
LogPrintf("spork - new %s ID %d Time %d bestHeight %d\n", hash.ToString(), spork.nSporkID, spork.nValue, chainActive.Tip()->nHeight);
if (!sporkManager.CheckSignature(spork)) {
LogPrintf("spork - invalid signature\n");
Misbehaving(pfrom->GetId(), 100);
return;
}
mapSporks[hash] = spork;
mapSporksActive[spork.nSporkID] = spork;
sporkManager.Relay(spork);
//does a task if needed
ExecuteSpork(spork.nSporkID, spork.nValue);
}
if (strCommand == "getsporks") {
std::map<int, CSporkMessage>::iterator it = mapSporksActive.begin();
while (it != mapSporksActive.end()) {
pfrom->PushMessage("spork", it->second);
it++;
}
}
}
// grab the spork, otherwise say it's off
bool IsSporkActive(int nSporkID)
{
int64_t r = -1;
if (mapSporksActive.count(nSporkID)) {
r = mapSporksActive[nSporkID].nValue;
} else {
if (nSporkID == SPORK_2_INSTANTSEND) r = SPORK_2_INSTANTSEND_DEFAULT;
if (nSporkID == SPORK_3_INSTANTSEND_BLOCK_FILTERING) r = SPORK_3_INSTANTSEND_BLOCK_FILTERING_DEFAULT;
if (nSporkID == SPORK_5_MAX_VALUE) r = SPORK_5_MAX_VALUE_DEFAULT;
if (nSporkID == SPORK_7_MASTERNODE_SCANNING) r = SPORK_7_MASTERNODE_SCANNING_DEFAULT;
if (nSporkID == SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT) r = SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT_DEFAULT;
if (nSporkID == SPORK_9_MASTERNODE_BUDGET_ENFORCEMENT) r = SPORK_9_MASTERNODE_BUDGET_ENFORCEMENT_DEFAULT;
if (nSporkID == SPORK_10_MASTERNODE_PAY_UPDATED_NODES) r = SPORK_10_MASTERNODE_PAY_UPDATED_NODES_DEFAULT;
if (nSporkID == SPORK_11_RESET_BUDGET) r = SPORK_11_RESET_BUDGET_DEFAULT;
if (nSporkID == SPORK_12_RECONSIDER_BLOCKS) r = SPORK_12_RECONSIDER_BLOCKS_DEFAULT;
if (nSporkID == SPORK_13_ENABLE_SUPERBLOCKS) r = SPORK_13_ENABLE_SUPERBLOCKS_DEFAULT;
if (nSporkID == SPORK_14_NEW_PROTOCOL_ENFORCEMENT) r = SPORK_14_NEW_PROTOCOL_ENFORCEMENT_DEFAULT;
if (nSporkID == SPORK_15_NEW_PROTOCOL_ENFORCEMENT_2) r = SPORK_15_NEW_PROTOCOL_ENFORCEMENT_2_DEFAULT;
if (nSporkID == SPORK_16_MN_WINNER_MINIMUM_AGE) r = SPORK_16_MN_WINNER_MINIMUM_AGE_DEFAULT;
if (r == -1) LogPrintf("GetSpork::Unknown Spork %d\n", nSporkID);
}
if (r == -1) r = 4070908800; //return 2099-1-1 by default
return r < GetTime();
}
// grab the value of the spork on the network, or the default
int64_t GetSporkValue(int nSporkID)
{
int64_t r = -1;
if (mapSporksActive.count(nSporkID)) {
r = mapSporksActive[nSporkID].nValue;
} else {
if (nSporkID == SPORK_2_INSTANTSEND) r = SPORK_2_INSTANTSEND_DEFAULT;
if (nSporkID == SPORK_3_INSTANTSEND_BLOCK_FILTERING) r = SPORK_3_INSTANTSEND_BLOCK_FILTERING_DEFAULT;
if (nSporkID == SPORK_5_MAX_VALUE) r = SPORK_5_MAX_VALUE_DEFAULT;
if (nSporkID == SPORK_7_MASTERNODE_SCANNING) r = SPORK_7_MASTERNODE_SCANNING_DEFAULT;
if (nSporkID == SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT) r = SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT_DEFAULT;
if (nSporkID == SPORK_9_MASTERNODE_BUDGET_ENFORCEMENT) r = SPORK_9_MASTERNODE_BUDGET_ENFORCEMENT_DEFAULT;
if (nSporkID == SPORK_10_MASTERNODE_PAY_UPDATED_NODES) r = SPORK_10_MASTERNODE_PAY_UPDATED_NODES_DEFAULT;
if (nSporkID == SPORK_11_RESET_BUDGET) r = SPORK_11_RESET_BUDGET_DEFAULT;
if (nSporkID == SPORK_12_RECONSIDER_BLOCKS) r = SPORK_12_RECONSIDER_BLOCKS_DEFAULT;
if (nSporkID == SPORK_13_ENABLE_SUPERBLOCKS) r = SPORK_13_ENABLE_SUPERBLOCKS_DEFAULT;
if (nSporkID == SPORK_14_NEW_PROTOCOL_ENFORCEMENT) r = SPORK_14_NEW_PROTOCOL_ENFORCEMENT_DEFAULT;
if (nSporkID == SPORK_15_NEW_PROTOCOL_ENFORCEMENT_2) r = SPORK_15_NEW_PROTOCOL_ENFORCEMENT_2_DEFAULT;
if (nSporkID == SPORK_16_MN_WINNER_MINIMUM_AGE) r = SPORK_16_MN_WINNER_MINIMUM_AGE_DEFAULT;
if (r == -1) LogPrintf("GetSpork::Unknown Spork %d\n", nSporkID);
}
return r;
}
void ExecuteSpork(int nSporkID, int nValue)
{
if (nSporkID == SPORK_11_RESET_BUDGET && nValue == 1) {
budget.Clear();
}
//correct fork via spork technology
if (nSporkID == SPORK_12_RECONSIDER_BLOCKS && nValue > 0) {
LogPrintf("Spork::ExecuteSpork -- Reconsider Last %d Blocks\n", nValue);
ReprocessBlocks(nValue);
}
}
void ReprocessBlocks(int nBlocks)
{
std::map<uint256, int64_t>::iterator it = mapRejectedBlocks.begin();
while (it != mapRejectedBlocks.end()) {
//use a window twice as large as is usual for the nBlocks we want to reset
if ((*it).second > GetTime() - (nBlocks * 60 * 5)) {
BlockMap::iterator mi = mapBlockIndex.find((*it).first);
if (mi != mapBlockIndex.end() && (*mi).second) {
LOCK(cs_main);
CBlockIndex* pindex = (*mi).second;
LogPrintf("ReprocessBlocks - %s\n", (*it).first.ToString());
CValidationState state;
ReconsiderBlock(state, pindex);
}
}
++it;
}
CValidationState state;
{
LOCK(cs_main);
DisconnectBlocksAndReprocess(nBlocks);
}
if (state.IsValid()) {
ActivateBestChain(state);
}
}
bool CSporkManager::CheckSignature(CSporkMessage& spork)
{
//note: need to investigate why this is failing
std::string strMessage = boost::lexical_cast<std::string>(spork.nSporkID) + boost::lexical_cast<std::string>(spork.nValue) + boost::lexical_cast<std::string>(spork.nTimeSigned);
CPubKey pubkey(ParseHex(Params().SporkKey()));
std::string errorMessage = "";
if (!privateSendSigner.VerifyMessage(pubkey, spork.vchSig, strMessage, errorMessage)) {
return false;
}
return true;
}
bool CSporkManager::Sign(CSporkMessage& spork)
{
std::string strMessage = boost::lexical_cast<std::string>(spork.nSporkID) + boost::lexical_cast<std::string>(spork.nValue) + boost::lexical_cast<std::string>(spork.nTimeSigned);
CKey key2;
CPubKey pubkey2;
std::string errorMessage = "";
if (!privateSendSigner.SetKey(strMasterPrivKey, errorMessage, key2, pubkey2)) {
LogPrintf("CMasternodePayments::Sign - ERROR: Invalid masternodeprivkey: '%s'\n", errorMessage);
return false;
}
if (!privateSendSigner.SignMessage(strMessage, errorMessage, spork.vchSig, key2)) {
LogPrintf("CMasternodePayments::Sign - Sign message failed");
return false;
}
if (!privateSendSigner.VerifyMessage(pubkey2, spork.vchSig, strMessage, errorMessage)) {
LogPrintf("CMasternodePayments::Sign - Verify message failed");
return false;
}
return true;
}
bool CSporkManager::UpdateSpork(int nSporkID, int64_t nValue)
{
CSporkMessage msg;
msg.nSporkID = nSporkID;
msg.nValue = nValue;
msg.nTimeSigned = GetTime();
if (Sign(msg)) {
Relay(msg);
mapSporks[msg.GetHash()] = msg;
mapSporksActive[nSporkID] = msg;
return true;
}
return false;
}
void CSporkManager::Relay(CSporkMessage& msg)
{
CInv inv(MSG_SPORK, msg.GetHash());
RelayInv(inv);
}
bool CSporkManager::SetPrivKey(std::string strPrivKey)
{
CSporkMessage msg;
// Test signing successful, proceed
strMasterPrivKey = strPrivKey;
Sign(msg);
if (CheckSignature(msg)) {
LogPrintf("CSporkManager::SetPrivKey - Successfully initialized as spork signer\n");
return true;
} else {
return false;
}
}
int CSporkManager::GetSporkIDByName(std::string strName)
{
if (strName == "SPORK_2_INSTANTSEND") return SPORK_2_INSTANTSEND;
if (strName == "SPORK_3_INSTANTSEND_BLOCK_FILTERING") return SPORK_3_INSTANTSEND_BLOCK_FILTERING;
if (strName == "SPORK_5_MAX_VALUE") return SPORK_5_MAX_VALUE;
if (strName == "SPORK_7_MASTERNODE_SCANNING") return SPORK_7_MASTERNODE_SCANNING;
if (strName == "SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT") return SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT;
if (strName == "SPORK_9_MASTERNODE_BUDGET_ENFORCEMENT") return SPORK_9_MASTERNODE_BUDGET_ENFORCEMENT;
if (strName == "SPORK_10_MASTERNODE_PAY_UPDATED_NODES") return SPORK_10_MASTERNODE_PAY_UPDATED_NODES;
if (strName == "SPORK_11_RESET_BUDGET") return SPORK_11_RESET_BUDGET;
if (strName == "SPORK_12_RECONSIDER_BLOCKS") return SPORK_12_RECONSIDER_BLOCKS;
if (strName == "SPORK_13_ENABLE_SUPERBLOCKS") return SPORK_13_ENABLE_SUPERBLOCKS;
if (strName == "SPORK_14_NEW_PROTOCOL_ENFORCEMENT") return SPORK_14_NEW_PROTOCOL_ENFORCEMENT;
if (strName == "SPORK_15_NEW_PROTOCOL_ENFORCEMENT_2") return SPORK_15_NEW_PROTOCOL_ENFORCEMENT_2;
if (strName == "SPORK_16_MN_WINNER_MINIMUM_AGE") return SPORK_16_MN_WINNER_MINIMUM_AGE;
return -1;
}
std::string CSporkManager::GetSporkNameByID(int id)
{
if (id == SPORK_2_INSTANTSEND) return "SPORK_2_INSTANTSEND";
if (id == SPORK_3_INSTANTSEND_BLOCK_FILTERING) return "SPORK_3_INSTANTSEND_BLOCK_FILTERING";
if (id == SPORK_5_MAX_VALUE) return "SPORK_5_MAX_VALUE";
if (id == SPORK_7_MASTERNODE_SCANNING) return "SPORK_7_MASTERNODE_SCANNING";
if (id == SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT) return "SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT";
if (id == SPORK_9_MASTERNODE_BUDGET_ENFORCEMENT) return "SPORK_9_MASTERNODE_BUDGET_ENFORCEMENT";
if (id == SPORK_10_MASTERNODE_PAY_UPDATED_NODES) return "SPORK_10_MASTERNODE_PAY_UPDATED_NODES";
if (id == SPORK_11_RESET_BUDGET) return "SPORK_11_RESET_BUDGET";
if (id == SPORK_12_RECONSIDER_BLOCKS) return "SPORK_12_RECONSIDER_BLOCKS";
if (id == SPORK_13_ENABLE_SUPERBLOCKS) return "SPORK_13_ENABLE_SUPERBLOCKS";
if (id == SPORK_14_NEW_PROTOCOL_ENFORCEMENT) return "SPORK_14_NEW_PROTOCOL_ENFORCEMENT";
if (id == SPORK_15_NEW_PROTOCOL_ENFORCEMENT_2) return "SPORK_15_NEW_PROTOCOL_ENFORCEMENT_2";
if (id == SPORK_16_MN_WINNER_MINIMUM_AGE) return "SPORK_16_MN_WINNER_MINIMUM_AGE";
return "Unknown";
}
|
#ifndef MMIO_HPP
#define MMIO_HPP
#include <assert.h>
#include <iostream>
#include <fstream>
#include <algorithm>
#include <complex>
#include <string>
#include <iomanip>
#include <type_traits>
#include <Eigen/Core>
#include <Eigen/SparseCore>
namespace mmio {
template<class T> struct is_complex : std::false_type {};
template<class T> struct is_complex<std::complex<T>> : std::true_type {};
/** Read a real / cplx scalar **/
template<typename V, std::enable_if_t<!is_complex<V>{}>* = nullptr>
inline V read_entry(std::istringstream& vals) {
V v;
vals >> v;
return v;
};
template<typename V, std::enable_if_t<is_complex<V>{}>* = nullptr>
inline V read_line(std::istringstream& vals) {
typename V::value_type v1, v2;
vals >> v1 >> v2;
return V(v1, v2);
};
/** Read a line real / cplx of coordinate values **/
template<typename V, typename I, std::enable_if_t<!is_complex<V>{}>* = nullptr>
inline Eigen::Triplet<V,I> read_line(std::istringstream& vals) {
I i, j;
V v;
vals >> i >> j >> v;
return Eigen::Triplet<V,I>(i-1,j-1,v);
};
template<typename V, typename I, std::enable_if_t<is_complex<V>{}>* = nullptr>
inline Eigen::Triplet<V,I> read_line(std::istringstream& vals) {
I i, j;
typename V::value_type v1, v2;
vals >> i >> j >> v1 >> v2;
return Eigen::Triplet<V,I>(i-1,j-1,V(v1,v2));
};
/** Write a line real / cplx of coordinate values **/
template<typename V, typename I>
inline std::stringstream get_line(I i, I j, V v) {
std::stringstream s;
s << std::setprecision(20);
s << i+1 << " " << j+1 << " " << v;
return s;
};
template<typename V, typename I>
inline std::stringstream get_line(I i, I j, std::complex<V> v) {
std::stringstream s;
s << std::setprecision(20);
s << i+1 << " " << j+1 << " " << v.real() << " " << v.imag();
return s;
};
/** Symmetric (real) / hermitian (cplx) **/
template<typename V, typename I>
inline Eigen::Triplet<V,I> symmetric(Eigen::Triplet<V,I>& a) {
return Eigen::Triplet<V,I>(a.col(), a.row(), a.value());
}
template<typename V, typename I>
inline Eigen::Triplet<std::complex<V>,I> symmetric(Eigen::Triplet<std::complex<V>,I>& a) {
return Eigen::Triplet<std::complex<V>,I>(a.col(), a.row(), std::conj(a.value()));
}
/** Skew-symmetric (real only, really) **/
template<typename V, typename I>
inline Eigen::Triplet<V,I> skew_symmetric(Eigen::Triplet<V,I>& a) {
return Eigen::Triplet<V,I>(a.col(), a.row(), - a.value());
}
enum class format {coordinate, array};
enum class type {real, integer, complex, pattern};
enum class property {general, symmetric, hermitian, skew_symmetric};
inline std::string prop2str(property p) {
if(p == property::general) return "general";
else if(p == property::symmetric) return "symmetric";
else if(p == property::hermitian) return "hermitian";
else return "skew_symmetric";
}
template<typename V>
struct V2str {
inline static std::string value() {
if(is_complex<V>{}) {
return "complex";
} else if (std::is_integral<V>::value) {
return "integer";
} else {
return "real";
}
}
};
struct Header {
bool bannerOK;
bool objectOK;
format f;
type t;
property p;
Header(std::istringstream& header) {
std::string banner, object, format, type, properties;
header >> banner >> object >> format >> type >> properties;
std::transform(object.begin(), object.end(), object.begin(), ::tolower);
std::transform(format.begin(), format.end(), format.begin(), ::tolower);
std::transform(type.begin(), type.end(), type.begin(), ::tolower);
std::transform(properties.begin(), properties.end(), properties.begin(), ::tolower);
this->bannerOK = ! banner.compare("%%MatrixMarket");
this->objectOK = ! object.compare("matrix");
assert(this->bannerOK);
assert(this->objectOK);
if(! format.compare("coordinate")) {
this->f = format::coordinate;
} else if(! format.compare("array")) {
this->f = format::array;
} else {
assert(false);
}
if (! type.compare("real")) {
this->t = type::real;
} else if (! type.compare("integer")) {
this->t = type::integer;
} else if (! type.compare("complex")) {
this->t = type::complex;
} else if (! type.compare("pattern")) {
this->t = type::pattern;
} else {
assert(false);
}
if (! properties.compare("general")) {
this->p = property::general;
} else if (! properties.compare("symmetric")) {
this->p = property::symmetric;
} else if (! properties.compare("skew-symmetric")) {
this->p = property::skew_symmetric;
} else if (! properties.compare("hermitian")) {
this->p = property::hermitian;
} else {
assert(false);
}
}
};
/**
* Read a sparse matrix in MM format
*/
template<typename V, typename I>
inline Eigen::SparseMatrix<V, Eigen::ColMajor, I> sp_mmread(std::string filename) {
std::ifstream mfile(filename);
if (mfile.is_open()) {
std::string line;
/** Header **/
std::getline(mfile, line);
std::istringstream header(line);
Header h(header);
assert(h.f == format::coordinate);
assert(h.t != type::pattern);
/** Find M N K row **/
while(std::getline(mfile, line)) {
if(line.size() == 0 || line[0] == '%') continue;
else break;
}
I M, N, K;
std::istringstream MNK(line);
MNK >> M >> N >> K;
std::vector<Eigen::Triplet<V,I>> data;
if(h.p != property::general) {
data.reserve(2*K);
} else {
data.reserve(K);
}
/** Read data **/
int lineread = 0;
while(std::getline(mfile, line)) {
if(line.size() == 0 || line[0] == '%') continue;
std::istringstream vals(line);
Eigen::Triplet<V,I> dataline = read_line<V,I>(vals);
data.push_back(dataline);
if(dataline.row() != dataline.col() && (h.p == property::symmetric || h.p == property::hermitian)) {
Eigen::Triplet<V,I> dataline2 = symmetric(dataline);
data.push_back(dataline2);
}
if(dataline.row() != dataline.col() && (h.p == property::skew_symmetric)) {
Eigen::Triplet<V,I> dataline2 = skew_symmetric(dataline);
data.push_back(dataline2);
}
if(h.p == property::skew_symmetric && dataline.row() == dataline.col()) {
assert(false);
}
if(h.p != property::general && dataline.row() < dataline.col()) {
assert(false);
}
lineread ++;
}
assert(lineread == K);
Eigen::SparseMatrix<V, Eigen::ColMajor, I> A(M, N);
A.setFromTriplets(data.begin(), data.end());
return std::move(A);
} else {
std::cout << "Couldn't open " << filename << std::endl;
throw("Couldn't open file");
}
}
/**
* Reads a dense matrix in MM format
*/
template<typename V>
inline Eigen::Matrix<V, Eigen::Dynamic, Eigen::Dynamic> dense_mmread(std::string filename) {
std::ifstream mfile(filename);
if (mfile.is_open()) {
std::string line;
/** Header **/
std::getline(mfile, line);
std::istringstream header(line);
Header h(header);
assert(h.p == property::general); // We don't really support anything else so far...
assert(h.f == format::array);
assert(h.t != type::pattern);
/** Find M N row **/
while(std::getline(mfile, line)) {
if(line.size() == 0 || line[0] == '%') continue;
else break;
}
int M, N;
std::istringstream MNK(line);
MNK >> M >> N;
Eigen::Matrix<V, Eigen::Dynamic, Eigen::Dynamic> A(M, N);
/** Read data **/
int lineread = 0;
while(std::getline(mfile, line)) {
if(line.size() == 0 || line[0] == '%') continue;
std::istringstream vals(line);
V v = read_entry<V>(vals);
int i = (lineread % M);
int j = (lineread / M);
A(i,j) = v;
lineread ++;
}
assert(lineread == M*N);
return std::move(A);
} else {
std::cout << "Couldn't open " << filename << std::endl;
throw("Couldn't open file");
}
}
/**
* Writes a sparse matrix in MM format, using the optional property p.
* Wether the matrix satisfies or not p is not verified
*/
template<typename V, int S, typename I>
inline void sp_mmwrite(std::string filename, Eigen::SparseMatrix<V,S,I> mat, property p = property::general) {
std::ofstream mfile;
mfile.open(filename);
// mfile.open (filename);
if (mfile.is_open()) {
std::string type = V2str<V>::value();
std::string prop = prop2str(p);
mfile << "%%MatrixMarket matrix coordinate " << type << " " << prop << "\n";
int NNZ = 0;
for (int k = 0; k < mat.outerSize(); ++k) {
for (typename Eigen::SparseMatrix<V,S,I>::InnerIterator it(mat,k); it; ++it) {
if( (p == property::symmetric || p == property::hermitian) && (it.row() < it.col()) ) continue;
if( (p == property::skew_symmetric) && (it.row() <= it.col()) ) continue;
NNZ ++;
}
}
mfile << mat.rows() << " " << mat.cols() << " " << NNZ << "\n";
for (int k = 0; k < mat.outerSize(); ++k) {
for (typename Eigen::SparseMatrix<V,S,I>::InnerIterator it(mat,k); it; ++it) {
if( (p == property::symmetric || p == property::hermitian) && (it.row() < it.col()) ) continue;
if( (p == property::skew_symmetric) && (it.row() <= it.col()) ) continue;
mfile << get_line(it.row(), it.col(), it.value()).rdbuf() << "\n";
}
}
} else {
std::cout << "Couldn't open " << filename << std::endl;
throw("Couldn't open file");
}
}
/**
* Writes a dense matrix in MM format, using the optional property p.
* Wether the matrix satisfies or not p is not verified
*/
template<typename V>
inline void dense_mmwrite(std::string filename, Eigen::Matrix<V, Eigen::Dynamic, Eigen::Dynamic> mat, property p = property::general) {
std::ofstream mfile;
mfile.open (filename);
if (mfile.is_open()) {
std::string type = V2str<V>::value();
std::string prop = prop2str(p);
mfile << "%%MatrixMarket matrix array " << type << " " << prop << "\n";
mfile << mat.rows() << " " << mat.cols() << "\n";
for(int j = 0; j < mat.cols(); j++) {
for(int i = 0; i < mat.rows(); i++) {
if( (p == property::symmetric || p == property::hermitian) && (i < j) ) continue;
if( (p == property::skew_symmetric) && (i <= j) ) continue;
mfile << mat(i,j) << "\n";
}
}
} else {
std::cout << "Couldn't open " << filename << std::endl;
throw("Couldn't open file");
}
}
}
#endif
|
#include "stdafx.h"
#include "../../../async_task.h"
#include "../wim_packet.h"
#include "upload_task.h"
#include "download_task.h"
#include "loader_handlers.h"
#include "loader_helpers.h"
#include "preview_proxy.h"
#include "web_file_info.h"
#include "../../../http_request.h"
#include "../../../tools/md5.h"
#include "../../../tools/system.h"
#include "../../../../corelib/enumerations.h"
#include "../../../core.h"
#include "../../../network_log.h"
#include "../../../utils.h"
#include "../../../log/log.h"
#include "../../../disk_cache/disk_cache.h"
#include "../../../profiling/profiler.h"
#include "../../../../common.shared/loader_errors.h"
#include "loader.h"
using namespace core;
using namespace wim;
namespace
{
bool is_suspendable_error(const loader_errors _error);
template<typename T>
T find_task_by_id(T first, T last, const std::string &_id)
{
return std::find_if(
first,
last,
[&_id]
(const auto &_item)
{
assert(_item);
return (_item->get_id() == _id);
});
}
}
loader::loader(std::wstring _cache_dir)
: file_sharing_threads_(std::make_unique<async_executer>("fs_loader", 1))
, cache_(disk_cache::disk_cache::make(std::move(_cache_dir)))
{
initialize_tasks_runners();
}
loader::~loader()
{
}
void loader::add_file_sharing_task(const std::shared_ptr<fs_loader_task>& _task)
{
assert(_task);
const auto &task_id = _task->get_id();
assert(!task_id.empty());
const auto iter_task = find_task_by_id(file_sharing_tasks_.cbegin(), file_sharing_tasks_.cend(), task_id);
if (iter_task != file_sharing_tasks_.cend())
{
assert(!"task with the same id already exist");
return;
}
file_sharing_tasks_.push_back(_task);
}
void loader::remove_file_sharing_task(const std::string &_id)
{
assert(!_id.empty());
const auto iter_task = find_task_by_id(file_sharing_tasks_.cbegin(), file_sharing_tasks_.cend(), _id);
if (iter_task == file_sharing_tasks_.cend())
{
return;
}
file_sharing_tasks_.erase(iter_task);
}
void loader::on_file_sharing_task_result(const std::shared_ptr<fs_loader_task>& _task, int32_t _error)
{
_task->on_result(_error);
remove_file_sharing_task(_task->get_id());
}
void loader::on_file_sharing_task_progress(const std::shared_ptr<fs_loader_task>& _task)
{
_task->on_progress();
}
bool loader::has_file_sharing_task(const std::string &_id) const
{
assert(!_id.empty());
return find_task_by_id(file_sharing_tasks_.cbegin(), file_sharing_tasks_.cend(), _id) != file_sharing_tasks_.cend();
}
void loader::resume_file_sharing_tasks()
{
for (const auto &task : file_sharing_tasks_)
{
if (task->get_last_error() != 0)
{
task->set_last_error(0);
task->resume(*this);
}
}
}
void loader::set_played(const std::string& _file_url, const std::wstring& _previews_folder, bool _played, const wim_packet_params& _params)
{
auto task = std::make_shared<download_task>(
"0",
_params,
_file_url,
std::wstring(),
std::wstring(),
_previews_folder);
add_file_sharing_task(task);
auto wr_this = weak_from_this();
std::weak_ptr<download_task> wr_task = task;
file_sharing_threads_->run_async_function(
[wr_task, _played]
{
const auto task = wr_task.lock();
if (!task)
return 0;
task->set_played(_played);
return 0;
}
)->on_result_ =
[wr_this, wr_task](int32_t _error)
{
const auto task = wr_task.lock();
if (!task)
return;
auto ptr_this = wr_this.lock();
if (!ptr_this)
return;
ptr_this->remove_file_sharing_task(task->get_id());
};
}
void loader::send_task_ranges_async(std::weak_ptr<upload_task> _wr_task)
{
auto wr_this = weak_from_this();
file_sharing_threads_->run_async_function([_wr_task]
{
auto task = _wr_task.lock();
if (!task)
return -1;
return (int32_t)task->send_next_range();
})->on_result_ = [wr_this, _wr_task](int32_t _error)
{
auto ptr_this = wr_this.lock();
if (!ptr_this)
return;
auto task = _wr_task.lock();
if (!task)
return;
if (_error != 0)
{
task->set_last_error(_error);
if (_error != (int32_t)loader_errors::network_error)
ptr_this->on_file_sharing_task_result(task, _error);
return;
}
ptr_this->on_file_sharing_task_progress(task);
if (!task->is_end())
{
ptr_this->send_task_ranges_async(task);
}
else
{
ptr_this->on_file_sharing_task_result(task, 0);
const auto current_time = std::chrono::system_clock::now();
core::stats::event_props_type props;
props.emplace_back("time", std::to_string((current_time - task->get_start_time())/std::chrono::milliseconds(1)));
props.emplace_back("size", std::to_string(task->get_file_size()/1024));
g_core->insert_event(core::stats::stats_event_names::filesharing_sent_success, props);
}
};
}
void loader::load_file_sharing_task_ranges_async(std::weak_ptr<download_task> _wr_task)
{
auto wr_this = weak_from_this();
file_sharing_threads_->run_async_function(
[_wr_task]
{
auto task = _wr_task.lock();
if (!task)
return -1;
auto err = task->load_next_range();
if (err == loader_errors::success)
{
if (task->is_end())
err = task->on_finish();
}
return (int32_t)err;
}
)->on_result_ =
[wr_this, _wr_task](int32_t _error)
{
auto ptr_this = wr_this.lock();
if (!ptr_this)
return;
auto task = _wr_task.lock();
if (!task)
return;
if (_error != 0)
{
task->set_last_error(_error);
if (_error != (int32_t)loader_errors::network_error)
{
ptr_this->on_file_sharing_task_result(task, _error);
}
return;
}
ptr_this->on_file_sharing_task_progress(task);
if (!task->is_end())
{
ptr_this->load_file_sharing_task_ranges_async(task);
}
else
{
ptr_this->on_file_sharing_task_result(task, 0);
}
};
}
std::shared_ptr<upload_progress_handler> loader::upload_file_sharing(
const std::string &_guid,
upload_file_params&& _file_params,
const wim_packet_params& _params)
{
assert(!_guid.empty());
assert(!_file_params.file_name.empty());
auto task = std::make_shared<upload_task>(_guid, _params, std::move(_file_params));
task->set_handler(std::make_shared<upload_progress_handler>());
add_file_sharing_task(task);
std::weak_ptr<upload_task> wr_task = task;
file_sharing_threads_->run_async_function(
[wr_task]
{
auto task = wr_task.lock();
if (!task)
return -1;
return (int32_t)task->open_file();
}
)->on_result_ =
[wr_this = weak_from_this(), wr_task](int32_t _error)
{
auto ptr_this = wr_this.lock();
if (!ptr_this)
return;
auto task = wr_task.lock();
if (!task)
return;
if (_error != 0)
{
ptr_this->on_file_sharing_task_result(task, _error);
return;
}
ptr_this->on_file_sharing_task_progress(task);
ptr_this->file_sharing_threads_->run_async_function(
[wr_task]
{
auto task = wr_task.lock();
if (!task)
return (int32_t)loader_errors::undefined;
return (int32_t)task->get_gate();
}
)->on_result_ =
[wr_this, wr_task](int32_t _error)
{
auto ptr_this = wr_this.lock();
if (!ptr_this)
return;
auto task = wr_task.lock();
if (!task)
return;
if (_error != 0)
{
ptr_this->on_file_sharing_task_result(task, _error);
return;
}
ptr_this->on_file_sharing_task_progress(task);
ptr_this->send_task_ranges_async(task);
};
};
return task->get_handler();
}
void cleanup_cache(const std::wstring& _cache_folder)
{
// copy'n'paste from async_loader.cpp. TODO: deduplicate!
constexpr int32_t max_files_to_delete = 100;
constexpr auto delete_files_older = std::chrono::hours(7 * 24);
constexpr auto cleanup_period = std::chrono::minutes(10);
static std::chrono::system_clock::time_point last_cleanup_time = std::chrono::system_clock::now();
std::chrono::system_clock::time_point current_time = std::chrono::system_clock::now();
if (current_time - last_cleanup_time < cleanup_period)
return;
tools::binary_stream bs;
bs.write<std::string_view>("Start cleanup files cache\r\n");
last_cleanup_time = current_time;
try
{
std::vector<boost::filesystem::wpath> files_to_delete;
boost::filesystem::wpath cache_path(_cache_folder);
boost::filesystem::directory_iterator end_iter;
boost::system::error_code error;
if (boost::filesystem::exists(cache_path, error) && boost::filesystem::is_directory(cache_path, error))
{
for (boost::filesystem::directory_iterator dir_iter(cache_path, error); (dir_iter != end_iter) && (files_to_delete.size() < max_files_to_delete) && !error; dir_iter.increment(error))
{
if (boost::filesystem::is_regular_file(dir_iter->status()))
{
const auto write_time = std::chrono::system_clock::from_time_t(boost::filesystem::last_write_time(dir_iter->path(), error));
if ((current_time - write_time) > delete_files_older)
files_to_delete.push_back(*dir_iter);
}
}
}
for (const auto& _file_path : files_to_delete)
{
boost::filesystem::remove(_file_path, error);
bs.write<std::string_view>("Delete file: ");
bs.write<std::string>(_file_path.string());
bs.write<std::string_view>("\r\n");
}
}
catch (const std::exception&)
{
}
bs.write<std::string_view>("Finish cleanup\r\n");
g_core->write_data_to_network_log(std::move(bs));
}
std::shared_ptr<download_progress_handler> loader::download_file_sharing(
const int64_t _seq,
const std::string& _file_url,
const file_sharing_function _function,
const std::wstring& _files_folder,
const std::wstring& _previews_folder,
const std::wstring& _filename,
const bool _force_request_metainfo,
const wim_packet_params& _params)
{
assert(_function > file_sharing_function::min);
assert(_function < file_sharing_function::max);
assert(_function != file_sharing_function::download_preview_metainfo);
auto task = std::make_shared<download_task>(
std::to_string(_seq),
_params,
_file_url,
_files_folder,
_previews_folder,
_filename
);
task->set_handler(std::make_shared<download_progress_handler>());
add_file_sharing_task(task);
auto wr_this = weak_from_this();
std::weak_ptr<download_task> wr_task = task;
file_sharing_threads_->run_async_function([wr_task, _function, _force_request_metainfo]
{
const auto task = wr_task.lock();
if (!task)
{
return 0;
}
// return -1 (failure) if there are no metainfo file or there are no downloaded fs link in the cache
if (!task->load_metainfo_from_local_cache())
{
return -1;
}
const auto check_file_existence = (
(_function == file_sharing_function::download_file) ||
(_function == file_sharing_function::check_local_copy_exists));
if (check_file_existence && !task->is_downloaded_file_exists())
{
return -1;
}
if (_force_request_metainfo)
{
return -1;
}
return 0;
})->on_result_ = [wr_this, wr_task, _function, _force_request_metainfo, _previews_folder](int32_t _error)
{
auto ptr_this = wr_this.lock();
if (!ptr_this)
return;
auto task = wr_task.lock();
if (!task)
return;
const auto is_local_copy_test_mode = (_function == file_sharing_function::check_local_copy_exists);
const auto is_file_and_metainfo_ready = (_error == 0);
if (is_file_and_metainfo_ready || is_local_copy_test_mode)
{
task->copy_if_needed();
ptr_this->on_file_sharing_task_result(task, _error);
ptr_this->file_sharing_threads_->run_async_function([wr_task, _previews_folder]
{
cleanup_cache(_previews_folder);
return 0;
});
return;
}
ptr_this->file_sharing_threads_->run_async_function([wr_task]
{
auto task = wr_task.lock();
if (!task)
{
return (int32_t)loader_errors::orphaned;
}
loader_errors error = task->download_metainfo();
if (error == loader_errors::metainfo_not_found)
{
task->delete_metainfo_file();
}
return (int32_t) error;
})->on_result_ = [wr_this, wr_task, _function, _force_request_metainfo, _previews_folder](int32_t _error)
{
auto ptr_this = wr_this.lock();
if (!ptr_this)
return;
auto task = wr_task.lock();
if (!task)
return;
const auto is_download_file_metainfo_mode = (_function == file_sharing_function::download_file_metainfo);
const auto success = (_error == 0);
if (success && (is_download_file_metainfo_mode || _force_request_metainfo))
{
task->serialize_metainfo();
}
if (!success || is_download_file_metainfo_mode)
{
ptr_this->on_file_sharing_task_result(task, _error);
return;
}
if (_force_request_metainfo)
{
if (task->is_downloaded_file_exists())
{
ptr_this->on_file_sharing_task_result(task, 0);
return;
}
}
g_core->insert_event(stats::stats_event_names::filesharing_download_success);
ptr_this->on_file_sharing_task_progress(task);
ptr_this->file_sharing_threads_->run_async_function([wr_task]
{
auto task = wr_task.lock();
if (!task)
return -1;
return (int32_t)task->open_temporary_file();
})->on_result_ = [wr_this, wr_task, _previews_folder](int32_t _error)
{
auto ptr_this = wr_this.lock();
if (!ptr_this)
return;
auto task = wr_task.lock();
if (!task)
return;
if (_error != 0)
{
ptr_this->on_file_sharing_task_result(task, _error);
return;
}
ptr_this->load_file_sharing_task_ranges_async(task);
ptr_this->file_sharing_threads_->run_async_function([wr_task, _previews_folder]
{
cleanup_cache(_previews_folder);
return 0;
});
};
};
};
return task->get_handler();
}
std::shared_ptr<get_file_direct_uri_handler> loader::get_file_direct_uri(
const int64_t _seq,
const std::string& _file_url,
const std::wstring& _cache_dir,
const wim_packet_params& _params)
{
auto handler = std::make_shared<get_file_direct_uri_handler>();
auto url = std::make_shared<std::string>();
file_sharing_threads_->run_async_function([url, _params, _file_url, _cache_dir]()->int32_t
{
loader_errors error = loader_errors::success;
download_task task(tools::system::generate_guid(), _params, _file_url, std::wstring(), _cache_dir, std::wstring());
error = task.download_metainfo();
if (error == loader_errors::success)
{
*url = task.get_file_direct_url();
}
return (int32_t)error;
})->on_result_ = [handler, url](int32_t _error)
{
handler->on_result(_error, *url);
};
return handler;
}
void loader::add_task(loader_task_sptr _task)
{
}
void loader::initialize_tasks_runners()
{
}
void loader::run_next_task(const tasks_runner_slot _slot)
{
}
void loader::resume_task(
const int64_t _id,
const wim_packet_params &_wim_params)
{
}
void loader::abort_file_sharing_process(const std::string &_process_id)
{
assert(!_process_id.empty());
remove_file_sharing_task(_process_id);
}
namespace
{
bool is_suspendable_error(const loader_errors _error)
{
return (_error == loader_errors::network_error) ||
(_error == loader_errors::suspend);
}
}
|
/*
Code by Drake Johnson
Displays multi-colored text in a windows console
*/
#ifndef CONS_HEADER_HEADER__
#define CONS_HEADER_HEADER__
#include "print.hpp"
#ifdef _WIN32
namespace cons
{
/**
The Header class creates a heading-style message. When the `display()` method
is called, the header will display fully formatted.
To set up a Header object, first make an object of the class with no parameters.
The properties of the header can then be modified through the setter methods. There
are also getter methods supplied. The header's properties are (1) the text of the
header, (2) the color of the text, and (3) the location of the cursor for the first
character of the header.
Default values for the properties are as follows:
- Text: "DEFAULT HEADER TEXT"
- Color: 15 (white foreground, black background)
After `display()` is called, the cursor will be moved to the next line.
Example usage:
@code
// Create Header object
cons::Header header;
// Set header text
header.set_text("Heading 1");
// Reset color attributes to 0
header.reset_color();
// Set foreground and background colors
header.set_foreground_color(cons::ConsoleColor::color::purple);
header.set_background_color(cons::ConsoleColor::color::white);
// Set position for first letter of header
header.set_cursor_location(0, 0);
@endcode
*/
class Header : public textf
{
private:
struct U_COORD
{
mutable unsigned X;
mutable unsigned Y;
[[nodiscard]] COORD get_short() const;
U_COORD& operator=(U_COORD other);
bool operator==(U_COORD other);
};
public:
Header(std::string text = "");
void display() const override;
void set_console_cursor(U_COORD position);
void set_console_cursor(unsigned x, unsigned y);
/**
@returns The position of the console's cursor as a U_COORD struct
*/
[[nodiscard]] U_COORD get_console_cursor() const;
private:
// INHERITED VARIABLES //
// std::string_view text_; //
// ConsoleColor color_; //
mutable U_COORD cursor_location_;
bool update_cursor_;
static U_COORD get_console_cursor_pos();
static U_COORD get_live_console_cursor();
[[nodiscard]] WORD setup_console() const override;
void restore_console(WORD old_attribs) const override;
};
} // namespace cons
# else // Not Windows system
// NOTE: Only Windows is supported for this header!
// If not using Windows, this header should cause a linker
// error.
# endif // _WIN32
#endif // !CONS_HEADER_HEADER__
|
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/vespalib/testkit/testapp.h>
#include <vespa/messagebus/result.h>
#include <vespa/messagebus/error.h>
#include <vespa/messagebus/errorcode.h>
#include <vespa/messagebus/testlib/simplemessage.h>
using namespace mbus;
struct MyMessage : public SimpleMessage
{
static int ctorCnt;
static int dtorCnt;
MyMessage(const string &str) : SimpleMessage(str) {
++ctorCnt;
}
virtual ~MyMessage() {
++dtorCnt;
}
};
int MyMessage::ctorCnt = 0;
int MyMessage::dtorCnt = 0;
struct Test : public vespalib::TestApp
{
Result sendOk(Message::UP msg);
Result sendFail(Message::UP msg);
int Main() override;
};
Result
Test::sendOk(Message::UP msg) {
(void) msg;
return Result();
}
Result
Test::sendFail(Message::UP msg) {
return Result(Error(ErrorCode::FATAL_ERROR, "error"), std::move(msg));
}
int
Test::Main()
{
TEST_INIT("result_test");
{ // test accepted
Message::UP msg(new MyMessage("test"));
Result res = sendOk(std::move(msg));
EXPECT_TRUE(msg.get() == 0);
EXPECT_TRUE(res.isAccepted());
EXPECT_TRUE(res.getError().getCode() == ErrorCode::NONE);
EXPECT_TRUE(res.getError().getMessage() == "");
Message::UP back = res.getMessage();
EXPECT_TRUE(back.get() == 0);
}
{ // test failed
Message::UP msg(new MyMessage("test"));
Message *raw = msg.get();
EXPECT_TRUE(raw != 0);
Result res = sendFail(std::move(msg));
EXPECT_TRUE(msg.get() == 0);
EXPECT_TRUE(!res.isAccepted());
EXPECT_TRUE(res.getError().getCode() == ErrorCode::FATAL_ERROR);
EXPECT_TRUE(res.getError().getMessage() == "error");
Message::UP back = res.getMessage();
EXPECT_TRUE(back.get() == raw);
}
EXPECT_TRUE(MyMessage::ctorCnt == 2);
EXPECT_TRUE(MyMessage::dtorCnt == 2);
TEST_DONE();
}
TEST_APPHOOK(Test);
|
#include "drape/batcher_helpers.hpp"
#include "drape/attribute_provider.hpp"
#include "drape/cpu_buffer.hpp"
#include "drape/index_storage.hpp"
#include "base/assert.hpp"
#include "base/math.hpp"
#include <algorithm>
namespace dp
{
namespace
{
bool IsEnoughMemory(uint32_t avVertex, uint32_t existVertex, uint32_t avIndex, uint32_t existIndex)
{
return avVertex >= existVertex && avIndex >= existIndex;
}
template<typename TGenerator>
void GenerateIndices(void * indexStorage, uint32_t count, uint32_t startIndex)
{
GenerateIndices<TGenerator>(indexStorage, count, TGenerator(startIndex));
}
template<typename TGenerator>
void GenerateIndices(void * indexStorage, uint32_t count, TGenerator const & generator)
{
if (dp::IndexStorage::IsSupported32bit())
{
auto pIndexStorage = static_cast<uint32_t *>(indexStorage);
std::generate(pIndexStorage, pIndexStorage + count, generator);
}
else
{
auto pIndexStorage = static_cast<uint16_t *>(indexStorage);
std::generate(pIndexStorage, pIndexStorage + count, generator);
}
}
class IndexGenerator
{
public:
explicit IndexGenerator(uint32_t startIndex)
: m_startIndex(startIndex)
, m_counter(0)
, m_minStripCounter(0) {}
protected:
uint32_t GetCounter() { return m_counter++; }
void ResetCounter()
{
m_counter = 0;
m_minStripCounter = 0;
}
uint32_t const m_startIndex;
int16_t GetCWNormalizer()
{
int16_t tmp = m_minStripCounter;
m_minStripCounter = static_cast<uint8_t>(base::cyclicClamp(m_minStripCounter + 1, 0, 5));
switch (tmp)
{
case 4: return 1;
case 5: return -1;
default: return 0;
}
}
private:
uint32_t m_counter;
uint8_t m_minStripCounter;
};
class ListIndexGenerator : public IndexGenerator
{
public:
explicit ListIndexGenerator(uint32_t startIndex)
: IndexGenerator(startIndex)
{}
uint32_t operator()() { return m_startIndex + GetCounter(); }
};
class StripIndexGenerator : public IndexGenerator
{
public:
explicit StripIndexGenerator(uint32_t startIndex)
: IndexGenerator(startIndex)
{}
uint32_t operator()()
{
uint32_t const counter = GetCounter();
return m_startIndex + counter - 2 * (counter / 3) + GetCWNormalizer();
}
};
class LineStripIndexGenerator : public IndexGenerator
{
public:
explicit LineStripIndexGenerator(uint32_t startIndex)
: IndexGenerator(startIndex)
{}
uint32_t operator()()
{
uint32_t const counter = GetCounter();
uint32_t const result = m_startIndex + m_counter;
if (counter % 2 == 0)
m_counter++;
return result;
}
private:
uint32_t m_counter = 0;
};
class LineRawIndexGenerator : public IndexGenerator
{
public:
LineRawIndexGenerator(uint32_t startIndex, std::vector<int> const & indices)
: IndexGenerator(startIndex)
, m_indices(indices)
{}
uint32_t operator()()
{
uint32_t const counter = GetCounter();
ASSERT_LESS(counter, m_indices.size(), ());
return static_cast<uint32_t>(m_startIndex + m_indices[counter]);
}
private:
std::vector<int> const & m_indices;
};
class FanIndexGenerator : public IndexGenerator
{
public:
explicit FanIndexGenerator(uint32_t startIndex)
: IndexGenerator(startIndex)
{}
uint32_t operator()()
{
uint32_t const counter = GetCounter();
if ((counter % 3) == 0)
return m_startIndex;
return m_startIndex + counter - 2 * (counter / 3);
}
};
class ListOfStripGenerator : public IndexGenerator
{
public:
ListOfStripGenerator(uint32_t startIndex, uint32_t vertexStride, uint32_t indexPerStrip)
: IndexGenerator(startIndex)
, m_vertexStride(vertexStride)
, m_indexPerStrip(indexPerStrip)
, m_base(0)
{}
uint32_t operator()()
{
uint32_t const counter = GetCounter();
uint32_t const result = m_startIndex + m_base + counter - 2 * (counter / 3) + GetCWNormalizer();
if (counter + 1 == m_indexPerStrip)
{
m_base += m_vertexStride;
ResetCounter();
}
return result;
}
private:
uint32_t m_vertexStride;
uint32_t m_indexPerStrip;
uint32_t m_base;
};
} // namespace
UniversalBatch::UniversalBatch(BatchCallbacks & callbacks, uint8_t minVerticesCount,
uint8_t minIndicesCount)
: m_callbacks(callbacks)
, m_canDivideStreams(true)
, m_minVerticesCount(minVerticesCount)
, m_minIndicesCount(minIndicesCount)
{}
void UniversalBatch::SetCanDivideStreams(bool canDivide)
{
m_canDivideStreams = canDivide;
}
bool UniversalBatch::CanDivideStreams() const
{
return m_canDivideStreams;
}
void UniversalBatch::SetVertexStride(uint8_t vertexStride)
{
m_vertexStride = vertexStride;
}
void UniversalBatch::FlushData(ref_ptr<AttributeProvider> streams,
uint32_t vertexCount) const
{
for (uint8_t i = 0; i < streams->GetStreamCount(); ++i)
FlushData(streams->GetBindingInfo(i), streams->GetRawPointer(i), vertexCount);
}
void UniversalBatch::FlushData(BindingInfo const & info, void const * data,
uint32_t elementCount) const
{
m_callbacks.FlushData(info, data, elementCount);
}
void * UniversalBatch::GetIndexStorage(uint32_t indexCount, uint32_t & startIndex)
{
return m_callbacks.GetIndexStorage(indexCount, startIndex);
}
void UniversalBatch::SubmitIndex()
{
m_callbacks.SubmitIndices();
}
uint32_t UniversalBatch::GetAvailableVertexCount() const
{
return m_callbacks.GetAvailableVertexCount();
}
uint32_t UniversalBatch::GetAvailableIndexCount() const
{
return m_callbacks.GetAvailableIndexCount();
}
void UniversalBatch::ChangeBuffer(ref_ptr<GraphicsContext> context) const
{
return m_callbacks.ChangeBuffer(context);
}
uint8_t UniversalBatch::GetVertexStride() const
{
return m_vertexStride;
}
bool UniversalBatch::IsBufferFilled(uint32_t availableVerticesCount,
uint32_t availableIndicesCount) const
{
return availableVerticesCount < m_minVerticesCount ||
availableIndicesCount < m_minIndicesCount;
}
TriangleListBatch::TriangleListBatch(BatchCallbacks & callbacks)
: TBase(callbacks, 3 /* minVerticesCount */, 3 /* minIndicesCount */)
{}
void TriangleListBatch::BatchData(ref_ptr<GraphicsContext> context,
ref_ptr<AttributeProvider> streams)
{
while (streams->IsDataExists())
{
if (IsBufferFilled(GetAvailableVertexCount(), GetAvailableIndexCount()))
ChangeBuffer(context);
uint32_t avVertex = GetAvailableVertexCount();
uint32_t avIndex = GetAvailableIndexCount();
uint32_t vertexCount = streams->GetVertexCount();
if (CanDivideStreams())
{
vertexCount = std::min(vertexCount, avVertex);
vertexCount = std::min(vertexCount, avIndex);
ASSERT(vertexCount >= 3, ());
vertexCount -= vertexCount % 3;
}
else if (!IsEnoughMemory(avVertex, vertexCount, avIndex, vertexCount))
{
ChangeBuffer(context);
avVertex = GetAvailableVertexCount();
avIndex = GetAvailableIndexCount();
ASSERT(IsEnoughMemory(avVertex, vertexCount, avIndex, vertexCount), ());
ASSERT(vertexCount % 3 == 0, ());
}
uint32_t startIndex = 0;
void * indicesStorage = GetIndexStorage(vertexCount, startIndex);
GenerateIndices<ListIndexGenerator>(indicesStorage, vertexCount, startIndex);
SubmitIndex();
FlushData(streams, vertexCount);
streams->Advance(vertexCount);
}
}
LineStripBatch::LineStripBatch(BatchCallbacks & callbacks)
: TBase(callbacks, 2 /* minVerticesCount */, 2 /* minIndicesCount */)
{}
void LineStripBatch::BatchData(ref_ptr<GraphicsContext> context,
ref_ptr<AttributeProvider> streams)
{
while (streams->IsDataExists())
{
if (IsBufferFilled(GetAvailableVertexCount(), GetAvailableIndexCount()))
ChangeBuffer(context);
uint32_t avVertex = GetAvailableVertexCount();
uint32_t avIndex = GetAvailableIndexCount();
uint32_t vertexCount = streams->GetVertexCount();
ASSERT_GREATER_OR_EQUAL(vertexCount, 2, ());
uint32_t indexCount = (vertexCount - 1) * 2;
if (!IsEnoughMemory(avVertex, vertexCount, avIndex, indexCount))
{
ChangeBuffer(context);
avVertex = GetAvailableVertexCount();
avIndex = GetAvailableIndexCount();
ASSERT(IsEnoughMemory(avVertex, vertexCount, avIndex, indexCount), ());
}
uint32_t startIndex = 0;
void * indicesStorage = GetIndexStorage(indexCount, startIndex);
GenerateIndices<LineStripIndexGenerator>(indicesStorage, indexCount, startIndex);
SubmitIndex();
FlushData(streams, vertexCount);
streams->Advance(vertexCount);
}
}
LineRawBatch::LineRawBatch(BatchCallbacks & callbacks, std::vector<int> const & indices)
: TBase(callbacks, 2 /* minVerticesCount */, 2 /* minIndicesCount */)
, m_indices(indices)
{}
void LineRawBatch::BatchData(ref_ptr<GraphicsContext> context, ref_ptr<AttributeProvider> streams)
{
while (streams->IsDataExists())
{
if (IsBufferFilled(GetAvailableVertexCount(), GetAvailableIndexCount()))
ChangeBuffer(context);
uint32_t avVertex = GetAvailableVertexCount();
uint32_t avIndex = GetAvailableIndexCount();
uint32_t vertexCount = streams->GetVertexCount();
ASSERT_GREATER_OR_EQUAL(vertexCount, 2, ());
auto const indexCount = static_cast<uint32_t>(m_indices.size());
if (!IsEnoughMemory(avVertex, vertexCount, avIndex, indexCount))
{
ChangeBuffer(context);
avVertex = GetAvailableVertexCount();
avIndex = GetAvailableIndexCount();
ASSERT(IsEnoughMemory(avVertex, vertexCount, avIndex, indexCount), ());
}
uint32_t startIndex = 0;
void * indicesStorage = GetIndexStorage(indexCount, startIndex);
LineRawIndexGenerator generator(startIndex, m_indices);
GenerateIndices(indicesStorage, indexCount, generator);
SubmitIndex();
FlushData(streams, vertexCount);
streams->Advance(vertexCount);
}
}
FanStripHelper::FanStripHelper(BatchCallbacks & callbacks)
: TBase(callbacks, 3 /* minVerticesCount */, 3 /* minIndicesCount */)
, m_isFullUploaded(false)
{}
uint32_t FanStripHelper::BatchIndexes(ref_ptr<GraphicsContext> context, uint32_t vertexCount)
{
uint32_t avVertex = GetAvailableVertexCount();
uint32_t avIndex = GetAvailableIndexCount();
uint32_t batchVertexCount = 0;
uint32_t batchIndexCount = 0;
CalcBatchPortion(vertexCount, avVertex, avIndex, batchVertexCount, batchIndexCount);
if (!IsFullUploaded() && !CanDivideStreams())
{
ChangeBuffer(context);
avVertex = GetAvailableVertexCount();
avIndex = GetAvailableIndexCount();
CalcBatchPortion(vertexCount, avVertex, avIndex, batchVertexCount, batchIndexCount);
ASSERT(IsFullUploaded(), ());
}
uint32_t startIndex = 0;
void * pIndexStorage = GetIndexStorage(batchIndexCount, startIndex);
GenerateIndexes(pIndexStorage, batchIndexCount, startIndex);
SubmitIndex();
return batchVertexCount;
}
void FanStripHelper::CalcBatchPortion(uint32_t vertexCount, uint32_t avVertex, uint32_t avIndex,
uint32_t & batchVertexCount, uint32_t & batchIndexCount)
{
uint32_t const indexCount = VtoICount(vertexCount);
batchVertexCount = vertexCount;
batchIndexCount = indexCount;
m_isFullUploaded = true;
if (vertexCount > avVertex || indexCount > avIndex)
{
uint32_t alignedAvVertex = AlignVCount(avVertex);
uint32_t alignedAvIndex = AlignICount(avIndex);
uint32_t indexCountForAvailableVertexCount = VtoICount(alignedAvVertex);
if (indexCountForAvailableVertexCount <= alignedAvIndex)
{
batchVertexCount = alignedAvVertex;
batchIndexCount = indexCountForAvailableVertexCount;
}
else
{
batchIndexCount = alignedAvIndex;
batchVertexCount = ItoVCount(batchIndexCount);
}
m_isFullUploaded = false;
}
}
bool FanStripHelper::IsFullUploaded() const
{
return m_isFullUploaded;
}
uint32_t FanStripHelper::VtoICount(uint32_t vCount) const
{
return 3 * (vCount - 2);
}
uint32_t FanStripHelper::ItoVCount(uint32_t iCount) const
{
return iCount / 3 + 2;
}
uint32_t FanStripHelper::AlignVCount(uint32_t vCount) const
{
return vCount;
}
uint32_t FanStripHelper::AlignICount(uint32_t iCount) const
{
return iCount - iCount % 3;
}
TriangleStripBatch::TriangleStripBatch(BatchCallbacks & callbacks)
: TBase(callbacks)
{}
void TriangleStripBatch::BatchData(ref_ptr<GraphicsContext> context,
ref_ptr<AttributeProvider> streams)
{
while (streams->IsDataExists())
{
if (IsBufferFilled(GetAvailableVertexCount(), GetAvailableIndexCount()))
ChangeBuffer(context);
uint32_t const batchVertexCount = BatchIndexes(context, streams->GetVertexCount());
FlushData(streams, batchVertexCount);
uint32_t const advanceCount = IsFullUploaded() ? batchVertexCount : (batchVertexCount - 2);
streams->Advance(advanceCount);
}
}
void TriangleStripBatch::GenerateIndexes(void * indexStorage, uint32_t count, uint32_t startIndex) const
{
GenerateIndices<StripIndexGenerator>(indexStorage, count, startIndex);
}
TriangleFanBatch::TriangleFanBatch(BatchCallbacks & callbacks) : TBase(callbacks) {}
/*
* What happens here
*
* We try to pack TriangleFan on GPU indexed like triangle list.
* If we have enough memory in VertexArrayBuffer to store all data from params, we just copy it
*
* If we have not enough memory we broke data on parts.
* On first iteration we create CPUBuffer for each separate atribute
* in params and copy to it first vertex of fan. This vertex will be need
* when we will upload second part of data.
*
* Than we copy vertex data on GPU as much as we can and move params cursor on
* "uploaded vertex count" - 1. This last vertex will be used for uploading next part of data
*
* On second iteration we need upload first vertex of fan that stored in cpuBuffers and than upload
* second part of data. But to avoid 2 separate call of glBufferSubData we at first do a copy of
* data from params to cpuBuffer and than copy continuous block of memory from cpuBuffer
*/
void TriangleFanBatch::BatchData(ref_ptr<GraphicsContext> context,
ref_ptr<AttributeProvider> streams)
{
std::vector<CPUBuffer> cpuBuffers;
while (streams->IsDataExists())
{
if (IsBufferFilled(GetAvailableVertexCount(), GetAvailableIndexCount()))
ChangeBuffer(context);
uint32_t vertexCount = streams->GetVertexCount();
uint32_t batchVertexCount = BatchIndexes(context, vertexCount);
if (!cpuBuffers.empty())
{
// if cpuBuffers not empty than on previous iteration we not move data on gpu
// and in cpuBuffers stored first vertex of fan.
// To avoid two separate call of glBufferSubData
// (for first vertex and for next part of data)
// we at first copy next part of data into
// cpuBuffers, and than copy it from cpuBuffers to GPU
for (size_t i = 0; i < streams->GetStreamCount(); ++i)
{
CPUBuffer & cpuBuffer = cpuBuffers[i];
ASSERT(cpuBuffer.GetCurrentElementNumber() == 1, ());
cpuBuffer.UploadData(streams->GetRawPointer(i), batchVertexCount);
// now in cpuBuffer we have correct "fan" created from second part of data
// first vertex of cpuBuffer if the first vertex of params, second vertex is
// the last vertex of previous uploaded data. We copy this data on GPU.
FlushData(streams->GetBindingInfo(i), cpuBuffer.Data(), batchVertexCount + 1);
}
uint32_t advanceCount = batchVertexCount;
if (!IsFullUploaded())
{
// not all data was moved on gpu and last vertex of fan
// will need on second iteration
advanceCount -= 1;
}
streams->Advance(advanceCount);
}
else // if m_cpuBuffer empty than it's first iteration
{
if (IsFullUploaded())
{
// We can upload all input data as one peace. For upload we need only one iteration
FlushData(streams, batchVertexCount);
streams->Advance(batchVertexCount);
}
else
{
// for each stream we must create CPU buffer.
// Copy first vertex of fan into cpuBuffer for next iterations
// Than move first part of data on GPU
cpuBuffers.reserve(streams->GetStreamCount());
for (size_t i = 0; i < streams->GetStreamCount(); ++i)
{
const BindingInfo & binding = streams->GetBindingInfo(i);
const void * rawDataPointer = streams->GetRawPointer(i);
FlushData(binding, rawDataPointer, batchVertexCount);
// "(vertexCount + 1) - batchVertexCount" we allocate CPUBuffer on all remaining data
// + first vertex of fan, that must be duplicate in the next buffer
// + last vertex of currently uploaded data.
cpuBuffers.emplace_back(binding.GetElementSize(), (vertexCount + 2) - batchVertexCount);
CPUBuffer & cpuBuffer = cpuBuffers.back();
cpuBuffer.UploadData(rawDataPointer, 1);
// Move cpu buffer cursor on second element of buffer.
// On next iteration first vertex of fan will be also available
cpuBuffer.Seek(1);
}
// advance on uploadVertexCount - 1 to copy last vertex also into next VAO with
// first vertex of data from CPUBuffers
streams->Advance(batchVertexCount - 1);
}
}
}
}
void TriangleFanBatch::GenerateIndexes(void * indexStorage, uint32_t count, uint32_t startIndex) const
{
GenerateIndices<FanIndexGenerator>(indexStorage, count, startIndex);
}
TriangleListOfStripBatch::TriangleListOfStripBatch(BatchCallbacks & callbacks)
: TBase(callbacks)
{}
void TriangleListOfStripBatch::BatchData(ref_ptr<GraphicsContext> context,
ref_ptr<AttributeProvider> streams)
{
while (streams->IsDataExists())
{
if (IsBufferFilled(GetAvailableVertexCount(), GetAvailableIndexCount()))
ChangeBuffer(context);
uint32_t const batchVertexCount = BatchIndexes(context, streams->GetVertexCount());
FlushData(streams, batchVertexCount);
streams->Advance(batchVertexCount);
}
}
bool TriangleListOfStripBatch::IsBufferFilled(uint32_t availableVerticesCount,
uint32_t availableIndicesCount) const
{
uint8_t const vertexStride = GetVertexStride();
ASSERT_GREATER_OR_EQUAL(vertexStride, 4, ());
uint32_t const indicesPerStride = TBase::VtoICount(vertexStride);
return availableVerticesCount < vertexStride || availableIndicesCount < indicesPerStride;
}
uint32_t TriangleListOfStripBatch::VtoICount(uint32_t vCount) const
{
uint8_t const vertexStride = GetVertexStride();
ASSERT_GREATER_OR_EQUAL(vertexStride, 4, ());
ASSERT_EQUAL(vCount % vertexStride, 0, ());
uint32_t const striptCount = vCount / vertexStride;
return striptCount * TBase::VtoICount(vertexStride);
}
uint32_t TriangleListOfStripBatch::ItoVCount(uint32_t iCount) const
{
uint8_t const vertexStride = GetVertexStride();
ASSERT_GREATER_OR_EQUAL(vertexStride, 4, ());
ASSERT_EQUAL(iCount % 3, 0, ());
return vertexStride * iCount / TBase::VtoICount(vertexStride);
}
uint32_t TriangleListOfStripBatch::AlignVCount(uint32_t vCount) const
{
return vCount - vCount % GetVertexStride();
}
uint32_t TriangleListOfStripBatch::AlignICount(uint32_t iCount) const
{
uint8_t const vertexStride = GetVertexStride();
ASSERT_GREATER_OR_EQUAL(vertexStride, 4, ());
uint32_t const indicesPerStride = TBase::VtoICount(vertexStride);
return iCount - iCount % indicesPerStride;
}
void TriangleListOfStripBatch::GenerateIndexes(void * indexStorage, uint32_t count, uint32_t startIndex) const
{
uint8_t const vertexStride = GetVertexStride();
GenerateIndices(indexStorage, count, ListOfStripGenerator(startIndex, vertexStride, VtoICount(vertexStride)));
}
} // namespace dp
|
#define Uses_TKeys
#define Uses_TEvent
#define Uses_TScreen
#define Uses_THardwareInfo
#include <tvision/tv.h>
#include <internal/platform.h>
#include <internal/win32con.h>
#include <internal/ncurdisp.h>
#include <internal/ncursinp.h>
#include <internal/ansidisp.h>
#include <internal/linuxcon.h>
#include <internal/sighandl.h>
#include <internal/terminal.h>
#include <internal/getenv.h>
#include <iostream.h>
#include <chrono>
using std::chrono::duration_cast;
using std::chrono::milliseconds;
using std::chrono::steady_clock;
TEvent THardwareInfo::eventQ[];
size_t THardwareInfo::eventCount = 0;
static bool alwaysFlush;
THardwareInfo::THardwareInfo() noexcept
{
pendingEvent = 0;
alwaysFlush = getEnv<int>("TVISION_MAX_FPS", 0) < 0;
#ifdef _TV_UNIX
static TSignalHandler h;
#endif
}
// For brevity.
static constexpr PlatformStrategy* &platf = PlatformStrategy::instance;
static constexpr NullPlatform* nullPlatf = &NullPlatform::instance;
void THardwareInfo::setCaretSize( ushort size ) noexcept { platf->setCaretSize(size); }
void THardwareInfo::setCaretPosition( ushort x, ushort y ) noexcept { platf->setCaretPosition(x, y); }
ushort THardwareInfo::getCaretSize() noexcept { return platf->getCaretSize(); }
BOOL THardwareInfo::isCaretVisible() noexcept { return platf->isCaretVisible(); }
ushort THardwareInfo::getScreenRows() noexcept { return platf->getScreenRows(); }
ushort THardwareInfo::getScreenCols() noexcept { return platf->getScreenCols(); }
ushort THardwareInfo::getScreenMode() noexcept { return platf->getScreenMode(); }
void THardwareInfo::setScreenMode( ushort mode ) noexcept {}
void THardwareInfo::clearScreen( ushort w, ushort h ) noexcept { platf->clearScreen(); }
void THardwareInfo::screenWrite( ushort x, ushort y, TScreenCell *buf, DWORD len ) noexcept
{
platf->screenWrite(x, y, buf, len);
if (alwaysFlush)
flushScreen();
}
void THardwareInfo::reloadScreenInfo() noexcept { platf->reloadScreenInfo(); }
DWORD THardwareInfo::getButtonCount() noexcept { return platf->getButtonCount(); }
void THardwareInfo::cursorOn() noexcept { platf->cursorOn(); }
void THardwareInfo::cursorOff() noexcept { platf->cursorOff(); }
void THardwareInfo::flushScreen() noexcept { platf->flushScreen(); }
void THardwareInfo::setUpConsole() noexcept
{
// Set up input/output control.
// At least with the ncurses implementation, display must be initialized
// before input.
if (platf == nullPlatf)
{
#ifdef _WIN32
if (!(platf = Win32ConsoleStrategy::create()))
{
cerr << "Error: cannot get a console." << endl;
ExitProcess(1);
}
#else
DisplayStrategy *disp;
if (getEnv<TStringView>("TVISION_DISPLAY") == "ncurses")
disp = new NcursesDisplay();
else
disp = new AnsiDisplay<NcursesDisplay>();
if (TermIO::isLinuxConsole())
platf = new LinuxConsoleStrategy( disp,
new NcursesInput(false) );
else
platf = new UnixPlatformStrategy( disp,
new NcursesInput() );
#endif
}
}
void THardwareInfo::restoreConsole() noexcept
{
// Tear down input/output control by deleting the platform strategy.
if (platf != nullPlatf)
{
delete platf;
platf = nullPlatf;
}
}
BOOL THardwareInfo::getPendingEvent(TEvent &event, ushort mask) noexcept
{
for (size_t i = 0; i < eventCount; ++i)
if (eventQ[i].what & mask)
{
event = eventQ[i];
for (; i + 1 < eventCount; ++i)
eventQ[i] = eventQ[i + 1];
--eventCount;
return True;
}
return False;
}
BOOL THardwareInfo::getMouseEvent( MouseEventType& event ) noexcept
{
TEvent ev;
if (getPendingEvent(ev, evMouse))
{
event = ev.mouse;
return True;
}
return False;
}
BOOL THardwareInfo::getKeyEvent( TEvent& event, Boolean blocking ) noexcept
{
readEvents(blocking);
if (getPendingEvent(event, ~evMouse))
{
if (event.what & evKeyboard)
{
// Set/Reset insert flag.
if( event.keyDown.keyCode == kbIns )
insertState = !insertState;
if( insertState )
event.keyDown.controlKeyState |= kbInsState;
return True;
}
return event.what != evNothing;
}
return False;
}
void THardwareInfo::readEvents(Boolean blocking) noexcept
{
// Do not read any more events until the queue is empty.
if (!eventCount)
{
// Flush the screen once for every time all events have been processed,
// only for blocking requests.
if (blocking)
THardwareInfo::flushScreen();
TEvent event;
// Non-blocking read.
while ( eventCount < eventQSize &&
platf->waitForEvent(0, event) )
eventQ[eventCount++] = event;
// Blocking read.
if (blocking && !eventCount && platf->waitForEvent(eventTimeoutMs, event))
eventQ[eventCount++] = event;
}
}
#ifndef _WIN32
extern "C" DWORD GetTickCount(void) noexcept
{
// This effectively gives a system time reference in milliseconds.
// steady_clock is best suited for measuring intervals.
return duration_cast<milliseconds>(steady_clock::now().time_since_epoch()).count();
}
#endif
|
//
// basic_overlapped_handle.cpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// 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)
//
// Disable autolinking for unit tests.
#if !defined(BOOST_ALL_NO_LIB)
#define BOOST_ALL_NO_LIB 1
#endif // !defined(BOOST_ALL_NO_LIB)
// Test that header file is self-contained.
#include "asio/windows/basic_overlapped_handle.hpp"
#include "../unit_test.hpp"
ASIO_TEST_SUITE
(
"basic_overlapped_handle",
ASIO_TEST_CASE(null_test)
)
|
#include <bits/stdc++.h>
using namespace std;
string pangrams(string s) {
transform(s.begin(),s.end(),s.begin(), ::tolower);
int freq [26] = {0};
for(int i=0; i<s.size(); i++)
freq[ s[i] - 'a' ]++;
for(int i=0; i<26; i++) { cout << freq[i] << " ";
if(freq[i] == 0) return "not pangram"; }
return "pangram";
}
int main()
{
ofstream fout(getenv("OUTPUT_PATH"));
string s;
getline(cin, s);
string result = pangrams(s);
fout << result << "\n";
fout.close();
return 0;
}
|
// Copyright (c) 2011-2014 The Bitcoin Core developers
// Copyright (c) 2019 The PIVX developers
// Copyright (c) 2021 The REBEL Coin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
//
// Unit tests for denial-of-service detection/prevention code
//
#include "test/test_rebelcoin.h"
#include "keystore.h"
#include "net_processing.h"
#include "net.h"
#include "pow.h"
#include "script/sign.h"
#include "serialize.h"
#include "util.h"
#include "validation.h"
#include <stdint.h>
#include <boost/test/unit_test.hpp>
// Tests this internal-to-validation.cpp method:
extern bool AddOrphanTx(const CTransactionRef& tx, NodeId peer);
extern void EraseOrphansFor(NodeId peer);
extern unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans);
struct COrphanTx {
CTransactionRef tx;
NodeId fromPeer;
};
extern std::map<uint256, COrphanTx> mapOrphanTransactions;
extern std::map<uint256, std::set<uint256> > mapOrphanTransactionsByPrev;
CService ip(uint32_t i)
{
struct in_addr s;
s.s_addr = i;
return CService(CNetAddr(s), Params().GetDefaultPort());
}
static NodeId id = 0;
BOOST_FIXTURE_TEST_SUITE(DoS_tests, TestingSetup)
void misbehave(NodeId id, int value) {
LOCK(cs_main);
Misbehaving(id, value); // Should get banned
}
BOOST_AUTO_TEST_CASE(DoS_banning)
{
std::atomic<bool> interruptDummy(false);
connman->ClearBanned();
CAddress addr1(ip(0xa0b0c001), NODE_NONE);
CNode dummyNode1(id++, NODE_NETWORK, 0, INVALID_SOCKET, addr1, 0, 0, "", true);
dummyNode1.SetSendVersion(PROTOCOL_VERSION);
GetNodeSignals().InitializeNode(&dummyNode1, *connman);
dummyNode1.nVersion = 1;
dummyNode1.fSuccessfullyConnected = true;
misbehave(dummyNode1.GetId(), 100); // Should get banned
SendMessages(&dummyNode1, *connman, interruptDummy);
BOOST_CHECK(connman->IsBanned(addr1));
BOOST_CHECK(!connman->IsBanned(ip(0xa0b0c001|0x0000ff00))); // Different IP, not banned
CAddress addr2(ip(0xa0b0c002), NODE_NONE);
CNode dummyNode2(id++, NODE_NETWORK, 0, INVALID_SOCKET, addr2, 1, 1, "", true);
dummyNode2.SetSendVersion(PROTOCOL_VERSION);
GetNodeSignals().InitializeNode(&dummyNode2, *connman);
dummyNode2.nVersion = 1;
dummyNode2.fSuccessfullyConnected = true;
misbehave(dummyNode2.GetId(), 50);
SendMessages(&dummyNode2, *connman, interruptDummy);
BOOST_CHECK(!connman->IsBanned(addr2)); // 2 not banned yet...
BOOST_CHECK(connman->IsBanned(addr1)); // ... but 1 still should be
misbehave(dummyNode2.GetId(), 50);
SendMessages(&dummyNode2, *connman, interruptDummy);
BOOST_CHECK(connman->IsBanned(addr2));
}
BOOST_AUTO_TEST_CASE(DoS_banscore)
{
std::atomic<bool> interruptDummy(false);
connman->ClearBanned();
gArgs.ForceSetArg("-banscore", "111"); // because 11 is my favorite number
CAddress addr1(ip(0xa0b0c001), NODE_NONE);
CNode dummyNode1(id++, NODE_NETWORK, 0, INVALID_SOCKET, addr1, 3, 1, "", true);
dummyNode1.SetSendVersion(PROTOCOL_VERSION);
GetNodeSignals().InitializeNode(&dummyNode1, *connman);
dummyNode1.nVersion = 1;
dummyNode1.fSuccessfullyConnected = true;
misbehave(dummyNode1.GetId(), 100);
SendMessages(&dummyNode1, *connman, interruptDummy);
BOOST_CHECK(!connman->IsBanned(addr1));
misbehave(dummyNode1.GetId(), 10);
SendMessages(&dummyNode1, *connman, interruptDummy);
BOOST_CHECK(!connman->IsBanned(addr1));
misbehave(dummyNode1.GetId(), 1);
SendMessages(&dummyNode1, *connman, interruptDummy);
BOOST_CHECK(connman->IsBanned(addr1));
gArgs.ForceSetArg("-banscore", std::to_string(DEFAULT_BANSCORE_THRESHOLD));
}
BOOST_AUTO_TEST_CASE(DoS_bantime)
{
std::atomic<bool> interruptDummy(false);
connman->ClearBanned();
int64_t nStartTime = GetTime();
SetMockTime(nStartTime); // Overrides future calls to GetTime()
CAddress addr(ip(0xa0b0c001), NODE_NONE);
CNode dummyNode(id++, NODE_NETWORK, 0, INVALID_SOCKET, addr, 4, 4, "", true);
dummyNode.SetSendVersion(PROTOCOL_VERSION);
GetNodeSignals().InitializeNode(&dummyNode, *connman);
dummyNode.nVersion = 1;
dummyNode.fSuccessfullyConnected = true;
misbehave(dummyNode.GetId(), 100);
SendMessages(&dummyNode, *connman, interruptDummy);
BOOST_CHECK(connman->IsBanned(addr));
SetMockTime(nStartTime+60*60);
BOOST_CHECK(connman->IsBanned(addr));
SetMockTime(nStartTime+60*60*24+1);
BOOST_CHECK(!connman->IsBanned(addr));
}
CTransactionRef RandomOrphan()
{
std::map<uint256, COrphanTx>::iterator it;
it = mapOrphanTransactions.lower_bound(InsecureRand256());
if (it == mapOrphanTransactions.end())
it = mapOrphanTransactions.begin();
return it->second.tx;
}
BOOST_AUTO_TEST_CASE(DoS_mapOrphans)
{
CKey key;
key.MakeNewKey(true);
CBasicKeyStore keystore;
keystore.AddKey(key);
// 50 orphan transactions:
for (int i = 0; i < 50; i++)
{
CMutableTransaction tx;
tx.vin.resize(1);
tx.vin[0].prevout.n = 0;
tx.vin[0].prevout.hash = InsecureRand256();
tx.vin[0].scriptSig << OP_1;
tx.vout.resize(1);
tx.vout[0].nValue = 1*CENT;
tx.vout[0].scriptPubKey = GetScriptForDestination(key.GetPubKey().GetID());
AddOrphanTx(MakeTransactionRef(tx), i);
}
// ... and 50 that depend on other orphans:
for (int i = 0; i < 50; i++)
{
CTransactionRef txPrev = RandomOrphan();
CMutableTransaction tx;
tx.vin.resize(1);
tx.vin[0].prevout.n = 0;
tx.vin[0].prevout.hash = txPrev->GetHash();
tx.vout.resize(1);
tx.vout[0].nValue = 1*CENT;
tx.vout[0].scriptPubKey = GetScriptForDestination(key.GetPubKey().GetID());
SignSignature(keystore, *txPrev, tx, 0, SIGHASH_ALL);
AddOrphanTx(MakeTransactionRef(tx), i);
}
// This really-big orphan should be ignored:
for (int i = 0; i < 10; i++)
{
CTransactionRef txPrev = RandomOrphan();
CMutableTransaction tx;
tx.vout.resize(1);
tx.vout[0].nValue = 1*CENT;
tx.vout[0].scriptPubKey = GetScriptForDestination(key.GetPubKey().GetID());
tx.vin.resize(500);
for (unsigned int j = 0; j < tx.vin.size(); j++)
{
tx.vin[j].prevout.n = j;
tx.vin[j].prevout.hash = txPrev->GetHash();
}
SignSignature(keystore, *txPrev, tx, 0, SIGHASH_ALL);
// Re-use same signature for other inputs
// (they don't have to be valid for this test)
for (unsigned int j = 1; j < tx.vin.size(); j++)
tx.vin[j].scriptSig = tx.vin[0].scriptSig;
BOOST_CHECK(!AddOrphanTx(MakeTransactionRef(tx), i));
}
// Test EraseOrphansFor:
for (NodeId i = 0; i < 3; i++)
{
size_t sizeBefore = mapOrphanTransactions.size();
EraseOrphansFor(i);
BOOST_CHECK(mapOrphanTransactions.size() < sizeBefore);
}
// Test LimitOrphanTxSize() function:
LimitOrphanTxSize(40);
BOOST_CHECK(mapOrphanTransactions.size() <= 40);
LimitOrphanTxSize(10);
BOOST_CHECK(mapOrphanTransactions.size() <= 10);
LimitOrphanTxSize(0);
BOOST_CHECK(mapOrphanTransactions.empty());
BOOST_CHECK(mapOrphanTransactionsByPrev.empty());
}
BOOST_AUTO_TEST_SUITE_END()
|
// Copyright (c) 2020 Huawei Technologies Co., Ltd
// Copyright (c) 2019, Facebook CORPORATION.
// All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://opensource.org/licenses/BSD-3-Clause
//
// 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 "ATen/native/npu/utils/OpAdapter.h"
namespace at {
namespace native {
using namespace at::native::npu;
Tensor mish_backward_npu(const Tensor& grad, const Tensor& input) {
Tensor result = OpPreparation::ApplyTensor(input);
OpCommand cmd;
cmd.Name("MishGrad")
.Input(grad)
.Input(input)
.Output(result)
.Run();
return result;
}
} // namespace native
} // namespace at
|
// This file is made available under Elastic License 2.0.
// This file is based on code available under the Apache license here:
// https://github.com/apache/incubator-doris/blob/master/be/src/util/bfd_parser.cpp
// 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 "util/bfd_parser.h"
#include <memory>
#include "common/logging.h"
namespace starrocks {
struct BfdFindCtx {
BfdFindCtx(bfd_symbol** syms_, bfd_vma pc_)
: found(false), syms(syms_), pc(pc_), file_name(nullptr), func_name(nullptr), lineno(0) {}
bool found;
bfd_symbol** syms;
bfd_vma pc;
const char* file_name;
const char* func_name;
unsigned int lineno;
};
std::mutex BfdParser::_bfd_mutex;
bool BfdParser::_is_bfd_inited = false;
static void find_addr_in_section(bfd* abfd, asection* sec, void* arg) {
BfdFindCtx* ctx = (BfdFindCtx*)arg;
if (ctx->found) {
return;
}
#ifdef bfd_get_section_flags
if ((bfd_get_section_flags(abfd, sec) & SEC_ALLOC) == 0) {
return;
}
#else
if ((bfd_section_flags(sec) & SEC_ALLOC) == 0) {
return;
}
#endif
#ifdef bfd_get_section_vma
auto vma = bfd_get_section_vma(abfd, sec);
#else
auto vma = bfd_section_vma(sec);
#endif
if (ctx->pc < vma) {
return;
}
#ifdef bfd_get_section_size
auto size = bfd_get_section_size(sec);
#else
auto size = bfd_section_size(sec);
#endif
if (ctx->pc >= vma + size) {
return;
}
ctx->found =
bfd_find_nearest_line(abfd, sec, ctx->syms, ctx->pc - vma, &ctx->file_name, &ctx->func_name, &ctx->lineno);
}
static void section_print(bfd* bfd, asection* sec, void* arg) {
std::string* str = (std::string*)arg;
str->append(sec->name);
str->push_back('\n');
}
void BfdParser::init_bfd() {
if (_is_bfd_inited) {
return;
}
std::lock_guard<std::mutex> lock(_bfd_mutex);
bfd_init();
if (!bfd_set_default_target("elf64-x86-64")) {
LOG(ERROR) << "set default target to elf64-x86-64 failed.";
}
_is_bfd_inited = true;
}
BfdParser* BfdParser::create() {
FILE* file = fopen("/proc/self/cmdline", "r");
if (file == nullptr) {
return nullptr;
}
char prog_name[1024];
fscanf(file, "%s ", prog_name);
fclose(file);
std::unique_ptr<BfdParser> parser(new BfdParser(prog_name));
if (parser->parse()) {
return nullptr;
}
return parser.release();
}
BfdParser* BfdParser::create(const std::string& prog_name) {
std::unique_ptr<BfdParser> parser(new BfdParser(prog_name));
if (parser->parse()) {
return nullptr;
}
return parser.release();
}
void BfdParser::list_targets(std::vector<std::string>* out) {
if (!_is_bfd_inited) {
init_bfd();
}
const char** targets = bfd_target_list();
const char** p = targets;
while ((*p) != nullptr) {
out->emplace_back(*p++);
}
free(targets);
}
BfdParser::BfdParser(const std::string& file_name)
: _file_name(file_name), _abfd(nullptr), _syms(nullptr), _num_symbols(0), _symbol_size(0) {
if (!_is_bfd_inited) {
init_bfd();
}
}
BfdParser::~BfdParser() {
if (_syms != nullptr) {
free(_syms);
}
if (_abfd != nullptr) {
bfd_close(_abfd);
}
}
void BfdParser::list_sections(std::string* ss) {
std::lock_guard<std::mutex> lock(_mutex);
bfd_map_over_sections(_abfd, section_print, (void*)ss);
}
static void list_matching_formats(char** p, std::string* message) {
if (!p || !*p) {
return;
}
message->append(": Matching formats: ");
while (*p) {
message->append(*p++);
}
message->push_back('\n');
}
int BfdParser::open_bfd() {
_abfd = bfd_openr(_file_name.c_str(), nullptr);
if (_abfd == nullptr) {
LOG(WARNING) << "bfd_openr failed because errmsg=" << bfd_errmsg(bfd_get_error());
return -1;
}
if (bfd_check_format(_abfd, bfd_archive)) {
LOG(WARNING) << "bfd_check_format for archive fialed because errmsg=" << bfd_errmsg(bfd_get_error());
return -1;
}
char** matches = nullptr;
if (!bfd_check_format_matches(_abfd, bfd_object, &matches)) {
if (bfd_get_error() == bfd_error_file_ambiguously_recognized) {
std::string message = _file_name;
list_matching_formats(matches, &message);
free(matches);
LOG(WARNING) << "bfd_check_format_matches failed because errmsg=" << bfd_errmsg(bfd_get_error()) << " and "
<< message;
} else {
LOG(WARNING) << "bfd_check_format_matches failed because errmsg=" << bfd_errmsg(bfd_get_error());
}
return -1;
}
return 0;
}
int BfdParser::load_symbols() {
if ((bfd_get_file_flags(_abfd) & HAS_SYMS) == 0) {
// No need to load symbols;
return 0;
}
_num_symbols = bfd_read_minisymbols(_abfd, FALSE, (void**)&_syms, &_symbol_size);
if (_num_symbols == 0) {
_num_symbols = bfd_read_minisymbols(_abfd, TRUE /* dynamic */, (void**)&_syms, &_symbol_size);
}
if (_num_symbols == 0) {
LOG(WARNING) << "Load symbols failed because errmsg=" << bfd_errmsg(bfd_get_error());
return -1;
}
return 0;
}
int BfdParser::parse() {
int ret = open_bfd();
if (ret != 0) {
LOG(WARNING) << "open bfd failed.";
return ret;
}
ret = load_symbols();
if (ret != 0) {
LOG(WARNING) << "Load symbols failed.";
return ret;
}
return 0;
}
int BfdParser::decode_address(const char* str, const char** end, std::string* file_name, std::string* func_name,
unsigned int* lineno) {
bfd_vma pc = bfd_scan_vma(str, end, 16);
BfdFindCtx ctx(_syms, pc);
std::lock_guard<std::mutex> lock(_mutex);
bfd_map_over_sections(_abfd, find_addr_in_section, (void*)&ctx);
if (!ctx.found) {
file_name->append("??");
func_name->append("??");
return -1;
}
// demange function
if (ctx.func_name != nullptr) {
#define DMGL_PARAMS (1 << 0)
#define DMGL_ANSI (1 << 1)
char* demangled_name = bfd_demangle(_abfd, ctx.func_name, DMGL_ANSI | DMGL_PARAMS);
if (demangled_name != nullptr) {
func_name->append(demangled_name);
free(demangled_name);
} else {
func_name->append(ctx.func_name);
}
} else {
func_name->append("??");
}
// file_name
if (ctx.file_name != nullptr) {
file_name->append(ctx.file_name);
} else {
file_name->append("??");
}
*lineno = ctx.lineno;
return 0;
#if 0
bool inline_found = true;
while (inline_found) {
printf("%s\t%s:%u\n", ctx.func_name, ctx.file_name, ctx.lineno);
inline_found = bfd_find_inliner_info(_abfd, &ctx.file_name, &ctx.func_name, &ctx.lineno);
printf("inline found = %d\n", inline_found);
if (inline_found) {
printf("inline file_name=%s func_name=%s\n", ctx.file_name, ctx.func_name);
}
}
#endif
}
} // namespace starrocks
|
//===-------------- PPCMIPeephole.cpp - MI Peephole Cleanups -------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===---------------------------------------------------------------------===//
//
// This pass performs peephole optimizations to clean up ugly code
// sequences at the MachineInstruction layer. It runs at the end of
// the SSA phases, following VSX swap removal. A pass of dead code
// elimination follows this one for quick clean-up of any dead
// instructions introduced here. Although we could do this as callbacks
// from the generic peephole pass, this would have a couple of bad
// effects: it might remove optimization opportunities for VSX swap
// removal, and it would miss cleanups made possible following VSX
// swap removal.
//
//===---------------------------------------------------------------------===//
#include "PPC.h"
#include "PPCInstrBuilder.h"
#include "PPCInstrInfo.h"
#include "PPCTargetMachine.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/Support/Debug.h"
using namespace llvm;
#define DEBUG_TYPE "ppc-mi-peepholes"
namespace llvm {
void initializePPCMIPeepholePass(PassRegistry&);
}
namespace {
struct PPCMIPeephole : public MachineFunctionPass {
static char ID;
const PPCInstrInfo *TII;
MachineFunction *MF;
MachineRegisterInfo *MRI;
PPCMIPeephole() : MachineFunctionPass(ID) {
initializePPCMIPeepholePass(*PassRegistry::getPassRegistry());
}
private:
// Initialize class variables.
void initialize(MachineFunction &MFParm);
// Perform peepholes.
bool simplifyCode(void);
// Find the "true" register represented by SrcReg (following chains
// of copies and subreg_to_reg operations).
unsigned lookThruCopyLike(unsigned SrcReg);
public:
// Main entry point for this pass.
bool runOnMachineFunction(MachineFunction &MF) override {
if (skipFunction(*MF.getFunction()))
return false;
initialize(MF);
return simplifyCode();
}
};
// Initialize class variables.
void PPCMIPeephole::initialize(MachineFunction &MFParm) {
MF = &MFParm;
MRI = &MF->getRegInfo();
TII = MF->getSubtarget<PPCSubtarget>().getInstrInfo();
DEBUG(dbgs() << "*** PowerPC MI peephole pass ***\n\n");
DEBUG(MF->dump());
}
// Perform peephole optimizations.
bool PPCMIPeephole::simplifyCode(void) {
bool Simplified = false;
MachineInstr* ToErase = nullptr;
for (MachineBasicBlock &MBB : *MF) {
for (MachineInstr &MI : MBB) {
// If the previous instruction was marked for elimination,
// remove it now.
if (ToErase) {
ToErase->eraseFromParent();
ToErase = nullptr;
}
// Ignore debug instructions.
if (MI.isDebugValue())
continue;
// Per-opcode peepholes.
switch (MI.getOpcode()) {
default:
break;
case PPC::XXPERMDI: {
// Perform simplifications of 2x64 vector swaps and splats.
// A swap is identified by an immediate value of 2, and a splat
// is identified by an immediate value of 0 or 3.
int Immed = MI.getOperand(3).getImm();
if (Immed != 1) {
// For each of these simplifications, we need the two source
// regs to match. Unfortunately, MachineCSE ignores COPY and
// SUBREG_TO_REG, so for example we can see
// XXPERMDI t, SUBREG_TO_REG(s), SUBREG_TO_REG(s), immed.
// We have to look through chains of COPY and SUBREG_TO_REG
// to find the real source values for comparison.
unsigned TrueReg1 = lookThruCopyLike(MI.getOperand(1).getReg());
unsigned TrueReg2 = lookThruCopyLike(MI.getOperand(2).getReg());
if (TrueReg1 == TrueReg2
&& TargetRegisterInfo::isVirtualRegister(TrueReg1)) {
MachineInstr *DefMI = MRI->getVRegDef(TrueReg1);
unsigned DefOpc = DefMI ? DefMI->getOpcode() : 0;
// If this is a splat fed by a splatting load, the splat is
// redundant. Replace with a copy. This doesn't happen directly due
// to code in PPCDAGToDAGISel.cpp, but it can happen when converting
// a load of a double to a vector of 64-bit integers.
auto isConversionOfLoadAndSplat = [=]() -> bool {
if (DefOpc != PPC::XVCVDPSXDS && DefOpc != PPC::XVCVDPUXDS)
return false;
unsigned DefReg = lookThruCopyLike(DefMI->getOperand(1).getReg());
if (TargetRegisterInfo::isVirtualRegister(DefReg)) {
MachineInstr *LoadMI = MRI->getVRegDef(DefReg);
if (LoadMI && LoadMI->getOpcode() == PPC::LXVDSX)
return true;
}
return false;
};
if (DefMI && (Immed == 0 || Immed == 3)) {
if (DefOpc == PPC::LXVDSX || isConversionOfLoadAndSplat()) {
DEBUG(dbgs()
<< "Optimizing load-and-splat/splat "
"to load-and-splat/copy: ");
DEBUG(MI.dump());
BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::COPY),
MI.getOperand(0).getReg())
.add(MI.getOperand(1));
ToErase = &MI;
Simplified = true;
}
}
// If this is a splat or a swap fed by another splat, we
// can replace it with a copy.
if (DefOpc == PPC::XXPERMDI) {
unsigned FeedImmed = DefMI->getOperand(3).getImm();
unsigned FeedReg1
= lookThruCopyLike(DefMI->getOperand(1).getReg());
unsigned FeedReg2
= lookThruCopyLike(DefMI->getOperand(2).getReg());
if ((FeedImmed == 0 || FeedImmed == 3) && FeedReg1 == FeedReg2) {
DEBUG(dbgs()
<< "Optimizing splat/swap or splat/splat "
"to splat/copy: ");
DEBUG(MI.dump());
BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::COPY),
MI.getOperand(0).getReg())
.add(MI.getOperand(1));
ToErase = &MI;
Simplified = true;
}
// If this is a splat fed by a swap, we can simplify modify
// the splat to splat the other value from the swap's input
// parameter.
else if ((Immed == 0 || Immed == 3)
&& FeedImmed == 2 && FeedReg1 == FeedReg2) {
DEBUG(dbgs() << "Optimizing swap/splat => splat: ");
DEBUG(MI.dump());
MI.getOperand(1).setReg(DefMI->getOperand(1).getReg());
MI.getOperand(2).setReg(DefMI->getOperand(2).getReg());
MI.getOperand(3).setImm(3 - Immed);
Simplified = true;
}
// If this is a swap fed by a swap, we can replace it
// with a copy from the first swap's input.
else if (Immed == 2 && FeedImmed == 2 && FeedReg1 == FeedReg2) {
DEBUG(dbgs() << "Optimizing swap/swap => copy: ");
DEBUG(MI.dump());
BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::COPY),
MI.getOperand(0).getReg())
.add(DefMI->getOperand(1));
ToErase = &MI;
Simplified = true;
}
} else if ((Immed == 0 || Immed == 3) && DefOpc == PPC::XXPERMDIs &&
(DefMI->getOperand(2).getImm() == 0 ||
DefMI->getOperand(2).getImm() == 3)) {
// Splat fed by another splat - switch the output of the first
// and remove the second.
DefMI->getOperand(0).setReg(MI.getOperand(0).getReg());
ToErase = &MI;
Simplified = true;
DEBUG(dbgs() << "Removing redundant splat: ");
DEBUG(MI.dump());
}
}
}
break;
}
case PPC::VSPLTB:
case PPC::VSPLTH:
case PPC::XXSPLTW: {
unsigned MyOpcode = MI.getOpcode();
unsigned OpNo = MyOpcode == PPC::XXSPLTW ? 1 : 2;
unsigned TrueReg = lookThruCopyLike(MI.getOperand(OpNo).getReg());
if (!TargetRegisterInfo::isVirtualRegister(TrueReg))
break;
MachineInstr *DefMI = MRI->getVRegDef(TrueReg);
if (!DefMI)
break;
unsigned DefOpcode = DefMI->getOpcode();
auto isConvertOfSplat = [=]() -> bool {
if (DefOpcode != PPC::XVCVSPSXWS && DefOpcode != PPC::XVCVSPUXWS)
return false;
unsigned ConvReg = DefMI->getOperand(1).getReg();
if (!TargetRegisterInfo::isVirtualRegister(ConvReg))
return false;
MachineInstr *Splt = MRI->getVRegDef(ConvReg);
return Splt && (Splt->getOpcode() == PPC::LXVWSX ||
Splt->getOpcode() == PPC::XXSPLTW);
};
bool AlreadySplat = (MyOpcode == DefOpcode) ||
(MyOpcode == PPC::VSPLTB && DefOpcode == PPC::VSPLTBs) ||
(MyOpcode == PPC::VSPLTH && DefOpcode == PPC::VSPLTHs) ||
(MyOpcode == PPC::XXSPLTW && DefOpcode == PPC::XXSPLTWs) ||
(MyOpcode == PPC::XXSPLTW && DefOpcode == PPC::LXVWSX) ||
(MyOpcode == PPC::XXSPLTW && DefOpcode == PPC::MTVSRWS)||
(MyOpcode == PPC::XXSPLTW && isConvertOfSplat());
// If the instruction[s] that feed this splat have already splat
// the value, this splat is redundant.
if (AlreadySplat) {
DEBUG(dbgs() << "Changing redundant splat to a copy: ");
DEBUG(MI.dump());
BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::COPY),
MI.getOperand(0).getReg())
.add(MI.getOperand(OpNo));
ToErase = &MI;
Simplified = true;
}
// Splat fed by a shift. Usually when we align value to splat into
// vector element zero.
if (DefOpcode == PPC::XXSLDWI) {
unsigned ShiftRes = DefMI->getOperand(0).getReg();
unsigned ShiftOp1 = DefMI->getOperand(1).getReg();
unsigned ShiftOp2 = DefMI->getOperand(2).getReg();
unsigned ShiftImm = DefMI->getOperand(3).getImm();
unsigned SplatImm = MI.getOperand(2).getImm();
if (ShiftOp1 == ShiftOp2) {
unsigned NewElem = (SplatImm + ShiftImm) & 0x3;
if (MRI->hasOneNonDBGUse(ShiftRes)) {
DEBUG(dbgs() << "Removing redundant shift: ");
DEBUG(DefMI->dump());
ToErase = DefMI;
}
Simplified = true;
DEBUG(dbgs() << "Changing splat immediate from " << SplatImm <<
" to " << NewElem << " in instruction: ");
DEBUG(MI.dump());
MI.getOperand(1).setReg(ShiftOp1);
MI.getOperand(2).setImm(NewElem);
}
}
break;
}
case PPC::XVCVDPSP: {
// If this is a DP->SP conversion fed by an FRSP, the FRSP is redundant.
unsigned TrueReg = lookThruCopyLike(MI.getOperand(1).getReg());
if (!TargetRegisterInfo::isVirtualRegister(TrueReg))
break;
MachineInstr *DefMI = MRI->getVRegDef(TrueReg);
// This can occur when building a vector of single precision or integer
// values.
if (DefMI && DefMI->getOpcode() == PPC::XXPERMDI) {
unsigned DefsReg1 = lookThruCopyLike(DefMI->getOperand(1).getReg());
unsigned DefsReg2 = lookThruCopyLike(DefMI->getOperand(2).getReg());
if (!TargetRegisterInfo::isVirtualRegister(DefsReg1) ||
!TargetRegisterInfo::isVirtualRegister(DefsReg2))
break;
MachineInstr *P1 = MRI->getVRegDef(DefsReg1);
MachineInstr *P2 = MRI->getVRegDef(DefsReg2);
if (!P1 || !P2)
break;
// Remove the passed FRSP instruction if it only feeds this MI and
// set any uses of that FRSP (in this MI) to the source of the FRSP.
auto removeFRSPIfPossible = [&](MachineInstr *RoundInstr) {
if (RoundInstr->getOpcode() == PPC::FRSP &&
MRI->hasOneNonDBGUse(RoundInstr->getOperand(0).getReg())) {
Simplified = true;
unsigned ConvReg1 = RoundInstr->getOperand(1).getReg();
unsigned FRSPDefines = RoundInstr->getOperand(0).getReg();
MachineInstr &Use = *(MRI->use_instr_begin(FRSPDefines));
for (int i = 0, e = Use.getNumOperands(); i < e; ++i)
if (Use.getOperand(i).isReg() &&
Use.getOperand(i).getReg() == FRSPDefines)
Use.getOperand(i).setReg(ConvReg1);
DEBUG(dbgs() << "Removing redundant FRSP:\n");
DEBUG(RoundInstr->dump());
DEBUG(dbgs() << "As it feeds instruction:\n");
DEBUG(MI.dump());
DEBUG(dbgs() << "Through instruction:\n");
DEBUG(DefMI->dump());
RoundInstr->eraseFromParent();
}
};
// If the input to XVCVDPSP is a vector that was built (even
// partially) out of FRSP's, the FRSP(s) can safely be removed
// since this instruction performs the same operation.
if (P1 != P2) {
removeFRSPIfPossible(P1);
removeFRSPIfPossible(P2);
break;
}
removeFRSPIfPossible(P1);
}
break;
}
}
}
// If the last instruction was marked for elimination,
// remove it now.
if (ToErase) {
ToErase->eraseFromParent();
ToErase = nullptr;
}
}
return Simplified;
}
// This is used to find the "true" source register for an
// XXPERMDI instruction, since MachineCSE does not handle the
// "copy-like" operations (Copy and SubregToReg). Returns
// the original SrcReg unless it is the target of a copy-like
// operation, in which case we chain backwards through all
// such operations to the ultimate source register. If a
// physical register is encountered, we stop the search.
unsigned PPCMIPeephole::lookThruCopyLike(unsigned SrcReg) {
while (true) {
MachineInstr *MI = MRI->getVRegDef(SrcReg);
if (!MI->isCopyLike())
return SrcReg;
unsigned CopySrcReg;
if (MI->isCopy())
CopySrcReg = MI->getOperand(1).getReg();
else {
assert(MI->isSubregToReg() && "bad opcode for lookThruCopyLike");
CopySrcReg = MI->getOperand(2).getReg();
}
if (!TargetRegisterInfo::isVirtualRegister(CopySrcReg))
return CopySrcReg;
SrcReg = CopySrcReg;
}
}
} // end default namespace
INITIALIZE_PASS_BEGIN(PPCMIPeephole, DEBUG_TYPE,
"PowerPC MI Peephole Optimization", false, false)
INITIALIZE_PASS_END(PPCMIPeephole, DEBUG_TYPE,
"PowerPC MI Peephole Optimization", false, false)
char PPCMIPeephole::ID = 0;
FunctionPass*
llvm::createPPCMIPeepholePass() { return new PPCMIPeephole(); }
|
#include "workLoop.h"
#include<memory>
int workLoop::init()
{
listening.init(serverConfig::getConfig().getAddr(), serverConfig::getConfig().getPort());
if (em.init() == -1)
return -1;
em.registerEvent(listening.getSocketFd(), epollManager::event_type::LISTEN_EVENT);
return 0;
}
int workLoop::run()
{
if (init() < 0)
return -1;
if (loop() < 0)
return -1;
return 0;
}
void workLoop::handleAccept()
{
int clientFd = accept(listening.getSocketFd(), nullptr, nullptr);
if (clientFd < 0)
{
if (errno == EWOULDBLOCK || errno == ECONNABORTED || errno == EPROTO || errno == EINTR)
return;
else
{
perror("Failed to accept");
return;
}
}
auto newCon = std::make_unique<connection>(clientFd);
em.registerEvent(clientFd, epollManager::event_type::RECEIVE_EVENT);
fd_to_connection[clientFd] = move(newCon);
return;
}
void workLoop::handleReceive(std::unique_ptr<connection>& con)
{
int ret = con->readData();
if (ret < 0)
{
fd_to_connection.erase(con->getSock());
}
else if (ret > 0)
{
em.registerEvent(con->getSock(), epollManager::event_type::SEND_EVENT);
}
return;
}
void workLoop::handleSend(std::unique_ptr<connection>& con)
{
int ret = con->sendData();
if (ret < 0)
{
fd_to_connection.erase(con->getSock());
}
return;
}
int workLoop::loop()
{
for (;;)
{
for (auto& oneEvent : em.poll())
{
int fd = oneEvent.data.fd;
int events = oneEvent.events;
if (events & (EPOLLERR | EPOLLIN))
{
if (fd == listening.getSocketFd())
{
handleAccept();
}
else
{
handleReceive(fd_to_connection[fd]);
}
}
else if (events & EPOLLOUT)
{
handleSend(fd_to_connection[fd]);
}
}
}
return 0;
}
|
//
// "$Id$"
//
// Pixmap drawing code for the Fast Light Tool Kit (FLTK).
//
// Copyright 1998-2012 by Bill Spitzak and others.
//
// This library is free software. Distribution and use rights are outlined in
// the file "COPYING" which should have been included with this file. If this
// file is missing or damaged, see the license at:
//
// http://www.fltk.org/COPYING.php
//
// Please report all bugs and problems on the following page:
//
// http://www.fltk.org/str.php
//
// NOTE: I believe many of the following comments (between the dash markers)
// are no longer accurate:
// --------------------------------------------------------------------
// Implemented without using the xpm library (which I can't use because
// it interferes with the color cube used by fl_draw_image).
// Current implementation is cheap and slow, and works best on a full-color
// display. Transparency is not handled, and colors are dithered to
// the color cube. Color index is achieved by adding the id
// characters together! Also mallocs a lot of temporary memory!
// Notice that there is no pixmap file interface. This is on purpose,
// as I want to discourage programs that require support files to work.
// All data needed by a program ui should be compiled in!!!
// --------------------------------------------------------------------
// The above comments were checked in as r2, and much has changed since then;
// transparency added, color cube not required, etc. -erco Oct 20 2013
#include <FL/Fl.H>
#include <FL/fl_draw.H>
#include <FL/x.H>
#include <stdio.h>
#include "flstring.h"
static int ncolors, chars_per_pixel;
/**
Get the dimensions of a pixmap.
An XPM image contains the dimensions in its data. This function
returns the width and height.
\param[in] data pointer to XPM image data.
\param[out] w,h width and height of image
\returns non-zero if the dimensions were parsed OK
\returns 0 if there were any problems
*/
int fl_measure_pixmap(/*const*/ char* const* data, int &w, int &h) {
return fl_measure_pixmap((const char*const*)data,w,h);
}
/**
Get the dimensions of a pixmap.
\see fl_measure_pixmap(char* const* data, int &w, int &h)
*/
int fl_measure_pixmap(const char * const *cdata, int &w, int &h) {
int i = sscanf(cdata[0],"%d%d%d%d",&w,&h,&ncolors,&chars_per_pixel);
if (i<4 || w<=0 || h<=0 ||
(chars_per_pixel!=1 && chars_per_pixel!=2) ) return w=0;
return 1;
}
uchar **fl_mask_bitmap; // if non-zero, create bitmap and store pointer here
/**
Draw XPM image data, with the top-left corner at the given position.
The image is dithered on 8-bit displays so you won't lose color
space for programs displaying both images and pixmaps.
\param[in] data pointer to XPM image data
\param[in] x,y position of top-left corner
\param[in] bg background color
\returns 0 if there was any error decoding the XPM data.
*/
int fl_draw_pixmap(/*const*/ char* const* data, int x,int y,Fl_Color bg) {
return fl_draw_pixmap((const char*const*)data,x,y,bg);
}
#ifdef WIN32
// to compute an unused color to be used for the pixmap background
FL_EXPORT UINT win_pixmap_bg_color; // the RGB() of the pixmap background color
static int color_count; // # of non-transparent colors used in pixmap
typedef struct { uchar r; uchar g; uchar b; } UsedColor;
static UsedColor *used_colors;
// Makes an RGB triplet different from all the colors used in the pixmap
// and compute win_pixmap_bg_color from this triplet
static void make_unused_color(uchar &r, uchar &g, uchar &b) {
int i;
r = 2; g = 3; b = 4;
while (1) {
for ( i=0; i<color_count; i++ )
if ( used_colors[i].r == r &&
used_colors[i].g == g &&
used_colors[i].b == b )
break;
if (i >= color_count) {
free((void*)used_colors); used_colors = NULL;
win_pixmap_bg_color = RGB(r, g, b);
return;
}
if (r < 255) {
r++;
} else {
r = 0;
if (g < 255) {
g++;
} else {
g = 0;
b++;
}
}
}
}
#endif
int fl_convert_pixmap(const char*const* cdata, uchar* out, Fl_Color bg) {
int w, h;
const uchar*const* data = (const uchar*const*)(cdata+1);
if (!fl_measure_pixmap(cdata, w, h))
return 0;
if ((chars_per_pixel < 1) || (chars_per_pixel > 2))
return 0;
typedef uchar uchar4[4];
uchar4 *colors = new uchar4[1<<(chars_per_pixel*8)];
#ifdef WIN32
uchar *transparent_c = (uchar *)0; // such that transparent_c[0,1,2] are the RGB of the transparent color
color_count = 0;
used_colors = (UsedColor*)malloc(abs(ncolors) * sizeof(UsedColor));
#endif
if (ncolors < 0) { // FLTK (non standard) compressed colormap
ncolors = -ncolors;
const uchar *p = *data++;
// if first color is ' ' it is transparent (put it later to make
// it not be transparent):
if (*p == ' ') {
uchar* c = colors[(int)' '];
Fl::get_color(bg, c[0], c[1], c[2]); c[3] = 0;
#ifdef WIN32
transparent_c = c;
#endif
p += 4;
ncolors--;
}
// read all the rest of the colors:
for (int i=0; i < ncolors; i++) {
uchar* c = colors[*p++];
#ifdef WIN32
used_colors[color_count].r = *(p+0);
used_colors[color_count].g = *(p+1);
used_colors[color_count].b = *(p+2);
color_count++;
#endif
*c++ = *p++;
*c++ = *p++;
*c++ = *p++;
*c = 255;
}
} else { // normal XPM colormap with names
for (int i=0; i<ncolors; i++) {
const uchar *p = *data++;
// the first 1 or 2 characters are the color index:
int ind = *p++;
uchar* c;
if (chars_per_pixel>1)
ind = (ind<<8)|*p++;
c = colors[ind];
// look for "c word", or last word if none:
const uchar *previous_word = p;
for (;;) {
while (*p && isspace(*p)) p++;
uchar what = *p++;
while (*p && !isspace(*p)) p++;
while (*p && isspace(*p)) p++;
if (!*p) {p = previous_word; break;}
if (what == 'c') break;
previous_word = p;
while (*p && !isspace(*p)) p++;
}
int parse = fl_parse_color((const char*)p, c[0], c[1], c[2]);
c[3] = 255;
if (parse) {
#ifdef WIN32
used_colors[color_count].r = c[0];
used_colors[color_count].g = c[1];
used_colors[color_count].b = c[2];
color_count++;
#endif
} else {
// assume "None" or "#transparent" for any errors
// "bg" should be transparent...
Fl::get_color(bg, c[0], c[1], c[2]);
c[3] = 0;
#ifdef WIN32
transparent_c = c;
#endif
} // if parse
} // for ncolors
} // if ncolors
#ifdef WIN32
if (transparent_c) {
make_unused_color(transparent_c[0], transparent_c[1], transparent_c[2]);
} else {
uchar r, g, b;
make_unused_color(r, g, b);
}
#endif
U32 *q = (U32*)out;
for (int Y = 0; Y < h; Y++) {
const uchar* p = data[Y];
if (chars_per_pixel <= 1) {
for (int X = 0; X < w; X++)
memcpy(q++, colors[*p++], 4);
} else {
for (int X = 0; X < w; X++) {
int ind = (*p++)<<8;
ind |= *p++;
memcpy(q++, colors[ind], 4);
}
}
}
delete[] colors;
return 1;
}
/**
Draw XPM image data, with the top-left corner at the given position.
\see fl_draw_pixmap(char* const* data, int x, int y, Fl_Color bg)
*/
int fl_draw_pixmap(const char*const* cdata, int x, int y, Fl_Color bg) {
int w, h;
if (!fl_measure_pixmap(cdata, w, h))
return 0;
uchar *buffer = new uchar[w*h*4];
if (!fl_convert_pixmap(cdata, buffer, bg)) {
delete[] buffer;
return 0;
}
// FIXME: Hack until fl_draw_image() supports alpha properly
#ifdef __APPLE_QUARTZ__
if (Fl_Surface_Device::surface() == Fl_Display_Device::display_device()) {
Fl_RGB_Image* rgb = new Fl_RGB_Image(buffer, w, h, 4);
rgb->alloc_array = 1;
rgb->draw(x, y);
delete rgb;
return 1;
} else {
#endif // __APPLE_QUARTZ__
// build the mask bitmap used by Fl_Pixmap:
if (fl_mask_bitmap) {
int W = (w+7)/8;
uchar* bitmap = new uchar[W * h];
*fl_mask_bitmap = bitmap;
const uchar *p = &buffer[3];
uchar b = 0;
for (int Y = 0; Y < h; Y++) {
b = 0;
for (int X = 0, bit = 1; X < w; X++, p += 4) {
if (*p > 127)
b |= bit;
bit <<= 1;
if (bit > 0x80 || X == w-1) {
*bitmap++ = b;
bit = 1;
b = 0;
}
} // if chars_per_pixel
} // for Y
}
fl_draw_image(buffer, x, y, w, h, 4);
#ifdef __APPLE_QUARTZ__
}
#endif
delete[] buffer;
return 1;
}
//
// End of "$Id$".
//
|
// Copyright (C) 2018 ETH Zurich
// Copyright (C) 2018 UT-Battelle, LLC
// All rights reserved.
//
// See LICENSE for terms of usage.
// See CITATION.md for citation guidelines, if DCA++ is used for scientific publications.
//
// Author: Raffaele Solca' (rasolca@itp.phys.ethz.ch)
//
// This file provides cublas related utilities to cublasHandels.
#ifndef DCA_LINALG_UTIL_HANDLE_FUNCTIONS_HPP
#define DCA_LINALG_UTIL_HANDLE_FUNCTIONS_HPP
#include <cublas_v2.h>
#include "dca/linalg/util/def.hpp"
#include "dca/linalg/util/handle_container.hpp"
#include "dca/linalg/util/stream_functions.hpp"
namespace dca {
namespace linalg {
namespace util {
// dca::linalg::util::
inline HandleContainer<DCA_MAX_THREADS>& getHandleContainer() {
static HandleContainer<DCA_MAX_THREADS> handle_container(getStreamContainer());
return handle_container;
}
// Returns the handle associated with thread 'thread_id'.
// Preconditions: 0 <= thread_id < DCA_MAX_THREADS.
inline cublasHandle_t getHandle(int thread_id) {
return getHandleContainer()(thread_id);
}
// Sets the stream of the handle associated with thread 'thread_id'
// with the stream returned by getStream(thread_id, stream_id).
// It returns the handle.
// Preconditions: 0 <= thread_id < DCA_MAX_THREADS,
// 0 <= stream_id < DCA_STREAMS_PER_THREAD.
inline cublasHandle_t getHandle(int thread_id, int stream_id) {
getHandleContainer().setStream(thread_id, getStream(thread_id, stream_id));
return getHandleContainer()(thread_id);
}
} // util
} // linalg
} // dca
#endif // DCA_LINALG_UTIL_HANDLE_FUNCTIONS_HPP
|
//===---- TargetInfo.cpp - Encapsulate target details -----------*- C++ -*-===//
//
// 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
//
//===----------------------------------------------------------------------===//
//
// These classes wrap the information about a call or function
// definition used to handle ABI compliancy.
//
//===----------------------------------------------------------------------===//
#include "TargetInfo.h"
#include "ABIInfo.h"
#include "CGBlocks.h"
#include "CGCXXABI.h"
#include "CGValue.h"
#include "CodeGenFunction.h"
#include "clang/AST/Attr.h"
#include "clang/AST/RecordLayout.h"
#include "clang/Basic/CodeGenOptions.h"
#include "clang/Basic/DiagnosticFrontend.h"
#include "clang/Basic/Builtins.h"
#include "clang/CodeGen/CGFunctionInfo.h"
#include "clang/CodeGen/SwiftCallingConv.h"
#include "llvm/ADT/SmallBitVector.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/ADT/Triple.h"
#include "llvm/ADT/Twine.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/IntrinsicsNVPTX.h"
#include "llvm/IR/IntrinsicsS390.h"
#include "llvm/IR/Type.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm> // std::sort
using namespace clang;
using namespace CodeGen;
// Helper for coercing an aggregate argument or return value into an integer
// array of the same size (including padding) and alignment. This alternate
// coercion happens only for the RenderScript ABI and can be removed after
// runtimes that rely on it are no longer supported.
//
// RenderScript assumes that the size of the argument / return value in the IR
// is the same as the size of the corresponding qualified type. This helper
// coerces the aggregate type into an array of the same size (including
// padding). This coercion is used in lieu of expansion of struct members or
// other canonical coercions that return a coerced-type of larger size.
//
// Ty - The argument / return value type
// Context - The associated ASTContext
// LLVMContext - The associated LLVMContext
static ABIArgInfo coerceToIntArray(QualType Ty,
ASTContext &Context,
llvm::LLVMContext &LLVMContext) {
// Alignment and Size are measured in bits.
const uint64_t Size = Context.getTypeSize(Ty);
const uint64_t Alignment = Context.getTypeAlign(Ty);
llvm::Type *IntType = llvm::Type::getIntNTy(LLVMContext, Alignment);
const uint64_t NumElements = (Size + Alignment - 1) / Alignment;
return ABIArgInfo::getDirect(llvm::ArrayType::get(IntType, NumElements));
}
static void AssignToArrayRange(CodeGen::CGBuilderTy &Builder,
llvm::Value *Array,
llvm::Value *Value,
unsigned FirstIndex,
unsigned LastIndex) {
// Alternatively, we could emit this as a loop in the source.
for (unsigned I = FirstIndex; I <= LastIndex; ++I) {
llvm::Value *Cell =
Builder.CreateConstInBoundsGEP1_32(Builder.getInt8Ty(), Array, I);
Builder.CreateAlignedStore(Value, Cell, CharUnits::One());
}
}
static bool isAggregateTypeForABI(QualType T) {
return !CodeGenFunction::hasScalarEvaluationKind(T) ||
T->isMemberFunctionPointerType();
}
ABIArgInfo ABIInfo::getNaturalAlignIndirect(QualType Ty, bool ByVal,
bool Realign,
llvm::Type *Padding) const {
return ABIArgInfo::getIndirect(getContext().getTypeAlignInChars(Ty), ByVal,
Realign, Padding);
}
ABIArgInfo
ABIInfo::getNaturalAlignIndirectInReg(QualType Ty, bool Realign) const {
return ABIArgInfo::getIndirectInReg(getContext().getTypeAlignInChars(Ty),
/*ByVal*/ false, Realign);
}
Address ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
QualType Ty) const {
return Address::invalid();
}
bool ABIInfo::isPromotableIntegerTypeForABI(QualType Ty) const {
if (Ty->isPromotableIntegerType())
return true;
if (const auto *EIT = Ty->getAs<ExtIntType>())
if (EIT->getNumBits() < getContext().getTypeSize(getContext().IntTy))
return true;
return false;
}
ABIInfo::~ABIInfo() {}
/// Does the given lowering require more than the given number of
/// registers when expanded?
///
/// This is intended to be the basis of a reasonable basic implementation
/// of should{Pass,Return}IndirectlyForSwift.
///
/// For most targets, a limit of four total registers is reasonable; this
/// limits the amount of code required in order to move around the value
/// in case it wasn't produced immediately prior to the call by the caller
/// (or wasn't produced in exactly the right registers) or isn't used
/// immediately within the callee. But some targets may need to further
/// limit the register count due to an inability to support that many
/// return registers.
static bool occupiesMoreThan(CodeGenTypes &cgt,
ArrayRef<llvm::Type*> scalarTypes,
unsigned maxAllRegisters) {
unsigned intCount = 0, fpCount = 0;
for (llvm::Type *type : scalarTypes) {
if (type->isPointerTy()) {
intCount++;
} else if (auto intTy = dyn_cast<llvm::IntegerType>(type)) {
auto ptrWidth = cgt.getTarget().getPointerWidth(0);
intCount += (intTy->getBitWidth() + ptrWidth - 1) / ptrWidth;
} else {
assert(type->isVectorTy() || type->isFloatingPointTy());
fpCount++;
}
}
return (intCount + fpCount > maxAllRegisters);
}
bool SwiftABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize,
llvm::Type *eltTy,
unsigned numElts) const {
// The default implementation of this assumes that the target guarantees
// 128-bit SIMD support but nothing more.
return (vectorSize.getQuantity() > 8 && vectorSize.getQuantity() <= 16);
}
static CGCXXABI::RecordArgABI getRecordArgABI(const RecordType *RT,
CGCXXABI &CXXABI) {
const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
if (!RD) {
if (!RT->getDecl()->canPassInRegisters())
return CGCXXABI::RAA_Indirect;
return CGCXXABI::RAA_Default;
}
return CXXABI.getRecordArgABI(RD);
}
static CGCXXABI::RecordArgABI getRecordArgABI(QualType T,
CGCXXABI &CXXABI) {
const RecordType *RT = T->getAs<RecordType>();
if (!RT)
return CGCXXABI::RAA_Default;
return getRecordArgABI(RT, CXXABI);
}
static bool classifyReturnType(const CGCXXABI &CXXABI, CGFunctionInfo &FI,
const ABIInfo &Info) {
QualType Ty = FI.getReturnType();
if (const auto *RT = Ty->getAs<RecordType>())
if (!isa<CXXRecordDecl>(RT->getDecl()) &&
!RT->getDecl()->canPassInRegisters()) {
FI.getReturnInfo() = Info.getNaturalAlignIndirect(Ty);
return true;
}
return CXXABI.classifyReturnType(FI);
}
/// Pass transparent unions as if they were the type of the first element. Sema
/// should ensure that all elements of the union have the same "machine type".
static QualType useFirstFieldIfTransparentUnion(QualType Ty) {
if (const RecordType *UT = Ty->getAsUnionType()) {
const RecordDecl *UD = UT->getDecl();
if (UD->hasAttr<TransparentUnionAttr>()) {
assert(!UD->field_empty() && "sema created an empty transparent union");
return UD->field_begin()->getType();
}
}
return Ty;
}
CGCXXABI &ABIInfo::getCXXABI() const {
return CGT.getCXXABI();
}
ASTContext &ABIInfo::getContext() const {
return CGT.getContext();
}
llvm::LLVMContext &ABIInfo::getVMContext() const {
return CGT.getLLVMContext();
}
const llvm::DataLayout &ABIInfo::getDataLayout() const {
return CGT.getDataLayout();
}
const TargetInfo &ABIInfo::getTarget() const {
return CGT.getTarget();
}
const CodeGenOptions &ABIInfo::getCodeGenOpts() const {
return CGT.getCodeGenOpts();
}
bool ABIInfo::isAndroid() const { return getTarget().getTriple().isAndroid(); }
bool ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
return false;
}
bool ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
uint64_t Members) const {
return false;
}
LLVM_DUMP_METHOD void ABIArgInfo::dump() const {
raw_ostream &OS = llvm::errs();
OS << "(ABIArgInfo Kind=";
switch (TheKind) {
case Direct:
OS << "Direct Type=";
if (llvm::Type *Ty = getCoerceToType())
Ty->print(OS);
else
OS << "null";
break;
case Extend:
OS << "Extend";
break;
case Ignore:
OS << "Ignore";
break;
case InAlloca:
OS << "InAlloca Offset=" << getInAllocaFieldIndex();
break;
case Indirect:
OS << "Indirect Align=" << getIndirectAlign().getQuantity()
<< " ByVal=" << getIndirectByVal()
<< " Realign=" << getIndirectRealign();
break;
case IndirectAliased:
OS << "Indirect Align=" << getIndirectAlign().getQuantity()
<< " AadrSpace=" << getIndirectAddrSpace()
<< " Realign=" << getIndirectRealign();
break;
case Expand:
OS << "Expand";
break;
case CoerceAndExpand:
OS << "CoerceAndExpand Type=";
getCoerceAndExpandType()->print(OS);
break;
}
OS << ")\n";
}
// Dynamically round a pointer up to a multiple of the given alignment.
static llvm::Value *emitRoundPointerUpToAlignment(CodeGenFunction &CGF,
llvm::Value *Ptr,
CharUnits Align) {
llvm::Value *PtrAsInt = Ptr;
// OverflowArgArea = (OverflowArgArea + Align - 1) & -Align;
PtrAsInt = CGF.Builder.CreatePtrToInt(PtrAsInt, CGF.IntPtrTy);
PtrAsInt = CGF.Builder.CreateAdd(PtrAsInt,
llvm::ConstantInt::get(CGF.IntPtrTy, Align.getQuantity() - 1));
PtrAsInt = CGF.Builder.CreateAnd(PtrAsInt,
llvm::ConstantInt::get(CGF.IntPtrTy, -Align.getQuantity()));
PtrAsInt = CGF.Builder.CreateIntToPtr(PtrAsInt,
Ptr->getType(),
Ptr->getName() + ".aligned");
return PtrAsInt;
}
/// Emit va_arg for a platform using the common void* representation,
/// where arguments are simply emitted in an array of slots on the stack.
///
/// This version implements the core direct-value passing rules.
///
/// \param SlotSize - The size and alignment of a stack slot.
/// Each argument will be allocated to a multiple of this number of
/// slots, and all the slots will be aligned to this value.
/// \param AllowHigherAlign - The slot alignment is not a cap;
/// an argument type with an alignment greater than the slot size
/// will be emitted on a higher-alignment address, potentially
/// leaving one or more empty slots behind as padding. If this
/// is false, the returned address might be less-aligned than
/// DirectAlign.
static Address emitVoidPtrDirectVAArg(CodeGenFunction &CGF,
Address VAListAddr,
llvm::Type *DirectTy,
CharUnits DirectSize,
CharUnits DirectAlign,
CharUnits SlotSize,
bool AllowHigherAlign) {
// Cast the element type to i8* if necessary. Some platforms define
// va_list as a struct containing an i8* instead of just an i8*.
if (VAListAddr.getElementType() != CGF.Int8PtrTy)
VAListAddr = CGF.Builder.CreateElementBitCast(VAListAddr, CGF.Int8PtrTy);
llvm::Value *Ptr = CGF.Builder.CreateLoad(VAListAddr, "argp.cur");
// If the CC aligns values higher than the slot size, do so if needed.
Address Addr = Address::invalid();
if (AllowHigherAlign && DirectAlign > SlotSize) {
Addr = Address(emitRoundPointerUpToAlignment(CGF, Ptr, DirectAlign),
DirectAlign);
} else {
Addr = Address(Ptr, SlotSize);
}
// Advance the pointer past the argument, then store that back.
CharUnits FullDirectSize = DirectSize.alignTo(SlotSize);
Address NextPtr =
CGF.Builder.CreateConstInBoundsByteGEP(Addr, FullDirectSize, "argp.next");
CGF.Builder.CreateStore(NextPtr.getPointer(), VAListAddr);
// If the argument is smaller than a slot, and this is a big-endian
// target, the argument will be right-adjusted in its slot.
if (DirectSize < SlotSize && CGF.CGM.getDataLayout().isBigEndian() &&
!DirectTy->isStructTy()) {
Addr = CGF.Builder.CreateConstInBoundsByteGEP(Addr, SlotSize - DirectSize);
}
Addr = CGF.Builder.CreateElementBitCast(Addr, DirectTy);
return Addr;
}
/// Emit va_arg for a platform using the common void* representation,
/// where arguments are simply emitted in an array of slots on the stack.
///
/// \param IsIndirect - Values of this type are passed indirectly.
/// \param ValueInfo - The size and alignment of this type, generally
/// computed with getContext().getTypeInfoInChars(ValueTy).
/// \param SlotSizeAndAlign - The size and alignment of a stack slot.
/// Each argument will be allocated to a multiple of this number of
/// slots, and all the slots will be aligned to this value.
/// \param AllowHigherAlign - The slot alignment is not a cap;
/// an argument type with an alignment greater than the slot size
/// will be emitted on a higher-alignment address, potentially
/// leaving one or more empty slots behind as padding.
static Address emitVoidPtrVAArg(CodeGenFunction &CGF, Address VAListAddr,
QualType ValueTy, bool IsIndirect,
TypeInfoChars ValueInfo,
CharUnits SlotSizeAndAlign,
bool AllowHigherAlign) {
// The size and alignment of the value that was passed directly.
CharUnits DirectSize, DirectAlign;
if (IsIndirect) {
DirectSize = CGF.getPointerSize();
DirectAlign = CGF.getPointerAlign();
} else {
DirectSize = ValueInfo.Width;
DirectAlign = ValueInfo.Align;
}
// Cast the address we've calculated to the right type.
llvm::Type *DirectTy = CGF.ConvertTypeForMem(ValueTy);
if (IsIndirect)
DirectTy = DirectTy->getPointerTo(0);
Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, DirectTy,
DirectSize, DirectAlign,
SlotSizeAndAlign,
AllowHigherAlign);
if (IsIndirect) {
Addr = Address(CGF.Builder.CreateLoad(Addr), ValueInfo.Align);
}
return Addr;
}
static Address complexTempStructure(CodeGenFunction &CGF, Address VAListAddr,
QualType Ty, CharUnits SlotSize,
CharUnits EltSize, const ComplexType *CTy) {
Address Addr =
emitVoidPtrDirectVAArg(CGF, VAListAddr, CGF.Int8Ty, SlotSize * 2,
SlotSize, SlotSize, /*AllowHigher*/ true);
Address RealAddr = Addr;
Address ImagAddr = RealAddr;
if (CGF.CGM.getDataLayout().isBigEndian()) {
RealAddr =
CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize - EltSize);
ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(ImagAddr,
2 * SlotSize - EltSize);
} else {
ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize);
}
llvm::Type *EltTy = CGF.ConvertTypeForMem(CTy->getElementType());
RealAddr = CGF.Builder.CreateElementBitCast(RealAddr, EltTy);
ImagAddr = CGF.Builder.CreateElementBitCast(ImagAddr, EltTy);
llvm::Value *Real = CGF.Builder.CreateLoad(RealAddr, ".vareal");
llvm::Value *Imag = CGF.Builder.CreateLoad(ImagAddr, ".vaimag");
Address Temp = CGF.CreateMemTemp(Ty, "vacplx");
CGF.EmitStoreOfComplex({Real, Imag}, CGF.MakeAddrLValue(Temp, Ty),
/*init*/ true);
return Temp;
}
static Address emitMergePHI(CodeGenFunction &CGF,
Address Addr1, llvm::BasicBlock *Block1,
Address Addr2, llvm::BasicBlock *Block2,
const llvm::Twine &Name = "") {
assert(Addr1.getType() == Addr2.getType());
llvm::PHINode *PHI = CGF.Builder.CreatePHI(Addr1.getType(), 2, Name);
PHI->addIncoming(Addr1.getPointer(), Block1);
PHI->addIncoming(Addr2.getPointer(), Block2);
CharUnits Align = std::min(Addr1.getAlignment(), Addr2.getAlignment());
return Address(PHI, Align);
}
TargetCodeGenInfo::~TargetCodeGenInfo() = default;
// If someone can figure out a general rule for this, that would be great.
// It's probably just doomed to be platform-dependent, though.
unsigned TargetCodeGenInfo::getSizeOfUnwindException() const {
// Verified for:
// x86-64 FreeBSD, Linux, Darwin
// x86-32 FreeBSD, Linux, Darwin
// PowerPC Linux, Darwin
// ARM Darwin (*not* EABI)
// AArch64 Linux
return 32;
}
bool TargetCodeGenInfo::isNoProtoCallVariadic(const CallArgList &args,
const FunctionNoProtoType *fnType) const {
// The following conventions are known to require this to be false:
// x86_stdcall
// MIPS
// For everything else, we just prefer false unless we opt out.
return false;
}
void
TargetCodeGenInfo::getDependentLibraryOption(llvm::StringRef Lib,
llvm::SmallString<24> &Opt) const {
// This assumes the user is passing a library name like "rt" instead of a
// filename like "librt.a/so", and that they don't care whether it's static or
// dynamic.
Opt = "-l";
Opt += Lib;
}
unsigned TargetCodeGenInfo::getOpenCLKernelCallingConv() const {
// OpenCL kernels are called via an explicit runtime API with arguments
// set with clSetKernelArg(), not as normal sub-functions.
// Return SPIR_KERNEL by default as the kernel calling convention to
// ensure the fingerprint is fixed such way that each OpenCL argument
// gets one matching argument in the produced kernel function argument
// list to enable feasible implementation of clSetKernelArg() with
// aggregates etc. In case we would use the default C calling conv here,
// clSetKernelArg() might break depending on the target-specific
// conventions; different targets might split structs passed as values
// to multiple function arguments etc.
return llvm::CallingConv::SPIR_KERNEL;
}
llvm::Constant *TargetCodeGenInfo::getNullPointer(const CodeGen::CodeGenModule &CGM,
llvm::PointerType *T, QualType QT) const {
return llvm::ConstantPointerNull::get(T);
}
LangAS TargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM,
const VarDecl *D) const {
assert(!CGM.getLangOpts().OpenCL &&
!(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) &&
"Address space agnostic languages only");
return D ? D->getType().getAddressSpace() : LangAS::Default;
}
llvm::Value *TargetCodeGenInfo::performAddrSpaceCast(
CodeGen::CodeGenFunction &CGF, llvm::Value *Src, LangAS SrcAddr,
LangAS DestAddr, llvm::Type *DestTy, bool isNonNull) const {
// Since target may map different address spaces in AST to the same address
// space, an address space conversion may end up as a bitcast.
if (auto *C = dyn_cast<llvm::Constant>(Src))
return performAddrSpaceCast(CGF.CGM, C, SrcAddr, DestAddr, DestTy);
// Try to preserve the source's name to make IR more readable.
return CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Src, DestTy, Src->hasName() ? Src->getName() + ".ascast" : "");
}
llvm::Constant *
TargetCodeGenInfo::performAddrSpaceCast(CodeGenModule &CGM, llvm::Constant *Src,
LangAS SrcAddr, LangAS DestAddr,
llvm::Type *DestTy) const {
// Since target may map different address spaces in AST to the same address
// space, an address space conversion may end up as a bitcast.
return llvm::ConstantExpr::getPointerCast(Src, DestTy);
}
llvm::SyncScope::ID
TargetCodeGenInfo::getLLVMSyncScopeID(const LangOptions &LangOpts,
SyncScope Scope,
llvm::AtomicOrdering Ordering,
llvm::LLVMContext &Ctx) const {
return Ctx.getOrInsertSyncScopeID(""); /* default sync scope */
}
static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays);
/// isEmptyField - Return true iff a the field is "empty", that is it
/// is an unnamed bit-field or an (array of) empty record(s).
static bool isEmptyField(ASTContext &Context, const FieldDecl *FD,
bool AllowArrays) {
if (FD->isUnnamedBitfield())
return true;
QualType FT = FD->getType();
// Constant arrays of empty records count as empty, strip them off.
// Constant arrays of zero length always count as empty.
bool WasArray = false;
if (AllowArrays)
while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
if (AT->getSize() == 0)
return true;
FT = AT->getElementType();
// The [[no_unique_address]] special case below does not apply to
// arrays of C++ empty records, so we need to remember this fact.
WasArray = true;
}
const RecordType *RT = FT->getAs<RecordType>();
if (!RT)
return false;
// C++ record fields are never empty, at least in the Itanium ABI.
//
// FIXME: We should use a predicate for whether this behavior is true in the
// current ABI.
//
// The exception to the above rule are fields marked with the
// [[no_unique_address]] attribute (since C++20). Those do count as empty
// according to the Itanium ABI. The exception applies only to records,
// not arrays of records, so we must also check whether we stripped off an
// array type above.
if (isa<CXXRecordDecl>(RT->getDecl()) &&
(WasArray || !FD->hasAttr<NoUniqueAddressAttr>()))
return false;
return isEmptyRecord(Context, FT, AllowArrays);
}
/// isEmptyRecord - Return true iff a structure contains only empty
/// fields. Note that a structure with a flexible array member is not
/// considered empty.
static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) {
const RecordType *RT = T->getAs<RecordType>();
if (!RT)
return false;
const RecordDecl *RD = RT->getDecl();
if (RD->hasFlexibleArrayMember())
return false;
// If this is a C++ record, check the bases first.
if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
for (const auto &I : CXXRD->bases())
if (!isEmptyRecord(Context, I.getType(), true))
return false;
for (const auto *I : RD->fields())
if (!isEmptyField(Context, I, AllowArrays))
return false;
return true;
}
/// isSingleElementStruct - Determine if a structure is a "single
/// element struct", i.e. it has exactly one non-empty field or
/// exactly one field which is itself a single element
/// struct. Structures with flexible array members are never
/// considered single element structs.
///
/// \return The field declaration for the single non-empty field, if
/// it exists.
static const Type *isSingleElementStruct(QualType T, ASTContext &Context) {
const RecordType *RT = T->getAs<RecordType>();
if (!RT)
return nullptr;
const RecordDecl *RD = RT->getDecl();
if (RD->hasFlexibleArrayMember())
return nullptr;
const Type *Found = nullptr;
// If this is a C++ record, check the bases first.
if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
for (const auto &I : CXXRD->bases()) {
// Ignore empty records.
if (isEmptyRecord(Context, I.getType(), true))
continue;
// If we already found an element then this isn't a single-element struct.
if (Found)
return nullptr;
// If this is non-empty and not a single element struct, the composite
// cannot be a single element struct.
Found = isSingleElementStruct(I.getType(), Context);
if (!Found)
return nullptr;
}
}
// Check for single element.
for (const auto *FD : RD->fields()) {
QualType FT = FD->getType();
// Ignore empty fields.
if (isEmptyField(Context, FD, true))
continue;
// If we already found an element then this isn't a single-element
// struct.
if (Found)
return nullptr;
// Treat single element arrays as the element.
while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
if (AT->getSize().getZExtValue() != 1)
break;
FT = AT->getElementType();
}
if (!isAggregateTypeForABI(FT)) {
Found = FT.getTypePtr();
} else {
Found = isSingleElementStruct(FT, Context);
if (!Found)
return nullptr;
}
}
// We don't consider a struct a single-element struct if it has
// padding beyond the element type.
if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T))
return nullptr;
return Found;
}
namespace {
Address EmitVAArgInstr(CodeGenFunction &CGF, Address VAListAddr, QualType Ty,
const ABIArgInfo &AI) {
// This default implementation defers to the llvm backend's va_arg
// instruction. It can handle only passing arguments directly
// (typically only handled in the backend for primitive types), or
// aggregates passed indirectly by pointer (NOTE: if the "byval"
// flag has ABI impact in the callee, this implementation cannot
// work.)
// Only a few cases are covered here at the moment -- those needed
// by the default abi.
llvm::Value *Val;
if (AI.isIndirect()) {
assert(!AI.getPaddingType() &&
"Unexpected PaddingType seen in arginfo in generic VAArg emitter!");
assert(
!AI.getIndirectRealign() &&
"Unexpected IndirectRealign seen in arginfo in generic VAArg emitter!");
auto TyInfo = CGF.getContext().getTypeInfoInChars(Ty);
CharUnits TyAlignForABI = TyInfo.Align;
llvm::Type *BaseTy =
llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
llvm::Value *Addr =
CGF.Builder.CreateVAArg(VAListAddr.getPointer(), BaseTy);
return Address(Addr, TyAlignForABI);
} else {
assert((AI.isDirect() || AI.isExtend()) &&
"Unexpected ArgInfo Kind in generic VAArg emitter!");
assert(!AI.getInReg() &&
"Unexpected InReg seen in arginfo in generic VAArg emitter!");
assert(!AI.getPaddingType() &&
"Unexpected PaddingType seen in arginfo in generic VAArg emitter!");
assert(!AI.getDirectOffset() &&
"Unexpected DirectOffset seen in arginfo in generic VAArg emitter!");
assert(!AI.getCoerceToType() &&
"Unexpected CoerceToType seen in arginfo in generic VAArg emitter!");
Address Temp = CGF.CreateMemTemp(Ty, "varet");
Val = CGF.Builder.CreateVAArg(VAListAddr.getPointer(), CGF.ConvertType(Ty));
CGF.Builder.CreateStore(Val, Temp);
return Temp;
}
}
/// DefaultABIInfo - The default implementation for ABI specific
/// details. This implementation provides information which results in
/// self-consistent and sensible LLVM IR generation, but does not
/// conform to any particular ABI.
class DefaultABIInfo : public ABIInfo {
public:
DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
ABIArgInfo classifyReturnType(QualType RetTy) const;
ABIArgInfo classifyArgumentType(QualType RetTy) const;
void computeInfo(CGFunctionInfo &FI) const override {
if (!getCXXABI().classifyReturnType(FI))
FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
for (auto &I : FI.arguments())
I.info = classifyArgumentType(I.type);
}
Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
QualType Ty) const override {
return EmitVAArgInstr(CGF, VAListAddr, Ty, classifyArgumentType(Ty));
}
};
class DefaultTargetCodeGenInfo : public TargetCodeGenInfo {
public:
DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
: TargetCodeGenInfo(std::make_unique<DefaultABIInfo>(CGT)) {}
};
ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const {
Ty = useFirstFieldIfTransparentUnion(Ty);
if (isAggregateTypeForABI(Ty)) {
// Records with non-trivial destructors/copy-constructors should not be
// passed by value.
if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
return getNaturalAlignIndirect(Ty);
}
// Treat an enum type as its underlying type.
if (const EnumType *EnumTy = Ty->getAs<EnumType>())
Ty = EnumTy->getDecl()->getIntegerType();
ASTContext &Context = getContext();
if (const auto *EIT = Ty->getAs<ExtIntType>())
if (EIT->getNumBits() >
Context.getTypeSize(Context.getTargetInfo().hasInt128Type()
? Context.Int128Ty
: Context.LongLongTy))
return getNaturalAlignIndirect(Ty);
return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
: ABIArgInfo::getDirect());
}
ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const {
if (RetTy->isVoidType())
return ABIArgInfo::getIgnore();
if (isAggregateTypeForABI(RetTy))
return getNaturalAlignIndirect(RetTy);
// Treat an enum type as its underlying type.
if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
RetTy = EnumTy->getDecl()->getIntegerType();
if (const auto *EIT = RetTy->getAs<ExtIntType>())
if (EIT->getNumBits() >
getContext().getTypeSize(getContext().getTargetInfo().hasInt128Type()
? getContext().Int128Ty
: getContext().LongLongTy))
return getNaturalAlignIndirect(RetTy);
return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
: ABIArgInfo::getDirect());
}
//===----------------------------------------------------------------------===//
// WebAssembly ABI Implementation
//
// This is a very simple ABI that relies a lot on DefaultABIInfo.
//===----------------------------------------------------------------------===//
class WebAssemblyABIInfo final : public SwiftABIInfo {
public:
enum ABIKind {
MVP = 0,
ExperimentalMV = 1,
};
private:
DefaultABIInfo defaultInfo;
ABIKind Kind;
public:
explicit WebAssemblyABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind)
: SwiftABIInfo(CGT), defaultInfo(CGT), Kind(Kind) {}
private:
ABIArgInfo classifyReturnType(QualType RetTy) const;
ABIArgInfo classifyArgumentType(QualType Ty) const;
// DefaultABIInfo's classifyReturnType and classifyArgumentType are
// non-virtual, but computeInfo and EmitVAArg are virtual, so we
// overload them.
void computeInfo(CGFunctionInfo &FI) const override {
if (!getCXXABI().classifyReturnType(FI))
FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
for (auto &Arg : FI.arguments())
Arg.info = classifyArgumentType(Arg.type);
}
Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
QualType Ty) const override;
bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
bool asReturnValue) const override {
return occupiesMoreThan(CGT, scalars, /*total*/ 4);
}
bool isSwiftErrorInRegister() const override {
return false;
}
};
class WebAssemblyTargetCodeGenInfo final : public TargetCodeGenInfo {
public:
explicit WebAssemblyTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
WebAssemblyABIInfo::ABIKind K)
: TargetCodeGenInfo(std::make_unique<WebAssemblyABIInfo>(CGT, K)) {}
void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
CodeGen::CodeGenModule &CGM) const override {
TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
if (const auto *FD = dyn_cast_or_null<FunctionDecl>(D)) {
if (const auto *Attr = FD->getAttr<WebAssemblyImportModuleAttr>()) {
llvm::Function *Fn = cast<llvm::Function>(GV);
llvm::AttrBuilder B;
B.addAttribute("wasm-import-module", Attr->getImportModule());
Fn->addFnAttrs(B);
}
if (const auto *Attr = FD->getAttr<WebAssemblyImportNameAttr>()) {
llvm::Function *Fn = cast<llvm::Function>(GV);
llvm::AttrBuilder B;
B.addAttribute("wasm-import-name", Attr->getImportName());
Fn->addFnAttrs(B);
}
if (const auto *Attr = FD->getAttr<WebAssemblyExportNameAttr>()) {
llvm::Function *Fn = cast<llvm::Function>(GV);
llvm::AttrBuilder B;
B.addAttribute("wasm-export-name", Attr->getExportName());
Fn->addFnAttrs(B);
}
}
if (auto *FD = dyn_cast_or_null<FunctionDecl>(D)) {
llvm::Function *Fn = cast<llvm::Function>(GV);
if (!FD->doesThisDeclarationHaveABody() && !FD->hasPrototype())
Fn->addFnAttr("no-prototype");
}
}
};
/// Classify argument of given type \p Ty.
ABIArgInfo WebAssemblyABIInfo::classifyArgumentType(QualType Ty) const {
Ty = useFirstFieldIfTransparentUnion(Ty);
if (isAggregateTypeForABI(Ty)) {
// Records with non-trivial destructors/copy-constructors should not be
// passed by value.
if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
// Ignore empty structs/unions.
if (isEmptyRecord(getContext(), Ty, true))
return ABIArgInfo::getIgnore();
// Lower single-element structs to just pass a regular value. TODO: We
// could do reasonable-size multiple-element structs too, using getExpand(),
// though watch out for things like bitfields.
if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
// For the experimental multivalue ABI, fully expand all other aggregates
if (Kind == ABIKind::ExperimentalMV) {
const RecordType *RT = Ty->getAs<RecordType>();
assert(RT);
bool HasBitField = false;
for (auto *Field : RT->getDecl()->fields()) {
if (Field->isBitField()) {
HasBitField = true;
break;
}
}
if (!HasBitField)
return ABIArgInfo::getExpand();
}
}
// Otherwise just do the default thing.
return defaultInfo.classifyArgumentType(Ty);
}
ABIArgInfo WebAssemblyABIInfo::classifyReturnType(QualType RetTy) const {
if (isAggregateTypeForABI(RetTy)) {
// Records with non-trivial destructors/copy-constructors should not be
// returned by value.
if (!getRecordArgABI(RetTy, getCXXABI())) {
// Ignore empty structs/unions.
if (isEmptyRecord(getContext(), RetTy, true))
return ABIArgInfo::getIgnore();
// Lower single-element structs to just return a regular value. TODO: We
// could do reasonable-size multiple-element structs too, using
// ABIArgInfo::getDirect().
if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
// For the experimental multivalue ABI, return all other aggregates
if (Kind == ABIKind::ExperimentalMV)
return ABIArgInfo::getDirect();
}
}
// Otherwise just do the default thing.
return defaultInfo.classifyReturnType(RetTy);
}
Address WebAssemblyABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
QualType Ty) const {
bool IsIndirect = isAggregateTypeForABI(Ty) &&
!isEmptyRecord(getContext(), Ty, true) &&
!isSingleElementStruct(Ty, getContext());
return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
getContext().getTypeInfoInChars(Ty),
CharUnits::fromQuantity(4),
/*AllowHigherAlign=*/true);
}
//===----------------------------------------------------------------------===//
// le32/PNaCl bitcode ABI Implementation
//
// This is a simplified version of the x86_32 ABI. Arguments and return values
// are always passed on the stack.
//===----------------------------------------------------------------------===//
class PNaClABIInfo : public ABIInfo {
public:
PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
ABIArgInfo classifyReturnType(QualType RetTy) const;
ABIArgInfo classifyArgumentType(QualType RetTy) const;
void computeInfo(CGFunctionInfo &FI) const override;
Address EmitVAArg(CodeGenFunction &CGF,
Address VAListAddr, QualType Ty) const override;
};
class PNaClTargetCodeGenInfo : public TargetCodeGenInfo {
public:
PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
: TargetCodeGenInfo(std::make_unique<PNaClABIInfo>(CGT)) {}
};
void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const {
if (!getCXXABI().classifyReturnType(FI))
FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
for (auto &I : FI.arguments())
I.info = classifyArgumentType(I.type);
}
Address PNaClABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
QualType Ty) const {
// The PNaCL ABI is a bit odd, in that varargs don't use normal
// function classification. Structs get passed directly for varargs
// functions, through a rewriting transform in
// pnacl-llvm/lib/Transforms/NaCl/ExpandVarArgs.cpp, which allows
// this target to actually support a va_arg instructions with an
// aggregate type, unlike other targets.
return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
}
/// Classify argument of given type \p Ty.
ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const {
if (isAggregateTypeForABI(Ty)) {
if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
return getNaturalAlignIndirect(Ty);
} else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
// Treat an enum type as its underlying type.
Ty = EnumTy->getDecl()->getIntegerType();
} else if (Ty->isFloatingType()) {
// Floating-point types don't go inreg.
return ABIArgInfo::getDirect();
} else if (const auto *EIT = Ty->getAs<ExtIntType>()) {
// Treat extended integers as integers if <=64, otherwise pass indirectly.
if (EIT->getNumBits() > 64)
return getNaturalAlignIndirect(Ty);
return ABIArgInfo::getDirect();
}
return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
: ABIArgInfo::getDirect());
}
ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const {
if (RetTy->isVoidType())
return ABIArgInfo::getIgnore();
// In the PNaCl ABI we always return records/structures on the stack.
if (isAggregateTypeForABI(RetTy))
return getNaturalAlignIndirect(RetTy);
// Treat extended integers as integers if <=64, otherwise pass indirectly.
if (const auto *EIT = RetTy->getAs<ExtIntType>()) {
if (EIT->getNumBits() > 64)
return getNaturalAlignIndirect(RetTy);
return ABIArgInfo::getDirect();
}
// Treat an enum type as its underlying type.
if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
RetTy = EnumTy->getDecl()->getIntegerType();
return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
: ABIArgInfo::getDirect());
}
/// IsX86_MMXType - Return true if this is an MMX type.
bool IsX86_MMXType(llvm::Type *IRType) {
// Return true if the type is an MMX type <2 x i32>, <4 x i16>, or <8 x i8>.
return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() &&
IRType->getScalarSizeInBits() != 64;
}
static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
StringRef Constraint,
llvm::Type* Ty) {
bool IsMMXCons = llvm::StringSwitch<bool>(Constraint)
.Cases("y", "&y", "^Ym", true)
.Default(false);
if (IsMMXCons && Ty->isVectorTy()) {
if (cast<llvm::VectorType>(Ty)->getPrimitiveSizeInBits().getFixedSize() !=
64) {
// Invalid MMX constraint
return nullptr;
}
return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
}
// No operation needed
return Ty;
}
/// Returns true if this type can be passed in SSE registers with the
/// X86_VectorCall calling convention. Shared between x86_32 and x86_64.
static bool isX86VectorTypeForVectorCall(ASTContext &Context, QualType Ty) {
if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
if (BT->isFloatingPoint() && BT->getKind() != BuiltinType::Half) {
if (BT->getKind() == BuiltinType::LongDouble) {
if (&Context.getTargetInfo().getLongDoubleFormat() ==
&llvm::APFloat::x87DoubleExtended())
return false;
}
return true;
}
} else if (const VectorType *VT = Ty->getAs<VectorType>()) {
// vectorcall can pass XMM, YMM, and ZMM vectors. We don't pass SSE1 MMX
// registers specially.
unsigned VecSize = Context.getTypeSize(VT);
if (VecSize == 128 || VecSize == 256 || VecSize == 512)
return true;
}
return false;
}
/// Returns true if this aggregate is small enough to be passed in SSE registers
/// in the X86_VectorCall calling convention. Shared between x86_32 and x86_64.
static bool isX86VectorCallAggregateSmallEnough(uint64_t NumMembers) {
return NumMembers <= 4;
}
/// Returns a Homogeneous Vector Aggregate ABIArgInfo, used in X86.
static ABIArgInfo getDirectX86Hva(llvm::Type* T = nullptr) {
auto AI = ABIArgInfo::getDirect(T);
AI.setInReg(true);
AI.setCanBeFlattened(false);
return AI;
}
//===----------------------------------------------------------------------===//
// X86-32 ABI Implementation
//===----------------------------------------------------------------------===//
/// Similar to llvm::CCState, but for Clang.
struct CCState {
CCState(CGFunctionInfo &FI)
: IsPreassigned(FI.arg_size()), CC(FI.getCallingConvention()) {}
llvm::SmallBitVector IsPreassigned;
unsigned CC = CallingConv::CC_C;
unsigned FreeRegs = 0;
unsigned FreeSSERegs = 0;
};
/// X86_32ABIInfo - The X86-32 ABI information.
class X86_32ABIInfo : public SwiftABIInfo {
enum Class {
Integer,
Float
};
static const unsigned MinABIStackAlignInBytes = 4;
bool IsDarwinVectorABI;
bool IsRetSmallStructInRegABI;
bool IsWin32StructABI;
bool IsSoftFloatABI;
bool IsMCUABI;
bool IsLinuxABI;
unsigned DefaultNumRegisterParameters;
static bool isRegisterSize(unsigned Size) {
return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
}
bool isHomogeneousAggregateBaseType(QualType Ty) const override {
// FIXME: Assumes vectorcall is in use.
return isX86VectorTypeForVectorCall(getContext(), Ty);
}
bool isHomogeneousAggregateSmallEnough(const Type *Ty,
uint64_t NumMembers) const override {
// FIXME: Assumes vectorcall is in use.
return isX86VectorCallAggregateSmallEnough(NumMembers);
}
bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const;
/// getIndirectResult - Give a source type \arg Ty, return a suitable result
/// such that the argument will be passed in memory.
ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
ABIArgInfo getIndirectReturnResult(QualType Ty, CCState &State) const;
/// Return the alignment to use for the given type on the stack.
unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
Class classify(QualType Ty) const;
ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const;
ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
/// Updates the number of available free registers, returns
/// true if any registers were allocated.
bool updateFreeRegs(QualType Ty, CCState &State) const;
bool shouldAggregateUseDirect(QualType Ty, CCState &State, bool &InReg,
bool &NeedsPadding) const;
bool shouldPrimitiveUseInReg(QualType Ty, CCState &State) const;
bool canExpandIndirectArgument(QualType Ty) const;
/// Rewrite the function info so that all memory arguments use
/// inalloca.
void rewriteWithInAlloca(CGFunctionInfo &FI) const;
void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
CharUnits &StackOffset, ABIArgInfo &Info,
QualType Type) const;
void runVectorCallFirstPass(CGFunctionInfo &FI, CCState &State) const;
public:
void computeInfo(CGFunctionInfo &FI) const override;
Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
QualType Ty) const override;
X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
bool RetSmallStructInRegABI, bool Win32StructABI,
unsigned NumRegisterParameters, bool SoftFloatABI)
: SwiftABIInfo(CGT), IsDarwinVectorABI(DarwinVectorABI),
IsRetSmallStructInRegABI(RetSmallStructInRegABI),
IsWin32StructABI(Win32StructABI), IsSoftFloatABI(SoftFloatABI),
IsMCUABI(CGT.getTarget().getTriple().isOSIAMCU()),
IsLinuxABI(CGT.getTarget().getTriple().isOSLinux() ||
CGT.getTarget().getTriple().isOSCygMing()),
DefaultNumRegisterParameters(NumRegisterParameters) {}
bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
bool asReturnValue) const override {
// LLVM's x86-32 lowering currently only assigns up to three
// integer registers and three fp registers. Oddly, it'll use up to
// four vector registers for vectors, but those can overlap with the
// scalar registers.
return occupiesMoreThan(CGT, scalars, /*total*/ 3);
}
bool isSwiftErrorInRegister() const override {
// x86-32 lowering does not support passing swifterror in a register.
return false;
}
};
class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
public:
X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
bool RetSmallStructInRegABI, bool Win32StructABI,
unsigned NumRegisterParameters, bool SoftFloatABI)
: TargetCodeGenInfo(std::make_unique<X86_32ABIInfo>(
CGT, DarwinVectorABI, RetSmallStructInRegABI, Win32StructABI,
NumRegisterParameters, SoftFloatABI)) {}
static bool isStructReturnInRegABI(
const llvm::Triple &Triple, const CodeGenOptions &Opts);
void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
CodeGen::CodeGenModule &CGM) const override;
int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
// Darwin uses different dwarf register numbers for EH.
if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
return 4;
}
bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
llvm::Value *Address) const override;
llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
StringRef Constraint,
llvm::Type* Ty) const override {
return X86AdjustInlineAsmType(CGF, Constraint, Ty);
}
void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue,
std::string &Constraints,
std::vector<llvm::Type *> &ResultRegTypes,
std::vector<llvm::Type *> &ResultTruncRegTypes,
std::vector<LValue> &ResultRegDests,
std::string &AsmString,
unsigned NumOutputs) const override;
llvm::Constant *
getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
unsigned Sig = (0xeb << 0) | // jmp rel8
(0x06 << 8) | // .+0x08
('v' << 16) |
('2' << 24);
return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
}
StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
return "movl\t%ebp, %ebp"
"\t\t// marker for objc_retainAutoreleaseReturnValue";
}
};
}
/// Rewrite input constraint references after adding some output constraints.
/// In the case where there is one output and one input and we add one output,
/// we need to replace all operand references greater than or equal to 1:
/// mov $0, $1
/// mov eax, $1
/// The result will be:
/// mov $0, $2
/// mov eax, $2
static void rewriteInputConstraintReferences(unsigned FirstIn,
unsigned NumNewOuts,
std::string &AsmString) {
std::string Buf;
llvm::raw_string_ostream OS(Buf);
size_t Pos = 0;
while (Pos < AsmString.size()) {
size_t DollarStart = AsmString.find('$', Pos);
if (DollarStart == std::string::npos)
DollarStart = AsmString.size();
size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart);
if (DollarEnd == std::string::npos)
DollarEnd = AsmString.size();
OS << StringRef(&AsmString[Pos], DollarEnd - Pos);
Pos = DollarEnd;
size_t NumDollars = DollarEnd - DollarStart;
if (NumDollars % 2 != 0 && Pos < AsmString.size()) {
// We have an operand reference.
size_t DigitStart = Pos;
if (AsmString[DigitStart] == '{') {
OS << '{';
++DigitStart;
}
size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart);
if (DigitEnd == std::string::npos)
DigitEnd = AsmString.size();
StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart);
unsigned OperandIndex;
if (!OperandStr.getAsInteger(10, OperandIndex)) {
if (OperandIndex >= FirstIn)
OperandIndex += NumNewOuts;
OS << OperandIndex;
} else {
OS << OperandStr;
}
Pos = DigitEnd;
}
}
AsmString = std::move(OS.str());
}
/// Add output constraints for EAX:EDX because they are return registers.
void X86_32TargetCodeGenInfo::addReturnRegisterOutputs(
CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints,
std::vector<llvm::Type *> &ResultRegTypes,
std::vector<llvm::Type *> &ResultTruncRegTypes,
std::vector<LValue> &ResultRegDests, std::string &AsmString,
unsigned NumOutputs) const {
uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType());
// Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is
// larger.
if (!Constraints.empty())
Constraints += ',';
if (RetWidth <= 32) {
Constraints += "={eax}";
ResultRegTypes.push_back(CGF.Int32Ty);
} else {
// Use the 'A' constraint for EAX:EDX.
Constraints += "=A";
ResultRegTypes.push_back(CGF.Int64Ty);
}
// Truncate EAX or EAX:EDX to an integer of the appropriate size.
llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth);
ResultTruncRegTypes.push_back(CoerceTy);
// Coerce the integer by bitcasting the return slot pointer.
ReturnSlot.setAddress(CGF.Builder.CreateBitCast(ReturnSlot.getAddress(CGF),
CoerceTy->getPointerTo()));
ResultRegDests.push_back(ReturnSlot);
rewriteInputConstraintReferences(NumOutputs, 1, AsmString);
}
/// shouldReturnTypeInRegister - Determine if the given type should be
/// returned in a register (for the Darwin and MCU ABI).
bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
ASTContext &Context) const {
uint64_t Size = Context.getTypeSize(Ty);
// For i386, type must be register sized.
// For the MCU ABI, it only needs to be <= 8-byte
if ((IsMCUABI && Size > 64) || (!IsMCUABI && !isRegisterSize(Size)))
return false;
if (Ty->isVectorType()) {
// 64- and 128- bit vectors inside structures are not returned in
// registers.
if (Size == 64 || Size == 128)
return false;
return true;
}
// If this is a builtin, pointer, enum, complex type, member pointer, or
// member function pointer it is ok.
if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
Ty->isAnyComplexType() || Ty->isEnumeralType() ||
Ty->isBlockPointerType() || Ty->isMemberPointerType())
return true;
// Arrays are treated like records.
if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
return shouldReturnTypeInRegister(AT->getElementType(), Context);
// Otherwise, it must be a record type.
const RecordType *RT = Ty->getAs<RecordType>();
if (!RT) return false;
// FIXME: Traverse bases here too.
// Structure types are passed in register if all fields would be
// passed in a register.
for (const auto *FD : RT->getDecl()->fields()) {
// Empty fields are ignored.
if (isEmptyField(Context, FD, true))
continue;
// Check fields recursively.
if (!shouldReturnTypeInRegister(FD->getType(), Context))
return false;
}
return true;
}
static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
// Treat complex types as the element type.
if (const ComplexType *CTy = Ty->getAs<ComplexType>())
Ty = CTy->getElementType();
// Check for a type which we know has a simple scalar argument-passing
// convention without any padding. (We're specifically looking for 32
// and 64-bit integer and integer-equivalents, float, and double.)
if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
!Ty->isEnumeralType() && !Ty->isBlockPointerType())
return false;
uint64_t Size = Context.getTypeSize(Ty);
return Size == 32 || Size == 64;
}
static bool addFieldSizes(ASTContext &Context, const RecordDecl *RD,
uint64_t &Size) {
for (const auto *FD : RD->fields()) {
// Scalar arguments on the stack get 4 byte alignment on x86. If the
// argument is smaller than 32-bits, expanding the struct will create
// alignment padding.
if (!is32Or64BitBasicType(FD->getType(), Context))
return false;
// FIXME: Reject bit-fields wholesale; there are two problems, we don't know
// how to expand them yet, and the predicate for telling if a bitfield still
// counts as "basic" is more complicated than what we were doing previously.
if (FD->isBitField())
return false;
Size += Context.getTypeSize(FD->getType());
}
return true;
}
static bool addBaseAndFieldSizes(ASTContext &Context, const CXXRecordDecl *RD,
uint64_t &Size) {
// Don't do this if there are any non-empty bases.
for (const CXXBaseSpecifier &Base : RD->bases()) {
if (!addBaseAndFieldSizes(Context, Base.getType()->getAsCXXRecordDecl(),
Size))
return false;
}
if (!addFieldSizes(Context, RD, Size))
return false;
return true;
}
/// Test whether an argument type which is to be passed indirectly (on the
/// stack) would have the equivalent layout if it was expanded into separate
/// arguments. If so, we prefer to do the latter to avoid inhibiting
/// optimizations.
bool X86_32ABIInfo::canExpandIndirectArgument(QualType Ty) const {
// We can only expand structure types.
const RecordType *RT = Ty->getAs<RecordType>();
if (!RT)
return false;
const RecordDecl *RD = RT->getDecl();
uint64_t Size = 0;
if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
if (!IsWin32StructABI) {
// On non-Windows, we have to conservatively match our old bitcode
// prototypes in order to be ABI-compatible at the bitcode level.
if (!CXXRD->isCLike())
return false;
} else {
// Don't do this for dynamic classes.
if (CXXRD->isDynamicClass())
return false;
}
if (!addBaseAndFieldSizes(getContext(), CXXRD, Size))
return false;
} else {
if (!addFieldSizes(getContext(), RD, Size))
return false;
}
// We can do this if there was no alignment padding.
return Size == getContext().getTypeSize(Ty);
}
ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(QualType RetTy, CCState &State) const {
// If the return value is indirect, then the hidden argument is consuming one
// integer register.
if (State.FreeRegs) {
--State.FreeRegs;
if (!IsMCUABI)
return getNaturalAlignIndirectInReg(RetTy);
}
return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
}
ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy,
CCState &State) const {
if (RetTy->isVoidType())
return ABIArgInfo::getIgnore();
const Type *Base = nullptr;
uint64_t NumElts = 0;
if ((State.CC == llvm::CallingConv::X86_VectorCall ||
State.CC == llvm::CallingConv::X86_RegCall) &&
isHomogeneousAggregate(RetTy, Base, NumElts)) {
// The LLVM struct type for such an aggregate should lower properly.
return ABIArgInfo::getDirect();
}
if (const VectorType *VT = RetTy->getAs<VectorType>()) {
// On Darwin, some vectors are returned in registers.
if (IsDarwinVectorABI) {
uint64_t Size = getContext().getTypeSize(RetTy);
// 128-bit vectors are a special case; they are returned in
// registers and we need to make sure to pick a type the LLVM
// backend will like.
if (Size == 128)
return ABIArgInfo::getDirect(llvm::FixedVectorType::get(
llvm::Type::getInt64Ty(getVMContext()), 2));
// Always return in register if it fits in a general purpose
// register, or if it is 64 bits and has a single element.
if ((Size == 8 || Size == 16 || Size == 32) ||
(Size == 64 && VT->getNumElements() == 1))
return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Size));
return getIndirectReturnResult(RetTy, State);
}
return ABIArgInfo::getDirect();
}
if (isAggregateTypeForABI(RetTy)) {
if (const RecordType *RT = RetTy->getAs<RecordType>()) {
// Structures with flexible arrays are always indirect.
if (RT->getDecl()->hasFlexibleArrayMember())
return getIndirectReturnResult(RetTy, State);
}
// If specified, structs and unions are always indirect.
if (!IsRetSmallStructInRegABI && !RetTy->isAnyComplexType())
return getIndirectReturnResult(RetTy, State);
// Ignore empty structs/unions.
if (isEmptyRecord(getContext(), RetTy, true))
return ABIArgInfo::getIgnore();
// Return complex of _Float16 as <2 x half> so the backend will use xmm0.
if (const ComplexType *CT = RetTy->getAs<ComplexType>()) {
QualType ET = getContext().getCanonicalType(CT->getElementType());
if (ET->isFloat16Type())
return ABIArgInfo::getDirect(llvm::FixedVectorType::get(
llvm::Type::getHalfTy(getVMContext()), 2));
}
// Small structures which are register sized are generally returned
// in a register.
if (shouldReturnTypeInRegister(RetTy, getContext())) {
uint64_t Size = getContext().getTypeSize(RetTy);
// As a special-case, if the struct is a "single-element" struct, and
// the field is of type "float" or "double", return it in a
// floating-point register. (MSVC does not apply this special case.)
// We apply a similar transformation for pointer types to improve the
// quality of the generated IR.
if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
|| SeltTy->hasPointerRepresentation())
return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
// FIXME: We should be able to narrow this integer in cases with dead
// padding.
return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
}
return getIndirectReturnResult(RetTy, State);
}
// Treat an enum type as its underlying type.
if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
RetTy = EnumTy->getDecl()->getIntegerType();
if (const auto *EIT = RetTy->getAs<ExtIntType>())
if (EIT->getNumBits() > 64)
return getIndirectReturnResult(RetTy, State);
return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
: ABIArgInfo::getDirect());
}
static bool isSIMDVectorType(ASTContext &Context, QualType Ty) {
return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
}
static bool isRecordWithSIMDVectorType(ASTContext &Context, QualType Ty) {
const RecordType *RT = Ty->getAs<RecordType>();
if (!RT)
return 0;
const RecordDecl *RD = RT->getDecl();
// If this is a C++ record, check the bases first.
if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
for (const auto &I : CXXRD->bases())
if (!isRecordWithSIMDVectorType(Context, I.getType()))
return false;
for (const auto *i : RD->fields()) {
QualType FT = i->getType();
if (isSIMDVectorType(Context, FT))
return true;
if (isRecordWithSIMDVectorType(Context, FT))
return true;
}
return false;
}
unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
unsigned Align) const {
// Otherwise, if the alignment is less than or equal to the minimum ABI
// alignment, just use the default; the backend will handle this.
if (Align <= MinABIStackAlignInBytes)
return 0; // Use default alignment.
if (IsLinuxABI) {
// Exclude other System V OS (e.g Darwin, PS4 and FreeBSD) since we don't
// want to spend any effort dealing with the ramifications of ABI breaks.
//
// If the vector type is __m128/__m256/__m512, return the default alignment.
if (Ty->isVectorType() && (Align == 16 || Align == 32 || Align == 64))
return Align;
}
// On non-Darwin, the stack type alignment is always 4.
if (!IsDarwinVectorABI) {
// Set explicit alignment, since we may need to realign the top.
return MinABIStackAlignInBytes;
}
// Otherwise, if the type contains an SSE vector type, the alignment is 16.
if (Align >= 16 && (isSIMDVectorType(getContext(), Ty) ||
isRecordWithSIMDVectorType(getContext(), Ty)))
return 16;
return MinABIStackAlignInBytes;
}
ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
CCState &State) const {
if (!ByVal) {
if (State.FreeRegs) {
--State.FreeRegs; // Non-byval indirects just use one pointer.
if (!IsMCUABI)
return getNaturalAlignIndirectInReg(Ty);
}
return getNaturalAlignIndirect(Ty, false);
}
// Compute the byval alignment.
unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
if (StackAlign == 0)
return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true);
// If the stack alignment is less than the type alignment, realign the
// argument.
bool Realign = TypeAlign > StackAlign;
return ABIArgInfo::getIndirect(CharUnits::fromQuantity(StackAlign),
/*ByVal=*/true, Realign);
}
X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
const Type *T = isSingleElementStruct(Ty, getContext());
if (!T)
T = Ty.getTypePtr();
if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
BuiltinType::Kind K = BT->getKind();
if (K == BuiltinType::Float || K == BuiltinType::Double)
return Float;
}
return Integer;
}
bool X86_32ABIInfo::updateFreeRegs(QualType Ty, CCState &State) const {
if (!IsSoftFloatABI) {
Class C = classify(Ty);
if (C == Float)
return false;
}
unsigned Size = getContext().getTypeSize(Ty);
unsigned SizeInRegs = (Size + 31) / 32;
if (SizeInRegs == 0)
return false;
if (!IsMCUABI) {
if (SizeInRegs > State.FreeRegs) {
State.FreeRegs = 0;
return false;
}
} else {
// The MCU psABI allows passing parameters in-reg even if there are
// earlier parameters that are passed on the stack. Also,
// it does not allow passing >8-byte structs in-register,
// even if there are 3 free registers available.
if (SizeInRegs > State.FreeRegs || SizeInRegs > 2)
return false;
}
State.FreeRegs -= SizeInRegs;
return true;
}
bool X86_32ABIInfo::shouldAggregateUseDirect(QualType Ty, CCState &State,
bool &InReg,
bool &NeedsPadding) const {
// On Windows, aggregates other than HFAs are never passed in registers, and
// they do not consume register slots. Homogenous floating-point aggregates
// (HFAs) have already been dealt with at this point.
if (IsWin32StructABI && isAggregateTypeForABI(Ty))
return false;
NeedsPadding = false;
InReg = !IsMCUABI;
if (!updateFreeRegs(Ty, State))
return false;
if (IsMCUABI)
return true;
if (State.CC == llvm::CallingConv::X86_FastCall ||
State.CC == llvm::CallingConv::X86_VectorCall ||
State.CC == llvm::CallingConv::X86_RegCall) {
if (getContext().getTypeSize(Ty) <= 32 && State.FreeRegs)
NeedsPadding = true;
return false;
}
return true;
}
bool X86_32ABIInfo::shouldPrimitiveUseInReg(QualType Ty, CCState &State) const {
if (!updateFreeRegs(Ty, State))
return false;
if (IsMCUABI)
return false;
if (State.CC == llvm::CallingConv::X86_FastCall ||
State.CC == llvm::CallingConv::X86_VectorCall ||
State.CC == llvm::CallingConv::X86_RegCall) {
if (getContext().getTypeSize(Ty) > 32)
return false;
return (Ty->isIntegralOrEnumerationType() || Ty->isPointerType() ||
Ty->isReferenceType());
}
return true;
}
void X86_32ABIInfo::runVectorCallFirstPass(CGFunctionInfo &FI, CCState &State) const {
// Vectorcall x86 works subtly different than in x64, so the format is
// a bit different than the x64 version. First, all vector types (not HVAs)
// are assigned, with the first 6 ending up in the [XYZ]MM0-5 registers.
// This differs from the x64 implementation, where the first 6 by INDEX get
// registers.
// In the second pass over the arguments, HVAs are passed in the remaining
// vector registers if possible, or indirectly by address. The address will be
// passed in ECX/EDX if available. Any other arguments are passed according to
// the usual fastcall rules.
MutableArrayRef<CGFunctionInfoArgInfo> Args = FI.arguments();
for (int I = 0, E = Args.size(); I < E; ++I) {
const Type *Base = nullptr;
uint64_t NumElts = 0;
const QualType &Ty = Args[I].type;
if ((Ty->isVectorType() || Ty->isBuiltinType()) &&
isHomogeneousAggregate(Ty, Base, NumElts)) {
if (State.FreeSSERegs >= NumElts) {
State.FreeSSERegs -= NumElts;
Args[I].info = ABIArgInfo::getDirectInReg();
State.IsPreassigned.set(I);
}
}
}
}
ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
CCState &State) const {
// FIXME: Set alignment on indirect arguments.
bool IsFastCall = State.CC == llvm::CallingConv::X86_FastCall;
bool IsRegCall = State.CC == llvm::CallingConv::X86_RegCall;
bool IsVectorCall = State.CC == llvm::CallingConv::X86_VectorCall;
Ty = useFirstFieldIfTransparentUnion(Ty);
TypeInfo TI = getContext().getTypeInfo(Ty);
// Check with the C++ ABI first.
const RecordType *RT = Ty->getAs<RecordType>();
if (RT) {
CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
if (RAA == CGCXXABI::RAA_Indirect) {
return getIndirectResult(Ty, false, State);
} else if (RAA == CGCXXABI::RAA_DirectInMemory) {
// The field index doesn't matter, we'll fix it up later.
return ABIArgInfo::getInAlloca(/*FieldIndex=*/0);
}
}
// Regcall uses the concept of a homogenous vector aggregate, similar
// to other targets.
const Type *Base = nullptr;
uint64_t NumElts = 0;
if ((IsRegCall || IsVectorCall) &&
isHomogeneousAggregate(Ty, Base, NumElts)) {
if (State.FreeSSERegs >= NumElts) {
State.FreeSSERegs -= NumElts;
// Vectorcall passes HVAs directly and does not flatten them, but regcall
// does.
if (IsVectorCall)
return getDirectX86Hva();
if (Ty->isBuiltinType() || Ty->isVectorType())
return ABIArgInfo::getDirect();
return ABIArgInfo::getExpand();
}
return getIndirectResult(Ty, /*ByVal=*/false, State);
}
if (isAggregateTypeForABI(Ty)) {
// Structures with flexible arrays are always indirect.
// FIXME: This should not be byval!
if (RT && RT->getDecl()->hasFlexibleArrayMember())
return getIndirectResult(Ty, true, State);
// Ignore empty structs/unions on non-Windows.
if (!IsWin32StructABI && isEmptyRecord(getContext(), Ty, true))
return ABIArgInfo::getIgnore();
llvm::LLVMContext &LLVMContext = getVMContext();
llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
bool NeedsPadding = false;
bool InReg;
if (shouldAggregateUseDirect(Ty, State, InReg, NeedsPadding)) {
unsigned SizeInRegs = (TI.Width + 31) / 32;
SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
if (InReg)
return ABIArgInfo::getDirectInReg(Result);
else
return ABIArgInfo::getDirect(Result);
}
llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr;
// Pass over-aligned aggregates on Windows indirectly. This behavior was
// added in MSVC 2015.
if (IsWin32StructABI && TI.isAlignRequired() && TI.Align > 32)
return getIndirectResult(Ty, /*ByVal=*/false, State);
// Expand small (<= 128-bit) record types when we know that the stack layout
// of those arguments will match the struct. This is important because the
// LLVM backend isn't smart enough to remove byval, which inhibits many
// optimizations.
// Don't do this for the MCU if there are still free integer registers
// (see X86_64 ABI for full explanation).
if (TI.Width <= 4 * 32 && (!IsMCUABI || State.FreeRegs == 0) &&
canExpandIndirectArgument(Ty))
return ABIArgInfo::getExpandWithPadding(
IsFastCall || IsVectorCall || IsRegCall, PaddingType);
return getIndirectResult(Ty, true, State);
}
if (const VectorType *VT = Ty->getAs<VectorType>()) {
// On Windows, vectors are passed directly if registers are available, or
// indirectly if not. This avoids the need to align argument memory. Pass
// user-defined vector types larger than 512 bits indirectly for simplicity.
if (IsWin32StructABI) {
if (TI.Width <= 512 && State.FreeSSERegs > 0) {
--State.FreeSSERegs;
return ABIArgInfo::getDirectInReg();
}
return getIndirectResult(Ty, /*ByVal=*/false, State);
}
// On Darwin, some vectors are passed in memory, we handle this by passing
// it as an i8/i16/i32/i64.
if (IsDarwinVectorABI) {
if ((TI.Width == 8 || TI.Width == 16 || TI.Width == 32) ||
(TI.Width == 64 && VT->getNumElements() == 1))
return ABIArgInfo::getDirect(
llvm::IntegerType::get(getVMContext(), TI.Width));
}
if (IsX86_MMXType(CGT.ConvertType(Ty)))
return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
return ABIArgInfo::getDirect();
}
if (const EnumType *EnumTy = Ty->getAs<EnumType>())
Ty = EnumTy->getDecl()->getIntegerType();
bool InReg = shouldPrimitiveUseInReg(Ty, State);
if (isPromotableIntegerTypeForABI(Ty)) {
if (InReg)
return ABIArgInfo::getExtendInReg(Ty);
return ABIArgInfo::getExtend(Ty);
}
if (const auto * EIT = Ty->getAs<ExtIntType>()) {
if (EIT->getNumBits() <= 64) {
if (InReg)
return ABIArgInfo::getDirectInReg();
return ABIArgInfo::getDirect();
}
return getIndirectResult(Ty, /*ByVal=*/false, State);
}
if (InReg)
return ABIArgInfo::getDirectInReg();
return ABIArgInfo::getDirect();
}
void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
CCState State(FI);
if (IsMCUABI)
State.FreeRegs = 3;
else if (State.CC == llvm::CallingConv::X86_FastCall) {
State.FreeRegs = 2;
State.FreeSSERegs = 3;
} else if (State.CC == llvm::CallingConv::X86_VectorCall) {
State.FreeRegs = 2;
State.FreeSSERegs = 6;
} else if (FI.getHasRegParm())
State.FreeRegs = FI.getRegParm();
else if (State.CC == llvm::CallingConv::X86_RegCall) {
State.FreeRegs = 5;
State.FreeSSERegs = 8;
} else if (IsWin32StructABI) {
// Since MSVC 2015, the first three SSE vectors have been passed in
// registers. The rest are passed indirectly.
State.FreeRegs = DefaultNumRegisterParameters;
State.FreeSSERegs = 3;
} else
State.FreeRegs = DefaultNumRegisterParameters;
if (!::classifyReturnType(getCXXABI(), FI, *this)) {
FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State);
} else if (FI.getReturnInfo().isIndirect()) {
// The C++ ABI is not aware of register usage, so we have to check if the
// return value was sret and put it in a register ourselves if appropriate.
if (State.FreeRegs) {
--State.FreeRegs; // The sret parameter consumes a register.
if (!IsMCUABI)
FI.getReturnInfo().setInReg(true);
}
}
// The chain argument effectively gives us another free register.
if (FI.isChainCall())
++State.FreeRegs;
// For vectorcall, do a first pass over the arguments, assigning FP and vector
// arguments to XMM registers as available.
if (State.CC == llvm::CallingConv::X86_VectorCall)
runVectorCallFirstPass(FI, State);
bool UsedInAlloca = false;
MutableArrayRef<CGFunctionInfoArgInfo> Args = FI.arguments();
for (int I = 0, E = Args.size(); I < E; ++I) {
// Skip arguments that have already been assigned.
if (State.IsPreassigned.test(I))
continue;
Args[I].info = classifyArgumentType(Args[I].type, State);
UsedInAlloca |= (Args[I].info.getKind() == ABIArgInfo::InAlloca);
}
// If we needed to use inalloca for any argument, do a second pass and rewrite
// all the memory arguments to use inalloca.
if (UsedInAlloca)
rewriteWithInAlloca(FI);
}
void
X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
CharUnits &StackOffset, ABIArgInfo &Info,
QualType Type) const {
// Arguments are always 4-byte-aligned.
CharUnits WordSize = CharUnits::fromQuantity(4);
assert(StackOffset.isMultipleOf(WordSize) && "unaligned inalloca struct");
// sret pointers and indirect things will require an extra pointer
// indirection, unless they are byval. Most things are byval, and will not
// require this indirection.
bool IsIndirect = false;
if (Info.isIndirect() && !Info.getIndirectByVal())
IsIndirect = true;
Info = ABIArgInfo::getInAlloca(FrameFields.size(), IsIndirect);
llvm::Type *LLTy = CGT.ConvertTypeForMem(Type);
if (IsIndirect)
LLTy = LLTy->getPointerTo(0);
FrameFields.push_back(LLTy);
StackOffset += IsIndirect ? WordSize : getContext().getTypeSizeInChars(Type);
// Insert padding bytes to respect alignment.
CharUnits FieldEnd = StackOffset;
StackOffset = FieldEnd.alignTo(WordSize);
if (StackOffset != FieldEnd) {
CharUnits NumBytes = StackOffset - FieldEnd;
llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext());
Ty = llvm::ArrayType::get(Ty, NumBytes.getQuantity());
FrameFields.push_back(Ty);
}
}
static bool isArgInAlloca(const ABIArgInfo &Info) {
// Leave ignored and inreg arguments alone.
switch (Info.getKind()) {
case ABIArgInfo::InAlloca:
return true;
case ABIArgInfo::Ignore:
case ABIArgInfo::IndirectAliased:
return false;
case ABIArgInfo::Indirect:
case ABIArgInfo::Direct:
case ABIArgInfo::Extend:
return !Info.getInReg();
case ABIArgInfo::Expand:
case ABIArgInfo::CoerceAndExpand:
// These are aggregate types which are never passed in registers when
// inalloca is involved.
return true;
}
llvm_unreachable("invalid enum");
}
void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const {
assert(IsWin32StructABI && "inalloca only supported on win32");
// Build a packed struct type for all of the arguments in memory.
SmallVector<llvm::Type *, 6> FrameFields;
// The stack alignment is always 4.
CharUnits StackAlign = CharUnits::fromQuantity(4);
CharUnits StackOffset;
CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end();
// Put 'this' into the struct before 'sret', if necessary.
bool IsThisCall =
FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall;
ABIArgInfo &Ret = FI.getReturnInfo();
if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall &&
isArgInAlloca(I->info)) {
addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
++I;
}
// Put the sret parameter into the inalloca struct if it's in memory.
if (Ret.isIndirect() && !Ret.getInReg()) {
addFieldToArgStruct(FrameFields, StackOffset, Ret, FI.getReturnType());
// On Windows, the hidden sret parameter is always returned in eax.
Ret.setInAllocaSRet(IsWin32StructABI);
}
// Skip the 'this' parameter in ecx.
if (IsThisCall)
++I;
// Put arguments passed in memory into the struct.
for (; I != E; ++I) {
if (isArgInAlloca(I->info))
addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
}
FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields,
/*isPacked=*/true),
StackAlign);
}
Address X86_32ABIInfo::EmitVAArg(CodeGenFunction &CGF,
Address VAListAddr, QualType Ty) const {
auto TypeInfo = getContext().getTypeInfoInChars(Ty);
// x86-32 changes the alignment of certain arguments on the stack.
//
// Just messing with TypeInfo like this works because we never pass
// anything indirectly.
TypeInfo.Align = CharUnits::fromQuantity(
getTypeStackAlignInBytes(Ty, TypeInfo.Align.getQuantity()));
return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
TypeInfo, CharUnits::fromQuantity(4),
/*AllowHigherAlign*/ true);
}
bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
const llvm::Triple &Triple, const CodeGenOptions &Opts) {
assert(Triple.getArch() == llvm::Triple::x86);
switch (Opts.getStructReturnConvention()) {
case CodeGenOptions::SRCK_Default:
break;
case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return
return false;
case CodeGenOptions::SRCK_InRegs: // -freg-struct-return
return true;
}
if (Triple.isOSDarwin() || Triple.isOSIAMCU())
return true;
switch (Triple.getOS()) {
case llvm::Triple::DragonFly:
case llvm::Triple::FreeBSD:
case llvm::Triple::OpenBSD:
case llvm::Triple::Win32:
return true;
default:
return false;
}
}
static void addX86InterruptAttrs(const FunctionDecl *FD, llvm::GlobalValue *GV,
CodeGen::CodeGenModule &CGM) {
if (!FD->hasAttr<AnyX86InterruptAttr>())
return;
llvm::Function *Fn = cast<llvm::Function>(GV);
Fn->setCallingConv(llvm::CallingConv::X86_INTR);
if (FD->getNumParams() == 0)
return;
auto PtrTy = cast<PointerType>(FD->getParamDecl(0)->getType());
llvm::Type *ByValTy = CGM.getTypes().ConvertType(PtrTy->getPointeeType());
llvm::Attribute NewAttr = llvm::Attribute::getWithByValType(
Fn->getContext(), ByValTy);
Fn->addParamAttr(0, NewAttr);
}
void X86_32TargetCodeGenInfo::setTargetAttributes(
const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
if (GV->isDeclaration())
return;
if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
llvm::Function *Fn = cast<llvm::Function>(GV);
Fn->addFnAttr("stackrealign");
}
addX86InterruptAttrs(FD, GV, CGM);
}
}
bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
CodeGen::CodeGenFunction &CGF,
llvm::Value *Address) const {
CodeGen::CGBuilderTy &Builder = CGF.Builder;
llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
// 0-7 are the eight integer registers; the order is different
// on Darwin (for EH), but the range is the same.
// 8 is %eip.
AssignToArrayRange(Builder, Address, Four8, 0, 8);
if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
// 12-16 are st(0..4). Not sure why we stop at 4.
// These have size 16, which is sizeof(long double) on
// platforms with 8-byte alignment for that type.
llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
} else {
// 9 is %eflags, which doesn't get a size on Darwin for some
// reason.
Builder.CreateAlignedStore(
Four8, Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, Address, 9),
CharUnits::One());
// 11-16 are st(0..5). Not sure why we stop at 5.
// These have size 12, which is sizeof(long double) on
// platforms with 4-byte alignment for that type.
llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
}
return false;
}
//===----------------------------------------------------------------------===//
// X86-64 ABI Implementation
//===----------------------------------------------------------------------===//
namespace {
/// The AVX ABI level for X86 targets.
enum class X86AVXABILevel {
None,
AVX,
AVX512
};
/// \p returns the size in bits of the largest (native) vector for \p AVXLevel.
static unsigned getNativeVectorSizeForAVXABI(X86AVXABILevel AVXLevel) {
switch (AVXLevel) {
case X86AVXABILevel::AVX512:
return 512;
case X86AVXABILevel::AVX:
return 256;
case X86AVXABILevel::None:
return 128;
}
llvm_unreachable("Unknown AVXLevel");
}
/// X86_64ABIInfo - The X86_64 ABI information.
class X86_64ABIInfo : public SwiftABIInfo {
enum Class {
Integer = 0,
SSE,
SSEUp,
X87,
X87Up,
ComplexX87,
NoClass,
Memory
};
/// merge - Implement the X86_64 ABI merging algorithm.
///
/// Merge an accumulating classification \arg Accum with a field
/// classification \arg Field.
///
/// \param Accum - The accumulating classification. This should
/// always be either NoClass or the result of a previous merge
/// call. In addition, this should never be Memory (the caller
/// should just return Memory for the aggregate).
static Class merge(Class Accum, Class Field);
/// postMerge - Implement the X86_64 ABI post merging algorithm.
///
/// Post merger cleanup, reduces a malformed Hi and Lo pair to
/// final MEMORY or SSE classes when necessary.
///
/// \param AggregateSize - The size of the current aggregate in
/// the classification process.
///
/// \param Lo - The classification for the parts of the type
/// residing in the low word of the containing object.
///
/// \param Hi - The classification for the parts of the type
/// residing in the higher words of the containing object.
///
void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
/// classify - Determine the x86_64 register classes in which the
/// given type T should be passed.
///
/// \param Lo - The classification for the parts of the type
/// residing in the low word of the containing object.
///
/// \param Hi - The classification for the parts of the type
/// residing in the high word of the containing object.
///
/// \param OffsetBase - The bit offset of this type in the
/// containing object. Some parameters are classified different
/// depending on whether they straddle an eightbyte boundary.
///
/// \param isNamedArg - Whether the argument in question is a "named"
/// argument, as used in AMD64-ABI 3.5.7.
///
/// If a word is unused its result will be NoClass; if a type should
/// be passed in Memory then at least the classification of \arg Lo
/// will be Memory.
///
/// The \arg Lo class will be NoClass iff the argument is ignored.
///
/// If the \arg Lo class is ComplexX87, then the \arg Hi class will
/// also be ComplexX87.
void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
bool isNamedArg) const;
llvm::Type *GetByteVectorType(QualType Ty) const;
llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
unsigned IROffset, QualType SourceTy,
unsigned SourceOffset) const;
llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
unsigned IROffset, QualType SourceTy,
unsigned SourceOffset) const;
/// getIndirectResult - Give a source type \arg Ty, return a suitable result
/// such that the argument will be returned in memory.
ABIArgInfo getIndirectReturnResult(QualType Ty) const;
/// getIndirectResult - Give a source type \arg Ty, return a suitable result
/// such that the argument will be passed in memory.
///
/// \param freeIntRegs - The number of free integer registers remaining
/// available.
ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
ABIArgInfo classifyReturnType(QualType RetTy) const;
ABIArgInfo classifyArgumentType(QualType Ty, unsigned freeIntRegs,
unsigned &neededInt, unsigned &neededSSE,
bool isNamedArg) const;
ABIArgInfo classifyRegCallStructType(QualType Ty, unsigned &NeededInt,
unsigned &NeededSSE) const;
ABIArgInfo classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
unsigned &NeededSSE) const;
bool IsIllegalVectorType(QualType Ty) const;
/// The 0.98 ABI revision clarified a lot of ambiguities,
/// unfortunately in ways that were not always consistent with
/// certain previous compilers. In particular, platforms which
/// required strict binary compatibility with older versions of GCC
/// may need to exempt themselves.
bool honorsRevision0_98() const {
return !getTarget().getTriple().isOSDarwin();
}
/// GCC classifies <1 x long long> as SSE but some platform ABIs choose to
/// classify it as INTEGER (for compatibility with older clang compilers).
bool classifyIntegerMMXAsSSE() const {
// Clang <= 3.8 did not do this.
if (getContext().getLangOpts().getClangABICompat() <=
LangOptions::ClangABI::Ver3_8)
return false;
const llvm::Triple &Triple = getTarget().getTriple();
if (Triple.isOSDarwin() || Triple.getOS() == llvm::Triple::PS4)
return false;
if (Triple.isOSFreeBSD() && Triple.getOSMajorVersion() >= 10)
return false;
return true;
}
// GCC classifies vectors of __int128 as memory.
bool passInt128VectorsInMem() const {
// Clang <= 9.0 did not do this.
if (getContext().getLangOpts().getClangABICompat() <=
LangOptions::ClangABI::Ver9)
return false;
const llvm::Triple &T = getTarget().getTriple();
return T.isOSLinux() || T.isOSNetBSD();
}
X86AVXABILevel AVXLevel;
// Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
// 64-bit hardware.
bool Has64BitPointers;
public:
X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) :
SwiftABIInfo(CGT), AVXLevel(AVXLevel),
Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
}
bool isPassedUsingAVXType(QualType type) const {
unsigned neededInt, neededSSE;
// The freeIntRegs argument doesn't matter here.
ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
/*isNamedArg*/true);
if (info.isDirect()) {
llvm::Type *ty = info.getCoerceToType();
if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
return vectorTy->getPrimitiveSizeInBits().getFixedSize() > 128;
}
return false;
}
void computeInfo(CGFunctionInfo &FI) const override;
Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
QualType Ty) const override;
Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
QualType Ty) const override;
bool has64BitPointers() const {
return Has64BitPointers;
}
bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
bool asReturnValue) const override {
return occupiesMoreThan(CGT, scalars, /*total*/ 4);
}
bool isSwiftErrorInRegister() const override {
return true;
}
};
/// WinX86_64ABIInfo - The Windows X86_64 ABI information.
class WinX86_64ABIInfo : public SwiftABIInfo {
public:
WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
: SwiftABIInfo(CGT), AVXLevel(AVXLevel),
IsMingw64(getTarget().getTriple().isWindowsGNUEnvironment()) {}
void computeInfo(CGFunctionInfo &FI) const override;
Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
QualType Ty) const override;
bool isHomogeneousAggregateBaseType(QualType Ty) const override {
// FIXME: Assumes vectorcall is in use.
return isX86VectorTypeForVectorCall(getContext(), Ty);
}
bool isHomogeneousAggregateSmallEnough(const Type *Ty,
uint64_t NumMembers) const override {
// FIXME: Assumes vectorcall is in use.
return isX86VectorCallAggregateSmallEnough(NumMembers);
}
bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type *> scalars,
bool asReturnValue) const override {
return occupiesMoreThan(CGT, scalars, /*total*/ 4);
}
bool isSwiftErrorInRegister() const override {
return true;
}
private:
ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs, bool IsReturnType,
bool IsVectorCall, bool IsRegCall) const;
ABIArgInfo reclassifyHvaArgForVectorCall(QualType Ty, unsigned &FreeSSERegs,
const ABIArgInfo ¤t) const;
X86AVXABILevel AVXLevel;
bool IsMingw64;
};
class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
public:
X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
: TargetCodeGenInfo(std::make_unique<X86_64ABIInfo>(CGT, AVXLevel)) {}
const X86_64ABIInfo &getABIInfo() const {
return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
}
/// Disable tail call on x86-64. The epilogue code before the tail jump blocks
/// autoreleaseRV/retainRV and autoreleaseRV/unsafeClaimRV optimizations.
bool markARCOptimizedReturnCallsAsNoTail() const override { return true; }
int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
return 7;
}
bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
llvm::Value *Address) const override {
llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
// 0-15 are the 16 integer registers.
// 16 is %rip.
AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
return false;
}
llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
StringRef Constraint,
llvm::Type* Ty) const override {
return X86AdjustInlineAsmType(CGF, Constraint, Ty);
}
bool isNoProtoCallVariadic(const CallArgList &args,
const FunctionNoProtoType *fnType) const override {
// The default CC on x86-64 sets %al to the number of SSA
// registers used, and GCC sets this when calling an unprototyped
// function, so we override the default behavior. However, don't do
// that when AVX types are involved: the ABI explicitly states it is
// undefined, and it doesn't work in practice because of how the ABI
// defines varargs anyway.
if (fnType->getCallConv() == CC_C) {
bool HasAVXType = false;
for (CallArgList::const_iterator
it = args.begin(), ie = args.end(); it != ie; ++it) {
if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
HasAVXType = true;
break;
}
}
if (!HasAVXType)
return true;
}
return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
}
llvm::Constant *
getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
unsigned Sig = (0xeb << 0) | // jmp rel8
(0x06 << 8) | // .+0x08
('v' << 16) |
('2' << 24);
return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
}
void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
CodeGen::CodeGenModule &CGM) const override {
if (GV->isDeclaration())
return;
if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
llvm::Function *Fn = cast<llvm::Function>(GV);
Fn->addFnAttr("stackrealign");
}
addX86InterruptAttrs(FD, GV, CGM);
}
}
void checkFunctionCallABI(CodeGenModule &CGM, SourceLocation CallLoc,
const FunctionDecl *Caller,
const FunctionDecl *Callee,
const CallArgList &Args) const override;
};
static void initFeatureMaps(const ASTContext &Ctx,
llvm::StringMap<bool> &CallerMap,
const FunctionDecl *Caller,
llvm::StringMap<bool> &CalleeMap,
const FunctionDecl *Callee) {
if (CalleeMap.empty() && CallerMap.empty()) {
// The caller is potentially nullptr in the case where the call isn't in a
// function. In this case, the getFunctionFeatureMap ensures we just get
// the TU level setting (since it cannot be modified by 'target'..
Ctx.getFunctionFeatureMap(CallerMap, Caller);
Ctx.getFunctionFeatureMap(CalleeMap, Callee);
}
}
static bool checkAVXParamFeature(DiagnosticsEngine &Diag,
SourceLocation CallLoc,
const llvm::StringMap<bool> &CallerMap,
const llvm::StringMap<bool> &CalleeMap,
QualType Ty, StringRef Feature,
bool IsArgument) {
bool CallerHasFeat = CallerMap.lookup(Feature);
bool CalleeHasFeat = CalleeMap.lookup(Feature);
if (!CallerHasFeat && !CalleeHasFeat)
return Diag.Report(CallLoc, diag::warn_avx_calling_convention)
<< IsArgument << Ty << Feature;
// Mixing calling conventions here is very clearly an error.
if (!CallerHasFeat || !CalleeHasFeat)
return Diag.Report(CallLoc, diag::err_avx_calling_convention)
<< IsArgument << Ty << Feature;
// Else, both caller and callee have the required feature, so there is no need
// to diagnose.
return false;
}
static bool checkAVXParam(DiagnosticsEngine &Diag, ASTContext &Ctx,
SourceLocation CallLoc,
const llvm::StringMap<bool> &CallerMap,
const llvm::StringMap<bool> &CalleeMap, QualType Ty,
bool IsArgument) {
uint64_t Size = Ctx.getTypeSize(Ty);
if (Size > 256)
return checkAVXParamFeature(Diag, CallLoc, CallerMap, CalleeMap, Ty,
"avx512f", IsArgument);
if (Size > 128)
return checkAVXParamFeature(Diag, CallLoc, CallerMap, CalleeMap, Ty, "avx",
IsArgument);
return false;
}
void X86_64TargetCodeGenInfo::checkFunctionCallABI(
CodeGenModule &CGM, SourceLocation CallLoc, const FunctionDecl *Caller,
const FunctionDecl *Callee, const CallArgList &Args) const {
llvm::StringMap<bool> CallerMap;
llvm::StringMap<bool> CalleeMap;
unsigned ArgIndex = 0;
// We need to loop through the actual call arguments rather than the the
// function's parameters, in case this variadic.
for (const CallArg &Arg : Args) {
// The "avx" feature changes how vectors >128 in size are passed. "avx512f"
// additionally changes how vectors >256 in size are passed. Like GCC, we
// warn when a function is called with an argument where this will change.
// Unlike GCC, we also error when it is an obvious ABI mismatch, that is,
// the caller and callee features are mismatched.
// Unfortunately, we cannot do this diagnostic in SEMA, since the callee can
// change its ABI with attribute-target after this call.
if (Arg.getType()->isVectorType() &&
CGM.getContext().getTypeSize(Arg.getType()) > 128) {
initFeatureMaps(CGM.getContext(), CallerMap, Caller, CalleeMap, Callee);
QualType Ty = Arg.getType();
// The CallArg seems to have desugared the type already, so for clearer
// diagnostics, replace it with the type in the FunctionDecl if possible.
if (ArgIndex < Callee->getNumParams())
Ty = Callee->getParamDecl(ArgIndex)->getType();
if (checkAVXParam(CGM.getDiags(), CGM.getContext(), CallLoc, CallerMap,
CalleeMap, Ty, /*IsArgument*/ true))
return;
}
++ArgIndex;
}
// Check return always, as we don't have a good way of knowing in codegen
// whether this value is used, tail-called, etc.
if (Callee->getReturnType()->isVectorType() &&
CGM.getContext().getTypeSize(Callee->getReturnType()) > 128) {
initFeatureMaps(CGM.getContext(), CallerMap, Caller, CalleeMap, Callee);
checkAVXParam(CGM.getDiags(), CGM.getContext(), CallLoc, CallerMap,
CalleeMap, Callee->getReturnType(),
/*IsArgument*/ false);
}
}
static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
// If the argument does not end in .lib, automatically add the suffix.
// If the argument contains a space, enclose it in quotes.
// This matches the behavior of MSVC.
bool Quote = Lib.contains(' ');
std::string ArgStr = Quote ? "\"" : "";
ArgStr += Lib;
if (!Lib.endswith_insensitive(".lib") && !Lib.endswith_insensitive(".a"))
ArgStr += ".lib";
ArgStr += Quote ? "\"" : "";
return ArgStr;
}
class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
public:
WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
bool DarwinVectorABI, bool RetSmallStructInRegABI, bool Win32StructABI,
unsigned NumRegisterParameters)
: X86_32TargetCodeGenInfo(CGT, DarwinVectorABI, RetSmallStructInRegABI,
Win32StructABI, NumRegisterParameters, false) {}
void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
CodeGen::CodeGenModule &CGM) const override;
void getDependentLibraryOption(llvm::StringRef Lib,
llvm::SmallString<24> &Opt) const override {
Opt = "/DEFAULTLIB:";
Opt += qualifyWindowsLibrary(Lib);
}
void getDetectMismatchOption(llvm::StringRef Name,
llvm::StringRef Value,
llvm::SmallString<32> &Opt) const override {
Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
}
};
static void addStackProbeTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
CodeGen::CodeGenModule &CGM) {
if (llvm::Function *Fn = dyn_cast_or_null<llvm::Function>(GV)) {
if (CGM.getCodeGenOpts().StackProbeSize != 4096)
Fn->addFnAttr("stack-probe-size",
llvm::utostr(CGM.getCodeGenOpts().StackProbeSize));
if (CGM.getCodeGenOpts().NoStackArgProbe)
Fn->addFnAttr("no-stack-arg-probe");
}
}
void WinX86_32TargetCodeGenInfo::setTargetAttributes(
const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
X86_32TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
if (GV->isDeclaration())
return;
addStackProbeTargetAttributes(D, GV, CGM);
}
class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
public:
WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
X86AVXABILevel AVXLevel)
: TargetCodeGenInfo(std::make_unique<WinX86_64ABIInfo>(CGT, AVXLevel)) {}
void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
CodeGen::CodeGenModule &CGM) const override;
int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
return 7;
}
bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
llvm::Value *Address) const override {
llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
// 0-15 are the 16 integer registers.
// 16 is %rip.
AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
return false;
}
void getDependentLibraryOption(llvm::StringRef Lib,
llvm::SmallString<24> &Opt) const override {
Opt = "/DEFAULTLIB:";
Opt += qualifyWindowsLibrary(Lib);
}
void getDetectMismatchOption(llvm::StringRef Name,
llvm::StringRef Value,
llvm::SmallString<32> &Opt) const override {
Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
}
};
void WinX86_64TargetCodeGenInfo::setTargetAttributes(
const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
if (GV->isDeclaration())
return;
if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
llvm::Function *Fn = cast<llvm::Function>(GV);
Fn->addFnAttr("stackrealign");
}
addX86InterruptAttrs(FD, GV, CGM);
}
addStackProbeTargetAttributes(D, GV, CGM);
}
}
void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
Class &Hi) const {
// AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
//
// (a) If one of the classes is Memory, the whole argument is passed in
// memory.
//
// (b) If X87UP is not preceded by X87, the whole argument is passed in
// memory.
//
// (c) If the size of the aggregate exceeds two eightbytes and the first
// eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
// argument is passed in memory. NOTE: This is necessary to keep the
// ABI working for processors that don't support the __m256 type.
//
// (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
//
// Some of these are enforced by the merging logic. Others can arise
// only with unions; for example:
// union { _Complex double; unsigned; }
//
// Note that clauses (b) and (c) were added in 0.98.
//
if (Hi == Memory)
Lo = Memory;
if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
Lo = Memory;
if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
Lo = Memory;
if (Hi == SSEUp && Lo != SSE)
Hi = SSE;
}
X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
// AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
// classified recursively so that always two fields are
// considered. The resulting class is calculated according to
// the classes of the fields in the eightbyte:
//
// (a) If both classes are equal, this is the resulting class.
//
// (b) If one of the classes is NO_CLASS, the resulting class is
// the other class.
//
// (c) If one of the classes is MEMORY, the result is the MEMORY
// class.
//
// (d) If one of the classes is INTEGER, the result is the
// INTEGER.
//
// (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
// MEMORY is used as class.
//
// (f) Otherwise class SSE is used.
// Accum should never be memory (we should have returned) or
// ComplexX87 (because this cannot be passed in a structure).
assert((Accum != Memory && Accum != ComplexX87) &&
"Invalid accumulated classification during merge.");
if (Accum == Field || Field == NoClass)
return Accum;
if (Field == Memory)
return Memory;
if (Accum == NoClass)
return Field;
if (Accum == Integer || Field == Integer)
return Integer;
if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
Accum == X87 || Accum == X87Up)
return Memory;
return SSE;
}
void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
Class &Lo, Class &Hi, bool isNamedArg) const {
// FIXME: This code can be simplified by introducing a simple value class for
// Class pairs with appropriate constructor methods for the various
// situations.
// FIXME: Some of the split computations are wrong; unaligned vectors
// shouldn't be passed in registers for example, so there is no chance they
// can straddle an eightbyte. Verify & simplify.
Lo = Hi = NoClass;
Class &Current = OffsetBase < 64 ? Lo : Hi;
Current = Memory;
if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
BuiltinType::Kind k = BT->getKind();
if (k == BuiltinType::Void) {
Current = NoClass;
} else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
Lo = Integer;
Hi = Integer;
} else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
Current = Integer;
} else if (k == BuiltinType::Float || k == BuiltinType::Double ||
k == BuiltinType::Float16) {
Current = SSE;
} else if (k == BuiltinType::LongDouble) {
const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
if (LDF == &llvm::APFloat::IEEEquad()) {
Lo = SSE;
Hi = SSEUp;
} else if (LDF == &llvm::APFloat::x87DoubleExtended()) {
Lo = X87;
Hi = X87Up;
} else if (LDF == &llvm::APFloat::IEEEdouble()) {
Current = SSE;
} else
llvm_unreachable("unexpected long double representation!");
}
// FIXME: _Decimal32 and _Decimal64 are SSE.
// FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
return;
}
if (const EnumType *ET = Ty->getAs<EnumType>()) {
// Classify the underlying integer type.
classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
return;
}
if (Ty->hasPointerRepresentation()) {
Current = Integer;
return;
}
if (Ty->isMemberPointerType()) {
if (Ty->isMemberFunctionPointerType()) {
if (Has64BitPointers) {
// If Has64BitPointers, this is an {i64, i64}, so classify both
// Lo and Hi now.
Lo = Hi = Integer;
} else {
// Otherwise, with 32-bit pointers, this is an {i32, i32}. If that
// straddles an eightbyte boundary, Hi should be classified as well.
uint64_t EB_FuncPtr = (OffsetBase) / 64;
uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64;
if (EB_FuncPtr != EB_ThisAdj) {
Lo = Hi = Integer;
} else {
Current = Integer;
}
}
} else {
Current = Integer;
}
return;
}
if (const VectorType *VT = Ty->getAs<VectorType>()) {
uint64_t Size = getContext().getTypeSize(VT);
if (Size == 1 || Size == 8 || Size == 16 || Size == 32) {
// gcc passes the following as integer:
// 4 bytes - <4 x char>, <2 x short>, <1 x int>, <1 x float>
// 2 bytes - <2 x char>, <1 x short>
// 1 byte - <1 x char>
Current = Integer;
// If this type crosses an eightbyte boundary, it should be
// split.
uint64_t EB_Lo = (OffsetBase) / 64;
uint64_t EB_Hi = (OffsetBase + Size - 1) / 64;
if (EB_Lo != EB_Hi)
Hi = Lo;
} else if (Size == 64) {
QualType ElementType = VT->getElementType();
// gcc passes <1 x double> in memory. :(
if (ElementType->isSpecificBuiltinType(BuiltinType::Double))
return;
// gcc passes <1 x long long> as SSE but clang used to unconditionally
// pass them as integer. For platforms where clang is the de facto
// platform compiler, we must continue to use integer.
if (!classifyIntegerMMXAsSSE() &&
(ElementType->isSpecificBuiltinType(BuiltinType::LongLong) ||
ElementType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
ElementType->isSpecificBuiltinType(BuiltinType::Long) ||
ElementType->isSpecificBuiltinType(BuiltinType::ULong)))
Current = Integer;
else
Current = SSE;
// If this type crosses an eightbyte boundary, it should be
// split.
if (OffsetBase && OffsetBase != 64)
Hi = Lo;
} else if (Size == 128 ||
(isNamedArg && Size <= getNativeVectorSizeForAVXABI(AVXLevel))) {
QualType ElementType = VT->getElementType();
// gcc passes 256 and 512 bit <X x __int128> vectors in memory. :(
if (passInt128VectorsInMem() && Size != 128 &&
(ElementType->isSpecificBuiltinType(BuiltinType::Int128) ||
ElementType->isSpecificBuiltinType(BuiltinType::UInt128)))
return;
// Arguments of 256-bits are split into four eightbyte chunks. The
// least significant one belongs to class SSE and all the others to class
// SSEUP. The original Lo and Hi design considers that types can't be
// greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
// This design isn't correct for 256-bits, but since there're no cases
// where the upper parts would need to be inspected, avoid adding
// complexity and just consider Hi to match the 64-256 part.
//
// Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
// registers if they are "named", i.e. not part of the "..." of a
// variadic function.
//
// Similarly, per 3.2.3. of the AVX512 draft, 512-bits ("named") args are
// split into eight eightbyte chunks, one SSE and seven SSEUP.
Lo = SSE;
Hi = SSEUp;
}
return;
}
if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
QualType ET = getContext().getCanonicalType(CT->getElementType());
uint64_t Size = getContext().getTypeSize(Ty);
if (ET->isIntegralOrEnumerationType()) {
if (Size <= 64)
Current = Integer;
else if (Size <= 128)
Lo = Hi = Integer;
} else if (ET->isFloat16Type() || ET == getContext().FloatTy) {
Current = SSE;
} else if (ET == getContext().DoubleTy) {
Lo = Hi = SSE;
} else if (ET == getContext().LongDoubleTy) {
const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
if (LDF == &llvm::APFloat::IEEEquad())
Current = Memory;
else if (LDF == &llvm::APFloat::x87DoubleExtended())
Current = ComplexX87;
else if (LDF == &llvm::APFloat::IEEEdouble())
Lo = Hi = SSE;
else
llvm_unreachable("unexpected long double representation!");
}
// If this complex type crosses an eightbyte boundary then it
// should be split.
uint64_t EB_Real = (OffsetBase) / 64;
uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
if (Hi == NoClass && EB_Real != EB_Imag)
Hi = Lo;
return;
}
if (const auto *EITy = Ty->getAs<ExtIntType>()) {
if (EITy->getNumBits() <= 64)
Current = Integer;
else if (EITy->getNumBits() <= 128)
Lo = Hi = Integer;
// Larger values need to get passed in memory.
return;
}
if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
// Arrays are treated like structures.
uint64_t Size = getContext().getTypeSize(Ty);
// AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
// than eight eightbytes, ..., it has class MEMORY.
if (Size > 512)
return;
// AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
// fields, it has class MEMORY.
//
// Only need to check alignment of array base.
if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
return;
// Otherwise implement simplified merge. We could be smarter about
// this, but it isn't worth it and would be harder to verify.
Current = NoClass;
uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
uint64_t ArraySize = AT->getSize().getZExtValue();
// The only case a 256-bit wide vector could be used is when the array
// contains a single 256-bit element. Since Lo and Hi logic isn't extended
// to work for sizes wider than 128, early check and fallback to memory.
//
if (Size > 128 &&
(Size != EltSize || Size > getNativeVectorSizeForAVXABI(AVXLevel)))
return;
for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
Class FieldLo, FieldHi;
classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
Lo = merge(Lo, FieldLo);
Hi = merge(Hi, FieldHi);
if (Lo == Memory || Hi == Memory)
break;
}
postMerge(Size, Lo, Hi);
assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
return;
}
if (const RecordType *RT = Ty->getAs<RecordType>()) {
uint64_t Size = getContext().getTypeSize(Ty);
// AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
// than eight eightbytes, ..., it has class MEMORY.
if (Size > 512)
return;
// AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
// copy constructor or a non-trivial destructor, it is passed by invisible
// reference.
if (getRecordArgABI(RT, getCXXABI()))
return;
const RecordDecl *RD = RT->getDecl();
// Assume variable sized types are passed in memory.
if (RD->hasFlexibleArrayMember())
return;
const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
// Reset Lo class, this will be recomputed.
Current = NoClass;
// If this is a C++ record, classify the bases first.
if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
for (const auto &I : CXXRD->bases()) {
assert(!I.isVirtual() && !I.getType()->isDependentType() &&
"Unexpected base class!");
const auto *Base =
cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
// Classify this field.
//
// AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
// single eightbyte, each is classified separately. Each eightbyte gets
// initialized to class NO_CLASS.
Class FieldLo, FieldHi;
uint64_t Offset =
OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
Lo = merge(Lo, FieldLo);
Hi = merge(Hi, FieldHi);
if (Lo == Memory || Hi == Memory) {
postMerge(Size, Lo, Hi);
return;
}
}
}
// Classify the fields one at a time, merging the results.
unsigned idx = 0;
bool UseClang11Compat = getContext().getLangOpts().getClangABICompat() <=
LangOptions::ClangABI::Ver11 ||
getContext().getTargetInfo().getTriple().isPS4();
bool IsUnion = RT->isUnionType() && !UseClang11Compat;
for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
i != e; ++i, ++idx) {
uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
bool BitField = i->isBitField();
// Ignore padding bit-fields.
if (BitField && i->isUnnamedBitfield())
continue;
// AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
// eight eightbytes, or it contains unaligned fields, it has class MEMORY.
//
// The only case a 256-bit or a 512-bit wide vector could be used is when
// the struct contains a single 256-bit or 512-bit element. Early check
// and fallback to memory.
//
// FIXME: Extended the Lo and Hi logic properly to work for size wider
// than 128.
if (Size > 128 &&
((!IsUnion && Size != getContext().getTypeSize(i->getType())) ||
Size > getNativeVectorSizeForAVXABI(AVXLevel))) {
Lo = Memory;
postMerge(Size, Lo, Hi);
return;
}
// Note, skip this test for bit-fields, see below.
if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
Lo = Memory;
postMerge(Size, Lo, Hi);
return;
}
// Classify this field.
//
// AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
// exceeds a single eightbyte, each is classified
// separately. Each eightbyte gets initialized to class
// NO_CLASS.
Class FieldLo, FieldHi;
// Bit-fields require special handling, they do not force the
// structure to be passed in memory even if unaligned, and
// therefore they can straddle an eightbyte.
if (BitField) {
assert(!i->isUnnamedBitfield());
uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
uint64_t Size = i->getBitWidthValue(getContext());
uint64_t EB_Lo = Offset / 64;
uint64_t EB_Hi = (Offset + Size - 1) / 64;
if (EB_Lo) {
assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
FieldLo = NoClass;
FieldHi = Integer;
} else {
FieldLo = Integer;
FieldHi = EB_Hi ? Integer : NoClass;
}
} else
classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
Lo = merge(Lo, FieldLo);
Hi = merge(Hi, FieldHi);
if (Lo == Memory || Hi == Memory)
break;
}
postMerge(Size, Lo, Hi);
}
}
ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
// If this is a scalar LLVM value then assume LLVM will pass it in the right
// place naturally.
if (!isAggregateTypeForABI(Ty)) {
// Treat an enum type as its underlying type.
if (const EnumType *EnumTy = Ty->getAs<EnumType>())
Ty = EnumTy->getDecl()->getIntegerType();
if (Ty->isExtIntType())
return getNaturalAlignIndirect(Ty);
return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
: ABIArgInfo::getDirect());
}
return getNaturalAlignIndirect(Ty);
}
bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
uint64_t Size = getContext().getTypeSize(VecTy);
unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel);
if (Size <= 64 || Size > LargestVector)
return true;
QualType EltTy = VecTy->getElementType();
if (passInt128VectorsInMem() &&
(EltTy->isSpecificBuiltinType(BuiltinType::Int128) ||
EltTy->isSpecificBuiltinType(BuiltinType::UInt128)))
return true;
}
return false;
}
ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
unsigned freeIntRegs) const {
// If this is a scalar LLVM value then assume LLVM will pass it in the right
// place naturally.
//
// This assumption is optimistic, as there could be free registers available
// when we need to pass this argument in memory, and LLVM could try to pass
// the argument in the free register. This does not seem to happen currently,
// but this code would be much safer if we could mark the argument with
// 'onstack'. See PR12193.
if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty) &&
!Ty->isExtIntType()) {
// Treat an enum type as its underlying type.
if (const EnumType *EnumTy = Ty->getAs<EnumType>())
Ty = EnumTy->getDecl()->getIntegerType();
return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
: ABIArgInfo::getDirect());
}
if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
// Compute the byval alignment. We specify the alignment of the byval in all
// cases so that the mid-level optimizer knows the alignment of the byval.
unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
// Attempt to avoid passing indirect results using byval when possible. This
// is important for good codegen.
//
// We do this by coercing the value into a scalar type which the backend can
// handle naturally (i.e., without using byval).
//
// For simplicity, we currently only do this when we have exhausted all of the
// free integer registers. Doing this when there are free integer registers
// would require more care, as we would have to ensure that the coerced value
// did not claim the unused register. That would require either reording the
// arguments to the function (so that any subsequent inreg values came first),
// or only doing this optimization when there were no following arguments that
// might be inreg.
//
// We currently expect it to be rare (particularly in well written code) for
// arguments to be passed on the stack when there are still free integer
// registers available (this would typically imply large structs being passed
// by value), so this seems like a fair tradeoff for now.
//
// We can revisit this if the backend grows support for 'onstack' parameter
// attributes. See PR12193.
if (freeIntRegs == 0) {
uint64_t Size = getContext().getTypeSize(Ty);
// If this type fits in an eightbyte, coerce it into the matching integral
// type, which will end up on the stack (with alignment 8).
if (Align == 8 && Size <= 64)
return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Size));
}
return ABIArgInfo::getIndirect(CharUnits::fromQuantity(Align));
}
/// The ABI specifies that a value should be passed in a full vector XMM/YMM
/// register. Pick an LLVM IR type that will be passed as a vector register.
llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
// Wrapper structs/arrays that only contain vectors are passed just like
// vectors; strip them off if present.
if (const Type *InnerTy = isSingleElementStruct(Ty, getContext()))
Ty = QualType(InnerTy, 0);
llvm::Type *IRType = CGT.ConvertType(Ty);
if (isa<llvm::VectorType>(IRType)) {
// Don't pass vXi128 vectors in their native type, the backend can't
// legalize them.
if (passInt128VectorsInMem() &&
cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy(128)) {
// Use a vXi64 vector.
uint64_t Size = getContext().getTypeSize(Ty);
return llvm::FixedVectorType::get(llvm::Type::getInt64Ty(getVMContext()),
Size / 64);
}
return IRType;
}
if (IRType->getTypeID() == llvm::Type::FP128TyID)
return IRType;
// We couldn't find the preferred IR vector type for 'Ty'.
uint64_t Size = getContext().getTypeSize(Ty);
assert((Size == 128 || Size == 256 || Size == 512) && "Invalid type found!");
// Return a LLVM IR vector type based on the size of 'Ty'.
return llvm::FixedVectorType::get(llvm::Type::getDoubleTy(getVMContext()),
Size / 64);
}
/// BitsContainNoUserData - Return true if the specified [start,end) bit range
/// is known to either be off the end of the specified type or being in
/// alignment padding. The user type specified is known to be at most 128 bits
/// in size, and have passed through X86_64ABIInfo::classify with a successful
/// classification that put one of the two halves in the INTEGER class.
///
/// It is conservatively correct to return false.
static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
unsigned EndBit, ASTContext &Context) {
// If the bytes being queried are off the end of the type, there is no user
// data hiding here. This handles analysis of builtins, vectors and other
// types that don't contain interesting padding.
unsigned TySize = (unsigned)Context.getTypeSize(Ty);
if (TySize <= StartBit)
return true;
if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
// Check each element to see if the element overlaps with the queried range.
for (unsigned i = 0; i != NumElts; ++i) {
// If the element is after the span we care about, then we're done..
unsigned EltOffset = i*EltSize;
if (EltOffset >= EndBit) break;
unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
if (!BitsContainNoUserData(AT->getElementType(), EltStart,
EndBit-EltOffset, Context))
return false;
}
// If it overlaps no elements, then it is safe to process as padding.
return true;
}
if (const RecordType *RT = Ty->getAs<RecordType>()) {
const RecordDecl *RD = RT->getDecl();
const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
// If this is a C++ record, check the bases first.
if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
for (const auto &I : CXXRD->bases()) {
assert(!I.isVirtual() && !I.getType()->isDependentType() &&
"Unexpected base class!");
const auto *Base =
cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
// If the base is after the span we care about, ignore it.
unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
if (BaseOffset >= EndBit) continue;
unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
if (!BitsContainNoUserData(I.getType(), BaseStart,
EndBit-BaseOffset, Context))
return false;
}
}
// Verify that no field has data that overlaps the region of interest. Yes
// this could be sped up a lot by being smarter about queried fields,
// however we're only looking at structs up to 16 bytes, so we don't care
// much.
unsigned idx = 0;
for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
i != e; ++i, ++idx) {
unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
// If we found a field after the region we care about, then we're done.
if (FieldOffset >= EndBit) break;
unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
Context))
return false;
}
// If nothing in this record overlapped the area of interest, then we're
// clean.
return true;
}
return false;
}
/// getFPTypeAtOffset - Return a floating point type at the specified offset.
static llvm::Type *getFPTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
const llvm::DataLayout &TD) {
if (IROffset == 0 && IRType->isFloatingPointTy())
return IRType;
// If this is a struct, recurse into the field at the specified offset.
if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
if (!STy->getNumContainedTypes())
return nullptr;
const llvm::StructLayout *SL = TD.getStructLayout(STy);
unsigned Elt = SL->getElementContainingOffset(IROffset);
IROffset -= SL->getElementOffset(Elt);
return getFPTypeAtOffset(STy->getElementType(Elt), IROffset, TD);
}
// If this is an array, recurse into the field at the specified offset.
if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
llvm::Type *EltTy = ATy->getElementType();
unsigned EltSize = TD.getTypeAllocSize(EltTy);
IROffset -= IROffset / EltSize * EltSize;
return getFPTypeAtOffset(EltTy, IROffset, TD);
}
return nullptr;
}
/// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
/// low 8 bytes of an XMM register, corresponding to the SSE class.
llvm::Type *X86_64ABIInfo::
GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
QualType SourceTy, unsigned SourceOffset) const {
const llvm::DataLayout &TD = getDataLayout();
unsigned SourceSize =
(unsigned)getContext().getTypeSize(SourceTy) / 8 - SourceOffset;
llvm::Type *T0 = getFPTypeAtOffset(IRType, IROffset, TD);
if (!T0 || T0->isDoubleTy())
return llvm::Type::getDoubleTy(getVMContext());
// Get the adjacent FP type.
llvm::Type *T1 = nullptr;
unsigned T0Size = TD.getTypeAllocSize(T0);
if (SourceSize > T0Size)
T1 = getFPTypeAtOffset(IRType, IROffset + T0Size, TD);
if (T1 == nullptr) {
// Check if IRType is a half + float. float type will be in IROffset+4 due
// to its alignment.
if (T0->isHalfTy() && SourceSize > 4)
T1 = getFPTypeAtOffset(IRType, IROffset + 4, TD);
// If we can't get a second FP type, return a simple half or float.
// avx512fp16-abi.c:pr51813_2 shows it works to return float for
// {float, i8} too.
if (T1 == nullptr)
return T0;
}
if (T0->isFloatTy() && T1->isFloatTy())
return llvm::FixedVectorType::get(T0, 2);
if (T0->isHalfTy() && T1->isHalfTy()) {
llvm::Type *T2 = nullptr;
if (SourceSize > 4)
T2 = getFPTypeAtOffset(IRType, IROffset + 4, TD);
if (T2 == nullptr)
return llvm::FixedVectorType::get(T0, 2);
return llvm::FixedVectorType::get(T0, 4);
}
if (T0->isHalfTy() || T1->isHalfTy())
return llvm::FixedVectorType::get(llvm::Type::getHalfTy(getVMContext()), 4);
return llvm::Type::getDoubleTy(getVMContext());
}
/// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
/// an 8-byte GPR. This means that we either have a scalar or we are talking
/// about the high or low part of an up-to-16-byte struct. This routine picks
/// the best LLVM IR type to represent this, which may be i64 or may be anything
/// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
/// etc).
///
/// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
/// the source type. IROffset is an offset in bytes into the LLVM IR type that
/// the 8-byte value references. PrefType may be null.
///
/// SourceTy is the source-level type for the entire argument. SourceOffset is
/// an offset into this that we're processing (which is always either 0 or 8).
///
llvm::Type *X86_64ABIInfo::
GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
QualType SourceTy, unsigned SourceOffset) const {
// If we're dealing with an un-offset LLVM IR type, then it means that we're
// returning an 8-byte unit starting with it. See if we can safely use it.
if (IROffset == 0) {
// Pointers and int64's always fill the 8-byte unit.
if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
IRType->isIntegerTy(64))
return IRType;
// If we have a 1/2/4-byte integer, we can use it only if the rest of the
// goodness in the source type is just tail padding. This is allowed to
// kick in for struct {double,int} on the int, but not on
// struct{double,int,int} because we wouldn't return the second int. We
// have to do this analysis on the source type because we can't depend on
// unions being lowered a specific way etc.
if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
IRType->isIntegerTy(32) ||
(isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
cast<llvm::IntegerType>(IRType)->getBitWidth();
if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
SourceOffset*8+64, getContext()))
return IRType;
}
}
if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
// If this is a struct, recurse into the field at the specified offset.
const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
if (IROffset < SL->getSizeInBytes()) {
unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
IROffset -= SL->getElementOffset(FieldIdx);
return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
SourceTy, SourceOffset);
}
}
if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
llvm::Type *EltTy = ATy->getElementType();
unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
unsigned EltOffset = IROffset/EltSize*EltSize;
return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
SourceOffset);
}
// Okay, we don't have any better idea of what to pass, so we pass this in an
// integer register that isn't too big to fit the rest of the struct.
unsigned TySizeInBytes =
(unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
assert(TySizeInBytes != SourceOffset && "Empty field?");
// It is always safe to classify this as an integer type up to i64 that
// isn't larger than the structure.
return llvm::IntegerType::get(getVMContext(),
std::min(TySizeInBytes-SourceOffset, 8U)*8);
}
/// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
/// be used as elements of a two register pair to pass or return, return a
/// first class aggregate to represent them. For example, if the low part of
/// a by-value argument should be passed as i32* and the high part as float,
/// return {i32*, float}.
static llvm::Type *
GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
const llvm::DataLayout &TD) {
// In order to correctly satisfy the ABI, we need to the high part to start
// at offset 8. If the high and low parts we inferred are both 4-byte types
// (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
// the second element at offset 8. Check for this:
unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
unsigned HiAlign = TD.getABITypeAlignment(Hi);
unsigned HiStart = llvm::alignTo(LoSize, HiAlign);
assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
// To handle this, we have to increase the size of the low part so that the
// second element will start at an 8 byte offset. We can't increase the size
// of the second element because it might make us access off the end of the
// struct.
if (HiStart != 8) {
// There are usually two sorts of types the ABI generation code can produce
// for the low part of a pair that aren't 8 bytes in size: half, float or
// i8/i16/i32. This can also include pointers when they are 32-bit (X32 and
// NaCl).
// Promote these to a larger type.
if (Lo->isHalfTy() || Lo->isFloatTy())
Lo = llvm::Type::getDoubleTy(Lo->getContext());
else {
assert((Lo->isIntegerTy() || Lo->isPointerTy())
&& "Invalid/unknown lo type");
Lo = llvm::Type::getInt64Ty(Lo->getContext());
}
}
llvm::StructType *Result = llvm::StructType::get(Lo, Hi);
// Verify that the second element is at an 8-byte offset.
assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
"Invalid x86-64 argument pair!");
return Result;
}
ABIArgInfo X86_64ABIInfo::
classifyReturnType(QualType RetTy) const {
// AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
// classification algorithm.
X86_64ABIInfo::Class Lo, Hi;
classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
// Check some invariants.
assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
llvm::Type *ResType = nullptr;
switch (Lo) {
case NoClass:
if (Hi == NoClass)
return ABIArgInfo::getIgnore();
// If the low part is just padding, it takes no register, leave ResType
// null.
assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
"Unknown missing lo part");
break;
case SSEUp:
case X87Up:
llvm_unreachable("Invalid classification for lo word.");
// AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
// hidden argument.
case Memory:
return getIndirectReturnResult(RetTy);
// AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
// available register of the sequence %rax, %rdx is used.
case Integer:
ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
// If we have a sign or zero extended integer, make sure to return Extend
// so that the parameter gets the right LLVM IR attributes.
if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
// Treat an enum type as its underlying type.
if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
RetTy = EnumTy->getDecl()->getIntegerType();
if (RetTy->isIntegralOrEnumerationType() &&
isPromotableIntegerTypeForABI(RetTy))
return ABIArgInfo::getExtend(RetTy);
}
break;
// AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
// available SSE register of the sequence %xmm0, %xmm1 is used.
case SSE:
ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
break;
// AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
// returned on the X87 stack in %st0 as 80-bit x87 number.
case X87:
ResType = llvm::Type::getX86_FP80Ty(getVMContext());
break;
// AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
// part of the value is returned in %st0 and the imaginary part in
// %st1.
case ComplexX87:
assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
llvm::Type::getX86_FP80Ty(getVMContext()));
break;
}
llvm::Type *HighPart = nullptr;
switch (Hi) {
// Memory was handled previously and X87 should
// never occur as a hi class.
case Memory:
case X87:
llvm_unreachable("Invalid classification for hi word.");
case ComplexX87: // Previously handled.
case NoClass:
break;
case Integer:
HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
if (Lo == NoClass) // Return HighPart at offset 8 in memory.
return ABIArgInfo::getDirect(HighPart, 8);
break;
case SSE:
HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
if (Lo == NoClass) // Return HighPart at offset 8 in memory.
return ABIArgInfo::getDirect(HighPart, 8);
break;
// AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
// is passed in the next available eightbyte chunk if the last used
// vector register.
//
// SSEUP should always be preceded by SSE, just widen.
case SSEUp:
assert(Lo == SSE && "Unexpected SSEUp classification.");
ResType = GetByteVectorType(RetTy);
break;
// AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
// returned together with the previous X87 value in %st0.
case X87Up:
// If X87Up is preceded by X87, we don't need to do
// anything. However, in some cases with unions it may not be
// preceded by X87. In such situations we follow gcc and pass the
// extra bits in an SSE reg.
if (Lo != X87) {
HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
if (Lo == NoClass) // Return HighPart at offset 8 in memory.
return ABIArgInfo::getDirect(HighPart, 8);
}
break;
}
// If a high part was specified, merge it together with the low part. It is
// known to pass in the high eightbyte of the result. We do this by forming a
// first class struct aggregate with the high and low part: {low, high}
if (HighPart)
ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
return ABIArgInfo::getDirect(ResType);
}
ABIArgInfo X86_64ABIInfo::classifyArgumentType(
QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
bool isNamedArg)
const
{
Ty = useFirstFieldIfTransparentUnion(Ty);
X86_64ABIInfo::Class Lo, Hi;
classify(Ty, 0, Lo, Hi, isNamedArg);
// Check some invariants.
// FIXME: Enforce these by construction.
assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
neededInt = 0;
neededSSE = 0;
llvm::Type *ResType = nullptr;
switch (Lo) {
case NoClass:
if (Hi == NoClass)
return ABIArgInfo::getIgnore();
// If the low part is just padding, it takes no register, leave ResType
// null.
assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
"Unknown missing lo part");
break;
// AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
// on the stack.
case Memory:
// AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
// COMPLEX_X87, it is passed in memory.
case X87:
case ComplexX87:
if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
++neededInt;
return getIndirectResult(Ty, freeIntRegs);
case SSEUp:
case X87Up:
llvm_unreachable("Invalid classification for lo word.");
// AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
// available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
// and %r9 is used.
case Integer:
++neededInt;
// Pick an 8-byte type based on the preferred type.
ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
// If we have a sign or zero extended integer, make sure to return Extend
// so that the parameter gets the right LLVM IR attributes.
if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
// Treat an enum type as its underlying type.
if (const EnumType *EnumTy = Ty->getAs<EnumType>())
Ty = EnumTy->getDecl()->getIntegerType();
if (Ty->isIntegralOrEnumerationType() &&
isPromotableIntegerTypeForABI(Ty))
return ABIArgInfo::getExtend(Ty);
}
break;
// AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
// available SSE register is used, the registers are taken in the
// order from %xmm0 to %xmm7.
case SSE: {
llvm::Type *IRType = CGT.ConvertType(Ty);
ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
++neededSSE;
break;
}
}
llvm::Type *HighPart = nullptr;
switch (Hi) {
// Memory was handled previously, ComplexX87 and X87 should
// never occur as hi classes, and X87Up must be preceded by X87,
// which is passed in memory.
case Memory:
case X87:
case ComplexX87:
llvm_unreachable("Invalid classification for hi word.");
case NoClass: break;
case Integer:
++neededInt;
// Pick an 8-byte type based on the preferred type.
HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
return ABIArgInfo::getDirect(HighPart, 8);
break;
// X87Up generally doesn't occur here (long double is passed in
// memory), except in situations involving unions.
case X87Up:
case SSE:
HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
return ABIArgInfo::getDirect(HighPart, 8);
++neededSSE;
break;
// AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
// eightbyte is passed in the upper half of the last used SSE
// register. This only happens when 128-bit vectors are passed.
case SSEUp:
assert(Lo == SSE && "Unexpected SSEUp classification");
ResType = GetByteVectorType(Ty);
break;
}
// If a high part was specified, merge it together with the low part. It is
// known to pass in the high eightbyte of the result. We do this by forming a
// first class struct aggregate with the high and low part: {low, high}
if (HighPart)
ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
return ABIArgInfo::getDirect(ResType);
}
ABIArgInfo
X86_64ABIInfo::classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
unsigned &NeededSSE) const {
auto RT = Ty->getAs<RecordType>();
assert(RT && "classifyRegCallStructType only valid with struct types");
if (RT->getDecl()->hasFlexibleArrayMember())
return getIndirectReturnResult(Ty);
// Sum up bases
if (auto CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
if (CXXRD->isDynamicClass()) {
NeededInt = NeededSSE = 0;
return getIndirectReturnResult(Ty);
}
for (const auto &I : CXXRD->bases())
if (classifyRegCallStructTypeImpl(I.getType(), NeededInt, NeededSSE)
.isIndirect()) {
NeededInt = NeededSSE = 0;
return getIndirectReturnResult(Ty);
}
}
// Sum up members
for (const auto *FD : RT->getDecl()->fields()) {
if (FD->getType()->isRecordType() && !FD->getType()->isUnionType()) {
if (classifyRegCallStructTypeImpl(FD->getType(), NeededInt, NeededSSE)
.isIndirect()) {
NeededInt = NeededSSE = 0;
return getIndirectReturnResult(Ty);
}
} else {
unsigned LocalNeededInt, LocalNeededSSE;
if (classifyArgumentType(FD->getType(), UINT_MAX, LocalNeededInt,
LocalNeededSSE, true)
.isIndirect()) {
NeededInt = NeededSSE = 0;
return getIndirectReturnResult(Ty);
}
NeededInt += LocalNeededInt;
NeededSSE += LocalNeededSSE;
}
}
return ABIArgInfo::getDirect();
}
ABIArgInfo X86_64ABIInfo::classifyRegCallStructType(QualType Ty,
unsigned &NeededInt,
unsigned &NeededSSE) const {
NeededInt = 0;
NeededSSE = 0;
return classifyRegCallStructTypeImpl(Ty, NeededInt, NeededSSE);
}
void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
const unsigned CallingConv = FI.getCallingConvention();
// It is possible to force Win64 calling convention on any x86_64 target by
// using __attribute__((ms_abi)). In such case to correctly emit Win64
// compatible code delegate this call to WinX86_64ABIInfo::computeInfo.
if (CallingConv == llvm::CallingConv::Win64) {
WinX86_64ABIInfo Win64ABIInfo(CGT, AVXLevel);
Win64ABIInfo.computeInfo(FI);
return;
}
bool IsRegCall = CallingConv == llvm::CallingConv::X86_RegCall;
// Keep track of the number of assigned registers.
unsigned FreeIntRegs = IsRegCall ? 11 : 6;
unsigned FreeSSERegs = IsRegCall ? 16 : 8;
unsigned NeededInt, NeededSSE;
if (!::classifyReturnType(getCXXABI(), FI, *this)) {
if (IsRegCall && FI.getReturnType()->getTypePtr()->isRecordType() &&
!FI.getReturnType()->getTypePtr()->isUnionType()) {
FI.getReturnInfo() =
classifyRegCallStructType(FI.getReturnType(), NeededInt, NeededSSE);
if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
FreeIntRegs -= NeededInt;
FreeSSERegs -= NeededSSE;
} else {
FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
}
} else if (IsRegCall && FI.getReturnType()->getAs<ComplexType>() &&
getContext().getCanonicalType(FI.getReturnType()
->getAs<ComplexType>()
->getElementType()) ==
getContext().LongDoubleTy)
// Complex Long Double Type is passed in Memory when Regcall
// calling convention is used.
FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
else
FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
}
// If the return value is indirect, then the hidden argument is consuming one
// integer register.
if (FI.getReturnInfo().isIndirect())
--FreeIntRegs;
// The chain argument effectively gives us another free register.
if (FI.isChainCall())
++FreeIntRegs;
unsigned NumRequiredArgs = FI.getNumRequiredArgs();
// AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
// get assigned (in left-to-right order) for passing as follows...
unsigned ArgNo = 0;
for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
it != ie; ++it, ++ArgNo) {
bool IsNamedArg = ArgNo < NumRequiredArgs;
if (IsRegCall && it->type->isStructureOrClassType())
it->info = classifyRegCallStructType(it->type, NeededInt, NeededSSE);
else
it->info = classifyArgumentType(it->type, FreeIntRegs, NeededInt,
NeededSSE, IsNamedArg);
// AMD64-ABI 3.2.3p3: If there are no registers available for any
// eightbyte of an argument, the whole argument is passed on the
// stack. If registers have already been assigned for some
// eightbytes of such an argument, the assignments get reverted.
if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
FreeIntRegs -= NeededInt;
FreeSSERegs -= NeededSSE;
} else {
it->info = getIndirectResult(it->type, FreeIntRegs);
}
}
}
static Address EmitX86_64VAArgFromMemory(CodeGenFunction &CGF,
Address VAListAddr, QualType Ty) {
Address overflow_arg_area_p =
CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_p");
llvm::Value *overflow_arg_area =
CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
// AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
// byte boundary if alignment needed by type exceeds 8 byte boundary.
// It isn't stated explicitly in the standard, but in practice we use
// alignment greater than 16 where necessary.
CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
if (Align > CharUnits::fromQuantity(8)) {
overflow_arg_area = emitRoundPointerUpToAlignment(CGF, overflow_arg_area,
Align);
}
// AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
llvm::Value *Res =
CGF.Builder.CreateBitCast(overflow_arg_area,
llvm::PointerType::getUnqual(LTy));
// AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
// l->overflow_arg_area + sizeof(type).
// AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
// an 8 byte boundary.
uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
llvm::Value *Offset =
llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7);
overflow_arg_area = CGF.Builder.CreateGEP(CGF.Int8Ty, overflow_arg_area,
Offset, "overflow_arg_area.next");
CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
// AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
return Address(Res, Align);
}
Address X86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
QualType Ty) const {
// Assume that va_list type is correct; should be pointer to LLVM type:
// struct {
// i32 gp_offset;
// i32 fp_offset;
// i8* overflow_arg_area;
// i8* reg_save_area;
// };
unsigned neededInt, neededSSE;
Ty = getContext().getCanonicalType(Ty);
ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
/*isNamedArg*/false);
// AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
// in the registers. If not go to step 7.
if (!neededInt && !neededSSE)
return EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
// AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
// general purpose registers needed to pass type and num_fp to hold
// the number of floating point registers needed.
// AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
// registers. In the case: l->gp_offset > 48 - num_gp * 8 or
// l->fp_offset > 304 - num_fp * 16 go to step 7.
//
// NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
// register save space).
llvm::Value *InRegs = nullptr;
Address gp_offset_p = Address::invalid(), fp_offset_p = Address::invalid();
llvm::Value *gp_offset = nullptr, *fp_offset = nullptr;
if (neededInt) {
gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "gp_offset_p");
gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
}
if (neededSSE) {
fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, "fp_offset_p");
fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
llvm::Value *FitsInFP =
llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
}
llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
// Emit code to load the value if it was passed in registers.
CGF.EmitBlock(InRegBlock);
// AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
// an offset of l->gp_offset and/or l->fp_offset. This may require
// copying to a temporary location in case the parameter is passed
// in different register classes or requires an alignment greater
// than 8 for general purpose registers and 16 for XMM registers.
//
// FIXME: This really results in shameful code when we end up needing to
// collect arguments from different places; often what should result in a
// simple assembling of a structure from scattered addresses has many more
// loads than necessary. Can we clean this up?
llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
llvm::Value *RegSaveArea = CGF.Builder.CreateLoad(
CGF.Builder.CreateStructGEP(VAListAddr, 3), "reg_save_area");
Address RegAddr = Address::invalid();
if (neededInt && neededSSE) {
// FIXME: Cleanup.
assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
Address Tmp = CGF.CreateMemTemp(Ty);
Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
llvm::Type *TyLo = ST->getElementType(0);
llvm::Type *TyHi = ST->getElementType(1);
assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
"Unexpected ABI info for mixed regs");
llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
llvm::Value *GPAddr =
CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, gp_offset);
llvm::Value *FPAddr =
CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, fp_offset);
llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr;
llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr;
// Copy the first element.
// FIXME: Our choice of alignment here and below is probably pessimistic.
llvm::Value *V = CGF.Builder.CreateAlignedLoad(
TyLo, CGF.Builder.CreateBitCast(RegLoAddr, PTyLo),
CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyLo)));
CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
// Copy the second element.
V = CGF.Builder.CreateAlignedLoad(
TyHi, CGF.Builder.CreateBitCast(RegHiAddr, PTyHi),
CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyHi)));
CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
} else if (neededInt) {
RegAddr = Address(CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, gp_offset),
CharUnits::fromQuantity(8));
RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
// Copy to a temporary if necessary to ensure the appropriate alignment.
auto TInfo = getContext().getTypeInfoInChars(Ty);
uint64_t TySize = TInfo.Width.getQuantity();
CharUnits TyAlign = TInfo.Align;
// Copy into a temporary if the type is more aligned than the
// register save area.
if (TyAlign.getQuantity() > 8) {
Address Tmp = CGF.CreateMemTemp(Ty);
CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, false);
RegAddr = Tmp;
}
} else if (neededSSE == 1) {
RegAddr = Address(CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, fp_offset),
CharUnits::fromQuantity(16));
RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
} else {
assert(neededSSE == 2 && "Invalid number of needed registers!");
// SSE registers are spaced 16 bytes apart in the register save
// area, we need to collect the two eightbytes together.
// The ABI isn't explicit about this, but it seems reasonable
// to assume that the slots are 16-byte aligned, since the stack is
// naturally 16-byte aligned and the prologue is expected to store
// all the SSE registers to the RSA.
Address RegAddrLo = Address(CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea,
fp_offset),
CharUnits::fromQuantity(16));
Address RegAddrHi =
CGF.Builder.CreateConstInBoundsByteGEP(RegAddrLo,
CharUnits::fromQuantity(16));
llvm::Type *ST = AI.canHaveCoerceToType()
? AI.getCoerceToType()
: llvm::StructType::get(CGF.DoubleTy, CGF.DoubleTy);
llvm::Value *V;
Address Tmp = CGF.CreateMemTemp(Ty);
Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast(
RegAddrLo, ST->getStructElementType(0)));
CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast(
RegAddrHi, ST->getStructElementType(1)));
CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
}
// AMD64-ABI 3.5.7p5: Step 5. Set:
// l->gp_offset = l->gp_offset + num_gp * 8
// l->fp_offset = l->fp_offset + num_fp * 16.
if (neededInt) {
llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
gp_offset_p);
}
if (neededSSE) {
llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
fp_offset_p);
}
CGF.EmitBranch(ContBlock);
// Emit code to load the value if it was passed in memory.
CGF.EmitBlock(InMemBlock);
Address MemAddr = EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
// Return the appropriate result.
CGF.EmitBlock(ContBlock);
Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, MemAddr, InMemBlock,
"vaarg.addr");
return ResAddr;
}
Address X86_64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
QualType Ty) const {
// MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
// not 1, 2, 4, or 8 bytes, must be passed by reference."
uint64_t Width = getContext().getTypeSize(Ty);
bool IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Width);
return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
CGF.getContext().getTypeInfoInChars(Ty),
CharUnits::fromQuantity(8),
/*allowHigherAlign*/ false);
}
ABIArgInfo WinX86_64ABIInfo::reclassifyHvaArgForVectorCall(
QualType Ty, unsigned &FreeSSERegs, const ABIArgInfo ¤t) const {
const Type *Base = nullptr;
uint64_t NumElts = 0;
if (!Ty->isBuiltinType() && !Ty->isVectorType() &&
isHomogeneousAggregate(Ty, Base, NumElts) && FreeSSERegs >= NumElts) {
FreeSSERegs -= NumElts;
return getDirectX86Hva();
}
return current;
}
ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs,
bool IsReturnType, bool IsVectorCall,
bool IsRegCall) const {
if (Ty->isVoidType())
return ABIArgInfo::getIgnore();
if (const EnumType *EnumTy = Ty->getAs<EnumType>())
Ty = EnumTy->getDecl()->getIntegerType();
TypeInfo Info = getContext().getTypeInfo(Ty);
uint64_t Width = Info.Width;
CharUnits Align = getContext().toCharUnitsFromBits(Info.Align);
const RecordType *RT = Ty->getAs<RecordType>();
if (RT) {
if (!IsReturnType) {
if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
}
if (RT->getDecl()->hasFlexibleArrayMember())
return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
}
const Type *Base = nullptr;
uint64_t NumElts = 0;
// vectorcall adds the concept of a homogenous vector aggregate, similar to
// other targets.
if ((IsVectorCall || IsRegCall) &&
isHomogeneousAggregate(Ty, Base, NumElts)) {
if (IsRegCall) {
if (FreeSSERegs >= NumElts) {
FreeSSERegs -= NumElts;
if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())
return ABIArgInfo::getDirect();
return ABIArgInfo::getExpand();
}
return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
} else if (IsVectorCall) {
if (FreeSSERegs >= NumElts &&
(IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())) {
FreeSSERegs -= NumElts;
return ABIArgInfo::getDirect();
} else if (IsReturnType) {
return ABIArgInfo::getExpand();
} else if (!Ty->isBuiltinType() && !Ty->isVectorType()) {
// HVAs are delayed and reclassified in the 2nd step.
return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
}
}
}
if (Ty->isMemberPointerType()) {
// If the member pointer is represented by an LLVM int or ptr, pass it
// directly.
llvm::Type *LLTy = CGT.ConvertType(Ty);
if (LLTy->isPointerTy() || LLTy->isIntegerTy())
return ABIArgInfo::getDirect();
}
if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) {
// MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
// not 1, 2, 4, or 8 bytes, must be passed by reference."
if (Width > 64 || !llvm::isPowerOf2_64(Width))
return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
// Otherwise, coerce it to a small integer.
return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width));
}
if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
switch (BT->getKind()) {
case BuiltinType::Bool:
// Bool type is always extended to the ABI, other builtin types are not
// extended.
return ABIArgInfo::getExtend(Ty);
case BuiltinType::LongDouble:
// Mingw64 GCC uses the old 80 bit extended precision floating point
// unit. It passes them indirectly through memory.
if (IsMingw64) {
const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
if (LDF == &llvm::APFloat::x87DoubleExtended())
return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
}
break;
case BuiltinType::Int128:
case BuiltinType::UInt128:
// If it's a parameter type, the normal ABI rule is that arguments larger
// than 8 bytes are passed indirectly. GCC follows it. We follow it too,
// even though it isn't particularly efficient.
if (!IsReturnType)
return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
// Mingw64 GCC returns i128 in XMM0. Coerce to v2i64 to handle that.
// Clang matches them for compatibility.
return ABIArgInfo::getDirect(llvm::FixedVectorType::get(
llvm::Type::getInt64Ty(getVMContext()), 2));
default:
break;
}
}
if (Ty->isExtIntType()) {
// MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
// not 1, 2, 4, or 8 bytes, must be passed by reference."
// However, non-power-of-two _ExtInts will be passed as 1,2,4 or 8 bytes
// anyway as long is it fits in them, so we don't have to check the power of
// 2.
if (Width <= 64)
return ABIArgInfo::getDirect();
return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
}
return ABIArgInfo::getDirect();
}
void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
const unsigned CC = FI.getCallingConvention();
bool IsVectorCall = CC == llvm::CallingConv::X86_VectorCall;
bool IsRegCall = CC == llvm::CallingConv::X86_RegCall;
// If __attribute__((sysv_abi)) is in use, use the SysV argument
// classification rules.
if (CC == llvm::CallingConv::X86_64_SysV) {
X86_64ABIInfo SysVABIInfo(CGT, AVXLevel);
SysVABIInfo.computeInfo(FI);
return;
}
unsigned FreeSSERegs = 0;
if (IsVectorCall) {
// We can use up to 4 SSE return registers with vectorcall.
FreeSSERegs = 4;
} else if (IsRegCall) {
// RegCall gives us 16 SSE registers.
FreeSSERegs = 16;
}
if (!getCXXABI().classifyReturnType(FI))
FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true,
IsVectorCall, IsRegCall);
if (IsVectorCall) {
// We can use up to 6 SSE register parameters with vectorcall.
FreeSSERegs = 6;
} else if (IsRegCall) {
// RegCall gives us 16 SSE registers, we can reuse the return registers.
FreeSSERegs = 16;
}
unsigned ArgNum = 0;
unsigned ZeroSSERegs = 0;
for (auto &I : FI.arguments()) {
// Vectorcall in x64 only permits the first 6 arguments to be passed as
// XMM/YMM registers. After the sixth argument, pretend no vector
// registers are left.
unsigned *MaybeFreeSSERegs =
(IsVectorCall && ArgNum >= 6) ? &ZeroSSERegs : &FreeSSERegs;
I.info =
classify(I.type, *MaybeFreeSSERegs, false, IsVectorCall, IsRegCall);
++ArgNum;
}
if (IsVectorCall) {
// For vectorcall, assign aggregate HVAs to any free vector registers in a
// second pass.
for (auto &I : FI.arguments())
I.info = reclassifyHvaArgForVectorCall(I.type, FreeSSERegs, I.info);
}
}
Address WinX86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
QualType Ty) const {
// MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
// not 1, 2, 4, or 8 bytes, must be passed by reference."
uint64_t Width = getContext().getTypeSize(Ty);
bool IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Width);
return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
CGF.getContext().getTypeInfoInChars(Ty),
CharUnits::fromQuantity(8),
/*allowHigherAlign*/ false);
}
static bool PPC_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
llvm::Value *Address, bool Is64Bit,
bool IsAIX) {
// This is calculated from the LLVM and GCC tables and verified
// against gcc output. AFAIK all PPC ABIs use the same encoding.
CodeGen::CGBuilderTy &Builder = CGF.Builder;
llvm::IntegerType *i8 = CGF.Int8Ty;
llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
// 0-31: r0-31, the 4-byte or 8-byte general-purpose registers
AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 0, 31);
// 32-63: fp0-31, the 8-byte floating-point registers
AssignToArrayRange(Builder, Address, Eight8, 32, 63);
// 64-67 are various 4-byte or 8-byte special-purpose registers:
// 64: mq
// 65: lr
// 66: ctr
// 67: ap
AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 64, 67);
// 68-76 are various 4-byte special-purpose registers:
// 68-75 cr0-7
// 76: xer
AssignToArrayRange(Builder, Address, Four8, 68, 76);
// 77-108: v0-31, the 16-byte vector registers
AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
// 109: vrsave
// 110: vscr
AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 109, 110);
// AIX does not utilize the rest of the registers.
if (IsAIX)
return false;
// 111: spe_acc
// 112: spefscr
// 113: sfp
AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 111, 113);
if (!Is64Bit)
return false;
// TODO: Need to verify if these registers are used on 64 bit AIX with Power8
// or above CPU.
// 64-bit only registers:
// 114: tfhar
// 115: tfiar
// 116: texasr
AssignToArrayRange(Builder, Address, Eight8, 114, 116);
return false;
}
// AIX
namespace {
/// AIXABIInfo - The AIX XCOFF ABI information.
class AIXABIInfo : public ABIInfo {
const bool Is64Bit;
const unsigned PtrByteSize;
CharUnits getParamTypeAlignment(QualType Ty) const;
public:
AIXABIInfo(CodeGen::CodeGenTypes &CGT, bool Is64Bit)
: ABIInfo(CGT), Is64Bit(Is64Bit), PtrByteSize(Is64Bit ? 8 : 4) {}
bool isPromotableTypeForABI(QualType Ty) const;
ABIArgInfo classifyReturnType(QualType RetTy) const;
ABIArgInfo classifyArgumentType(QualType Ty) const;
void computeInfo(CGFunctionInfo &FI) const override {
if (!getCXXABI().classifyReturnType(FI))
FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
for (auto &I : FI.arguments())
I.info = classifyArgumentType(I.type);
}
Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
QualType Ty) const override;
};
class AIXTargetCodeGenInfo : public TargetCodeGenInfo {
const bool Is64Bit;
public:
AIXTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool Is64Bit)
: TargetCodeGenInfo(std::make_unique<AIXABIInfo>(CGT, Is64Bit)),
Is64Bit(Is64Bit) {}
int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
return 1; // r1 is the dedicated stack pointer
}
bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
llvm::Value *Address) const override;
};
} // namespace
// Return true if the ABI requires Ty to be passed sign- or zero-
// extended to 32/64 bits.
bool AIXABIInfo::isPromotableTypeForABI(QualType Ty) const {
// Treat an enum type as its underlying type.
if (const EnumType *EnumTy = Ty->getAs<EnumType>())
Ty = EnumTy->getDecl()->getIntegerType();
// Promotable integer types are required to be promoted by the ABI.
if (Ty->isPromotableIntegerType())
return true;
if (!Is64Bit)
return false;
// For 64 bit mode, in addition to the usual promotable integer types, we also
// need to extend all 32-bit types, since the ABI requires promotion to 64
// bits.
if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
switch (BT->getKind()) {
case BuiltinType::Int:
case BuiltinType::UInt:
return true;
default:
break;
}
return false;
}
ABIArgInfo AIXABIInfo::classifyReturnType(QualType RetTy) const {
if (RetTy->isAnyComplexType())
return ABIArgInfo::getDirect();
if (RetTy->isVectorType())
return ABIArgInfo::getDirect();
if (RetTy->isVoidType())
return ABIArgInfo::getIgnore();
if (isAggregateTypeForABI(RetTy))
return getNaturalAlignIndirect(RetTy);
return (isPromotableTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
: ABIArgInfo::getDirect());
}
ABIArgInfo AIXABIInfo::classifyArgumentType(QualType Ty) const {
Ty = useFirstFieldIfTransparentUnion(Ty);
if (Ty->isAnyComplexType())
return ABIArgInfo::getDirect();
if (Ty->isVectorType())
return ABIArgInfo::getDirect();
if (isAggregateTypeForABI(Ty)) {
// Records with non-trivial destructors/copy-constructors should not be
// passed by value.
if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
CharUnits CCAlign = getParamTypeAlignment(Ty);
CharUnits TyAlign = getContext().getTypeAlignInChars(Ty);
return ABIArgInfo::getIndirect(CCAlign, /*ByVal*/ true,
/*Realign*/ TyAlign > CCAlign);
}
return (isPromotableTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
: ABIArgInfo::getDirect());
}
CharUnits AIXABIInfo::getParamTypeAlignment(QualType Ty) const {
// Complex types are passed just like their elements.
if (const ComplexType *CTy = Ty->getAs<ComplexType>())
Ty = CTy->getElementType();
if (Ty->isVectorType())
return CharUnits::fromQuantity(16);
// If the structure contains a vector type, the alignment is 16.
if (isRecordWithSIMDVectorType(getContext(), Ty))
return CharUnits::fromQuantity(16);
return CharUnits::fromQuantity(PtrByteSize);
}
Address AIXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
QualType Ty) const {
auto TypeInfo = getContext().getTypeInfoInChars(Ty);
TypeInfo.Align = getParamTypeAlignment(Ty);
CharUnits SlotSize = CharUnits::fromQuantity(PtrByteSize);
// If we have a complex type and the base type is smaller than the register
// size, the ABI calls for the real and imaginary parts to be right-adjusted
// in separate words in 32bit mode or doublewords in 64bit mode. However,
// Clang expects us to produce a pointer to a structure with the two parts
// packed tightly. So generate loads of the real and imaginary parts relative
// to the va_list pointer, and store them to a temporary structure. We do the
// same as the PPC64ABI here.
if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
CharUnits EltSize = TypeInfo.Width / 2;
if (EltSize < SlotSize)
return complexTempStructure(CGF, VAListAddr, Ty, SlotSize, EltSize, CTy);
}
return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false, TypeInfo,
SlotSize, /*AllowHigher*/ true);
}
bool AIXTargetCodeGenInfo::initDwarfEHRegSizeTable(
CodeGen::CodeGenFunction &CGF, llvm::Value *Address) const {
return PPC_initDwarfEHRegSizeTable(CGF, Address, Is64Bit, /*IsAIX*/ true);
}
// PowerPC-32
namespace {
/// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information.
class PPC32_SVR4_ABIInfo : public DefaultABIInfo {
bool IsSoftFloatABI;
bool IsRetSmallStructInRegABI;
CharUnits getParamTypeAlignment(QualType Ty) const;
public:
PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, bool SoftFloatABI,
bool RetSmallStructInRegABI)
: DefaultABIInfo(CGT), IsSoftFloatABI(SoftFloatABI),
IsRetSmallStructInRegABI(RetSmallStructInRegABI) {}
ABIArgInfo classifyReturnType(QualType RetTy) const;
void computeInfo(CGFunctionInfo &FI) const override {
if (!getCXXABI().classifyReturnType(FI))
FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
for (auto &I : FI.arguments())
I.info = classifyArgumentType(I.type);
}
Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
QualType Ty) const override;
};
class PPC32TargetCodeGenInfo : public TargetCodeGenInfo {
public:
PPC32TargetCodeGenInfo(CodeGenTypes &CGT, bool SoftFloatABI,
bool RetSmallStructInRegABI)
: TargetCodeGenInfo(std::make_unique<PPC32_SVR4_ABIInfo>(
CGT, SoftFloatABI, RetSmallStructInRegABI)) {}
static bool isStructReturnInRegABI(const llvm::Triple &Triple,
const CodeGenOptions &Opts);
int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
// This is recovered from gcc output.
return 1; // r1 is the dedicated stack pointer
}
bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
llvm::Value *Address) const override;
};
}
CharUnits PPC32_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
// Complex types are passed just like their elements.
if (const ComplexType *CTy = Ty->getAs<ComplexType>())
Ty = CTy->getElementType();
if (Ty->isVectorType())
return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16
: 4);
// For single-element float/vector structs, we consider the whole type
// to have the same alignment requirements as its single element.
const Type *AlignTy = nullptr;
if (const Type *EltType = isSingleElementStruct(Ty, getContext())) {
const BuiltinType *BT = EltType->getAs<BuiltinType>();
if ((EltType->isVectorType() && getContext().getTypeSize(EltType) == 128) ||
(BT && BT->isFloatingPoint()))
AlignTy = EltType;
}
if (AlignTy)
return CharUnits::fromQuantity(AlignTy->isVectorType() ? 16 : 4);
return CharUnits::fromQuantity(4);
}
ABIArgInfo PPC32_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
uint64_t Size;
// -msvr4-struct-return puts small aggregates in GPR3 and GPR4.
if (isAggregateTypeForABI(RetTy) && IsRetSmallStructInRegABI &&
(Size = getContext().getTypeSize(RetTy)) <= 64) {
// System V ABI (1995), page 3-22, specified:
// > A structure or union whose size is less than or equal to 8 bytes
// > shall be returned in r3 and r4, as if it were first stored in the
// > 8-byte aligned memory area and then the low addressed word were
// > loaded into r3 and the high-addressed word into r4. Bits beyond
// > the last member of the structure or union are not defined.
//
// GCC for big-endian PPC32 inserts the pad before the first member,
// not "beyond the last member" of the struct. To stay compatible
// with GCC, we coerce the struct to an integer of the same size.
// LLVM will extend it and return i32 in r3, or i64 in r3:r4.
if (Size == 0)
return ABIArgInfo::getIgnore();
else {
llvm::Type *CoerceTy = llvm::Type::getIntNTy(getVMContext(), Size);
return ABIArgInfo::getDirect(CoerceTy);
}
}
return DefaultABIInfo::classifyReturnType(RetTy);
}
// TODO: this implementation is now likely redundant with
// DefaultABIInfo::EmitVAArg.
Address PPC32_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAList,
QualType Ty) const {
if (getTarget().getTriple().isOSDarwin()) {
auto TI = getContext().getTypeInfoInChars(Ty);
TI.Align = getParamTypeAlignment(Ty);
CharUnits SlotSize = CharUnits::fromQuantity(4);
return emitVoidPtrVAArg(CGF, VAList, Ty,
classifyArgumentType(Ty).isIndirect(), TI, SlotSize,
/*AllowHigherAlign=*/true);
}
const unsigned OverflowLimit = 8;
if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
// TODO: Implement this. For now ignore.
(void)CTy;
return Address::invalid(); // FIXME?
}
// struct __va_list_tag {
// unsigned char gpr;
// unsigned char fpr;
// unsigned short reserved;
// void *overflow_arg_area;
// void *reg_save_area;
// };
bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64;
bool isInt = !Ty->isFloatingType();
bool isF64 = Ty->isFloatingType() && getContext().getTypeSize(Ty) == 64;
// All aggregates are passed indirectly? That doesn't seem consistent
// with the argument-lowering code.
bool isIndirect = isAggregateTypeForABI(Ty);
CGBuilderTy &Builder = CGF.Builder;
// The calling convention either uses 1-2 GPRs or 1 FPR.
Address NumRegsAddr = Address::invalid();
if (isInt || IsSoftFloatABI) {
NumRegsAddr = Builder.CreateStructGEP(VAList, 0, "gpr");
} else {
NumRegsAddr = Builder.CreateStructGEP(VAList, 1, "fpr");
}
llvm::Value *NumRegs = Builder.CreateLoad(NumRegsAddr, "numUsedRegs");
// "Align" the register count when TY is i64.
if (isI64 || (isF64 && IsSoftFloatABI)) {
NumRegs = Builder.CreateAdd(NumRegs, Builder.getInt8(1));
NumRegs = Builder.CreateAnd(NumRegs, Builder.getInt8((uint8_t) ~1U));
}
llvm::Value *CC =
Builder.CreateICmpULT(NumRegs, Builder.getInt8(OverflowLimit), "cond");
llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs");
llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow");
llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
Builder.CreateCondBr(CC, UsingRegs, UsingOverflow);
llvm::Type *DirectTy = CGF.ConvertType(Ty);
if (isIndirect) DirectTy = DirectTy->getPointerTo(0);
// Case 1: consume registers.
Address RegAddr = Address::invalid();
{
CGF.EmitBlock(UsingRegs);
Address RegSaveAreaPtr = Builder.CreateStructGEP(VAList, 4);
RegAddr = Address(Builder.CreateLoad(RegSaveAreaPtr),
CharUnits::fromQuantity(8));
assert(RegAddr.getElementType() == CGF.Int8Ty);
// Floating-point registers start after the general-purpose registers.
if (!(isInt || IsSoftFloatABI)) {
RegAddr = Builder.CreateConstInBoundsByteGEP(RegAddr,
CharUnits::fromQuantity(32));
}
// Get the address of the saved value by scaling the number of
// registers we've used by the number of
CharUnits RegSize = CharUnits::fromQuantity((isInt || IsSoftFloatABI) ? 4 : 8);
llvm::Value *RegOffset =
Builder.CreateMul(NumRegs, Builder.getInt8(RegSize.getQuantity()));
RegAddr = Address(Builder.CreateInBoundsGEP(CGF.Int8Ty,
RegAddr.getPointer(), RegOffset),
RegAddr.getAlignment().alignmentOfArrayElement(RegSize));
RegAddr = Builder.CreateElementBitCast(RegAddr, DirectTy);
// Increase the used-register count.
NumRegs =
Builder.CreateAdd(NumRegs,
Builder.getInt8((isI64 || (isF64 && IsSoftFloatABI)) ? 2 : 1));
Builder.CreateStore(NumRegs, NumRegsAddr);
CGF.EmitBranch(Cont);
}
// Case 2: consume space in the overflow area.
Address MemAddr = Address::invalid();
{
CGF.EmitBlock(UsingOverflow);
Builder.CreateStore(Builder.getInt8(OverflowLimit), NumRegsAddr);
// Everything in the overflow area is rounded up to a size of at least 4.
CharUnits OverflowAreaAlign = CharUnits::fromQuantity(4);
CharUnits Size;
if (!isIndirect) {
auto TypeInfo = CGF.getContext().getTypeInfoInChars(Ty);
Size = TypeInfo.Width.alignTo(OverflowAreaAlign);
} else {
Size = CGF.getPointerSize();
}
Address OverflowAreaAddr = Builder.CreateStructGEP(VAList, 3);
Address OverflowArea(Builder.CreateLoad(OverflowAreaAddr, "argp.cur"),
OverflowAreaAlign);
// Round up address of argument to alignment
CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
if (Align > OverflowAreaAlign) {
llvm::Value *Ptr = OverflowArea.getPointer();
OverflowArea = Address(emitRoundPointerUpToAlignment(CGF, Ptr, Align),
Align);
}
MemAddr = Builder.CreateElementBitCast(OverflowArea, DirectTy);
// Increase the overflow area.
OverflowArea = Builder.CreateConstInBoundsByteGEP(OverflowArea, Size);
Builder.CreateStore(OverflowArea.getPointer(), OverflowAreaAddr);
CGF.EmitBranch(Cont);
}
CGF.EmitBlock(Cont);
// Merge the cases with a phi.
Address Result = emitMergePHI(CGF, RegAddr, UsingRegs, MemAddr, UsingOverflow,
"vaarg.addr");
// Load the pointer if the argument was passed indirectly.
if (isIndirect) {
Result = Address(Builder.CreateLoad(Result, "aggr"),
getContext().getTypeAlignInChars(Ty));
}
return Result;
}
bool PPC32TargetCodeGenInfo::isStructReturnInRegABI(
const llvm::Triple &Triple, const CodeGenOptions &Opts) {
assert(Triple.isPPC32());
switch (Opts.getStructReturnConvention()) {
case CodeGenOptions::SRCK_Default:
break;
case CodeGenOptions::SRCK_OnStack: // -maix-struct-return
return false;
case CodeGenOptions::SRCK_InRegs: // -msvr4-struct-return
return true;
}
if (Triple.isOSBinFormatELF() && !Triple.isOSLinux())
return true;
return false;
}
bool
PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
llvm::Value *Address) const {
return PPC_initDwarfEHRegSizeTable(CGF, Address, /*Is64Bit*/ false,
/*IsAIX*/ false);
}
// PowerPC-64
namespace {
/// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
class PPC64_SVR4_ABIInfo : public SwiftABIInfo {
public:
enum ABIKind {
ELFv1 = 0,
ELFv2
};
private:
static const unsigned GPRBits = 64;
ABIKind Kind;
bool IsSoftFloatABI;
public:
PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind,
bool SoftFloatABI)
: SwiftABIInfo(CGT), Kind(Kind), IsSoftFloatABI(SoftFloatABI) {}
bool isPromotableTypeForABI(QualType Ty) const;
CharUnits getParamTypeAlignment(QualType Ty) const;
ABIArgInfo classifyReturnType(QualType RetTy) const;
ABIArgInfo classifyArgumentType(QualType Ty) const;
bool isHomogeneousAggregateBaseType(QualType Ty) const override;
bool isHomogeneousAggregateSmallEnough(const Type *Ty,
uint64_t Members) const override;
// TODO: We can add more logic to computeInfo to improve performance.
// Example: For aggregate arguments that fit in a register, we could
// use getDirectInReg (as is done below for structs containing a single
// floating-point value) to avoid pushing them to memory on function
// entry. This would require changing the logic in PPCISelLowering
// when lowering the parameters in the caller and args in the callee.
void computeInfo(CGFunctionInfo &FI) const override {
if (!getCXXABI().classifyReturnType(FI))
FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
for (auto &I : FI.arguments()) {
// We rely on the default argument classification for the most part.
// One exception: An aggregate containing a single floating-point
// or vector item must be passed in a register if one is available.
const Type *T = isSingleElementStruct(I.type, getContext());
if (T) {
const BuiltinType *BT = T->getAs<BuiltinType>();
if ((T->isVectorType() && getContext().getTypeSize(T) == 128) ||
(BT && BT->isFloatingPoint())) {
QualType QT(T, 0);
I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
continue;
}
}
I.info = classifyArgumentType(I.type);
}
}
Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
QualType Ty) const override;
bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
bool asReturnValue) const override {
return occupiesMoreThan(CGT, scalars, /*total*/ 4);
}
bool isSwiftErrorInRegister() const override {
return false;
}
};
class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
public:
PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT,
PPC64_SVR4_ABIInfo::ABIKind Kind,
bool SoftFloatABI)
: TargetCodeGenInfo(
std::make_unique<PPC64_SVR4_ABIInfo>(CGT, Kind, SoftFloatABI)) {}
int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
// This is recovered from gcc output.
return 1; // r1 is the dedicated stack pointer
}
bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
llvm::Value *Address) const override;
};
class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
public:
PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
// This is recovered from gcc output.
return 1; // r1 is the dedicated stack pointer
}
bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
llvm::Value *Address) const override;
};
}
// Return true if the ABI requires Ty to be passed sign- or zero-
// extended to 64 bits.
bool
PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
// Treat an enum type as its underlying type.
if (const EnumType *EnumTy = Ty->getAs<EnumType>())
Ty = EnumTy->getDecl()->getIntegerType();
// Promotable integer types are required to be promoted by the ABI.
if (isPromotableIntegerTypeForABI(Ty))
return true;
// In addition to the usual promotable integer types, we also need to
// extend all 32-bit types, since the ABI requires promotion to 64 bits.
if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
switch (BT->getKind()) {
case BuiltinType::Int:
case BuiltinType::UInt:
return true;
default:
break;
}
if (const auto *EIT = Ty->getAs<ExtIntType>())
if (EIT->getNumBits() < 64)
return true;
return false;
}
/// isAlignedParamType - Determine whether a type requires 16-byte or
/// higher alignment in the parameter area. Always returns at least 8.
CharUnits PPC64_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
// Complex types are passed just like their elements.
if (const ComplexType *CTy = Ty->getAs<ComplexType>())
Ty = CTy->getElementType();
// Only vector types of size 16 bytes need alignment (larger types are
// passed via reference, smaller types are not aligned).
if (Ty->isVectorType()) {
return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16 : 8);
} else if (Ty->isRealFloatingType() &&
&getContext().getFloatTypeSemantics(Ty) ==
&llvm::APFloat::IEEEquad()) {
// According to ABI document section 'Optional Save Areas': If extended
// precision floating-point values in IEEE BINARY 128 QUADRUPLE PRECISION
// format are supported, map them to a single quadword, quadword aligned.
return CharUnits::fromQuantity(16);
}
// For single-element float/vector structs, we consider the whole type
// to have the same alignment requirements as its single element.
const Type *AlignAsType = nullptr;
const Type *EltType = isSingleElementStruct(Ty, getContext());
if (EltType) {
const BuiltinType *BT = EltType->getAs<BuiltinType>();
if ((EltType->isVectorType() && getContext().getTypeSize(EltType) == 128) ||
(BT && BT->isFloatingPoint()))
AlignAsType = EltType;
}
// Likewise for ELFv2 homogeneous aggregates.
const Type *Base = nullptr;
uint64_t Members = 0;
if (!AlignAsType && Kind == ELFv2 &&
isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members))
AlignAsType = Base;
// With special case aggregates, only vector base types need alignment.
if (AlignAsType) {
return CharUnits::fromQuantity(AlignAsType->isVectorType() ? 16 : 8);
}
// Otherwise, we only need alignment for any aggregate type that
// has an alignment requirement of >= 16 bytes.
if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128) {
return CharUnits::fromQuantity(16);
}
return CharUnits::fromQuantity(8);
}
/// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous
/// aggregate. Base is set to the base element type, and Members is set
/// to the number of base elements.
bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base,
uint64_t &Members) const {
if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
uint64_t NElements = AT->getSize().getZExtValue();
if (NElements == 0)
return false;
if (!isHomogeneousAggregate(AT->getElementType(), Base, Members))
return false;
Members *= NElements;
} else if (const RecordType *RT = Ty->getAs<RecordType>()) {
const RecordDecl *RD = RT->getDecl();
if (RD->hasFlexibleArrayMember())
return false;
Members = 0;
// If this is a C++ record, check the properties of the record such as
// bases and ABI specific restrictions
if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
if (!getCXXABI().isPermittedToBeHomogeneousAggregate(CXXRD))
return false;
for (const auto &I : CXXRD->bases()) {
// Ignore empty records.
if (isEmptyRecord(getContext(), I.getType(), true))
continue;
uint64_t FldMembers;
if (!isHomogeneousAggregate(I.getType(), Base, FldMembers))
return false;
Members += FldMembers;
}
}
for (const auto *FD : RD->fields()) {
// Ignore (non-zero arrays of) empty records.
QualType FT = FD->getType();
while (const ConstantArrayType *AT =
getContext().getAsConstantArrayType(FT)) {
if (AT->getSize().getZExtValue() == 0)
return false;
FT = AT->getElementType();
}
if (isEmptyRecord(getContext(), FT, true))
continue;
// For compatibility with GCC, ignore empty bitfields in C++ mode.
if (getContext().getLangOpts().CPlusPlus &&
FD->isZeroLengthBitField(getContext()))
continue;
uint64_t FldMembers;
if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers))
return false;
Members = (RD->isUnion() ?
std::max(Members, FldMembers) : Members + FldMembers);
}
if (!Base)
return false;
// Ensure there is no padding.
if (getContext().getTypeSize(Base) * Members !=
getContext().getTypeSize(Ty))
return false;
} else {
Members = 1;
if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
Members = 2;
Ty = CT->getElementType();
}
// Most ABIs only support float, double, and some vector type widths.
if (!isHomogeneousAggregateBaseType(Ty))
return false;
// The base type must be the same for all members. Types that
// agree in both total size and mode (float vs. vector) are
// treated as being equivalent here.
const Type *TyPtr = Ty.getTypePtr();
if (!Base) {
Base = TyPtr;
// If it's a non-power-of-2 vector, its size is already a power-of-2,
// so make sure to widen it explicitly.
if (const VectorType *VT = Base->getAs<VectorType>()) {
QualType EltTy = VT->getElementType();
unsigned NumElements =
getContext().getTypeSize(VT) / getContext().getTypeSize(EltTy);
Base = getContext()
.getVectorType(EltTy, NumElements, VT->getVectorKind())
.getTypePtr();
}
}
if (Base->isVectorType() != TyPtr->isVectorType() ||
getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr))
return false;
}
return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members);
}
bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
// Homogeneous aggregates for ELFv2 must have base types of float,
// double, long double, or 128-bit vectors.
if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
if (BT->getKind() == BuiltinType::Float ||
BT->getKind() == BuiltinType::Double ||
BT->getKind() == BuiltinType::LongDouble ||
BT->getKind() == BuiltinType::Ibm128 ||
(getContext().getTargetInfo().hasFloat128Type() &&
(BT->getKind() == BuiltinType::Float128))) {
if (IsSoftFloatABI)
return false;
return true;
}
}
if (const VectorType *VT = Ty->getAs<VectorType>()) {
if (getContext().getTypeSize(VT) == 128)
return true;
}
return false;
}
bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough(
const Type *Base, uint64_t Members) const {
// Vector and fp128 types require one register, other floating point types
// require one or two registers depending on their size.
uint32_t NumRegs =
((getContext().getTargetInfo().hasFloat128Type() &&
Base->isFloat128Type()) ||
Base->isVectorType()) ? 1
: (getContext().getTypeSize(Base) + 63) / 64;
// Homogeneous Aggregates may occupy at most 8 registers.
return Members * NumRegs <= 8;
}
ABIArgInfo
PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
Ty = useFirstFieldIfTransparentUnion(Ty);
if (Ty->isAnyComplexType())
return ABIArgInfo::getDirect();
// Non-Altivec vector types are passed in GPRs (smaller than 16 bytes)
// or via reference (larger than 16 bytes).
if (Ty->isVectorType()) {
uint64_t Size = getContext().getTypeSize(Ty);
if (Size > 128)
return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
else if (Size < 128) {
llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
return ABIArgInfo::getDirect(CoerceTy);
}
}
if (const auto *EIT = Ty->getAs<ExtIntType>())
if (EIT->getNumBits() > 128)
return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
if (isAggregateTypeForABI(Ty)) {
if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
uint64_t ABIAlign = getParamTypeAlignment(Ty).getQuantity();
uint64_t TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
// ELFv2 homogeneous aggregates are passed as array types.
const Type *Base = nullptr;
uint64_t Members = 0;
if (Kind == ELFv2 &&
isHomogeneousAggregate(Ty, Base, Members)) {
llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
return ABIArgInfo::getDirect(CoerceTy);
}
// If an aggregate may end up fully in registers, we do not
// use the ByVal method, but pass the aggregate as array.
// This is usually beneficial since we avoid forcing the
// back-end to store the argument to memory.
uint64_t Bits = getContext().getTypeSize(Ty);
if (Bits > 0 && Bits <= 8 * GPRBits) {
llvm::Type *CoerceTy;
// Types up to 8 bytes are passed as integer type (which will be
// properly aligned in the argument save area doubleword).
if (Bits <= GPRBits)
CoerceTy =
llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
// Larger types are passed as arrays, with the base type selected
// according to the required alignment in the save area.
else {
uint64_t RegBits = ABIAlign * 8;
uint64_t NumRegs = llvm::alignTo(Bits, RegBits) / RegBits;
llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits);
CoerceTy = llvm::ArrayType::get(RegTy, NumRegs);
}
return ABIArgInfo::getDirect(CoerceTy);
}
// All other aggregates are passed ByVal.
return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
/*ByVal=*/true,
/*Realign=*/TyAlign > ABIAlign);
}
return (isPromotableTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
: ABIArgInfo::getDirect());
}
ABIArgInfo
PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
if (RetTy->isVoidType())
return ABIArgInfo::getIgnore();
if (RetTy->isAnyComplexType())
return ABIArgInfo::getDirect();
// Non-Altivec vector types are returned in GPRs (smaller than 16 bytes)
// or via reference (larger than 16 bytes).
if (RetTy->isVectorType()) {
uint64_t Size = getContext().getTypeSize(RetTy);
if (Size > 128)
return getNaturalAlignIndirect(RetTy);
else if (Size < 128) {
llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
return ABIArgInfo::getDirect(CoerceTy);
}
}
if (const auto *EIT = RetTy->getAs<ExtIntType>())
if (EIT->getNumBits() > 128)
return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
if (isAggregateTypeForABI(RetTy)) {
// ELFv2 homogeneous aggregates are returned as array types.
const Type *Base = nullptr;
uint64_t Members = 0;
if (Kind == ELFv2 &&
isHomogeneousAggregate(RetTy, Base, Members)) {
llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
return ABIArgInfo::getDirect(CoerceTy);
}
// ELFv2 small aggregates are returned in up to two registers.
uint64_t Bits = getContext().getTypeSize(RetTy);
if (Kind == ELFv2 && Bits <= 2 * GPRBits) {
if (Bits == 0)
return ABIArgInfo::getIgnore();
llvm::Type *CoerceTy;
if (Bits > GPRBits) {
CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits);
CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy);
} else
CoerceTy =
llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
return ABIArgInfo::getDirect(CoerceTy);
}
// All other aggregates are returned indirectly.
return getNaturalAlignIndirect(RetTy);
}
return (isPromotableTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
: ABIArgInfo::getDirect());
}
// Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
Address PPC64_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
QualType Ty) const {
auto TypeInfo = getContext().getTypeInfoInChars(Ty);
TypeInfo.Align = getParamTypeAlignment(Ty);
CharUnits SlotSize = CharUnits::fromQuantity(8);
// If we have a complex type and the base type is smaller than 8 bytes,
// the ABI calls for the real and imaginary parts to be right-adjusted
// in separate doublewords. However, Clang expects us to produce a
// pointer to a structure with the two parts packed tightly. So generate
// loads of the real and imaginary parts relative to the va_list pointer,
// and store them to a temporary structure.
if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
CharUnits EltSize = TypeInfo.Width / 2;
if (EltSize < SlotSize)
return complexTempStructure(CGF, VAListAddr, Ty, SlotSize, EltSize, CTy);
}
// Otherwise, just use the general rule.
return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
TypeInfo, SlotSize, /*AllowHigher*/ true);
}
bool
PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
CodeGen::CodeGenFunction &CGF,
llvm::Value *Address) const {
return PPC_initDwarfEHRegSizeTable(CGF, Address, /*Is64Bit*/ true,
/*IsAIX*/ false);
}
bool
PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
llvm::Value *Address) const {
return PPC_initDwarfEHRegSizeTable(CGF, Address, /*Is64Bit*/ true,
/*IsAIX*/ false);
}
//===----------------------------------------------------------------------===//
// AArch64 ABI Implementation
//===----------------------------------------------------------------------===//
namespace {
class AArch64ABIInfo : public SwiftABIInfo {
public:
enum ABIKind {
AAPCS = 0,
DarwinPCS,
Win64
};
private:
ABIKind Kind;
public:
AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind)
: SwiftABIInfo(CGT), Kind(Kind) {}
private:
ABIKind getABIKind() const { return Kind; }
bool isDarwinPCS() const { return Kind == DarwinPCS; }
ABIArgInfo classifyReturnType(QualType RetTy, bool IsVariadic) const;
ABIArgInfo classifyArgumentType(QualType RetTy, bool IsVariadic,
unsigned CallingConvention) const;
ABIArgInfo coerceIllegalVector(QualType Ty) const;
bool isHomogeneousAggregateBaseType(QualType Ty) const override;
bool isHomogeneousAggregateSmallEnough(const Type *Ty,
uint64_t Members) const override;
bool isIllegalVectorType(QualType Ty) const;
void computeInfo(CGFunctionInfo &FI) const override {
if (!::classifyReturnType(getCXXABI(), FI, *this))
FI.getReturnInfo() =
classifyReturnType(FI.getReturnType(), FI.isVariadic());
for (auto &it : FI.arguments())
it.info = classifyArgumentType(it.type, FI.isVariadic(),
FI.getCallingConvention());
}
Address EmitDarwinVAArg(Address VAListAddr, QualType Ty,
CodeGenFunction &CGF) const;
Address EmitAAPCSVAArg(Address VAListAddr, QualType Ty,
CodeGenFunction &CGF) const;
Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
QualType Ty) const override {
llvm::Type *BaseTy = CGF.ConvertType(Ty);
if (isa<llvm::ScalableVectorType>(BaseTy))
llvm::report_fatal_error("Passing SVE types to variadic functions is "
"currently not supported");
return Kind == Win64 ? EmitMSVAArg(CGF, VAListAddr, Ty)
: isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF)
: EmitAAPCSVAArg(VAListAddr, Ty, CGF);
}
Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
QualType Ty) const override;
bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
bool asReturnValue) const override {
return occupiesMoreThan(CGT, scalars, /*total*/ 4);
}
bool isSwiftErrorInRegister() const override {
return true;
}
bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy,
unsigned elts) const override;
bool allowBFloatArgsAndRet() const override {
return getTarget().hasBFloat16Type();
}
};
class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
public:
AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind)
: TargetCodeGenInfo(std::make_unique<AArch64ABIInfo>(CGT, Kind)) {}
StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
return "mov\tfp, fp\t\t// marker for objc_retainAutoreleaseReturnValue";
}
int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
return 31;
}
bool doesReturnSlotInterfereWithArgs() const override { return false; }
void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
CodeGen::CodeGenModule &CGM) const override {
const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
if (!FD)
return;
const auto *TA = FD->getAttr<TargetAttr>();
if (TA == nullptr)
return;
ParsedTargetAttr Attr = TA->parse();
if (Attr.BranchProtection.empty())
return;
TargetInfo::BranchProtectionInfo BPI;
StringRef Error;
(void)CGM.getTarget().validateBranchProtection(Attr.BranchProtection,
BPI, Error);
assert(Error.empty());
auto *Fn = cast<llvm::Function>(GV);
static const char *SignReturnAddrStr[] = {"none", "non-leaf", "all"};
Fn->addFnAttr("sign-return-address", SignReturnAddrStr[static_cast<int>(BPI.SignReturnAddr)]);
if (BPI.SignReturnAddr != LangOptions::SignReturnAddressScopeKind::None) {
Fn->addFnAttr("sign-return-address-key",
BPI.SignKey == LangOptions::SignReturnAddressKeyKind::AKey
? "a_key"
: "b_key");
}
Fn->addFnAttr("branch-target-enforcement",
BPI.BranchTargetEnforcement ? "true" : "false");
}
bool isScalarizableAsmOperand(CodeGen::CodeGenFunction &CGF,
llvm::Type *Ty) const override {
if (CGF.getTarget().hasFeature("ls64")) {
auto *ST = dyn_cast<llvm::StructType>(Ty);
if (ST && ST->getNumElements() == 1) {
auto *AT = dyn_cast<llvm::ArrayType>(ST->getElementType(0));
if (AT && AT->getNumElements() == 8 &&
AT->getElementType()->isIntegerTy(64))
return true;
}
}
return TargetCodeGenInfo::isScalarizableAsmOperand(CGF, Ty);
}
};
class WindowsAArch64TargetCodeGenInfo : public AArch64TargetCodeGenInfo {
public:
WindowsAArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind K)
: AArch64TargetCodeGenInfo(CGT, K) {}
void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
CodeGen::CodeGenModule &CGM) const override;
void getDependentLibraryOption(llvm::StringRef Lib,
llvm::SmallString<24> &Opt) const override {
Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib);
}
void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value,
llvm::SmallString<32> &Opt) const override {
Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
}
};
void WindowsAArch64TargetCodeGenInfo::setTargetAttributes(
const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
AArch64TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
if (GV->isDeclaration())
return;
addStackProbeTargetAttributes(D, GV, CGM);
}
}
ABIArgInfo AArch64ABIInfo::coerceIllegalVector(QualType Ty) const {
assert(Ty->isVectorType() && "expected vector type!");
const auto *VT = Ty->castAs<VectorType>();
if (VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector) {
assert(VT->getElementType()->isBuiltinType() && "expected builtin type!");
assert(VT->getElementType()->castAs<BuiltinType>()->getKind() ==
BuiltinType::UChar &&
"unexpected builtin type for SVE predicate!");
return ABIArgInfo::getDirect(llvm::ScalableVectorType::get(
llvm::Type::getInt1Ty(getVMContext()), 16));
}
if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector) {
assert(VT->getElementType()->isBuiltinType() && "expected builtin type!");
const auto *BT = VT->getElementType()->castAs<BuiltinType>();
llvm::ScalableVectorType *ResType = nullptr;
switch (BT->getKind()) {
default:
llvm_unreachable("unexpected builtin type for SVE vector!");
case BuiltinType::SChar:
case BuiltinType::UChar:
ResType = llvm::ScalableVectorType::get(
llvm::Type::getInt8Ty(getVMContext()), 16);
break;
case BuiltinType::Short:
case BuiltinType::UShort:
ResType = llvm::ScalableVectorType::get(
llvm::Type::getInt16Ty(getVMContext()), 8);
break;
case BuiltinType::Int:
case BuiltinType::UInt:
ResType = llvm::ScalableVectorType::get(
llvm::Type::getInt32Ty(getVMContext()), 4);
break;
case BuiltinType::Long:
case BuiltinType::ULong:
ResType = llvm::ScalableVectorType::get(
llvm::Type::getInt64Ty(getVMContext()), 2);
break;
case BuiltinType::Half:
ResType = llvm::ScalableVectorType::get(
llvm::Type::getHalfTy(getVMContext()), 8);
break;
case BuiltinType::Float:
ResType = llvm::ScalableVectorType::get(
llvm::Type::getFloatTy(getVMContext()), 4);
break;
case BuiltinType::Double:
ResType = llvm::ScalableVectorType::get(
llvm::Type::getDoubleTy(getVMContext()), 2);
break;
case BuiltinType::BFloat16:
ResType = llvm::ScalableVectorType::get(
llvm::Type::getBFloatTy(getVMContext()), 8);
break;
}
return ABIArgInfo::getDirect(ResType);
}
uint64_t Size = getContext().getTypeSize(Ty);
// Android promotes <2 x i8> to i16, not i32
if (isAndroid() && (Size <= 16)) {
llvm::Type *ResType = llvm::Type::getInt16Ty(getVMContext());
return ABIArgInfo::getDirect(ResType);
}
if (Size <= 32) {
llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
return ABIArgInfo::getDirect(ResType);
}
if (Size == 64) {
auto *ResType =
llvm::FixedVectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
return ABIArgInfo::getDirect(ResType);
}
if (Size == 128) {
auto *ResType =
llvm::FixedVectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
return ABIArgInfo::getDirect(ResType);
}
return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
}
ABIArgInfo
AArch64ABIInfo::classifyArgumentType(QualType Ty, bool IsVariadic,
unsigned CallingConvention) const {
Ty = useFirstFieldIfTransparentUnion(Ty);
// Handle illegal vector types here.
if (isIllegalVectorType(Ty))
return coerceIllegalVector(Ty);
if (!isAggregateTypeForABI(Ty)) {
// Treat an enum type as its underlying type.
if (const EnumType *EnumTy = Ty->getAs<EnumType>())
Ty = EnumTy->getDecl()->getIntegerType();
if (const auto *EIT = Ty->getAs<ExtIntType>())
if (EIT->getNumBits() > 128)
return getNaturalAlignIndirect(Ty);
return (isPromotableIntegerTypeForABI(Ty) && isDarwinPCS()
? ABIArgInfo::getExtend(Ty)
: ABIArgInfo::getDirect());
}
// Structures with either a non-trivial destructor or a non-trivial
// copy constructor are always indirect.
if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
CGCXXABI::RAA_DirectInMemory);
}
// Empty records are always ignored on Darwin, but actually passed in C++ mode
// elsewhere for GNU compatibility.
uint64_t Size = getContext().getTypeSize(Ty);
bool IsEmpty = isEmptyRecord(getContext(), Ty, true);
if (IsEmpty || Size == 0) {
if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
return ABIArgInfo::getIgnore();
// GNU C mode. The only argument that gets ignored is an empty one with size
// 0.
if (IsEmpty && Size == 0)
return ABIArgInfo::getIgnore();
return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
}
// Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
const Type *Base = nullptr;
uint64_t Members = 0;
bool IsWin64 = Kind == Win64 || CallingConvention == llvm::CallingConv::Win64;
bool IsWinVariadic = IsWin64 && IsVariadic;
// In variadic functions on Windows, all composite types are treated alike,
// no special handling of HFAs/HVAs.
if (!IsWinVariadic && isHomogeneousAggregate(Ty, Base, Members)) {
if (Kind != AArch64ABIInfo::AAPCS)
return ABIArgInfo::getDirect(
llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members));
// For alignment adjusted HFAs, cap the argument alignment to 16, leave it
// default otherwise.
unsigned Align =
getContext().getTypeUnadjustedAlignInChars(Ty).getQuantity();
unsigned BaseAlign = getContext().getTypeAlignInChars(Base).getQuantity();
Align = (Align > BaseAlign && Align >= 16) ? 16 : 0;
return ABIArgInfo::getDirect(
llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members), 0,
nullptr, true, Align);
}
// Aggregates <= 16 bytes are passed directly in registers or on the stack.
if (Size <= 128) {
// On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
// same size and alignment.
if (getTarget().isRenderScriptTarget()) {
return coerceToIntArray(Ty, getContext(), getVMContext());
}
unsigned Alignment;
if (Kind == AArch64ABIInfo::AAPCS) {
Alignment = getContext().getTypeUnadjustedAlign(Ty);
Alignment = Alignment < 128 ? 64 : 128;
} else {
Alignment = std::max(getContext().getTypeAlign(Ty),
(unsigned)getTarget().getPointerWidth(0));
}
Size = llvm::alignTo(Size, Alignment);
// We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
// For aggregates with 16-byte alignment, we use i128.
llvm::Type *BaseTy = llvm::Type::getIntNTy(getVMContext(), Alignment);
return ABIArgInfo::getDirect(
Size == Alignment ? BaseTy
: llvm::ArrayType::get(BaseTy, Size / Alignment));
}
return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
}
ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy,
bool IsVariadic) const {
if (RetTy->isVoidType())
return ABIArgInfo::getIgnore();
if (const auto *VT = RetTy->getAs<VectorType>()) {
if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector ||
VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector)
return coerceIllegalVector(RetTy);
}
// Large vector types should be returned via memory.
if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
return getNaturalAlignIndirect(RetTy);
if (!isAggregateTypeForABI(RetTy)) {
// Treat an enum type as its underlying type.
if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
RetTy = EnumTy->getDecl()->getIntegerType();
if (const auto *EIT = RetTy->getAs<ExtIntType>())
if (EIT->getNumBits() > 128)
return getNaturalAlignIndirect(RetTy);
return (isPromotableIntegerTypeForABI(RetTy) && isDarwinPCS()
? ABIArgInfo::getExtend(RetTy)
: ABIArgInfo::getDirect());
}
uint64_t Size = getContext().getTypeSize(RetTy);
if (isEmptyRecord(getContext(), RetTy, true) || Size == 0)
return ABIArgInfo::getIgnore();
const Type *Base = nullptr;
uint64_t Members = 0;
if (isHomogeneousAggregate(RetTy, Base, Members) &&
!(getTarget().getTriple().getArch() == llvm::Triple::aarch64_32 &&
IsVariadic))
// Homogeneous Floating-point Aggregates (HFAs) are returned directly.
return ABIArgInfo::getDirect();
// Aggregates <= 16 bytes are returned directly in registers or on the stack.
if (Size <= 128) {
// On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
// same size and alignment.
if (getTarget().isRenderScriptTarget()) {
return coerceToIntArray(RetTy, getContext(), getVMContext());
}
if (Size <= 64 && getDataLayout().isLittleEndian()) {
// Composite types are returned in lower bits of a 64-bit register for LE,
// and in higher bits for BE. However, integer types are always returned
// in lower bits for both LE and BE, and they are not rounded up to
// 64-bits. We can skip rounding up of composite types for LE, but not for
// BE, otherwise composite types will be indistinguishable from integer
// types.
return ABIArgInfo::getDirect(
llvm::IntegerType::get(getVMContext(), Size));
}
unsigned Alignment = getContext().getTypeAlign(RetTy);
Size = llvm::alignTo(Size, 64); // round up to multiple of 8 bytes
// We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
// For aggregates with 16-byte alignment, we use i128.
if (Alignment < 128 && Size == 128) {
llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
}
return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
}
return getNaturalAlignIndirect(RetTy);
}
/// isIllegalVectorType - check whether the vector type is legal for AArch64.
bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const {
if (const VectorType *VT = Ty->getAs<VectorType>()) {
// Check whether VT is a fixed-length SVE vector. These types are
// represented as scalable vectors in function args/return and must be
// coerced from fixed vectors.
if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector ||
VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector)
return true;
// Check whether VT is legal.
unsigned NumElements = VT->getNumElements();
uint64_t Size = getContext().getTypeSize(VT);
// NumElements should be power of 2.
if (!llvm::isPowerOf2_32(NumElements))
return true;
// arm64_32 has to be compatible with the ARM logic here, which allows huge
// vectors for some reason.
llvm::Triple Triple = getTarget().getTriple();
if (Triple.getArch() == llvm::Triple::aarch64_32 &&
Triple.isOSBinFormatMachO())
return Size <= 32;
return Size != 64 && (Size != 128 || NumElements == 1);
}
return false;
}
bool AArch64ABIInfo::isLegalVectorTypeForSwift(CharUnits totalSize,
llvm::Type *eltTy,
unsigned elts) const {
if (!llvm::isPowerOf2_32(elts))
return false;
if (totalSize.getQuantity() != 8 &&
(totalSize.getQuantity() != 16 || elts == 1))
return false;
return true;
}
bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
// Homogeneous aggregates for AAPCS64 must have base types of a floating
// point type or a short-vector type. This is the same as the 32-bit ABI,
// but with the difference that any floating-point type is allowed,
// including __fp16.
if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
if (BT->isFloatingPoint())
return true;
} else if (const VectorType *VT = Ty->getAs<VectorType>()) {
unsigned VecSize = getContext().getTypeSize(VT);
if (VecSize == 64 || VecSize == 128)
return true;
}
return false;
}
bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
uint64_t Members) const {
return Members <= 4;
}
Address AArch64ABIInfo::EmitAAPCSVAArg(Address VAListAddr, QualType Ty,
CodeGenFunction &CGF) const {
ABIArgInfo AI = classifyArgumentType(Ty, /*IsVariadic=*/true,
CGF.CurFnInfo->getCallingConvention());
bool IsIndirect = AI.isIndirect();
llvm::Type *BaseTy = CGF.ConvertType(Ty);
if (IsIndirect)
BaseTy = llvm::PointerType::getUnqual(BaseTy);
else if (AI.getCoerceToType())
BaseTy = AI.getCoerceToType();
unsigned NumRegs = 1;
if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) {
BaseTy = ArrTy->getElementType();
NumRegs = ArrTy->getNumElements();
}
bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy();
// The AArch64 va_list type and handling is specified in the Procedure Call
// Standard, section B.4:
//
// struct {
// void *__stack;
// void *__gr_top;
// void *__vr_top;
// int __gr_offs;
// int __vr_offs;
// };
llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
CharUnits TySize = getContext().getTypeSizeInChars(Ty);
CharUnits TyAlign = getContext().getTypeUnadjustedAlignInChars(Ty);
Address reg_offs_p = Address::invalid();
llvm::Value *reg_offs = nullptr;
int reg_top_index;
int RegSize = IsIndirect ? 8 : TySize.getQuantity();
if (!IsFPR) {
// 3 is the field number of __gr_offs
reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 3, "gr_offs_p");
reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
reg_top_index = 1; // field number for __gr_top
RegSize = llvm::alignTo(RegSize, 8);
} else {
// 4 is the field number of __vr_offs.
reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 4, "vr_offs_p");
reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
reg_top_index = 2; // field number for __vr_top
RegSize = 16 * NumRegs;
}
//=======================================
// Find out where argument was passed
//=======================================
// If reg_offs >= 0 we're already using the stack for this type of
// argument. We don't want to keep updating reg_offs (in case it overflows,
// though anyone passing 2GB of arguments, each at most 16 bytes, deserves
// whatever they get).
llvm::Value *UsingStack = nullptr;
UsingStack = CGF.Builder.CreateICmpSGE(
reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0));
CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
// Otherwise, at least some kind of argument could go in these registers, the
// question is whether this particular type is too big.
CGF.EmitBlock(MaybeRegBlock);
// Integer arguments may need to correct register alignment (for example a
// "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
// align __gr_offs to calculate the potential address.
if (!IsFPR && !IsIndirect && TyAlign.getQuantity() > 8) {
int Align = TyAlign.getQuantity();
reg_offs = CGF.Builder.CreateAdd(
reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
"align_regoffs");
reg_offs = CGF.Builder.CreateAnd(
reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align),
"aligned_regoffs");
}
// Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
// The fact that this is done unconditionally reflects the fact that
// allocating an argument to the stack also uses up all the remaining
// registers of the appropriate kind.
llvm::Value *NewOffset = nullptr;
NewOffset = CGF.Builder.CreateAdd(
reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs");
CGF.Builder.CreateStore(NewOffset, reg_offs_p);
// Now we're in a position to decide whether this argument really was in
// registers or not.
llvm::Value *InRegs = nullptr;
InRegs = CGF.Builder.CreateICmpSLE(
NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg");
CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
//=======================================
// Argument was in registers
//=======================================
// Now we emit the code for if the argument was originally passed in
// registers. First start the appropriate block:
CGF.EmitBlock(InRegBlock);
llvm::Value *reg_top = nullptr;
Address reg_top_p =
CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index, "reg_top_p");
reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
Address BaseAddr(CGF.Builder.CreateInBoundsGEP(CGF.Int8Ty, reg_top, reg_offs),
CharUnits::fromQuantity(IsFPR ? 16 : 8));
Address RegAddr = Address::invalid();
llvm::Type *MemTy = CGF.ConvertTypeForMem(Ty);
if (IsIndirect) {
// If it's been passed indirectly (actually a struct), whatever we find from
// stored registers or on the stack will actually be a struct **.
MemTy = llvm::PointerType::getUnqual(MemTy);
}
const Type *Base = nullptr;
uint64_t NumMembers = 0;
bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers);
if (IsHFA && NumMembers > 1) {
// Homogeneous aggregates passed in registers will have their elements split
// and stored 16-bytes apart regardless of size (they're notionally in qN,
// qN+1, ...). We reload and store into a temporary local variable
// contiguously.
assert(!IsIndirect && "Homogeneous aggregates should be passed directly");
auto BaseTyInfo = getContext().getTypeInfoInChars(QualType(Base, 0));
llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
Address Tmp = CGF.CreateTempAlloca(HFATy,
std::max(TyAlign, BaseTyInfo.Align));
// On big-endian platforms, the value will be right-aligned in its slot.
int Offset = 0;
if (CGF.CGM.getDataLayout().isBigEndian() &&
BaseTyInfo.Width.getQuantity() < 16)
Offset = 16 - BaseTyInfo.Width.getQuantity();
for (unsigned i = 0; i < NumMembers; ++i) {
CharUnits BaseOffset = CharUnits::fromQuantity(16 * i + Offset);
Address LoadAddr =
CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, BaseOffset);
LoadAddr = CGF.Builder.CreateElementBitCast(LoadAddr, BaseTy);
Address StoreAddr = CGF.Builder.CreateConstArrayGEP(Tmp, i);
llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
CGF.Builder.CreateStore(Elem, StoreAddr);
}
RegAddr = CGF.Builder.CreateElementBitCast(Tmp, MemTy);
} else {
// Otherwise the object is contiguous in memory.
// It might be right-aligned in its slot.
CharUnits SlotSize = BaseAddr.getAlignment();
if (CGF.CGM.getDataLayout().isBigEndian() && !IsIndirect &&
(IsHFA || !isAggregateTypeForABI(Ty)) &&
TySize < SlotSize) {
CharUnits Offset = SlotSize - TySize;
BaseAddr = CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, Offset);
}
RegAddr = CGF.Builder.CreateElementBitCast(BaseAddr, MemTy);
}
CGF.EmitBranch(ContBlock);
//=======================================
// Argument was on the stack
//=======================================
CGF.EmitBlock(OnStackBlock);
Address stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "stack_p");
llvm::Value *OnStackPtr = CGF.Builder.CreateLoad(stack_p, "stack");
// Again, stack arguments may need realignment. In this case both integer and
// floating-point ones might be affected.
if (!IsIndirect && TyAlign.getQuantity() > 8) {
int Align = TyAlign.getQuantity();
OnStackPtr = CGF.Builder.CreatePtrToInt(OnStackPtr, CGF.Int64Ty);
OnStackPtr = CGF.Builder.CreateAdd(
OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
"align_stack");
OnStackPtr = CGF.Builder.CreateAnd(
OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, -Align),
"align_stack");
OnStackPtr = CGF.Builder.CreateIntToPtr(OnStackPtr, CGF.Int8PtrTy);
}
Address OnStackAddr(OnStackPtr,
std::max(CharUnits::fromQuantity(8), TyAlign));
// All stack slots are multiples of 8 bytes.
CharUnits StackSlotSize = CharUnits::fromQuantity(8);
CharUnits StackSize;
if (IsIndirect)
StackSize = StackSlotSize;
else
StackSize = TySize.alignTo(StackSlotSize);
llvm::Value *StackSizeC = CGF.Builder.getSize(StackSize);
llvm::Value *NewStack = CGF.Builder.CreateInBoundsGEP(
CGF.Int8Ty, OnStackPtr, StackSizeC, "new_stack");
// Write the new value of __stack for the next call to va_arg
CGF.Builder.CreateStore(NewStack, stack_p);
if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
TySize < StackSlotSize) {
CharUnits Offset = StackSlotSize - TySize;
OnStackAddr = CGF.Builder.CreateConstInBoundsByteGEP(OnStackAddr, Offset);
}
OnStackAddr = CGF.Builder.CreateElementBitCast(OnStackAddr, MemTy);
CGF.EmitBranch(ContBlock);
//=======================================
// Tidy up
//=======================================
CGF.EmitBlock(ContBlock);
Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
OnStackAddr, OnStackBlock, "vaargs.addr");
if (IsIndirect)
return Address(CGF.Builder.CreateLoad(ResAddr, "vaarg.addr"),
TyAlign);
return ResAddr;
}
Address AArch64ABIInfo::EmitDarwinVAArg(Address VAListAddr, QualType Ty,
CodeGenFunction &CGF) const {
// The backend's lowering doesn't support va_arg for aggregates or
// illegal vector types. Lower VAArg here for these cases and use
// the LLVM va_arg instruction for everything else.
if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty))
return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
uint64_t PointerSize = getTarget().getPointerWidth(0) / 8;
CharUnits SlotSize = CharUnits::fromQuantity(PointerSize);
// Empty records are ignored for parameter passing purposes.
if (isEmptyRecord(getContext(), Ty, true)) {
Address Addr(CGF.Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
return Addr;
}
// The size of the actual thing passed, which might end up just
// being a pointer for indirect types.
auto TyInfo = getContext().getTypeInfoInChars(Ty);
// Arguments bigger than 16 bytes which aren't homogeneous
// aggregates should be passed indirectly.
bool IsIndirect = false;
if (TyInfo.Width.getQuantity() > 16) {
const Type *Base = nullptr;
uint64_t Members = 0;
IsIndirect = !isHomogeneousAggregate(Ty, Base, Members);
}
return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
TyInfo, SlotSize, /*AllowHigherAlign*/ true);
}
Address AArch64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
QualType Ty) const {
bool IsIndirect = false;
// Composites larger than 16 bytes are passed by reference.
if (isAggregateTypeForABI(Ty) && getContext().getTypeSize(Ty) > 128)
IsIndirect = true;
return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
CGF.getContext().getTypeInfoInChars(Ty),
CharUnits::fromQuantity(8),
/*allowHigherAlign*/ false);
}
//===----------------------------------------------------------------------===//
// ARM ABI Implementation
//===----------------------------------------------------------------------===//
namespace {
class ARMABIInfo : public SwiftABIInfo {
public:
enum ABIKind {
APCS = 0,
AAPCS = 1,
AAPCS_VFP = 2,
AAPCS16_VFP = 3,
};
private:
ABIKind Kind;
bool IsFloatABISoftFP;
public:
ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind)
: SwiftABIInfo(CGT), Kind(_Kind) {
setCCs();
IsFloatABISoftFP = CGT.getCodeGenOpts().FloatABI == "softfp" ||
CGT.getCodeGenOpts().FloatABI == ""; // default
}
bool isEABI() const {
switch (getTarget().getTriple().getEnvironment()) {
case llvm::Triple::Android:
case llvm::Triple::EABI:
case llvm::Triple::EABIHF:
case llvm::Triple::GNUEABI:
case llvm::Triple::GNUEABIHF:
case llvm::Triple::MuslEABI:
case llvm::Triple::MuslEABIHF:
return true;
default:
return false;
}
}
bool isEABIHF() const {
switch (getTarget().getTriple().getEnvironment()) {
case llvm::Triple::EABIHF:
case llvm::Triple::GNUEABIHF:
case llvm::Triple::MuslEABIHF:
return true;
default:
return false;
}
}
ABIKind getABIKind() const { return Kind; }
bool allowBFloatArgsAndRet() const override {
return !IsFloatABISoftFP && getTarget().hasBFloat16Type();
}
private:
ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic,
unsigned functionCallConv) const;
ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic,
unsigned functionCallConv) const;
ABIArgInfo classifyHomogeneousAggregate(QualType Ty, const Type *Base,
uint64_t Members) const;
ABIArgInfo coerceIllegalVector(QualType Ty) const;
bool isIllegalVectorType(QualType Ty) const;
bool containsAnyFP16Vectors(QualType Ty) const;
bool isHomogeneousAggregateBaseType(QualType Ty) const override;
bool isHomogeneousAggregateSmallEnough(const Type *Ty,
uint64_t Members) const override;
bool isEffectivelyAAPCS_VFP(unsigned callConvention, bool acceptHalf) const;
void computeInfo(CGFunctionInfo &FI) const override;
Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
QualType Ty) const override;
llvm::CallingConv::ID getLLVMDefaultCC() const;
llvm::CallingConv::ID getABIDefaultCC() const;
void setCCs();
bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
bool asReturnValue) const override {
return occupiesMoreThan(CGT, scalars, /*total*/ 4);
}
bool isSwiftErrorInRegister() const override {
return true;
}
bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy,
unsigned elts) const override;
};
class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
public:
ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
: TargetCodeGenInfo(std::make_unique<ARMABIInfo>(CGT, K)) {}
const ARMABIInfo &getABIInfo() const {
return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
}
int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
return 13;
}
StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
return "mov\tr7, r7\t\t// marker for objc_retainAutoreleaseReturnValue";
}
bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
llvm::Value *Address) const override {
llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
// 0-15 are the 16 integer registers.
AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
return false;
}
unsigned getSizeOfUnwindException() const override {
if (getABIInfo().isEABI()) return 88;
return TargetCodeGenInfo::getSizeOfUnwindException();
}
void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
CodeGen::CodeGenModule &CGM) const override {
if (GV->isDeclaration())
return;
const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
if (!FD)
return;
const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
if (!Attr)
return;
const char *Kind;
switch (Attr->getInterrupt()) {
case ARMInterruptAttr::Generic: Kind = ""; break;
case ARMInterruptAttr::IRQ: Kind = "IRQ"; break;
case ARMInterruptAttr::FIQ: Kind = "FIQ"; break;
case ARMInterruptAttr::SWI: Kind = "SWI"; break;
case ARMInterruptAttr::ABORT: Kind = "ABORT"; break;
case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break;
}
llvm::Function *Fn = cast<llvm::Function>(GV);
Fn->addFnAttr("interrupt", Kind);
ARMABIInfo::ABIKind ABI = cast<ARMABIInfo>(getABIInfo()).getABIKind();
if (ABI == ARMABIInfo::APCS)
return;
// AAPCS guarantees that sp will be 8-byte aligned on any public interface,
// however this is not necessarily true on taking any interrupt. Instruct
// the backend to perform a realignment as part of the function prologue.
llvm::AttrBuilder B;
B.addStackAlignmentAttr(8);
Fn->addFnAttrs(B);
}
};
class WindowsARMTargetCodeGenInfo : public ARMTargetCodeGenInfo {
public:
WindowsARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
: ARMTargetCodeGenInfo(CGT, K) {}
void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
CodeGen::CodeGenModule &CGM) const override;
void getDependentLibraryOption(llvm::StringRef Lib,
llvm::SmallString<24> &Opt) const override {
Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib);
}
void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value,
llvm::SmallString<32> &Opt) const override {
Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
}
};
void WindowsARMTargetCodeGenInfo::setTargetAttributes(
const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
ARMTargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
if (GV->isDeclaration())
return;
addStackProbeTargetAttributes(D, GV, CGM);
}
}
void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
if (!::classifyReturnType(getCXXABI(), FI, *this))
FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), FI.isVariadic(),
FI.getCallingConvention());
for (auto &I : FI.arguments())
I.info = classifyArgumentType(I.type, FI.isVariadic(),
FI.getCallingConvention());
// Always honor user-specified calling convention.
if (FI.getCallingConvention() != llvm::CallingConv::C)
return;
llvm::CallingConv::ID cc = getRuntimeCC();
if (cc != llvm::CallingConv::C)
FI.setEffectiveCallingConvention(cc);
}
/// Return the default calling convention that LLVM will use.
llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
// The default calling convention that LLVM will infer.
if (isEABIHF() || getTarget().getTriple().isWatchABI())
return llvm::CallingConv::ARM_AAPCS_VFP;
else if (isEABI())
return llvm::CallingConv::ARM_AAPCS;
else
return llvm::CallingConv::ARM_APCS;
}
/// Return the calling convention that our ABI would like us to use
/// as the C calling convention.
llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
switch (getABIKind()) {
case APCS: return llvm::CallingConv::ARM_APCS;
case AAPCS: return llvm::CallingConv::ARM_AAPCS;
case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
case AAPCS16_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
}
llvm_unreachable("bad ABI kind");
}
void ARMABIInfo::setCCs() {
assert(getRuntimeCC() == llvm::CallingConv::C);
// Don't muddy up the IR with a ton of explicit annotations if
// they'd just match what LLVM will infer from the triple.
llvm::CallingConv::ID abiCC = getABIDefaultCC();
if (abiCC != getLLVMDefaultCC())
RuntimeCC = abiCC;
}
ABIArgInfo ARMABIInfo::coerceIllegalVector(QualType Ty) const {
uint64_t Size = getContext().getTypeSize(Ty);
if (Size <= 32) {
llvm::Type *ResType =
llvm::Type::getInt32Ty(getVMContext());
return ABIArgInfo::getDirect(ResType);
}
if (Size == 64 || Size == 128) {
auto *ResType = llvm::FixedVectorType::get(
llvm::Type::getInt32Ty(getVMContext()), Size / 32);
return ABIArgInfo::getDirect(ResType);
}
return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
}
ABIArgInfo ARMABIInfo::classifyHomogeneousAggregate(QualType Ty,
const Type *Base,
uint64_t Members) const {
assert(Base && "Base class should be set for homogeneous aggregate");
// Base can be a floating-point or a vector.
if (const VectorType *VT = Base->getAs<VectorType>()) {
// FP16 vectors should be converted to integer vectors
if (!getTarget().hasLegalHalfType() && containsAnyFP16Vectors(Ty)) {
uint64_t Size = getContext().getTypeSize(VT);
auto *NewVecTy = llvm::FixedVectorType::get(
llvm::Type::getInt32Ty(getVMContext()), Size / 32);
llvm::Type *Ty = llvm::ArrayType::get(NewVecTy, Members);
return ABIArgInfo::getDirect(Ty, 0, nullptr, false);
}
}
unsigned Align = 0;
if (getABIKind() == ARMABIInfo::AAPCS ||
getABIKind() == ARMABIInfo::AAPCS_VFP) {
// For alignment adjusted HFAs, cap the argument alignment to 8, leave it
// default otherwise.
Align = getContext().getTypeUnadjustedAlignInChars(Ty).getQuantity();
unsigned BaseAlign = getContext().getTypeAlignInChars(Base).getQuantity();
Align = (Align > BaseAlign && Align >= 8) ? 8 : 0;
}
return ABIArgInfo::getDirect(nullptr, 0, nullptr, false, Align);
}
ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty, bool isVariadic,
unsigned functionCallConv) const {
// 6.1.2.1 The following argument types are VFP CPRCs:
// A single-precision floating-point type (including promoted
// half-precision types); A double-precision floating-point type;
// A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
// with a Base Type of a single- or double-precision floating-point type,
// 64-bit containerized vectors or 128-bit containerized vectors with one
// to four Elements.
// Variadic functions should always marshal to the base standard.
bool IsAAPCS_VFP =
!isVariadic && isEffectivelyAAPCS_VFP(functionCallConv, /* AAPCS16 */ false);
Ty = useFirstFieldIfTransparentUnion(Ty);
// Handle illegal vector types here.
if (isIllegalVectorType(Ty))
return coerceIllegalVector(Ty);
if (!isAggregateTypeForABI(Ty)) {
// Treat an enum type as its underlying type.
if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
Ty = EnumTy->getDecl()->getIntegerType();
}
if (const auto *EIT = Ty->getAs<ExtIntType>())
if (EIT->getNumBits() > 64)
return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
: ABIArgInfo::getDirect());
}
if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
}
// Ignore empty records.
if (isEmptyRecord(getContext(), Ty, true))
return ABIArgInfo::getIgnore();
if (IsAAPCS_VFP) {
// Homogeneous Aggregates need to be expanded when we can fit the aggregate
// into VFP registers.
const Type *Base = nullptr;
uint64_t Members = 0;
if (isHomogeneousAggregate(Ty, Base, Members))
return classifyHomogeneousAggregate(Ty, Base, Members);
} else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
// WatchOS does have homogeneous aggregates. Note that we intentionally use
// this convention even for a variadic function: the backend will use GPRs
// if needed.
const Type *Base = nullptr;
uint64_t Members = 0;
if (isHomogeneousAggregate(Ty, Base, Members)) {
assert(Base && Members <= 4 && "unexpected homogeneous aggregate");
llvm::Type *Ty =
llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members);
return ABIArgInfo::getDirect(Ty, 0, nullptr, false);
}
}
if (getABIKind() == ARMABIInfo::AAPCS16_VFP &&
getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(16)) {
// WatchOS is adopting the 64-bit AAPCS rule on composite types: if they're
// bigger than 128-bits, they get placed in space allocated by the caller,
// and a pointer is passed.
return ABIArgInfo::getIndirect(
CharUnits::fromQuantity(getContext().getTypeAlign(Ty) / 8), false);
}
// Support byval for ARM.
// The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
// most 8-byte. We realign the indirect argument if type alignment is bigger
// than ABI alignment.
uint64_t ABIAlign = 4;
uint64_t TyAlign;
if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
getABIKind() == ARMABIInfo::AAPCS) {
TyAlign = getContext().getTypeUnadjustedAlignInChars(Ty).getQuantity();
ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
} else {
TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
}
if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
assert(getABIKind() != ARMABIInfo::AAPCS16_VFP && "unexpected byval");
return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
/*ByVal=*/true,
/*Realign=*/TyAlign > ABIAlign);
}
// On RenderScript, coerce Aggregates <= 64 bytes to an integer array of
// same size and alignment.
if (getTarget().isRenderScriptTarget()) {
return coerceToIntArray(Ty, getContext(), getVMContext());
}
// Otherwise, pass by coercing to a structure of the appropriate size.
llvm::Type* ElemTy;
unsigned SizeRegs;
// FIXME: Try to match the types of the arguments more accurately where
// we can.
if (TyAlign <= 4) {
ElemTy = llvm::Type::getInt32Ty(getVMContext());
SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
} else {
ElemTy = llvm::Type::getInt64Ty(getVMContext());
SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
}
return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs));
}
static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
llvm::LLVMContext &VMContext) {
// APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
// is called integer-like if its size is less than or equal to one word, and
// the offset of each of its addressable sub-fields is zero.
uint64_t Size = Context.getTypeSize(Ty);
// Check that the type fits in a word.
if (Size > 32)
return false;
// FIXME: Handle vector types!
if (Ty->isVectorType())
return false;
// Float types are never treated as "integer like".
if (Ty->isRealFloatingType())
return false;
// If this is a builtin or pointer type then it is ok.
if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
return true;
// Small complex integer types are "integer like".
if (const ComplexType *CT = Ty->getAs<ComplexType>())
return isIntegerLikeType(CT->getElementType(), Context, VMContext);
// Single element and zero sized arrays should be allowed, by the definition
// above, but they are not.
// Otherwise, it must be a record type.
const RecordType *RT = Ty->getAs<RecordType>();
if (!RT) return false;
// Ignore records with flexible arrays.
const RecordDecl *RD = RT->getDecl();
if (RD->hasFlexibleArrayMember())
return false;
// Check that all sub-fields are at offset 0, and are themselves "integer
// like".
const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
bool HadField = false;
unsigned idx = 0;
for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
i != e; ++i, ++idx) {
const FieldDecl *FD = *i;
// Bit-fields are not addressable, we only need to verify they are "integer
// like". We still have to disallow a subsequent non-bitfield, for example:
// struct { int : 0; int x }
// is non-integer like according to gcc.
if (FD->isBitField()) {
if (!RD->isUnion())
HadField = true;
if (!isIntegerLikeType(FD->getType(), Context, VMContext))
return false;
continue;
}
// Check if this field is at offset 0.
if (Layout.getFieldOffset(idx) != 0)
return false;
if (!isIntegerLikeType(FD->getType(), Context, VMContext))
return false;
// Only allow at most one field in a structure. This doesn't match the
// wording above, but follows gcc in situations with a field following an
// empty structure.
if (!RD->isUnion()) {
if (HadField)
return false;
HadField = true;
}
}
return true;
}
ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy, bool isVariadic,
unsigned functionCallConv) const {
// Variadic functions should always marshal to the base standard.
bool IsAAPCS_VFP =
!isVariadic && isEffectivelyAAPCS_VFP(functionCallConv, /* AAPCS16 */ true);
if (RetTy->isVoidType())
return ABIArgInfo::getIgnore();
if (const VectorType *VT = RetTy->getAs<VectorType>()) {
// Large vector types should be returned via memory.
if (getContext().getTypeSize(RetTy) > 128)
return getNaturalAlignIndirect(RetTy);
// TODO: FP16/BF16 vectors should be converted to integer vectors
// This check is similar to isIllegalVectorType - refactor?
if ((!getTarget().hasLegalHalfType() &&
(VT->getElementType()->isFloat16Type() ||
VT->getElementType()->isHalfType())) ||
(IsFloatABISoftFP &&
VT->getElementType()->isBFloat16Type()))
return coerceIllegalVector(RetTy);
}
if (!isAggregateTypeForABI(RetTy)) {
// Treat an enum type as its underlying type.
if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
RetTy = EnumTy->getDecl()->getIntegerType();
if (const auto *EIT = RetTy->getAs<ExtIntType>())
if (EIT->getNumBits() > 64)
return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
return isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
: ABIArgInfo::getDirect();
}
// Are we following APCS?
if (getABIKind() == APCS) {
if (isEmptyRecord(getContext(), RetTy, false))
return ABIArgInfo::getIgnore();
// Complex types are all returned as packed integers.
//
// FIXME: Consider using 2 x vector types if the back end handles them
// correctly.
if (RetTy->isAnyComplexType())
return ABIArgInfo::getDirect(llvm::IntegerType::get(
getVMContext(), getContext().getTypeSize(RetTy)));
// Integer like structures are returned in r0.
if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
// Return in the smallest viable integer type.
uint64_t Size = getContext().getTypeSize(RetTy);
if (Size <= 8)
return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
if (Size <= 16)
return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
}
// Otherwise return in memory.
return getNaturalAlignIndirect(RetTy);
}
// Otherwise this is an AAPCS variant.
if (isEmptyRecord(getContext(), RetTy, true))
return ABIArgInfo::getIgnore();
// Check for homogeneous aggregates with AAPCS-VFP.
if (IsAAPCS_VFP) {
const Type *Base = nullptr;
uint64_t Members = 0;
if (isHomogeneousAggregate(RetTy, Base, Members))
return classifyHomogeneousAggregate(RetTy, Base, Members);
}
// Aggregates <= 4 bytes are returned in r0; other aggregates
// are returned indirectly.
uint64_t Size = getContext().getTypeSize(RetTy);
if (Size <= 32) {
// On RenderScript, coerce Aggregates <= 4 bytes to an integer array of
// same size and alignment.
if (getTarget().isRenderScriptTarget()) {
return coerceToIntArray(RetTy, getContext(), getVMContext());
}
if (getDataLayout().isBigEndian())
// Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4)
return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
// Return in the smallest viable integer type.
if (Size <= 8)
return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
if (Size <= 16)
return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
} else if (Size <= 128 && getABIKind() == AAPCS16_VFP) {
llvm::Type *Int32Ty = llvm::Type::getInt32Ty(getVMContext());
llvm::Type *CoerceTy =
llvm::ArrayType::get(Int32Ty, llvm::alignTo(Size, 32) / 32);
return ABIArgInfo::getDirect(CoerceTy);
}
return getNaturalAlignIndirect(RetTy);
}
/// isIllegalVector - check whether Ty is an illegal vector type.
bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
if (const VectorType *VT = Ty->getAs<VectorType> ()) {
// On targets that don't support half, fp16 or bfloat, they are expanded
// into float, and we don't want the ABI to depend on whether or not they
// are supported in hardware. Thus return false to coerce vectors of these
// types into integer vectors.
// We do not depend on hasLegalHalfType for bfloat as it is a
// separate IR type.
if ((!getTarget().hasLegalHalfType() &&
(VT->getElementType()->isFloat16Type() ||
VT->getElementType()->isHalfType())) ||
(IsFloatABISoftFP &&
VT->getElementType()->isBFloat16Type()))
return true;
if (isAndroid()) {
// Android shipped using Clang 3.1, which supported a slightly different
// vector ABI. The primary differences were that 3-element vector types
// were legal, and so were sub 32-bit vectors (i.e. <2 x i8>). This path
// accepts that legacy behavior for Android only.
// Check whether VT is legal.
unsigned NumElements = VT->getNumElements();
// NumElements should be power of 2 or equal to 3.
if (!llvm::isPowerOf2_32(NumElements) && NumElements != 3)
return true;
} else {
// Check whether VT is legal.
unsigned NumElements = VT->getNumElements();
uint64_t Size = getContext().getTypeSize(VT);
// NumElements should be power of 2.
if (!llvm::isPowerOf2_32(NumElements))
return true;
// Size should be greater than 32 bits.
return Size <= 32;
}
}
return false;
}
/// Return true if a type contains any 16-bit floating point vectors
bool ARMABIInfo::containsAnyFP16Vectors(QualType Ty) const {
if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
uint64_t NElements = AT->getSize().getZExtValue();
if (NElements == 0)
return false;
return containsAnyFP16Vectors(AT->getElementType());
} else if (const RecordType *RT = Ty->getAs<RecordType>()) {
const RecordDecl *RD = RT->getDecl();
// If this is a C++ record, check the bases first.
if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
if (llvm::any_of(CXXRD->bases(), [this](const CXXBaseSpecifier &B) {
return containsAnyFP16Vectors(B.getType());
}))
return true;
if (llvm::any_of(RD->fields(), [this](FieldDecl *FD) {
return FD && containsAnyFP16Vectors(FD->getType());
}))
return true;
return false;
} else {
if (const VectorType *VT = Ty->getAs<VectorType>())
return (VT->getElementType()->isFloat16Type() ||
VT->getElementType()->isBFloat16Type() ||
VT->getElementType()->isHalfType());
return false;
}
}
bool ARMABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize,
llvm::Type *eltTy,
unsigned numElts) const {
if (!llvm::isPowerOf2_32(numElts))
return false;
unsigned size = getDataLayout().getTypeStoreSizeInBits(eltTy);
if (size > 64)
return false;
if (vectorSize.getQuantity() != 8 &&
(vectorSize.getQuantity() != 16 || numElts == 1))
return false;
return true;
}
bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
// Homogeneous aggregates for AAPCS-VFP must have base types of float,
// double, or 64-bit or 128-bit vectors.
if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
if (BT->getKind() == BuiltinType::Float ||
BT->getKind() == BuiltinType::Double ||
BT->getKind() == BuiltinType::LongDouble)
return true;
} else if (const VectorType *VT = Ty->getAs<VectorType>()) {
unsigned VecSize = getContext().getTypeSize(VT);
if (VecSize == 64 || VecSize == 128)
return true;
}
return false;
}
bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
uint64_t Members) const {
return Members <= 4;
}
bool ARMABIInfo::isEffectivelyAAPCS_VFP(unsigned callConvention,
bool acceptHalf) const {
// Give precedence to user-specified calling conventions.
if (callConvention != llvm::CallingConv::C)
return (callConvention == llvm::CallingConv::ARM_AAPCS_VFP);
else
return (getABIKind() == AAPCS_VFP) ||
(acceptHalf && (getABIKind() == AAPCS16_VFP));
}
Address ARMABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
QualType Ty) const {
CharUnits SlotSize = CharUnits::fromQuantity(4);
// Empty records are ignored for parameter passing purposes.
if (isEmptyRecord(getContext(), Ty, true)) {
Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize);
Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
return Addr;
}
CharUnits TySize = getContext().getTypeSizeInChars(Ty);
CharUnits TyAlignForABI = getContext().getTypeUnadjustedAlignInChars(Ty);
// Use indirect if size of the illegal vector is bigger than 16 bytes.
bool IsIndirect = false;
const Type *Base = nullptr;
uint64_t Members = 0;
if (TySize > CharUnits::fromQuantity(16) && isIllegalVectorType(Ty)) {
IsIndirect = true;
// ARMv7k passes structs bigger than 16 bytes indirectly, in space
// allocated by the caller.
} else if (TySize > CharUnits::fromQuantity(16) &&
getABIKind() == ARMABIInfo::AAPCS16_VFP &&
!isHomogeneousAggregate(Ty, Base, Members)) {
IsIndirect = true;
// Otherwise, bound the type's ABI alignment.
// The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
// APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
// Our callers should be prepared to handle an under-aligned address.
} else if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
getABIKind() == ARMABIInfo::AAPCS) {
TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(8));
} else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
// ARMv7k allows type alignment up to 16 bytes.
TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(16));
} else {
TyAlignForABI = CharUnits::fromQuantity(4);
}
TypeInfoChars TyInfo(TySize, TyAlignForABI, AlignRequirementKind::None);
return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TyInfo,
SlotSize, /*AllowHigherAlign*/ true);
}
//===----------------------------------------------------------------------===//
// NVPTX ABI Implementation
//===----------------------------------------------------------------------===//
namespace {
class NVPTXTargetCodeGenInfo;
class NVPTXABIInfo : public ABIInfo {
NVPTXTargetCodeGenInfo &CGInfo;
public:
NVPTXABIInfo(CodeGenTypes &CGT, NVPTXTargetCodeGenInfo &Info)
: ABIInfo(CGT), CGInfo(Info) {}
ABIArgInfo classifyReturnType(QualType RetTy) const;
ABIArgInfo classifyArgumentType(QualType Ty) const;
void computeInfo(CGFunctionInfo &FI) const override;
Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
QualType Ty) const override;
bool isUnsupportedType(QualType T) const;
ABIArgInfo coerceToIntArrayWithLimit(QualType Ty, unsigned MaxSize) const;
};
class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
public:
NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
: TargetCodeGenInfo(std::make_unique<NVPTXABIInfo>(CGT, *this)) {}
void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
CodeGen::CodeGenModule &M) const override;
bool shouldEmitStaticExternCAliases() const override;
llvm::Type *getCUDADeviceBuiltinSurfaceDeviceType() const override {
// On the device side, surface reference is represented as an object handle
// in 64-bit integer.
return llvm::Type::getInt64Ty(getABIInfo().getVMContext());
}
llvm::Type *getCUDADeviceBuiltinTextureDeviceType() const override {
// On the device side, texture reference is represented as an object handle
// in 64-bit integer.
return llvm::Type::getInt64Ty(getABIInfo().getVMContext());
}
bool emitCUDADeviceBuiltinSurfaceDeviceCopy(CodeGenFunction &CGF, LValue Dst,
LValue Src) const override {
emitBuiltinSurfTexDeviceCopy(CGF, Dst, Src);
return true;
}
bool emitCUDADeviceBuiltinTextureDeviceCopy(CodeGenFunction &CGF, LValue Dst,
LValue Src) const override {
emitBuiltinSurfTexDeviceCopy(CGF, Dst, Src);
return true;
}
private:
// Adds a NamedMDNode with GV, Name, and Operand as operands, and adds the
// resulting MDNode to the nvvm.annotations MDNode.
static void addNVVMMetadata(llvm::GlobalValue *GV, StringRef Name,
int Operand);
static void emitBuiltinSurfTexDeviceCopy(CodeGenFunction &CGF, LValue Dst,
LValue Src) {
llvm::Value *Handle = nullptr;
llvm::Constant *C =
llvm::dyn_cast<llvm::Constant>(Src.getAddress(CGF).getPointer());
// Lookup `addrspacecast` through the constant pointer if any.
if (auto *ASC = llvm::dyn_cast_or_null<llvm::AddrSpaceCastOperator>(C))
C = llvm::cast<llvm::Constant>(ASC->getPointerOperand());
if (auto *GV = llvm::dyn_cast_or_null<llvm::GlobalVariable>(C)) {
// Load the handle from the specific global variable using
// `nvvm.texsurf.handle.internal` intrinsic.
Handle = CGF.EmitRuntimeCall(
CGF.CGM.getIntrinsic(llvm::Intrinsic::nvvm_texsurf_handle_internal,
{GV->getType()}),
{GV}, "texsurf_handle");
} else
Handle = CGF.EmitLoadOfScalar(Src, SourceLocation());
CGF.EmitStoreOfScalar(Handle, Dst);
}
};
/// Checks if the type is unsupported directly by the current target.
bool NVPTXABIInfo::isUnsupportedType(QualType T) const {
ASTContext &Context = getContext();
if (!Context.getTargetInfo().hasFloat16Type() && T->isFloat16Type())
return true;
if (!Context.getTargetInfo().hasFloat128Type() &&
(T->isFloat128Type() ||
(T->isRealFloatingType() && Context.getTypeSize(T) == 128)))
return true;
if (const auto *EIT = T->getAs<ExtIntType>())
return EIT->getNumBits() >
(Context.getTargetInfo().hasInt128Type() ? 128U : 64U);
if (!Context.getTargetInfo().hasInt128Type() && T->isIntegerType() &&
Context.getTypeSize(T) > 64U)
return true;
if (const auto *AT = T->getAsArrayTypeUnsafe())
return isUnsupportedType(AT->getElementType());
const auto *RT = T->getAs<RecordType>();
if (!RT)
return false;
const RecordDecl *RD = RT->getDecl();
// If this is a C++ record, check the bases first.
if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
for (const CXXBaseSpecifier &I : CXXRD->bases())
if (isUnsupportedType(I.getType()))
return true;
for (const FieldDecl *I : RD->fields())
if (isUnsupportedType(I->getType()))
return true;
return false;
}
/// Coerce the given type into an array with maximum allowed size of elements.
ABIArgInfo NVPTXABIInfo::coerceToIntArrayWithLimit(QualType Ty,
unsigned MaxSize) const {
// Alignment and Size are measured in bits.
const uint64_t Size = getContext().getTypeSize(Ty);
const uint64_t Alignment = getContext().getTypeAlign(Ty);
const unsigned Div = std::min<unsigned>(MaxSize, Alignment);
llvm::Type *IntType = llvm::Type::getIntNTy(getVMContext(), Div);
const uint64_t NumElements = (Size + Div - 1) / Div;
return ABIArgInfo::getDirect(llvm::ArrayType::get(IntType, NumElements));
}
ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
if (RetTy->isVoidType())
return ABIArgInfo::getIgnore();
if (getContext().getLangOpts().OpenMP &&
getContext().getLangOpts().OpenMPIsDevice && isUnsupportedType(RetTy))
return coerceToIntArrayWithLimit(RetTy, 64);
// note: this is different from default ABI
if (!RetTy->isScalarType())
return ABIArgInfo::getDirect();
// Treat an enum type as its underlying type.
if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
RetTy = EnumTy->getDecl()->getIntegerType();
return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
: ABIArgInfo::getDirect());
}
ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
// Treat an enum type as its underlying type.
if (const EnumType *EnumTy = Ty->getAs<EnumType>())
Ty = EnumTy->getDecl()->getIntegerType();
// Return aggregates type as indirect by value
if (isAggregateTypeForABI(Ty)) {
// Under CUDA device compilation, tex/surf builtin types are replaced with
// object types and passed directly.
if (getContext().getLangOpts().CUDAIsDevice) {
if (Ty->isCUDADeviceBuiltinSurfaceType())
return ABIArgInfo::getDirect(
CGInfo.getCUDADeviceBuiltinSurfaceDeviceType());
if (Ty->isCUDADeviceBuiltinTextureType())
return ABIArgInfo::getDirect(
CGInfo.getCUDADeviceBuiltinTextureDeviceType());
}
return getNaturalAlignIndirect(Ty, /* byval */ true);
}
if (const auto *EIT = Ty->getAs<ExtIntType>()) {
if ((EIT->getNumBits() > 128) ||
(!getContext().getTargetInfo().hasInt128Type() &&
EIT->getNumBits() > 64))
return getNaturalAlignIndirect(Ty, /* byval */ true);
}
return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
: ABIArgInfo::getDirect());
}
void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
if (!getCXXABI().classifyReturnType(FI))
FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
for (auto &I : FI.arguments())
I.info = classifyArgumentType(I.type);
// Always honor user-specified calling convention.
if (FI.getCallingConvention() != llvm::CallingConv::C)
return;
FI.setEffectiveCallingConvention(getRuntimeCC());
}
Address NVPTXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
QualType Ty) const {
llvm_unreachable("NVPTX does not support varargs");
}
void NVPTXTargetCodeGenInfo::setTargetAttributes(
const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
if (GV->isDeclaration())
return;
const VarDecl *VD = dyn_cast_or_null<VarDecl>(D);
if (VD) {
if (M.getLangOpts().CUDA) {
if (VD->getType()->isCUDADeviceBuiltinSurfaceType())
addNVVMMetadata(GV, "surface", 1);
else if (VD->getType()->isCUDADeviceBuiltinTextureType())
addNVVMMetadata(GV, "texture", 1);
return;
}
}
const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
if (!FD) return;
llvm::Function *F = cast<llvm::Function>(GV);
// Perform special handling in OpenCL mode
if (M.getLangOpts().OpenCL || M.getLangOpts().SYCLIsDevice) {
// Use OpenCL function attributes to check for kernel functions
// By default, all functions are device functions
if (FD->hasAttr<OpenCLKernelAttr>()) {
// OpenCL __kernel functions get kernel metadata
// Create !{<func-ref>, metadata !"kernel", i32 1} node
addNVVMMetadata(F, "kernel", 1);
// And kernel functions are not subject to inlining
F->addFnAttr(llvm::Attribute::NoInline);
}
}
// Perform special handling in CUDA mode.
if (M.getLangOpts().CUDA) {
// CUDA __global__ functions get a kernel metadata entry. Since
// __global__ functions cannot be called from the device, we do not
// need to set the noinline attribute.
if (FD->hasAttr<CUDAGlobalAttr>()) {
// Create !{<func-ref>, metadata !"kernel", i32 1} node
addNVVMMetadata(F, "kernel", 1);
}
if (CUDALaunchBoundsAttr *Attr = FD->getAttr<CUDALaunchBoundsAttr>()) {
// Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node
llvm::APSInt MaxThreads(32);
MaxThreads = Attr->getMaxThreads()->EvaluateKnownConstInt(M.getContext());
if (MaxThreads > 0)
addNVVMMetadata(F, "maxntidx", MaxThreads.getExtValue());
// min blocks is an optional argument for CUDALaunchBoundsAttr. If it was
// not specified in __launch_bounds__ or if the user specified a 0 value,
// we don't have to add a PTX directive.
if (Attr->getMinBlocks()) {
llvm::APSInt MinBlocks(32);
MinBlocks = Attr->getMinBlocks()->EvaluateKnownConstInt(M.getContext());
if (MinBlocks > 0)
// Create !{<func-ref>, metadata !"minctasm", i32 <val>} node
addNVVMMetadata(F, "minctasm", MinBlocks.getExtValue());
}
}
}
}
void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::GlobalValue *GV,
StringRef Name, int Operand) {
llvm::Module *M = GV->getParent();
llvm::LLVMContext &Ctx = M->getContext();
// Get "nvvm.annotations" metadata node
llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
llvm::Metadata *MDVals[] = {
llvm::ConstantAsMetadata::get(GV), llvm::MDString::get(Ctx, Name),
llvm::ConstantAsMetadata::get(
llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))};
// Append metadata to nvvm.annotations
MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
}
bool NVPTXTargetCodeGenInfo::shouldEmitStaticExternCAliases() const {
return false;
}
}
//===----------------------------------------------------------------------===//
// SystemZ ABI Implementation
//===----------------------------------------------------------------------===//
namespace {
class SystemZABIInfo : public SwiftABIInfo {
bool HasVector;
bool IsSoftFloatABI;
public:
SystemZABIInfo(CodeGenTypes &CGT, bool HV, bool SF)
: SwiftABIInfo(CGT), HasVector(HV), IsSoftFloatABI(SF) {}
bool isPromotableIntegerTypeForABI(QualType Ty) const;
bool isCompoundType(QualType Ty) const;
bool isVectorArgumentType(QualType Ty) const;
bool isFPArgumentType(QualType Ty) const;
QualType GetSingleElementType(QualType Ty) const;
ABIArgInfo classifyReturnType(QualType RetTy) const;
ABIArgInfo classifyArgumentType(QualType ArgTy) const;
void computeInfo(CGFunctionInfo &FI) const override {
if (!getCXXABI().classifyReturnType(FI))
FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
for (auto &I : FI.arguments())
I.info = classifyArgumentType(I.type);
}
Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
QualType Ty) const override;
bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
bool asReturnValue) const override {
return occupiesMoreThan(CGT, scalars, /*total*/ 4);
}
bool isSwiftErrorInRegister() const override {
return false;
}
};
class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
public:
SystemZTargetCodeGenInfo(CodeGenTypes &CGT, bool HasVector, bool SoftFloatABI)
: TargetCodeGenInfo(
std::make_unique<SystemZABIInfo>(CGT, HasVector, SoftFloatABI)) {}
llvm::Value *testFPKind(llvm::Value *V, unsigned BuiltinID,
CGBuilderTy &Builder,
CodeGenModule &CGM) const override {
assert(V->getType()->isFloatingPointTy() && "V should have an FP type.");
// Only use TDC in constrained FP mode.
if (!Builder.getIsFPConstrained())
return nullptr;
llvm::Type *Ty = V->getType();
if (Ty->isFloatTy() || Ty->isDoubleTy() || Ty->isFP128Ty()) {
llvm::Module &M = CGM.getModule();
auto &Ctx = M.getContext();
llvm::Function *TDCFunc =
llvm::Intrinsic::getDeclaration(&M, llvm::Intrinsic::s390_tdc, Ty);
unsigned TDCBits = 0;
switch (BuiltinID) {
case Builtin::BI__builtin_isnan:
TDCBits = 0xf;
break;
case Builtin::BIfinite:
case Builtin::BI__finite:
case Builtin::BIfinitef:
case Builtin::BI__finitef:
case Builtin::BIfinitel:
case Builtin::BI__finitel:
case Builtin::BI__builtin_isfinite:
TDCBits = 0xfc0;
break;
case Builtin::BI__builtin_isinf:
TDCBits = 0x30;
break;
default:
break;
}
if (TDCBits)
return Builder.CreateCall(
TDCFunc,
{V, llvm::ConstantInt::get(llvm::Type::getInt64Ty(Ctx), TDCBits)});
}
return nullptr;
}
};
}
bool SystemZABIInfo::isPromotableIntegerTypeForABI(QualType Ty) const {
// Treat an enum type as its underlying type.
if (const EnumType *EnumTy = Ty->getAs<EnumType>())
Ty = EnumTy->getDecl()->getIntegerType();
// Promotable integer types are required to be promoted by the ABI.
if (ABIInfo::isPromotableIntegerTypeForABI(Ty))
return true;
if (const auto *EIT = Ty->getAs<ExtIntType>())
if (EIT->getNumBits() < 64)
return true;
// 32-bit values must also be promoted.
if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
switch (BT->getKind()) {
case BuiltinType::Int:
case BuiltinType::UInt:
return true;
default:
return false;
}
return false;
}
bool SystemZABIInfo::isCompoundType(QualType Ty) const {
return (Ty->isAnyComplexType() ||
Ty->isVectorType() ||
isAggregateTypeForABI(Ty));
}
bool SystemZABIInfo::isVectorArgumentType(QualType Ty) const {
return (HasVector &&
Ty->isVectorType() &&
getContext().getTypeSize(Ty) <= 128);
}
bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
if (IsSoftFloatABI)
return false;
if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
switch (BT->getKind()) {
case BuiltinType::Float:
case BuiltinType::Double:
return true;
default:
return false;
}
return false;
}
QualType SystemZABIInfo::GetSingleElementType(QualType Ty) const {
const RecordType *RT = Ty->getAs<RecordType>();
if (RT && RT->isStructureOrClassType()) {
const RecordDecl *RD = RT->getDecl();
QualType Found;
// If this is a C++ record, check the bases first.
if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
for (const auto &I : CXXRD->bases()) {
QualType Base = I.getType();
// Empty bases don't affect things either way.
if (isEmptyRecord(getContext(), Base, true))
continue;
if (!Found.isNull())
return Ty;
Found = GetSingleElementType(Base);
}
// Check the fields.
for (const auto *FD : RD->fields()) {
// For compatibility with GCC, ignore empty bitfields in C++ mode.
// Unlike isSingleElementStruct(), empty structure and array fields
// do count. So do anonymous bitfields that aren't zero-sized.
if (getContext().getLangOpts().CPlusPlus &&
FD->isZeroLengthBitField(getContext()))
continue;
// Like isSingleElementStruct(), ignore C++20 empty data members.
if (FD->hasAttr<NoUniqueAddressAttr>() &&
isEmptyRecord(getContext(), FD->getType(), true))
continue;
// Unlike isSingleElementStruct(), arrays do not count.
// Nested structures still do though.
if (!Found.isNull())
return Ty;
Found = GetSingleElementType(FD->getType());
}
// Unlike isSingleElementStruct(), trailing padding is allowed.
// An 8-byte aligned struct s { float f; } is passed as a double.
if (!Found.isNull())
return Found;
}
return Ty;
}
Address SystemZABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
QualType Ty) const {
// Assume that va_list type is correct; should be pointer to LLVM type:
// struct {
// i64 __gpr;
// i64 __fpr;
// i8 *__overflow_arg_area;
// i8 *__reg_save_area;
// };
// Every non-vector argument occupies 8 bytes and is passed by preference
// in either GPRs or FPRs. Vector arguments occupy 8 or 16 bytes and are
// always passed on the stack.
Ty = getContext().getCanonicalType(Ty);
auto TyInfo = getContext().getTypeInfoInChars(Ty);
llvm::Type *ArgTy = CGF.ConvertTypeForMem(Ty);
llvm::Type *DirectTy = ArgTy;
ABIArgInfo AI = classifyArgumentType(Ty);
bool IsIndirect = AI.isIndirect();
bool InFPRs = false;
bool IsVector = false;
CharUnits UnpaddedSize;
CharUnits DirectAlign;
if (IsIndirect) {
DirectTy = llvm::PointerType::getUnqual(DirectTy);
UnpaddedSize = DirectAlign = CharUnits::fromQuantity(8);
} else {
if (AI.getCoerceToType())
ArgTy = AI.getCoerceToType();
InFPRs = (!IsSoftFloatABI && (ArgTy->isFloatTy() || ArgTy->isDoubleTy()));
IsVector = ArgTy->isVectorTy();
UnpaddedSize = TyInfo.Width;
DirectAlign = TyInfo.Align;
}
CharUnits PaddedSize = CharUnits::fromQuantity(8);
if (IsVector && UnpaddedSize > PaddedSize)
PaddedSize = CharUnits::fromQuantity(16);
assert((UnpaddedSize <= PaddedSize) && "Invalid argument size.");
CharUnits Padding = (PaddedSize - UnpaddedSize);
llvm::Type *IndexTy = CGF.Int64Ty;
llvm::Value *PaddedSizeV =
llvm::ConstantInt::get(IndexTy, PaddedSize.getQuantity());
if (IsVector) {
// Work out the address of a vector argument on the stack.
// Vector arguments are always passed in the high bits of a
// single (8 byte) or double (16 byte) stack slot.
Address OverflowArgAreaPtr =
CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr");
Address OverflowArgArea =
Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
TyInfo.Align);
Address MemAddr =
CGF.Builder.CreateElementBitCast(OverflowArgArea, DirectTy, "mem_addr");
// Update overflow_arg_area_ptr pointer
llvm::Value *NewOverflowArgArea =
CGF.Builder.CreateGEP(OverflowArgArea.getElementType(),
OverflowArgArea.getPointer(), PaddedSizeV,
"overflow_arg_area");
CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
return MemAddr;
}
assert(PaddedSize.getQuantity() == 8);
unsigned MaxRegs, RegCountField, RegSaveIndex;
CharUnits RegPadding;
if (InFPRs) {
MaxRegs = 4; // Maximum of 4 FPR arguments
RegCountField = 1; // __fpr
RegSaveIndex = 16; // save offset for f0
RegPadding = CharUnits(); // floats are passed in the high bits of an FPR
} else {
MaxRegs = 5; // Maximum of 5 GPR arguments
RegCountField = 0; // __gpr
RegSaveIndex = 2; // save offset for r2
RegPadding = Padding; // values are passed in the low bits of a GPR
}
Address RegCountPtr =
CGF.Builder.CreateStructGEP(VAListAddr, RegCountField, "reg_count_ptr");
llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
"fits_in_regs");
llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
// Emit code to load the value if it was passed in registers.
CGF.EmitBlock(InRegBlock);
// Work out the address of an argument register.
llvm::Value *ScaledRegCount =
CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
llvm::Value *RegBase =
llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize.getQuantity()
+ RegPadding.getQuantity());
llvm::Value *RegOffset =
CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
Address RegSaveAreaPtr =
CGF.Builder.CreateStructGEP(VAListAddr, 3, "reg_save_area_ptr");
llvm::Value *RegSaveArea =
CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
Address RawRegAddr(CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, RegOffset,
"raw_reg_addr"),
PaddedSize);
Address RegAddr =
CGF.Builder.CreateElementBitCast(RawRegAddr, DirectTy, "reg_addr");
// Update the register count
llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
llvm::Value *NewRegCount =
CGF.Builder.CreateAdd(RegCount, One, "reg_count");
CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
CGF.EmitBranch(ContBlock);
// Emit code to load the value if it was passed in memory.
CGF.EmitBlock(InMemBlock);
// Work out the address of a stack argument.
Address OverflowArgAreaPtr =
CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr");
Address OverflowArgArea =
Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
PaddedSize);
Address RawMemAddr =
CGF.Builder.CreateConstByteGEP(OverflowArgArea, Padding, "raw_mem_addr");
Address MemAddr =
CGF.Builder.CreateElementBitCast(RawMemAddr, DirectTy, "mem_addr");
// Update overflow_arg_area_ptr pointer
llvm::Value *NewOverflowArgArea =
CGF.Builder.CreateGEP(OverflowArgArea.getElementType(),
OverflowArgArea.getPointer(), PaddedSizeV,
"overflow_arg_area");
CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
CGF.EmitBranch(ContBlock);
// Return the appropriate result.
CGF.EmitBlock(ContBlock);
Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
MemAddr, InMemBlock, "va_arg.addr");
if (IsIndirect)
ResAddr = Address(CGF.Builder.CreateLoad(ResAddr, "indirect_arg"),
TyInfo.Align);
return ResAddr;
}
ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
if (RetTy->isVoidType())
return ABIArgInfo::getIgnore();
if (isVectorArgumentType(RetTy))
return ABIArgInfo::getDirect();
if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
return getNaturalAlignIndirect(RetTy);
return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
: ABIArgInfo::getDirect());
}
ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
// Handle the generic C++ ABI.
if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
// Integers and enums are extended to full register width.
if (isPromotableIntegerTypeForABI(Ty))
return ABIArgInfo::getExtend(Ty);
// Handle vector types and vector-like structure types. Note that
// as opposed to float-like structure types, we do not allow any
// padding for vector-like structures, so verify the sizes match.
uint64_t Size = getContext().getTypeSize(Ty);
QualType SingleElementTy = GetSingleElementType(Ty);
if (isVectorArgumentType(SingleElementTy) &&
getContext().getTypeSize(SingleElementTy) == Size)
return ABIArgInfo::getDirect(CGT.ConvertType(SingleElementTy));
// Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
// Handle small structures.
if (const RecordType *RT = Ty->getAs<RecordType>()) {
// Structures with flexible arrays have variable length, so really
// fail the size test above.
const RecordDecl *RD = RT->getDecl();
if (RD->hasFlexibleArrayMember())
return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
// The structure is passed as an unextended integer, a float, or a double.
llvm::Type *PassTy;
if (isFPArgumentType(SingleElementTy)) {
assert(Size == 32 || Size == 64);
if (Size == 32)
PassTy = llvm::Type::getFloatTy(getVMContext());
else
PassTy = llvm::Type::getDoubleTy(getVMContext());
} else
PassTy = llvm::IntegerType::get(getVMContext(), Size);
return ABIArgInfo::getDirect(PassTy);
}
// Non-structure compounds are passed indirectly.
if (isCompoundType(Ty))
return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
return ABIArgInfo::getDirect(nullptr);
}
//===----------------------------------------------------------------------===//
// MSP430 ABI Implementation
//===----------------------------------------------------------------------===//
namespace {
class MSP430ABIInfo : public DefaultABIInfo {
static ABIArgInfo complexArgInfo() {
ABIArgInfo Info = ABIArgInfo::getDirect();
Info.setCanBeFlattened(false);
return Info;
}
public:
MSP430ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
ABIArgInfo classifyReturnType(QualType RetTy) const {
if (RetTy->isAnyComplexType())
return complexArgInfo();
return DefaultABIInfo::classifyReturnType(RetTy);
}
ABIArgInfo classifyArgumentType(QualType RetTy) const {
if (RetTy->isAnyComplexType())
return complexArgInfo();
return DefaultABIInfo::classifyArgumentType(RetTy);
}
// Just copy the original implementations because
// DefaultABIInfo::classify{Return,Argument}Type() are not virtual
void computeInfo(CGFunctionInfo &FI) const override {
if (!getCXXABI().classifyReturnType(FI))
FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
for (auto &I : FI.arguments())
I.info = classifyArgumentType(I.type);
}
Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
QualType Ty) const override {
return EmitVAArgInstr(CGF, VAListAddr, Ty, classifyArgumentType(Ty));
}
};
class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
public:
MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
: TargetCodeGenInfo(std::make_unique<MSP430ABIInfo>(CGT)) {}
void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
CodeGen::CodeGenModule &M) const override;
};
}
void MSP430TargetCodeGenInfo::setTargetAttributes(
const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
if (GV->isDeclaration())
return;
if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
const auto *InterruptAttr = FD->getAttr<MSP430InterruptAttr>();
if (!InterruptAttr)
return;
// Handle 'interrupt' attribute:
llvm::Function *F = cast<llvm::Function>(GV);
// Step 1: Set ISR calling convention.
F->setCallingConv(llvm::CallingConv::MSP430_INTR);
// Step 2: Add attributes goodness.
F->addFnAttr(llvm::Attribute::NoInline);
F->addFnAttr("interrupt", llvm::utostr(InterruptAttr->getNumber()));
}
}
//===----------------------------------------------------------------------===//
// MIPS ABI Implementation. This works for both little-endian and
// big-endian variants.
//===----------------------------------------------------------------------===//
namespace {
class MipsABIInfo : public ABIInfo {
bool IsO32;
unsigned MinABIStackAlignInBytes, StackAlignInBytes;
void CoerceToIntArgs(uint64_t TySize,
SmallVectorImpl<llvm::Type *> &ArgList) const;
llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
public:
MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
StackAlignInBytes(IsO32 ? 8 : 16) {}
ABIArgInfo classifyReturnType(QualType RetTy) const;
ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
void computeInfo(CGFunctionInfo &FI) const override;
Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
QualType Ty) const override;
ABIArgInfo extendType(QualType Ty) const;
};
class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
unsigned SizeOfUnwindException;
public:
MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
: TargetCodeGenInfo(std::make_unique<MipsABIInfo>(CGT, IsO32)),
SizeOfUnwindException(IsO32 ? 24 : 32) {}
int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
return 29;
}
void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
CodeGen::CodeGenModule &CGM) const override {
const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
if (!FD) return;
llvm::Function *Fn = cast<llvm::Function>(GV);
if (FD->hasAttr<MipsLongCallAttr>())
Fn->addFnAttr("long-call");
else if (FD->hasAttr<MipsShortCallAttr>())
Fn->addFnAttr("short-call");
// Other attributes do not have a meaning for declarations.
if (GV->isDeclaration())
return;
if (FD->hasAttr<Mips16Attr>()) {
Fn->addFnAttr("mips16");
}
else if (FD->hasAttr<NoMips16Attr>()) {
Fn->addFnAttr("nomips16");
}
if (FD->hasAttr<MicroMipsAttr>())
Fn->addFnAttr("micromips");
else if (FD->hasAttr<NoMicroMipsAttr>())
Fn->addFnAttr("nomicromips");
const MipsInterruptAttr *Attr = FD->getAttr<MipsInterruptAttr>();
if (!Attr)
return;
const char *Kind;
switch (Attr->getInterrupt()) {
case MipsInterruptAttr::eic: Kind = "eic"; break;
case MipsInterruptAttr::sw0: Kind = "sw0"; break;
case MipsInterruptAttr::sw1: Kind = "sw1"; break;
case MipsInterruptAttr::hw0: Kind = "hw0"; break;
case MipsInterruptAttr::hw1: Kind = "hw1"; break;
case MipsInterruptAttr::hw2: Kind = "hw2"; break;
case MipsInterruptAttr::hw3: Kind = "hw3"; break;
case MipsInterruptAttr::hw4: Kind = "hw4"; break;
case MipsInterruptAttr::hw5: Kind = "hw5"; break;
}
Fn->addFnAttr("interrupt", Kind);
}
bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
llvm::Value *Address) const override;
unsigned getSizeOfUnwindException() const override {
return SizeOfUnwindException;
}
};
}
void MipsABIInfo::CoerceToIntArgs(
uint64_t TySize, SmallVectorImpl<llvm::Type *> &ArgList) const {
llvm::IntegerType *IntTy =
llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
// Add (TySize / MinABIStackAlignInBytes) args of IntTy.
for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
ArgList.push_back(IntTy);
// If necessary, add one more integer type to ArgList.
unsigned R = TySize % (MinABIStackAlignInBytes * 8);
if (R)
ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
}
// In N32/64, an aligned double precision floating point field is passed in
// a register.
llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
SmallVector<llvm::Type*, 8> ArgList, IntArgList;
if (IsO32) {
CoerceToIntArgs(TySize, ArgList);
return llvm::StructType::get(getVMContext(), ArgList);
}
if (Ty->isComplexType())
return CGT.ConvertType(Ty);
const RecordType *RT = Ty->getAs<RecordType>();
// Unions/vectors are passed in integer registers.
if (!RT || !RT->isStructureOrClassType()) {
CoerceToIntArgs(TySize, ArgList);
return llvm::StructType::get(getVMContext(), ArgList);
}
const RecordDecl *RD = RT->getDecl();
const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
uint64_t LastOffset = 0;
unsigned idx = 0;
llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
// Iterate over fields in the struct/class and check if there are any aligned
// double fields.
for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
i != e; ++i, ++idx) {
const QualType Ty = i->getType();
const BuiltinType *BT = Ty->getAs<BuiltinType>();
if (!BT || BT->getKind() != BuiltinType::Double)
continue;
uint64_t Offset = Layout.getFieldOffset(idx);
if (Offset % 64) // Ignore doubles that are not aligned.
continue;
// Add ((Offset - LastOffset) / 64) args of type i64.
for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
ArgList.push_back(I64);
// Add double type.
ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
LastOffset = Offset + 64;
}
CoerceToIntArgs(TySize - LastOffset, IntArgList);
ArgList.append(IntArgList.begin(), IntArgList.end());
return llvm::StructType::get(getVMContext(), ArgList);
}
llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
uint64_t Offset) const {
if (OrigOffset + MinABIStackAlignInBytes > Offset)
return nullptr;
return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
}
ABIArgInfo
MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
Ty = useFirstFieldIfTransparentUnion(Ty);
uint64_t OrigOffset = Offset;
uint64_t TySize = getContext().getTypeSize(Ty);
uint64_t Align = getContext().getTypeAlign(Ty) / 8;
Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
(uint64_t)StackAlignInBytes);
unsigned CurrOffset = llvm::alignTo(Offset, Align);
Offset = CurrOffset + llvm::alignTo(TySize, Align * 8) / 8;
if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
// Ignore empty aggregates.
if (TySize == 0)
return ABIArgInfo::getIgnore();
if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Offset = OrigOffset + MinABIStackAlignInBytes;
return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
}
// If we have reached here, aggregates are passed directly by coercing to
// another structure type. Padding is inserted if the offset of the
// aggregate is unaligned.
ABIArgInfo ArgInfo =
ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
getPaddingType(OrigOffset, CurrOffset));
ArgInfo.setInReg(true);
return ArgInfo;
}
// Treat an enum type as its underlying type.
if (const EnumType *EnumTy = Ty->getAs<EnumType>())
Ty = EnumTy->getDecl()->getIntegerType();
// Make sure we pass indirectly things that are too large.
if (const auto *EIT = Ty->getAs<ExtIntType>())
if (EIT->getNumBits() > 128 ||
(EIT->getNumBits() > 64 &&
!getContext().getTargetInfo().hasInt128Type()))
return getNaturalAlignIndirect(Ty);
// All integral types are promoted to the GPR width.
if (Ty->isIntegralOrEnumerationType())
return extendType(Ty);
return ABIArgInfo::getDirect(
nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset));
}
llvm::Type*
MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
const RecordType *RT = RetTy->getAs<RecordType>();
SmallVector<llvm::Type*, 8> RTList;
if (RT && RT->isStructureOrClassType()) {
const RecordDecl *RD = RT->getDecl();
const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
unsigned FieldCnt = Layout.getFieldCount();
// N32/64 returns struct/classes in floating point registers if the
// following conditions are met:
// 1. The size of the struct/class is no larger than 128-bit.
// 2. The struct/class has one or two fields all of which are floating
// point types.
// 3. The offset of the first field is zero (this follows what gcc does).
//
// Any other composite results are returned in integer registers.
//
if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
for (; b != e; ++b) {
const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
if (!BT || !BT->isFloatingPoint())
break;
RTList.push_back(CGT.ConvertType(b->getType()));
}
if (b == e)
return llvm::StructType::get(getVMContext(), RTList,
RD->hasAttr<PackedAttr>());
RTList.clear();
}
}
CoerceToIntArgs(Size, RTList);
return llvm::StructType::get(getVMContext(), RTList);
}
ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
uint64_t Size = getContext().getTypeSize(RetTy);
if (RetTy->isVoidType())
return ABIArgInfo::getIgnore();
// O32 doesn't treat zero-sized structs differently from other structs.
// However, N32/N64 ignores zero sized return values.
if (!IsO32 && Size == 0)
return ABIArgInfo::getIgnore();
if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
if (Size <= 128) {
if (RetTy->isAnyComplexType())
return ABIArgInfo::getDirect();
// O32 returns integer vectors in registers and N32/N64 returns all small
// aggregates in registers.
if (!IsO32 ||
(RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) {
ABIArgInfo ArgInfo =
ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
ArgInfo.setInReg(true);
return ArgInfo;
}
}
return getNaturalAlignIndirect(RetTy);
}
// Treat an enum type as its underlying type.
if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
RetTy = EnumTy->getDecl()->getIntegerType();
// Make sure we pass indirectly things that are too large.
if (const auto *EIT = RetTy->getAs<ExtIntType>())
if (EIT->getNumBits() > 128 ||
(EIT->getNumBits() > 64 &&
!getContext().getTargetInfo().hasInt128Type()))
return getNaturalAlignIndirect(RetTy);
if (isPromotableIntegerTypeForABI(RetTy))
return ABIArgInfo::getExtend(RetTy);
if ((RetTy->isUnsignedIntegerOrEnumerationType() ||
RetTy->isSignedIntegerOrEnumerationType()) && Size == 32 && !IsO32)
return ABIArgInfo::getSignExtend(RetTy);
return ABIArgInfo::getDirect();
}
void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
ABIArgInfo &RetInfo = FI.getReturnInfo();
if (!getCXXABI().classifyReturnType(FI))
RetInfo = classifyReturnType(FI.getReturnType());
// Check if a pointer to an aggregate is passed as a hidden argument.
uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
for (auto &I : FI.arguments())
I.info = classifyArgumentType(I.type, Offset);
}
Address MipsABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
QualType OrigTy) const {
QualType Ty = OrigTy;
// Integer arguments are promoted to 32-bit on O32 and 64-bit on N32/N64.
// Pointers are also promoted in the same way but this only matters for N32.
unsigned SlotSizeInBits = IsO32 ? 32 : 64;
unsigned PtrWidth = getTarget().getPointerWidth(0);
bool DidPromote = false;
if ((Ty->isIntegerType() &&
getContext().getIntWidth(Ty) < SlotSizeInBits) ||
(Ty->isPointerType() && PtrWidth < SlotSizeInBits)) {
DidPromote = true;
Ty = getContext().getIntTypeForBitwidth(SlotSizeInBits,
Ty->isSignedIntegerType());
}
auto TyInfo = getContext().getTypeInfoInChars(Ty);
// The alignment of things in the argument area is never larger than
// StackAlignInBytes.
TyInfo.Align =
std::min(TyInfo.Align, CharUnits::fromQuantity(StackAlignInBytes));
// MinABIStackAlignInBytes is the size of argument slots on the stack.
CharUnits ArgSlotSize = CharUnits::fromQuantity(MinABIStackAlignInBytes);
Address Addr = emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
TyInfo, ArgSlotSize, /*AllowHigherAlign*/ true);
// If there was a promotion, "unpromote" into a temporary.
// TODO: can we just use a pointer into a subset of the original slot?
if (DidPromote) {
Address Temp = CGF.CreateMemTemp(OrigTy, "vaarg.promotion-temp");
llvm::Value *Promoted = CGF.Builder.CreateLoad(Addr);
// Truncate down to the right width.
llvm::Type *IntTy = (OrigTy->isIntegerType() ? Temp.getElementType()
: CGF.IntPtrTy);
llvm::Value *V = CGF.Builder.CreateTrunc(Promoted, IntTy);
if (OrigTy->isPointerType())
V = CGF.Builder.CreateIntToPtr(V, Temp.getElementType());
CGF.Builder.CreateStore(V, Temp);
Addr = Temp;
}
return Addr;
}
ABIArgInfo MipsABIInfo::extendType(QualType Ty) const {
int TySize = getContext().getTypeSize(Ty);
// MIPS64 ABI requires unsigned 32 bit integers to be sign extended.
if (Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
return ABIArgInfo::getSignExtend(Ty);
return ABIArgInfo::getExtend(Ty);
}
bool
MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
llvm::Value *Address) const {
// This information comes from gcc's implementation, which seems to
// as canonical as it gets.
// Everything on MIPS is 4 bytes. Double-precision FP registers
// are aliased to pairs of single-precision FP registers.
llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
// 0-31 are the general purpose registers, $0 - $31.
// 32-63 are the floating-point registers, $f0 - $f31.
// 64 and 65 are the multiply/divide registers, $hi and $lo.
// 66 is the (notional, I think) register for signal-handler return.
AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
// 67-74 are the floating-point status registers, $fcc0 - $fcc7.
// They are one bit wide and ignored here.
// 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
// (coprocessor 1 is the FP unit)
// 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
// 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
// 176-181 are the DSP accumulator registers.
AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
return false;
}
//===----------------------------------------------------------------------===//
// M68k ABI Implementation
//===----------------------------------------------------------------------===//
namespace {
class M68kTargetCodeGenInfo : public TargetCodeGenInfo {
public:
M68kTargetCodeGenInfo(CodeGenTypes &CGT)
: TargetCodeGenInfo(std::make_unique<DefaultABIInfo>(CGT)) {}
void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
CodeGen::CodeGenModule &M) const override;
};
} // namespace
void M68kTargetCodeGenInfo::setTargetAttributes(
const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
if (const auto *FD = dyn_cast_or_null<FunctionDecl>(D)) {
if (const auto *attr = FD->getAttr<M68kInterruptAttr>()) {
// Handle 'interrupt' attribute:
llvm::Function *F = cast<llvm::Function>(GV);
// Step 1: Set ISR calling convention.
F->setCallingConv(llvm::CallingConv::M68k_INTR);
// Step 2: Add attributes goodness.
F->addFnAttr(llvm::Attribute::NoInline);
// Step 3: Emit ISR vector alias.
unsigned Num = attr->getNumber() / 2;
llvm::GlobalAlias::create(llvm::Function::ExternalLinkage,
"__isr_" + Twine(Num), F);
}
}
}
//===----------------------------------------------------------------------===//
// AVR ABI Implementation. Documented at
// https://gcc.gnu.org/wiki/avr-gcc#Calling_Convention
// https://gcc.gnu.org/wiki/avr-gcc#Reduced_Tiny
//===----------------------------------------------------------------------===//
namespace {
class AVRABIInfo : public DefaultABIInfo {
public:
AVRABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
ABIArgInfo classifyReturnType(QualType Ty) const {
// A return struct with size less than or equal to 8 bytes is returned
// directly via registers R18-R25.
if (isAggregateTypeForABI(Ty) && getContext().getTypeSize(Ty) <= 64)
return ABIArgInfo::getDirect();
else
return DefaultABIInfo::classifyReturnType(Ty);
}
// Just copy the original implementation of DefaultABIInfo::computeInfo(),
// since DefaultABIInfo::classify{Return,Argument}Type() are not virtual.
void computeInfo(CGFunctionInfo &FI) const override {
if (!getCXXABI().classifyReturnType(FI))
FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
for (auto &I : FI.arguments())
I.info = classifyArgumentType(I.type);
}
};
class AVRTargetCodeGenInfo : public TargetCodeGenInfo {
public:
AVRTargetCodeGenInfo(CodeGenTypes &CGT)
: TargetCodeGenInfo(std::make_unique<AVRABIInfo>(CGT)) {}
LangAS getGlobalVarAddressSpace(CodeGenModule &CGM,
const VarDecl *D) const override {
// Check if a global/static variable is defined within address space 1
// but not constant.
LangAS AS = D->getType().getAddressSpace();
if (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 1 &&
!D->getType().isConstQualified())
CGM.getDiags().Report(D->getLocation(),
diag::err_verify_nonconst_addrspace)
<< "__flash";
return TargetCodeGenInfo::getGlobalVarAddressSpace(CGM, D);
}
void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
CodeGen::CodeGenModule &CGM) const override {
if (GV->isDeclaration())
return;
const auto *FD = dyn_cast_or_null<FunctionDecl>(D);
if (!FD) return;
auto *Fn = cast<llvm::Function>(GV);
if (FD->getAttr<AVRInterruptAttr>())
Fn->addFnAttr("interrupt");
if (FD->getAttr<AVRSignalAttr>())
Fn->addFnAttr("signal");
}
};
}
//===----------------------------------------------------------------------===//
// TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
// Currently subclassed only to implement custom OpenCL C function attribute
// handling.
//===----------------------------------------------------------------------===//
namespace {
class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
public:
TCETargetCodeGenInfo(CodeGenTypes &CGT)
: DefaultTargetCodeGenInfo(CGT) {}
void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
CodeGen::CodeGenModule &M) const override;
};
void TCETargetCodeGenInfo::setTargetAttributes(
const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
if (GV->isDeclaration())
return;
const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
if (!FD) return;
llvm::Function *F = cast<llvm::Function>(GV);
if (M.getLangOpts().OpenCL) {
if (FD->hasAttr<OpenCLKernelAttr>()) {
// OpenCL C Kernel functions are not subject to inlining
F->addFnAttr(llvm::Attribute::NoInline);
const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
if (Attr) {
// Convert the reqd_work_group_size() attributes to metadata.
llvm::LLVMContext &Context = F->getContext();
llvm::NamedMDNode *OpenCLMetadata =
M.getModule().getOrInsertNamedMetadata(
"opencl.kernel_wg_size_info");
SmallVector<llvm::Metadata *, 5> Operands;
Operands.push_back(llvm::ConstantAsMetadata::get(F));
ASTContext &Ctx = M.getContext();
unsigned XDim = Attr->getXDimVal(Ctx)->getZExtValue();
unsigned YDim = Attr->getYDimVal(Ctx)->getZExtValue();
unsigned ZDim = Attr->getZDimVal(Ctx)->getZExtValue();
Operands.push_back(llvm::ConstantAsMetadata::get(
llvm::Constant::getIntegerValue(M.Int32Ty, llvm::APInt(32, XDim))));
Operands.push_back(llvm::ConstantAsMetadata::get(
llvm::Constant::getIntegerValue(M.Int32Ty, llvm::APInt(32, YDim))));
Operands.push_back(llvm::ConstantAsMetadata::get(
llvm::Constant::getIntegerValue(M.Int32Ty, llvm::APInt(32, ZDim))));
// Add a boolean constant operand for "required" (true) or "hint"
// (false) for implementing the work_group_size_hint attr later.
// Currently always true as the hint is not yet implemented.
Operands.push_back(
llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context)));
OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
}
}
}
}
}
//===----------------------------------------------------------------------===//
// Hexagon ABI Implementation
//===----------------------------------------------------------------------===//
namespace {
class HexagonABIInfo : public DefaultABIInfo {
public:
HexagonABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
private:
ABIArgInfo classifyReturnType(QualType RetTy) const;
ABIArgInfo classifyArgumentType(QualType RetTy) const;
ABIArgInfo classifyArgumentType(QualType RetTy, unsigned *RegsLeft) const;
void computeInfo(CGFunctionInfo &FI) const override;
Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
QualType Ty) const override;
Address EmitVAArgFromMemory(CodeGenFunction &CFG, Address VAListAddr,
QualType Ty) const;
Address EmitVAArgForHexagon(CodeGenFunction &CFG, Address VAListAddr,
QualType Ty) const;
Address EmitVAArgForHexagonLinux(CodeGenFunction &CFG, Address VAListAddr,
QualType Ty) const;
};
class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
public:
HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
: TargetCodeGenInfo(std::make_unique<HexagonABIInfo>(CGT)) {}
int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
return 29;
}
void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
CodeGen::CodeGenModule &GCM) const override {
if (GV->isDeclaration())
return;
const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
if (!FD)
return;
}
};
} // namespace
void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
unsigned RegsLeft = 6;
if (!getCXXABI().classifyReturnType(FI))
FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
for (auto &I : FI.arguments())
I.info = classifyArgumentType(I.type, &RegsLeft);
}
static bool HexagonAdjustRegsLeft(uint64_t Size, unsigned *RegsLeft) {
assert(Size <= 64 && "Not expecting to pass arguments larger than 64 bits"
" through registers");
if (*RegsLeft == 0)
return false;
if (Size <= 32) {
(*RegsLeft)--;
return true;
}
if (2 <= (*RegsLeft & (~1U))) {
*RegsLeft = (*RegsLeft & (~1U)) - 2;
return true;
}
// Next available register was r5 but candidate was greater than 32-bits so it
// has to go on the stack. However we still consume r5
if (*RegsLeft == 1)
*RegsLeft = 0;
return false;
}
ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty,
unsigned *RegsLeft) const {
if (!isAggregateTypeForABI(Ty)) {
// Treat an enum type as its underlying type.
if (const EnumType *EnumTy = Ty->getAs<EnumType>())
Ty = EnumTy->getDecl()->getIntegerType();
uint64_t Size = getContext().getTypeSize(Ty);
if (Size <= 64)
HexagonAdjustRegsLeft(Size, RegsLeft);
if (Size > 64 && Ty->isExtIntType())
return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
return isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
: ABIArgInfo::getDirect();
}
if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
// Ignore empty records.
if (isEmptyRecord(getContext(), Ty, true))
return ABIArgInfo::getIgnore();
uint64_t Size = getContext().getTypeSize(Ty);
unsigned Align = getContext().getTypeAlign(Ty);
if (Size > 64)
return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
if (HexagonAdjustRegsLeft(Size, RegsLeft))
Align = Size <= 32 ? 32 : 64;
if (Size <= Align) {
// Pass in the smallest viable integer type.
if (!llvm::isPowerOf2_64(Size))
Size = llvm::NextPowerOf2(Size);
return ABIArgInfo::getDirect(llvm::Type::getIntNTy(getVMContext(), Size));
}
return DefaultABIInfo::classifyArgumentType(Ty);
}
ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
if (RetTy->isVoidType())
return ABIArgInfo::getIgnore();
const TargetInfo &T = CGT.getTarget();
uint64_t Size = getContext().getTypeSize(RetTy);
if (RetTy->getAs<VectorType>()) {
// HVX vectors are returned in vector registers or register pairs.
if (T.hasFeature("hvx")) {
assert(T.hasFeature("hvx-length64b") || T.hasFeature("hvx-length128b"));
uint64_t VecSize = T.hasFeature("hvx-length64b") ? 64*8 : 128*8;
if (Size == VecSize || Size == 2*VecSize)
return ABIArgInfo::getDirectInReg();
}
// Large vector types should be returned via memory.
if (Size > 64)
return getNaturalAlignIndirect(RetTy);
}
if (!isAggregateTypeForABI(RetTy)) {
// Treat an enum type as its underlying type.
if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
RetTy = EnumTy->getDecl()->getIntegerType();
if (Size > 64 && RetTy->isExtIntType())
return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
return isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
: ABIArgInfo::getDirect();
}
if (isEmptyRecord(getContext(), RetTy, true))
return ABIArgInfo::getIgnore();
// Aggregates <= 8 bytes are returned in registers, other aggregates
// are returned indirectly.
if (Size <= 64) {
// Return in the smallest viable integer type.
if (!llvm::isPowerOf2_64(Size))
Size = llvm::NextPowerOf2(Size);
return ABIArgInfo::getDirect(llvm::Type::getIntNTy(getVMContext(), Size));
}
return getNaturalAlignIndirect(RetTy, /*ByVal=*/true);
}
Address HexagonABIInfo::EmitVAArgFromMemory(CodeGenFunction &CGF,
Address VAListAddr,
QualType Ty) const {
// Load the overflow area pointer.
Address __overflow_area_pointer_p =
CGF.Builder.CreateStructGEP(VAListAddr, 2, "__overflow_area_pointer_p");
llvm::Value *__overflow_area_pointer = CGF.Builder.CreateLoad(
__overflow_area_pointer_p, "__overflow_area_pointer");
uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
if (Align > 4) {
// Alignment should be a power of 2.
assert((Align & (Align - 1)) == 0 && "Alignment is not power of 2!");
// overflow_arg_area = (overflow_arg_area + align - 1) & -align;
llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int64Ty, Align - 1);
// Add offset to the current pointer to access the argument.
__overflow_area_pointer =
CGF.Builder.CreateGEP(CGF.Int8Ty, __overflow_area_pointer, Offset);
llvm::Value *AsInt =
CGF.Builder.CreatePtrToInt(__overflow_area_pointer, CGF.Int32Ty);
// Create a mask which should be "AND"ed
// with (overflow_arg_area + align - 1)
llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int32Ty, -(int)Align);
__overflow_area_pointer = CGF.Builder.CreateIntToPtr(
CGF.Builder.CreateAnd(AsInt, Mask), __overflow_area_pointer->getType(),
"__overflow_area_pointer.align");
}
// Get the type of the argument from memory and bitcast
// overflow area pointer to the argument type.
llvm::Type *PTy = CGF.ConvertTypeForMem(Ty);
Address AddrTyped = CGF.Builder.CreateBitCast(
Address(__overflow_area_pointer, CharUnits::fromQuantity(Align)),
llvm::PointerType::getUnqual(PTy));
// Round up to the minimum stack alignment for varargs which is 4 bytes.
uint64_t Offset = llvm::alignTo(CGF.getContext().getTypeSize(Ty) / 8, 4);
__overflow_area_pointer = CGF.Builder.CreateGEP(
CGF.Int8Ty, __overflow_area_pointer,
llvm::ConstantInt::get(CGF.Int32Ty, Offset),
"__overflow_area_pointer.next");
CGF.Builder.CreateStore(__overflow_area_pointer, __overflow_area_pointer_p);
return AddrTyped;
}
Address HexagonABIInfo::EmitVAArgForHexagon(CodeGenFunction &CGF,
Address VAListAddr,
QualType Ty) const {
// FIXME: Need to handle alignment
llvm::Type *BP = CGF.Int8PtrTy;
llvm::Type *BPP = CGF.Int8PtrPtrTy;
CGBuilderTy &Builder = CGF.Builder;
Address VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
// Handle address alignment for type alignment > 32 bits
uint64_t TyAlign = CGF.getContext().getTypeAlign(Ty) / 8;
if (TyAlign > 4) {
assert((TyAlign & (TyAlign - 1)) == 0 && "Alignment is not power of 2!");
llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int32Ty);
AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt32(TyAlign - 1));
AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt32(~(TyAlign - 1)));
Addr = Builder.CreateIntToPtr(AddrAsInt, BP);
}
llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
Address AddrTyped = Builder.CreateBitCast(
Address(Addr, CharUnits::fromQuantity(TyAlign)), PTy);
uint64_t Offset = llvm::alignTo(CGF.getContext().getTypeSize(Ty) / 8, 4);
llvm::Value *NextAddr = Builder.CreateGEP(
CGF.Int8Ty, Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset), "ap.next");
Builder.CreateStore(NextAddr, VAListAddrAsBPP);
return AddrTyped;
}
Address HexagonABIInfo::EmitVAArgForHexagonLinux(CodeGenFunction &CGF,
Address VAListAddr,
QualType Ty) const {
int ArgSize = CGF.getContext().getTypeSize(Ty) / 8;
if (ArgSize > 8)
return EmitVAArgFromMemory(CGF, VAListAddr, Ty);
// Here we have check if the argument is in register area or
// in overflow area.
// If the saved register area pointer + argsize rounded up to alignment >
// saved register area end pointer, argument is in overflow area.
unsigned RegsLeft = 6;
Ty = CGF.getContext().getCanonicalType(Ty);
(void)classifyArgumentType(Ty, &RegsLeft);
llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
// Get rounded size of the argument.GCC does not allow vararg of
// size < 4 bytes. We follow the same logic here.
ArgSize = (CGF.getContext().getTypeSize(Ty) <= 32) ? 4 : 8;
int ArgAlign = (CGF.getContext().getTypeSize(Ty) <= 32) ? 4 : 8;
// Argument may be in saved register area
CGF.EmitBlock(MaybeRegBlock);
// Load the current saved register area pointer.
Address __current_saved_reg_area_pointer_p = CGF.Builder.CreateStructGEP(
VAListAddr, 0, "__current_saved_reg_area_pointer_p");
llvm::Value *__current_saved_reg_area_pointer = CGF.Builder.CreateLoad(
__current_saved_reg_area_pointer_p, "__current_saved_reg_area_pointer");
// Load the saved register area end pointer.
Address __saved_reg_area_end_pointer_p = CGF.Builder.CreateStructGEP(
VAListAddr, 1, "__saved_reg_area_end_pointer_p");
llvm::Value *__saved_reg_area_end_pointer = CGF.Builder.CreateLoad(
__saved_reg_area_end_pointer_p, "__saved_reg_area_end_pointer");
// If the size of argument is > 4 bytes, check if the stack
// location is aligned to 8 bytes
if (ArgAlign > 4) {
llvm::Value *__current_saved_reg_area_pointer_int =
CGF.Builder.CreatePtrToInt(__current_saved_reg_area_pointer,
CGF.Int32Ty);
__current_saved_reg_area_pointer_int = CGF.Builder.CreateAdd(
__current_saved_reg_area_pointer_int,
llvm::ConstantInt::get(CGF.Int32Ty, (ArgAlign - 1)),
"align_current_saved_reg_area_pointer");
__current_saved_reg_area_pointer_int =
CGF.Builder.CreateAnd(__current_saved_reg_area_pointer_int,
llvm::ConstantInt::get(CGF.Int32Ty, -ArgAlign),
"align_current_saved_reg_area_pointer");
__current_saved_reg_area_pointer =
CGF.Builder.CreateIntToPtr(__current_saved_reg_area_pointer_int,
__current_saved_reg_area_pointer->getType(),
"align_current_saved_reg_area_pointer");
}
llvm::Value *__new_saved_reg_area_pointer =
CGF.Builder.CreateGEP(CGF.Int8Ty, __current_saved_reg_area_pointer,
llvm::ConstantInt::get(CGF.Int32Ty, ArgSize),
"__new_saved_reg_area_pointer");
llvm::Value *UsingStack = 0;
UsingStack = CGF.Builder.CreateICmpSGT(__new_saved_reg_area_pointer,
__saved_reg_area_end_pointer);
CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, InRegBlock);
// Argument in saved register area
// Implement the block where argument is in register saved area
CGF.EmitBlock(InRegBlock);
llvm::Type *PTy = CGF.ConvertType(Ty);
llvm::Value *__saved_reg_area_p = CGF.Builder.CreateBitCast(
__current_saved_reg_area_pointer, llvm::PointerType::getUnqual(PTy));
CGF.Builder.CreateStore(__new_saved_reg_area_pointer,
__current_saved_reg_area_pointer_p);
CGF.EmitBranch(ContBlock);
// Argument in overflow area
// Implement the block where the argument is in overflow area.
CGF.EmitBlock(OnStackBlock);
// Load the overflow area pointer
Address __overflow_area_pointer_p =
CGF.Builder.CreateStructGEP(VAListAddr, 2, "__overflow_area_pointer_p");
llvm::Value *__overflow_area_pointer = CGF.Builder.CreateLoad(
__overflow_area_pointer_p, "__overflow_area_pointer");
// Align the overflow area pointer according to the alignment of the argument
if (ArgAlign > 4) {
llvm::Value *__overflow_area_pointer_int =
CGF.Builder.CreatePtrToInt(__overflow_area_pointer, CGF.Int32Ty);
__overflow_area_pointer_int =
CGF.Builder.CreateAdd(__overflow_area_pointer_int,
llvm::ConstantInt::get(CGF.Int32Ty, ArgAlign - 1),
"align_overflow_area_pointer");
__overflow_area_pointer_int =
CGF.Builder.CreateAnd(__overflow_area_pointer_int,
llvm::ConstantInt::get(CGF.Int32Ty, -ArgAlign),
"align_overflow_area_pointer");
__overflow_area_pointer = CGF.Builder.CreateIntToPtr(
__overflow_area_pointer_int, __overflow_area_pointer->getType(),
"align_overflow_area_pointer");
}
// Get the pointer for next argument in overflow area and store it
// to overflow area pointer.
llvm::Value *__new_overflow_area_pointer = CGF.Builder.CreateGEP(
CGF.Int8Ty, __overflow_area_pointer,
llvm::ConstantInt::get(CGF.Int32Ty, ArgSize),
"__overflow_area_pointer.next");
CGF.Builder.CreateStore(__new_overflow_area_pointer,
__overflow_area_pointer_p);
CGF.Builder.CreateStore(__new_overflow_area_pointer,
__current_saved_reg_area_pointer_p);
// Bitcast the overflow area pointer to the type of argument.
llvm::Type *OverflowPTy = CGF.ConvertTypeForMem(Ty);
llvm::Value *__overflow_area_p = CGF.Builder.CreateBitCast(
__overflow_area_pointer, llvm::PointerType::getUnqual(OverflowPTy));
CGF.EmitBranch(ContBlock);
// Get the correct pointer to load the variable argument
// Implement the ContBlock
CGF.EmitBlock(ContBlock);
llvm::Type *MemPTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
llvm::PHINode *ArgAddr = CGF.Builder.CreatePHI(MemPTy, 2, "vaarg.addr");
ArgAddr->addIncoming(__saved_reg_area_p, InRegBlock);
ArgAddr->addIncoming(__overflow_area_p, OnStackBlock);
return Address(ArgAddr, CharUnits::fromQuantity(ArgAlign));
}
Address HexagonABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
QualType Ty) const {
if (getTarget().getTriple().isMusl())
return EmitVAArgForHexagonLinux(CGF, VAListAddr, Ty);
return EmitVAArgForHexagon(CGF, VAListAddr, Ty);
}
//===----------------------------------------------------------------------===//
// Lanai ABI Implementation
//===----------------------------------------------------------------------===//
namespace {
class LanaiABIInfo : public DefaultABIInfo {
public:
LanaiABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
bool shouldUseInReg(QualType Ty, CCState &State) const;
void computeInfo(CGFunctionInfo &FI) const override {
CCState State(FI);
// Lanai uses 4 registers to pass arguments unless the function has the
// regparm attribute set.
if (FI.getHasRegParm()) {
State.FreeRegs = FI.getRegParm();
} else {
State.FreeRegs = 4;
}
if (!getCXXABI().classifyReturnType(FI))
FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
for (auto &I : FI.arguments())
I.info = classifyArgumentType(I.type, State);
}
ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
};
} // end anonymous namespace
bool LanaiABIInfo::shouldUseInReg(QualType Ty, CCState &State) const {
unsigned Size = getContext().getTypeSize(Ty);
unsigned SizeInRegs = llvm::alignTo(Size, 32U) / 32U;
if (SizeInRegs == 0)
return false;
if (SizeInRegs > State.FreeRegs) {
State.FreeRegs = 0;
return false;
}
State.FreeRegs -= SizeInRegs;
return true;
}
ABIArgInfo LanaiABIInfo::getIndirectResult(QualType Ty, bool ByVal,
CCState &State) const {
if (!ByVal) {
if (State.FreeRegs) {
--State.FreeRegs; // Non-byval indirects just use one pointer.
return getNaturalAlignIndirectInReg(Ty);
}
return getNaturalAlignIndirect(Ty, false);
}
// Compute the byval alignment.
const unsigned MinABIStackAlignInBytes = 4;
unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true,
/*Realign=*/TypeAlign >
MinABIStackAlignInBytes);
}
ABIArgInfo LanaiABIInfo::classifyArgumentType(QualType Ty,
CCState &State) const {
// Check with the C++ ABI first.
const RecordType *RT = Ty->getAs<RecordType>();
if (RT) {
CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
if (RAA == CGCXXABI::RAA_Indirect) {
return getIndirectResult(Ty, /*ByVal=*/false, State);
} else if (RAA == CGCXXABI::RAA_DirectInMemory) {
return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
}
}
if (isAggregateTypeForABI(Ty)) {
// Structures with flexible arrays are always indirect.
if (RT && RT->getDecl()->hasFlexibleArrayMember())
return getIndirectResult(Ty, /*ByVal=*/true, State);
// Ignore empty structs/unions.
if (isEmptyRecord(getContext(), Ty, true))
return ABIArgInfo::getIgnore();
llvm::LLVMContext &LLVMContext = getVMContext();
unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
if (SizeInRegs <= State.FreeRegs) {
llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32);
llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
State.FreeRegs -= SizeInRegs;
return ABIArgInfo::getDirectInReg(Result);
} else {
State.FreeRegs = 0;
}
return getIndirectResult(Ty, true, State);
}
// Treat an enum type as its underlying type.
if (const auto *EnumTy = Ty->getAs<EnumType>())
Ty = EnumTy->getDecl()->getIntegerType();
bool InReg = shouldUseInReg(Ty, State);
// Don't pass >64 bit integers in registers.
if (const auto *EIT = Ty->getAs<ExtIntType>())
if (EIT->getNumBits() > 64)
return getIndirectResult(Ty, /*ByVal=*/true, State);
if (isPromotableIntegerTypeForABI(Ty)) {
if (InReg)
return ABIArgInfo::getDirectInReg();
return ABIArgInfo::getExtend(Ty);
}
if (InReg)
return ABIArgInfo::getDirectInReg();
return ABIArgInfo::getDirect();
}
namespace {
class LanaiTargetCodeGenInfo : public TargetCodeGenInfo {
public:
LanaiTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
: TargetCodeGenInfo(std::make_unique<LanaiABIInfo>(CGT)) {}
};
}
//===----------------------------------------------------------------------===//
// AMDGPU ABI Implementation
//===----------------------------------------------------------------------===//
namespace {
class AMDGPUABIInfo final : public DefaultABIInfo {
private:
static const unsigned MaxNumRegsForArgsRet = 16;
unsigned numRegsForType(QualType Ty) const;
bool isHomogeneousAggregateBaseType(QualType Ty) const override;
bool isHomogeneousAggregateSmallEnough(const Type *Base,
uint64_t Members) const override;
// Coerce HIP scalar pointer arguments from generic pointers to global ones.
llvm::Type *coerceKernelArgumentType(llvm::Type *Ty, unsigned FromAS,
unsigned ToAS) const {
// Single value types.
if (Ty->isPointerTy() && Ty->getPointerAddressSpace() == FromAS)
return llvm::PointerType::get(
cast<llvm::PointerType>(Ty)->getElementType(), ToAS);
return Ty;
}
public:
explicit AMDGPUABIInfo(CodeGen::CodeGenTypes &CGT) :
DefaultABIInfo(CGT) {}
ABIArgInfo classifyReturnType(QualType RetTy) const;
ABIArgInfo classifyKernelArgumentType(QualType Ty) const;
ABIArgInfo classifyArgumentType(QualType Ty, unsigned &NumRegsLeft) const;
void computeInfo(CGFunctionInfo &FI) const override;
Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
QualType Ty) const override;
};
bool AMDGPUABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
return true;
}
bool AMDGPUABIInfo::isHomogeneousAggregateSmallEnough(
const Type *Base, uint64_t Members) const {
uint32_t NumRegs = (getContext().getTypeSize(Base) + 31) / 32;
// Homogeneous Aggregates may occupy at most 16 registers.
return Members * NumRegs <= MaxNumRegsForArgsRet;
}
/// Estimate number of registers the type will use when passed in registers.
unsigned AMDGPUABIInfo::numRegsForType(QualType Ty) const {
unsigned NumRegs = 0;
if (const VectorType *VT = Ty->getAs<VectorType>()) {
// Compute from the number of elements. The reported size is based on the
// in-memory size, which includes the padding 4th element for 3-vectors.
QualType EltTy = VT->getElementType();
unsigned EltSize = getContext().getTypeSize(EltTy);
// 16-bit element vectors should be passed as packed.
if (EltSize == 16)
return (VT->getNumElements() + 1) / 2;
unsigned EltNumRegs = (EltSize + 31) / 32;
return EltNumRegs * VT->getNumElements();
}
if (const RecordType *RT = Ty->getAs<RecordType>()) {
const RecordDecl *RD = RT->getDecl();
assert(!RD->hasFlexibleArrayMember());
for (const FieldDecl *Field : RD->fields()) {
QualType FieldTy = Field->getType();
NumRegs += numRegsForType(FieldTy);
}
return NumRegs;
}
return (getContext().getTypeSize(Ty) + 31) / 32;
}
void AMDGPUABIInfo::computeInfo(CGFunctionInfo &FI) const {
llvm::CallingConv::ID CC = FI.getCallingConvention();
if (!getCXXABI().classifyReturnType(FI))
FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
unsigned NumRegsLeft = MaxNumRegsForArgsRet;
for (auto &Arg : FI.arguments()) {
if (CC == llvm::CallingConv::AMDGPU_KERNEL) {
Arg.info = classifyKernelArgumentType(Arg.type);
} else {
Arg.info = classifyArgumentType(Arg.type, NumRegsLeft);
}
}
}
Address AMDGPUABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
QualType Ty) const {
llvm_unreachable("AMDGPU does not support varargs");
}
ABIArgInfo AMDGPUABIInfo::classifyReturnType(QualType RetTy) const {
if (isAggregateTypeForABI(RetTy)) {
// Records with non-trivial destructors/copy-constructors should not be
// returned by value.
if (!getRecordArgABI(RetTy, getCXXABI())) {
// Ignore empty structs/unions.
if (isEmptyRecord(getContext(), RetTy, true))
return ABIArgInfo::getIgnore();
// Lower single-element structs to just return a regular value.
if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
if (const RecordType *RT = RetTy->getAs<RecordType>()) {
const RecordDecl *RD = RT->getDecl();
if (RD->hasFlexibleArrayMember())
return DefaultABIInfo::classifyReturnType(RetTy);
}
// Pack aggregates <= 4 bytes into single VGPR or pair.
uint64_t Size = getContext().getTypeSize(RetTy);
if (Size <= 16)
return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
if (Size <= 32)
return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
if (Size <= 64) {
llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext());
return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2));
}
if (numRegsForType(RetTy) <= MaxNumRegsForArgsRet)
return ABIArgInfo::getDirect();
}
}
// Otherwise just do the default thing.
return DefaultABIInfo::classifyReturnType(RetTy);
}
/// For kernels all parameters are really passed in a special buffer. It doesn't
/// make sense to pass anything byval, so everything must be direct.
ABIArgInfo AMDGPUABIInfo::classifyKernelArgumentType(QualType Ty) const {
Ty = useFirstFieldIfTransparentUnion(Ty);
// TODO: Can we omit empty structs?
if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
Ty = QualType(SeltTy, 0);
llvm::Type *OrigLTy = CGT.ConvertType(Ty);
llvm::Type *LTy = OrigLTy;
if (getContext().getLangOpts().HIP) {
LTy = coerceKernelArgumentType(
OrigLTy, /*FromAS=*/getContext().getTargetAddressSpace(LangAS::Default),
/*ToAS=*/getContext().getTargetAddressSpace(LangAS::cuda_device));
}
// FIXME: Should also use this for OpenCL, but it requires addressing the
// problem of kernels being called.
//
// FIXME: This doesn't apply the optimization of coercing pointers in structs
// to global address space when using byref. This would require implementing a
// new kind of coercion of the in-memory type when for indirect arguments.
if (!getContext().getLangOpts().OpenCL && LTy == OrigLTy &&
isAggregateTypeForABI(Ty)) {
return ABIArgInfo::getIndirectAliased(
getContext().getTypeAlignInChars(Ty),
getContext().getTargetAddressSpace(LangAS::opencl_constant),
false /*Realign*/, nullptr /*Padding*/);
}
// If we set CanBeFlattened to true, CodeGen will expand the struct to its
// individual elements, which confuses the Clover OpenCL backend; therefore we
// have to set it to false here. Other args of getDirect() are just defaults.
return ABIArgInfo::getDirect(LTy, 0, nullptr, false);
}
ABIArgInfo AMDGPUABIInfo::classifyArgumentType(QualType Ty,
unsigned &NumRegsLeft) const {
assert(NumRegsLeft <= MaxNumRegsForArgsRet && "register estimate underflow");
Ty = useFirstFieldIfTransparentUnion(Ty);
if (isAggregateTypeForABI(Ty)) {
// Records with non-trivial destructors/copy-constructors should not be
// passed by value.
if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
// Ignore empty structs/unions.
if (isEmptyRecord(getContext(), Ty, true))
return ABIArgInfo::getIgnore();
// Lower single-element structs to just pass a regular value. TODO: We
// could do reasonable-size multiple-element structs too, using getExpand(),
// though watch out for things like bitfields.
if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
if (const RecordType *RT = Ty->getAs<RecordType>()) {
const RecordDecl *RD = RT->getDecl();
if (RD->hasFlexibleArrayMember())
return DefaultABIInfo::classifyArgumentType(Ty);
}
// Pack aggregates <= 8 bytes into single VGPR or pair.
uint64_t Size = getContext().getTypeSize(Ty);
if (Size <= 64) {
unsigned NumRegs = (Size + 31) / 32;
NumRegsLeft -= std::min(NumRegsLeft, NumRegs);
if (Size <= 16)
return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
if (Size <= 32)
return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
// XXX: Should this be i64 instead, and should the limit increase?
llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext());
return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2));
}
if (NumRegsLeft > 0) {
unsigned NumRegs = numRegsForType(Ty);
if (NumRegsLeft >= NumRegs) {
NumRegsLeft -= NumRegs;
return ABIArgInfo::getDirect();
}
}
}
// Otherwise just do the default thing.
ABIArgInfo ArgInfo = DefaultABIInfo::classifyArgumentType(Ty);
if (!ArgInfo.isIndirect()) {
unsigned NumRegs = numRegsForType(Ty);
NumRegsLeft -= std::min(NumRegs, NumRegsLeft);
}
return ArgInfo;
}
class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo {
public:
AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT)
: TargetCodeGenInfo(std::make_unique<AMDGPUABIInfo>(CGT)) {}
void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
CodeGen::CodeGenModule &M) const override;
unsigned getOpenCLKernelCallingConv() const override;
llvm::Constant *getNullPointer(const CodeGen::CodeGenModule &CGM,
llvm::PointerType *T, QualType QT) const override;
LangAS getASTAllocaAddressSpace() const override {
return getLangASFromTargetAS(
getABIInfo().getDataLayout().getAllocaAddrSpace());
}
LangAS getGlobalVarAddressSpace(CodeGenModule &CGM,
const VarDecl *D) const override;
llvm::SyncScope::ID getLLVMSyncScopeID(const LangOptions &LangOpts,
SyncScope Scope,
llvm::AtomicOrdering Ordering,
llvm::LLVMContext &Ctx) const override;
llvm::Function *
createEnqueuedBlockKernel(CodeGenFunction &CGF,
llvm::Function *BlockInvokeFunc,
llvm::Value *BlockLiteral) const override;
bool shouldEmitStaticExternCAliases() const override;
void setCUDAKernelCallingConvention(const FunctionType *&FT) const override;
};
}
static bool requiresAMDGPUProtectedVisibility(const Decl *D,
llvm::GlobalValue *GV) {
if (GV->getVisibility() != llvm::GlobalValue::HiddenVisibility)
return false;
return D->hasAttr<OpenCLKernelAttr>() ||
(isa<FunctionDecl>(D) && D->hasAttr<CUDAGlobalAttr>()) ||
(isa<VarDecl>(D) &&
(D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>() ||
cast<VarDecl>(D)->getType()->isCUDADeviceBuiltinSurfaceType() ||
cast<VarDecl>(D)->getType()->isCUDADeviceBuiltinTextureType()));
}
void AMDGPUTargetCodeGenInfo::setTargetAttributes(
const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
if (requiresAMDGPUProtectedVisibility(D, GV)) {
GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
GV->setDSOLocal(true);
}
if (GV->isDeclaration())
return;
const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
if (!FD)
return;
llvm::Function *F = cast<llvm::Function>(GV);
const auto *ReqdWGS = M.getLangOpts().OpenCL ?
FD->getAttr<ReqdWorkGroupSizeAttr>() : nullptr;
const bool IsOpenCLKernel = M.getLangOpts().OpenCL &&
FD->hasAttr<OpenCLKernelAttr>();
const bool IsHIPKernel = M.getLangOpts().HIP &&
FD->hasAttr<CUDAGlobalAttr>();
if ((IsOpenCLKernel || IsHIPKernel) &&
(M.getTriple().getOS() == llvm::Triple::AMDHSA))
F->addFnAttr("amdgpu-implicitarg-num-bytes", "56");
if (IsHIPKernel)
F->addFnAttr("uniform-work-group-size", "true");
const auto *FlatWGS = FD->getAttr<AMDGPUFlatWorkGroupSizeAttr>();
if (ReqdWGS || FlatWGS) {
unsigned Min = 0;
unsigned Max = 0;
unsigned XDim = 0;
unsigned YDim = 0;
unsigned ZDim = 0;
ASTContext &Ctx = M.getContext();
if (FlatWGS) {
Min = FlatWGS->getMin()->EvaluateKnownConstInt(Ctx).getExtValue();
Max = FlatWGS->getMax()->EvaluateKnownConstInt(Ctx).getExtValue();
}
if (ReqdWGS) {
XDim = ReqdWGS->getXDimVal(Ctx)->getZExtValue();
YDim = ReqdWGS->getYDimVal(Ctx)->getZExtValue();
ZDim = ReqdWGS->getZDimVal(Ctx)->getZExtValue();
}
if (ReqdWGS && Min == 0 && Max == 0)
Min = Max = XDim * YDim * ZDim;
if (Min != 0) {
assert(Min <= Max && "Min must be less than or equal Max");
std::string AttrVal = llvm::utostr(Min) + "," + llvm::utostr(Max);
F->addFnAttr("amdgpu-flat-work-group-size", AttrVal);
} else
assert(Max == 0 && "Max must be zero");
} else if (IsOpenCLKernel || IsHIPKernel) {
// By default, restrict the maximum size to a value specified by
// --gpu-max-threads-per-block=n or its default value for HIP.
const unsigned OpenCLDefaultMaxWorkGroupSize = 256;
const unsigned DefaultMaxWorkGroupSize =
IsOpenCLKernel ? OpenCLDefaultMaxWorkGroupSize
: M.getLangOpts().GPUMaxThreadsPerBlock;
std::string AttrVal =
std::string("1,") + llvm::utostr(DefaultMaxWorkGroupSize);
F->addFnAttr("amdgpu-flat-work-group-size", AttrVal);
}
if (const auto *Attr = FD->getAttr<AMDGPUWavesPerEUAttr>()) {
unsigned Min =
Attr->getMin()->EvaluateKnownConstInt(M.getContext()).getExtValue();
unsigned Max = Attr->getMax() ? Attr->getMax()
->EvaluateKnownConstInt(M.getContext())
.getExtValue()
: 0;
if (Min != 0) {
assert((Max == 0 || Min <= Max) && "Min must be less than or equal Max");
std::string AttrVal = llvm::utostr(Min);
if (Max != 0)
AttrVal = AttrVal + "," + llvm::utostr(Max);
F->addFnAttr("amdgpu-waves-per-eu", AttrVal);
} else
assert(Max == 0 && "Max must be zero");
}
if (const auto *Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) {
unsigned NumSGPR = Attr->getNumSGPR();
if (NumSGPR != 0)
F->addFnAttr("amdgpu-num-sgpr", llvm::utostr(NumSGPR));
}
if (const auto *Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) {
uint32_t NumVGPR = Attr->getNumVGPR();
if (NumVGPR != 0)
F->addFnAttr("amdgpu-num-vgpr", llvm::utostr(NumVGPR));
}
if (M.getContext().getTargetInfo().allowAMDGPUUnsafeFPAtomics())
F->addFnAttr("amdgpu-unsafe-fp-atomics", "true");
if (!getABIInfo().getCodeGenOpts().EmitIEEENaNCompliantInsts)
F->addFnAttr("amdgpu-ieee", "false");
}
unsigned AMDGPUTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
return llvm::CallingConv::AMDGPU_KERNEL;
}
// Currently LLVM assumes null pointers always have value 0,
// which results in incorrectly transformed IR. Therefore, instead of
// emitting null pointers in private and local address spaces, a null
// pointer in generic address space is emitted which is casted to a
// pointer in local or private address space.
llvm::Constant *AMDGPUTargetCodeGenInfo::getNullPointer(
const CodeGen::CodeGenModule &CGM, llvm::PointerType *PT,
QualType QT) const {
if (CGM.getContext().getTargetNullPointerValue(QT) == 0)
return llvm::ConstantPointerNull::get(PT);
auto &Ctx = CGM.getContext();
auto NPT = llvm::PointerType::get(PT->getElementType(),
Ctx.getTargetAddressSpace(LangAS::opencl_generic));
return llvm::ConstantExpr::getAddrSpaceCast(
llvm::ConstantPointerNull::get(NPT), PT);
}
LangAS
AMDGPUTargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM,
const VarDecl *D) const {
assert(!CGM.getLangOpts().OpenCL &&
!(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) &&
"Address space agnostic languages only");
LangAS DefaultGlobalAS = getLangASFromTargetAS(
CGM.getContext().getTargetAddressSpace(LangAS::opencl_global));
if (!D)
return DefaultGlobalAS;
LangAS AddrSpace = D->getType().getAddressSpace();
assert(AddrSpace == LangAS::Default || isTargetAddressSpace(AddrSpace));
if (AddrSpace != LangAS::Default)
return AddrSpace;
if (CGM.isTypeConstant(D->getType(), false)) {
if (auto ConstAS = CGM.getTarget().getConstantAddressSpace())
return ConstAS.getValue();
}
return DefaultGlobalAS;
}
llvm::SyncScope::ID
AMDGPUTargetCodeGenInfo::getLLVMSyncScopeID(const LangOptions &LangOpts,
SyncScope Scope,
llvm::AtomicOrdering Ordering,
llvm::LLVMContext &Ctx) const {
std::string Name;
switch (Scope) {
case SyncScope::OpenCLWorkGroup:
Name = "workgroup";
break;
case SyncScope::OpenCLDevice:
Name = "agent";
break;
case SyncScope::OpenCLAllSVMDevices:
Name = "";
break;
case SyncScope::OpenCLSubGroup:
Name = "wavefront";
}
if (Ordering != llvm::AtomicOrdering::SequentiallyConsistent) {
if (!Name.empty())
Name = Twine(Twine(Name) + Twine("-")).str();
Name = Twine(Twine(Name) + Twine("one-as")).str();
}
return Ctx.getOrInsertSyncScopeID(Name);
}
bool AMDGPUTargetCodeGenInfo::shouldEmitStaticExternCAliases() const {
return false;
}
void AMDGPUTargetCodeGenInfo::setCUDAKernelCallingConvention(
const FunctionType *&FT) const {
FT = getABIInfo().getContext().adjustFunctionType(
FT, FT->getExtInfo().withCallingConv(CC_OpenCLKernel));
}
//===----------------------------------------------------------------------===//
// SPARC v8 ABI Implementation.
// Based on the SPARC Compliance Definition version 2.4.1.
//
// Ensures that complex values are passed in registers.
//
namespace {
class SparcV8ABIInfo : public DefaultABIInfo {
public:
SparcV8ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
private:
ABIArgInfo classifyReturnType(QualType RetTy) const;
void computeInfo(CGFunctionInfo &FI) const override;
};
} // end anonymous namespace
ABIArgInfo
SparcV8ABIInfo::classifyReturnType(QualType Ty) const {
if (Ty->isAnyComplexType()) {
return ABIArgInfo::getDirect();
}
else {
return DefaultABIInfo::classifyReturnType(Ty);
}
}
void SparcV8ABIInfo::computeInfo(CGFunctionInfo &FI) const {
FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
for (auto &Arg : FI.arguments())
Arg.info = classifyArgumentType(Arg.type);
}
namespace {
class SparcV8TargetCodeGenInfo : public TargetCodeGenInfo {
public:
SparcV8TargetCodeGenInfo(CodeGenTypes &CGT)
: TargetCodeGenInfo(std::make_unique<SparcV8ABIInfo>(CGT)) {}
};
} // end anonymous namespace
//===----------------------------------------------------------------------===//
// SPARC v9 ABI Implementation.
// Based on the SPARC Compliance Definition version 2.4.1.
//
// Function arguments a mapped to a nominal "parameter array" and promoted to
// registers depending on their type. Each argument occupies 8 or 16 bytes in
// the array, structs larger than 16 bytes are passed indirectly.
//
// One case requires special care:
//
// struct mixed {
// int i;
// float f;
// };
//
// When a struct mixed is passed by value, it only occupies 8 bytes in the
// parameter array, but the int is passed in an integer register, and the float
// is passed in a floating point register. This is represented as two arguments
// with the LLVM IR inreg attribute:
//
// declare void f(i32 inreg %i, float inreg %f)
//
// The code generator will only allocate 4 bytes from the parameter array for
// the inreg arguments. All other arguments are allocated a multiple of 8
// bytes.
//
namespace {
class SparcV9ABIInfo : public ABIInfo {
public:
SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
private:
ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
void computeInfo(CGFunctionInfo &FI) const override;
Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
QualType Ty) const override;
// Coercion type builder for structs passed in registers. The coercion type
// serves two purposes:
//
// 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
// in registers.
// 2. Expose aligned floating point elements as first-level elements, so the
// code generator knows to pass them in floating point registers.
//
// We also compute the InReg flag which indicates that the struct contains
// aligned 32-bit floats.
//
struct CoerceBuilder {
llvm::LLVMContext &Context;
const llvm::DataLayout &DL;
SmallVector<llvm::Type*, 8> Elems;
uint64_t Size;
bool InReg;
CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
: Context(c), DL(dl), Size(0), InReg(false) {}
// Pad Elems with integers until Size is ToSize.
void pad(uint64_t ToSize) {
assert(ToSize >= Size && "Cannot remove elements");
if (ToSize == Size)
return;
// Finish the current 64-bit word.
uint64_t Aligned = llvm::alignTo(Size, 64);
if (Aligned > Size && Aligned <= ToSize) {
Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
Size = Aligned;
}
// Add whole 64-bit words.
while (Size + 64 <= ToSize) {
Elems.push_back(llvm::Type::getInt64Ty(Context));
Size += 64;
}
// Final in-word padding.
if (Size < ToSize) {
Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
Size = ToSize;
}
}
// Add a floating point element at Offset.
void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
// Unaligned floats are treated as integers.
if (Offset % Bits)
return;
// The InReg flag is only required if there are any floats < 64 bits.
if (Bits < 64)
InReg = true;
pad(Offset);
Elems.push_back(Ty);
Size = Offset + Bits;
}
// Add a struct type to the coercion type, starting at Offset (in bits).
void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
llvm::Type *ElemTy = StrTy->getElementType(i);
uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
switch (ElemTy->getTypeID()) {
case llvm::Type::StructTyID:
addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
break;
case llvm::Type::FloatTyID:
addFloat(ElemOffset, ElemTy, 32);
break;
case llvm::Type::DoubleTyID:
addFloat(ElemOffset, ElemTy, 64);
break;
case llvm::Type::FP128TyID:
addFloat(ElemOffset, ElemTy, 128);
break;
case llvm::Type::PointerTyID:
if (ElemOffset % 64 == 0) {
pad(ElemOffset);
Elems.push_back(ElemTy);
Size += 64;
}
break;
default:
break;
}
}
}
// Check if Ty is a usable substitute for the coercion type.
bool isUsableType(llvm::StructType *Ty) const {
return llvm::makeArrayRef(Elems) == Ty->elements();
}
// Get the coercion type as a literal struct type.
llvm::Type *getType() const {
if (Elems.size() == 1)
return Elems.front();
else
return llvm::StructType::get(Context, Elems);
}
};
};
} // end anonymous namespace
ABIArgInfo
SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
if (Ty->isVoidType())
return ABIArgInfo::getIgnore();
uint64_t Size = getContext().getTypeSize(Ty);
// Anything too big to fit in registers is passed with an explicit indirect
// pointer / sret pointer.
if (Size > SizeLimit)
return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
// Treat an enum type as its underlying type.
if (const EnumType *EnumTy = Ty->getAs<EnumType>())
Ty = EnumTy->getDecl()->getIntegerType();
// Integer types smaller than a register are extended.
if (Size < 64 && Ty->isIntegerType())
return ABIArgInfo::getExtend(Ty);
if (const auto *EIT = Ty->getAs<ExtIntType>())
if (EIT->getNumBits() < 64)
return ABIArgInfo::getExtend(Ty);
// Other non-aggregates go in registers.
if (!isAggregateTypeForABI(Ty))
return ABIArgInfo::getDirect();
// If a C++ object has either a non-trivial copy constructor or a non-trivial
// destructor, it is passed with an explicit indirect pointer / sret pointer.
if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
// This is a small aggregate type that should be passed in registers.
// Build a coercion type from the LLVM struct type.
llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
if (!StrTy)
return ABIArgInfo::getDirect();
CoerceBuilder CB(getVMContext(), getDataLayout());
CB.addStruct(0, StrTy);
CB.pad(llvm::alignTo(CB.DL.getTypeSizeInBits(StrTy), 64));
// Try to use the original type for coercion.
llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
if (CB.InReg)
return ABIArgInfo::getDirectInReg(CoerceTy);
else
return ABIArgInfo::getDirect(CoerceTy);
}
Address SparcV9ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
QualType Ty) const {
ABIArgInfo AI = classifyType(Ty, 16 * 8);
llvm::Type *ArgTy = CGT.ConvertType(Ty);
if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
AI.setCoerceToType(ArgTy);
CharUnits SlotSize = CharUnits::fromQuantity(8);
CGBuilderTy &Builder = CGF.Builder;
Address Addr(Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
auto TypeInfo = getContext().getTypeInfoInChars(Ty);
Address ArgAddr = Address::invalid();
CharUnits Stride;
switch (AI.getKind()) {
case ABIArgInfo::Expand:
case ABIArgInfo::CoerceAndExpand:
case ABIArgInfo::InAlloca:
llvm_unreachable("Unsupported ABI kind for va_arg");
case ABIArgInfo::Extend: {
Stride = SlotSize;
CharUnits Offset = SlotSize - TypeInfo.Width;
ArgAddr = Builder.CreateConstInBoundsByteGEP(Addr, Offset, "extend");
break;
}
case ABIArgInfo::Direct: {
auto AllocSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
Stride = CharUnits::fromQuantity(AllocSize).alignTo(SlotSize);
ArgAddr = Addr;
break;
}
case ABIArgInfo::Indirect:
case ABIArgInfo::IndirectAliased:
Stride = SlotSize;
ArgAddr = Builder.CreateElementBitCast(Addr, ArgPtrTy, "indirect");
ArgAddr = Address(Builder.CreateLoad(ArgAddr, "indirect.arg"),
TypeInfo.Align);
break;
case ABIArgInfo::Ignore:
return Address(llvm::UndefValue::get(ArgPtrTy), TypeInfo.Align);
}
// Update VAList.
Address NextPtr = Builder.CreateConstInBoundsByteGEP(Addr, Stride, "ap.next");
Builder.CreateStore(NextPtr.getPointer(), VAListAddr);
return Builder.CreateBitCast(ArgAddr, ArgPtrTy, "arg.addr");
}
void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
for (auto &I : FI.arguments())
I.info = classifyType(I.type, 16 * 8);
}
namespace {
class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
public:
SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
: TargetCodeGenInfo(std::make_unique<SparcV9ABIInfo>(CGT)) {}
int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
return 14;
}
bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
llvm::Value *Address) const override;
};
} // end anonymous namespace
bool
SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
llvm::Value *Address) const {
// This is calculated from the LLVM and GCC tables and verified
// against gcc output. AFAIK all ABIs use the same encoding.
CodeGen::CGBuilderTy &Builder = CGF.Builder;
llvm::IntegerType *i8 = CGF.Int8Ty;
llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
// 0-31: the 8-byte general-purpose registers
AssignToArrayRange(Builder, Address, Eight8, 0, 31);
// 32-63: f0-31, the 4-byte floating-point registers
AssignToArrayRange(Builder, Address, Four8, 32, 63);
// Y = 64
// PSR = 65
// WIM = 66
// TBR = 67
// PC = 68
// NPC = 69
// FSR = 70
// CSR = 71
AssignToArrayRange(Builder, Address, Eight8, 64, 71);
// 72-87: d0-15, the 8-byte floating-point registers
AssignToArrayRange(Builder, Address, Eight8, 72, 87);
return false;
}
// ARC ABI implementation.
namespace {
class ARCABIInfo : public DefaultABIInfo {
public:
using DefaultABIInfo::DefaultABIInfo;
private:
Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
QualType Ty) const override;
void updateState(const ABIArgInfo &Info, QualType Ty, CCState &State) const {
if (!State.FreeRegs)
return;
if (Info.isIndirect() && Info.getInReg())
State.FreeRegs--;
else if (Info.isDirect() && Info.getInReg()) {
unsigned sz = (getContext().getTypeSize(Ty) + 31) / 32;
if (sz < State.FreeRegs)
State.FreeRegs -= sz;
else
State.FreeRegs = 0;
}
}
void computeInfo(CGFunctionInfo &FI) const override {
CCState State(FI);
// ARC uses 8 registers to pass arguments.
State.FreeRegs = 8;
if (!getCXXABI().classifyReturnType(FI))
FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
updateState(FI.getReturnInfo(), FI.getReturnType(), State);
for (auto &I : FI.arguments()) {
I.info = classifyArgumentType(I.type, State.FreeRegs);
updateState(I.info, I.type, State);
}
}
ABIArgInfo getIndirectByRef(QualType Ty, bool HasFreeRegs) const;
ABIArgInfo getIndirectByValue(QualType Ty) const;
ABIArgInfo classifyArgumentType(QualType Ty, uint8_t FreeRegs) const;
ABIArgInfo classifyReturnType(QualType RetTy) const;
};
class ARCTargetCodeGenInfo : public TargetCodeGenInfo {
public:
ARCTargetCodeGenInfo(CodeGenTypes &CGT)
: TargetCodeGenInfo(std::make_unique<ARCABIInfo>(CGT)) {}
};
ABIArgInfo ARCABIInfo::getIndirectByRef(QualType Ty, bool HasFreeRegs) const {
return HasFreeRegs ? getNaturalAlignIndirectInReg(Ty) :
getNaturalAlignIndirect(Ty, false);
}
ABIArgInfo ARCABIInfo::getIndirectByValue(QualType Ty) const {
// Compute the byval alignment.
const unsigned MinABIStackAlignInBytes = 4;
unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true,
TypeAlign > MinABIStackAlignInBytes);
}
Address ARCABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
QualType Ty) const {
return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
getContext().getTypeInfoInChars(Ty),
CharUnits::fromQuantity(4), true);
}
ABIArgInfo ARCABIInfo::classifyArgumentType(QualType Ty,
uint8_t FreeRegs) const {
// Handle the generic C++ ABI.
const RecordType *RT = Ty->getAs<RecordType>();
if (RT) {
CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
if (RAA == CGCXXABI::RAA_Indirect)
return getIndirectByRef(Ty, FreeRegs > 0);
if (RAA == CGCXXABI::RAA_DirectInMemory)
return getIndirectByValue(Ty);
}
// Treat an enum type as its underlying type.
if (const EnumType *EnumTy = Ty->getAs<EnumType>())
Ty = EnumTy->getDecl()->getIntegerType();
auto SizeInRegs = llvm::alignTo(getContext().getTypeSize(Ty), 32) / 32;
if (isAggregateTypeForABI(Ty)) {
// Structures with flexible arrays are always indirect.
if (RT && RT->getDecl()->hasFlexibleArrayMember())
return getIndirectByValue(Ty);
// Ignore empty structs/unions.
if (isEmptyRecord(getContext(), Ty, true))
return ABIArgInfo::getIgnore();
llvm::LLVMContext &LLVMContext = getVMContext();
llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32);
llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
return FreeRegs >= SizeInRegs ?
ABIArgInfo::getDirectInReg(Result) :
ABIArgInfo::getDirect(Result, 0, nullptr, false);
}
if (const auto *EIT = Ty->getAs<ExtIntType>())
if (EIT->getNumBits() > 64)
return getIndirectByValue(Ty);
return isPromotableIntegerTypeForABI(Ty)
? (FreeRegs >= SizeInRegs ? ABIArgInfo::getExtendInReg(Ty)
: ABIArgInfo::getExtend(Ty))
: (FreeRegs >= SizeInRegs ? ABIArgInfo::getDirectInReg()
: ABIArgInfo::getDirect());
}
ABIArgInfo ARCABIInfo::classifyReturnType(QualType RetTy) const {
if (RetTy->isAnyComplexType())
return ABIArgInfo::getDirectInReg();
// Arguments of size > 4 registers are indirect.
auto RetSize = llvm::alignTo(getContext().getTypeSize(RetTy), 32) / 32;
if (RetSize > 4)
return getIndirectByRef(RetTy, /*HasFreeRegs*/ true);
return DefaultABIInfo::classifyReturnType(RetTy);
}
} // End anonymous namespace.
//===----------------------------------------------------------------------===//
// XCore ABI Implementation
//===----------------------------------------------------------------------===//
namespace {
/// A SmallStringEnc instance is used to build up the TypeString by passing
/// it by reference between functions that append to it.
typedef llvm::SmallString<128> SmallStringEnc;
/// TypeStringCache caches the meta encodings of Types.
///
/// The reason for caching TypeStrings is two fold:
/// 1. To cache a type's encoding for later uses;
/// 2. As a means to break recursive member type inclusion.
///
/// A cache Entry can have a Status of:
/// NonRecursive: The type encoding is not recursive;
/// Recursive: The type encoding is recursive;
/// Incomplete: An incomplete TypeString;
/// IncompleteUsed: An incomplete TypeString that has been used in a
/// Recursive type encoding.
///
/// A NonRecursive entry will have all of its sub-members expanded as fully
/// as possible. Whilst it may contain types which are recursive, the type
/// itself is not recursive and thus its encoding may be safely used whenever
/// the type is encountered.
///
/// A Recursive entry will have all of its sub-members expanded as fully as
/// possible. The type itself is recursive and it may contain other types which
/// are recursive. The Recursive encoding must not be used during the expansion
/// of a recursive type's recursive branch. For simplicity the code uses
/// IncompleteCount to reject all usage of Recursive encodings for member types.
///
/// An Incomplete entry is always a RecordType and only encodes its
/// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and
/// are placed into the cache during type expansion as a means to identify and
/// handle recursive inclusion of types as sub-members. If there is recursion
/// the entry becomes IncompleteUsed.
///
/// During the expansion of a RecordType's members:
///
/// If the cache contains a NonRecursive encoding for the member type, the
/// cached encoding is used;
///
/// If the cache contains a Recursive encoding for the member type, the
/// cached encoding is 'Swapped' out, as it may be incorrect, and...
///
/// If the member is a RecordType, an Incomplete encoding is placed into the
/// cache to break potential recursive inclusion of itself as a sub-member;
///
/// Once a member RecordType has been expanded, its temporary incomplete
/// entry is removed from the cache. If a Recursive encoding was swapped out
/// it is swapped back in;
///
/// If an incomplete entry is used to expand a sub-member, the incomplete
/// entry is marked as IncompleteUsed. The cache keeps count of how many
/// IncompleteUsed entries it currently contains in IncompleteUsedCount;
///
/// If a member's encoding is found to be a NonRecursive or Recursive viz:
/// IncompleteUsedCount==0, the member's encoding is added to the cache.
/// Else the member is part of a recursive type and thus the recursion has
/// been exited too soon for the encoding to be correct for the member.
///
class TypeStringCache {
enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed};
struct Entry {
std::string Str; // The encoded TypeString for the type.
enum Status State; // Information about the encoding in 'Str'.
std::string Swapped; // A temporary place holder for a Recursive encoding
// during the expansion of RecordType's members.
};
std::map<const IdentifierInfo *, struct Entry> Map;
unsigned IncompleteCount; // Number of Incomplete entries in the Map.
unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map.
public:
TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {}
void addIncomplete(const IdentifierInfo *ID, std::string StubEnc);
bool removeIncomplete(const IdentifierInfo *ID);
void addIfComplete(const IdentifierInfo *ID, StringRef Str,
bool IsRecursive);
StringRef lookupStr(const IdentifierInfo *ID);
};
/// TypeString encodings for enum & union fields must be order.
/// FieldEncoding is a helper for this ordering process.
class FieldEncoding {
bool HasName;
std::string Enc;
public:
FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {}
StringRef str() { return Enc; }
bool operator<(const FieldEncoding &rhs) const {
if (HasName != rhs.HasName) return HasName;
return Enc < rhs.Enc;
}
};
class XCoreABIInfo : public DefaultABIInfo {
public:
XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
QualType Ty) const override;
};
class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
mutable TypeStringCache TSC;
void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
const CodeGen::CodeGenModule &M) const;
public:
XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
: TargetCodeGenInfo(std::make_unique<XCoreABIInfo>(CGT)) {}
void emitTargetMetadata(CodeGen::CodeGenModule &CGM,
const llvm::MapVector<GlobalDecl, StringRef>
&MangledDeclNames) const override;
};
} // End anonymous namespace.
// TODO: this implementation is likely now redundant with the default
// EmitVAArg.
Address XCoreABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
QualType Ty) const {
CGBuilderTy &Builder = CGF.Builder;
// Get the VAList.
CharUnits SlotSize = CharUnits::fromQuantity(4);
Address AP(Builder.CreateLoad(VAListAddr), SlotSize);
// Handle the argument.
ABIArgInfo AI = classifyArgumentType(Ty);
CharUnits TypeAlign = getContext().getTypeAlignInChars(Ty);
llvm::Type *ArgTy = CGT.ConvertType(Ty);
if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
AI.setCoerceToType(ArgTy);
llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
Address Val = Address::invalid();
CharUnits ArgSize = CharUnits::Zero();
switch (AI.getKind()) {
case ABIArgInfo::Expand:
case ABIArgInfo::CoerceAndExpand:
case ABIArgInfo::InAlloca:
llvm_unreachable("Unsupported ABI kind for va_arg");
case ABIArgInfo::Ignore:
Val = Address(llvm::UndefValue::get(ArgPtrTy), TypeAlign);
ArgSize = CharUnits::Zero();
break;
case ABIArgInfo::Extend:
case ABIArgInfo::Direct:
Val = Builder.CreateBitCast(AP, ArgPtrTy);
ArgSize = CharUnits::fromQuantity(
getDataLayout().getTypeAllocSize(AI.getCoerceToType()));
ArgSize = ArgSize.alignTo(SlotSize);
break;
case ABIArgInfo::Indirect:
case ABIArgInfo::IndirectAliased:
Val = Builder.CreateElementBitCast(AP, ArgPtrTy);
Val = Address(Builder.CreateLoad(Val), TypeAlign);
ArgSize = SlotSize;
break;
}
// Increment the VAList.
if (!ArgSize.isZero()) {
Address APN = Builder.CreateConstInBoundsByteGEP(AP, ArgSize);
Builder.CreateStore(APN.getPointer(), VAListAddr);
}
return Val;
}
/// During the expansion of a RecordType, an incomplete TypeString is placed
/// into the cache as a means to identify and break recursion.
/// If there is a Recursive encoding in the cache, it is swapped out and will
/// be reinserted by removeIncomplete().
/// All other types of encoding should have been used rather than arriving here.
void TypeStringCache::addIncomplete(const IdentifierInfo *ID,
std::string StubEnc) {
if (!ID)
return;
Entry &E = Map[ID];
assert( (E.Str.empty() || E.State == Recursive) &&
"Incorrectly use of addIncomplete");
assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()");
E.Swapped.swap(E.Str); // swap out the Recursive
E.Str.swap(StubEnc);
E.State = Incomplete;
++IncompleteCount;
}
/// Once the RecordType has been expanded, the temporary incomplete TypeString
/// must be removed from the cache.
/// If a Recursive was swapped out by addIncomplete(), it will be replaced.
/// Returns true if the RecordType was defined recursively.
bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) {
if (!ID)
return false;
auto I = Map.find(ID);
assert(I != Map.end() && "Entry not present");
Entry &E = I->second;
assert( (E.State == Incomplete ||
E.State == IncompleteUsed) &&
"Entry must be an incomplete type");
bool IsRecursive = false;
if (E.State == IncompleteUsed) {
// We made use of our Incomplete encoding, thus we are recursive.
IsRecursive = true;
--IncompleteUsedCount;
}
if (E.Swapped.empty())
Map.erase(I);
else {
// Swap the Recursive back.
E.Swapped.swap(E.Str);
E.Swapped.clear();
E.State = Recursive;
}
--IncompleteCount;
return IsRecursive;
}
/// Add the encoded TypeString to the cache only if it is NonRecursive or
/// Recursive (viz: all sub-members were expanded as fully as possible).
void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str,
bool IsRecursive) {
if (!ID || IncompleteUsedCount)
return; // No key or it is is an incomplete sub-type so don't add.
Entry &E = Map[ID];
if (IsRecursive && !E.Str.empty()) {
assert(E.State==Recursive && E.Str.size() == Str.size() &&
"This is not the same Recursive entry");
// The parent container was not recursive after all, so we could have used
// this Recursive sub-member entry after all, but we assumed the worse when
// we started viz: IncompleteCount!=0.
return;
}
assert(E.Str.empty() && "Entry already present");
E.Str = Str.str();
E.State = IsRecursive? Recursive : NonRecursive;
}
/// Return a cached TypeString encoding for the ID. If there isn't one, or we
/// are recursively expanding a type (IncompleteCount != 0) and the cached
/// encoding is Recursive, return an empty StringRef.
StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) {
if (!ID)
return StringRef(); // We have no key.
auto I = Map.find(ID);
if (I == Map.end())
return StringRef(); // We have no encoding.
Entry &E = I->second;
if (E.State == Recursive && IncompleteCount)
return StringRef(); // We don't use Recursive encodings for member types.
if (E.State == Incomplete) {
// The incomplete type is being used to break out of recursion.
E.State = IncompleteUsed;
++IncompleteUsedCount;
}
return E.Str;
}
/// The XCore ABI includes a type information section that communicates symbol
/// type information to the linker. The linker uses this information to verify
/// safety/correctness of things such as array bound and pointers et al.
/// The ABI only requires C (and XC) language modules to emit TypeStrings.
/// This type information (TypeString) is emitted into meta data for all global
/// symbols: definitions, declarations, functions & variables.
///
/// The TypeString carries type, qualifier, name, size & value details.
/// Please see 'Tools Development Guide' section 2.16.2 for format details:
/// https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf
/// The output is tested by test/CodeGen/xcore-stringtype.c.
///
static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
const CodeGen::CodeGenModule &CGM,
TypeStringCache &TSC);
/// XCore uses emitTargetMD to emit TypeString metadata for global symbols.
void XCoreTargetCodeGenInfo::emitTargetMD(
const Decl *D, llvm::GlobalValue *GV,
const CodeGen::CodeGenModule &CGM) const {
SmallStringEnc Enc;
if (getTypeString(Enc, D, CGM, TSC)) {
llvm::LLVMContext &Ctx = CGM.getModule().getContext();
llvm::Metadata *MDVals[] = {llvm::ConstantAsMetadata::get(GV),
llvm::MDString::get(Ctx, Enc.str())};
llvm::NamedMDNode *MD =
CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings");
MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
}
}
void XCoreTargetCodeGenInfo::emitTargetMetadata(
CodeGen::CodeGenModule &CGM,
const llvm::MapVector<GlobalDecl, StringRef> &MangledDeclNames) const {
// Warning, new MangledDeclNames may be appended within this loop.
// We rely on MapVector insertions adding new elements to the end
// of the container.
for (unsigned I = 0; I != MangledDeclNames.size(); ++I) {
auto Val = *(MangledDeclNames.begin() + I);
llvm::GlobalValue *GV = CGM.GetGlobalValue(Val.second);
if (GV) {
const Decl *D = Val.first.getDecl()->getMostRecentDecl();
emitTargetMD(D, GV, CGM);
}
}
}
//===----------------------------------------------------------------------===//
// SPIR ABI Implementation
//===----------------------------------------------------------------------===//
namespace {
class SPIRABIInfo : public DefaultABIInfo {
public:
SPIRABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) { setCCs(); }
ABIArgInfo classifyKernelArgumentType(QualType Ty) const;
void computeInfo(CGFunctionInfo &FI) const override;
private:
void setCCs();
};
ABIArgInfo SPIRABIInfo::classifyKernelArgumentType(QualType Ty) const {
Ty = useFirstFieldIfTransparentUnion(Ty);
if (getContext().getLangOpts().SYCLIsDevice && isAggregateTypeForABI(Ty)) {
// Pass all aggregate types allowed by Sema by value.
return getNaturalAlignIndirect(Ty);
}
return DefaultABIInfo::classifyArgumentType(Ty);
}
void SPIRABIInfo::computeInfo(CGFunctionInfo &FI) const {
llvm::CallingConv::ID CC = FI.getCallingConvention();
if (!getCXXABI().classifyReturnType(FI))
FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
for (auto &Arg : FI.arguments()) {
if (CC == llvm::CallingConv::SPIR_KERNEL) {
Arg.info = classifyKernelArgumentType(Arg.type);
} else {
Arg.info = classifyArgumentType(Arg.type);
}
}
}
} // end anonymous namespace
namespace {
class SPIRTargetCodeGenInfo : public TargetCodeGenInfo {
public:
SPIRTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
: TargetCodeGenInfo(std::make_unique<SPIRABIInfo>(CGT)) {}
unsigned getOpenCLKernelCallingConv() const override;
LangAS getASTAllocaAddressSpace() const override {
return getLangASFromTargetAS(
getABIInfo().getDataLayout().getAllocaAddrSpace());
}
bool shouldEmitStaticExternCAliases() const override;
};
} // End anonymous namespace.
void SPIRABIInfo::setCCs() {
assert(getRuntimeCC() == llvm::CallingConv::C);
RuntimeCC = llvm::CallingConv::SPIR_FUNC;
}
namespace clang {
namespace CodeGen {
void computeSPIRKernelABIInfo(CodeGenModule &CGM, CGFunctionInfo &FI) {
SPIRABIInfo SPIRABI(CGM.getTypes());
SPIRABI.computeInfo(FI);
}
}
}
unsigned SPIRTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
return llvm::CallingConv::SPIR_KERNEL;
}
bool SPIRTargetCodeGenInfo::shouldEmitStaticExternCAliases() const {
return false;
}
static bool appendType(SmallStringEnc &Enc, QualType QType,
const CodeGen::CodeGenModule &CGM,
TypeStringCache &TSC);
/// Helper function for appendRecordType().
/// Builds a SmallVector containing the encoded field types in declaration
/// order.
static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE,
const RecordDecl *RD,
const CodeGen::CodeGenModule &CGM,
TypeStringCache &TSC) {
for (const auto *Field : RD->fields()) {
SmallStringEnc Enc;
Enc += "m(";
Enc += Field->getName();
Enc += "){";
if (Field->isBitField()) {
Enc += "b(";
llvm::raw_svector_ostream OS(Enc);
OS << Field->getBitWidthValue(CGM.getContext());
Enc += ':';
}
if (!appendType(Enc, Field->getType(), CGM, TSC))
return false;
if (Field->isBitField())
Enc += ')';
Enc += '}';
FE.emplace_back(!Field->getName().empty(), Enc);
}
return true;
}
/// Appends structure and union types to Enc and adds encoding to cache.
/// Recursively calls appendType (via extractFieldType) for each field.
/// Union types have their fields ordered according to the ABI.
static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT,
const CodeGen::CodeGenModule &CGM,
TypeStringCache &TSC, const IdentifierInfo *ID) {
// Append the cached TypeString if we have one.
StringRef TypeString = TSC.lookupStr(ID);
if (!TypeString.empty()) {
Enc += TypeString;
return true;
}
// Start to emit an incomplete TypeString.
size_t Start = Enc.size();
Enc += (RT->isUnionType()? 'u' : 's');
Enc += '(';
if (ID)
Enc += ID->getName();
Enc += "){";
// We collect all encoded fields and order as necessary.
bool IsRecursive = false;
const RecordDecl *RD = RT->getDecl()->getDefinition();
if (RD && !RD->field_empty()) {
// An incomplete TypeString stub is placed in the cache for this RecordType
// so that recursive calls to this RecordType will use it whilst building a
// complete TypeString for this RecordType.
SmallVector<FieldEncoding, 16> FE;
std::string StubEnc(Enc.substr(Start).str());
StubEnc += '}'; // StubEnc now holds a valid incomplete TypeString.
TSC.addIncomplete(ID, std::move(StubEnc));
if (!extractFieldType(FE, RD, CGM, TSC)) {
(void) TSC.removeIncomplete(ID);
return false;
}
IsRecursive = TSC.removeIncomplete(ID);
// The ABI requires unions to be sorted but not structures.
// See FieldEncoding::operator< for sort algorithm.
if (RT->isUnionType())
llvm::sort(FE);
// We can now complete the TypeString.
unsigned E = FE.size();
for (unsigned I = 0; I != E; ++I) {
if (I)
Enc += ',';
Enc += FE[I].str();
}
}
Enc += '}';
TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive);
return true;
}
/// Appends enum types to Enc and adds the encoding to the cache.
static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET,
TypeStringCache &TSC,
const IdentifierInfo *ID) {
// Append the cached TypeString if we have one.
StringRef TypeString = TSC.lookupStr(ID);
if (!TypeString.empty()) {
Enc += TypeString;
return true;
}
size_t Start = Enc.size();
Enc += "e(";
if (ID)
Enc += ID->getName();
Enc += "){";
// We collect all encoded enumerations and order them alphanumerically.
if (const EnumDecl *ED = ET->getDecl()->getDefinition()) {
SmallVector<FieldEncoding, 16> FE;
for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E;
++I) {
SmallStringEnc EnumEnc;
EnumEnc += "m(";
EnumEnc += I->getName();
EnumEnc += "){";
I->getInitVal().toString(EnumEnc);
EnumEnc += '}';
FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc));
}
llvm::sort(FE);
unsigned E = FE.size();
for (unsigned I = 0; I != E; ++I) {
if (I)
Enc += ',';
Enc += FE[I].str();
}
}
Enc += '}';
TSC.addIfComplete(ID, Enc.substr(Start), false);
return true;
}
/// Appends type's qualifier to Enc.
/// This is done prior to appending the type's encoding.
static void appendQualifier(SmallStringEnc &Enc, QualType QT) {
// Qualifiers are emitted in alphabetical order.
static const char *const Table[]={"","c:","r:","cr:","v:","cv:","rv:","crv:"};
int Lookup = 0;
if (QT.isConstQualified())
Lookup += 1<<0;
if (QT.isRestrictQualified())
Lookup += 1<<1;
if (QT.isVolatileQualified())
Lookup += 1<<2;
Enc += Table[Lookup];
}
/// Appends built-in types to Enc.
static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) {
const char *EncType;
switch (BT->getKind()) {
case BuiltinType::Void:
EncType = "0";
break;
case BuiltinType::Bool:
EncType = "b";
break;
case BuiltinType::Char_U:
EncType = "uc";
break;
case BuiltinType::UChar:
EncType = "uc";
break;
case BuiltinType::SChar:
EncType = "sc";
break;
case BuiltinType::UShort:
EncType = "us";
break;
case BuiltinType::Short:
EncType = "ss";
break;
case BuiltinType::UInt:
EncType = "ui";
break;
case BuiltinType::Int:
EncType = "si";
break;
case BuiltinType::ULong:
EncType = "ul";
break;
case BuiltinType::Long:
EncType = "sl";
break;
case BuiltinType::ULongLong:
EncType = "ull";
break;
case BuiltinType::LongLong:
EncType = "sll";
break;
case BuiltinType::Float:
EncType = "ft";
break;
case BuiltinType::Double:
EncType = "d";
break;
case BuiltinType::LongDouble:
EncType = "ld";
break;
default:
return false;
}
Enc += EncType;
return true;
}
/// Appends a pointer encoding to Enc before calling appendType for the pointee.
static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT,
const CodeGen::CodeGenModule &CGM,
TypeStringCache &TSC) {
Enc += "p(";
if (!appendType(Enc, PT->getPointeeType(), CGM, TSC))
return false;
Enc += ')';
return true;
}
/// Appends array encoding to Enc before calling appendType for the element.
static bool appendArrayType(SmallStringEnc &Enc, QualType QT,
const ArrayType *AT,
const CodeGen::CodeGenModule &CGM,
TypeStringCache &TSC, StringRef NoSizeEnc) {
if (AT->getSizeModifier() != ArrayType::Normal)
return false;
Enc += "a(";
if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
CAT->getSize().toStringUnsigned(Enc);
else
Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "".
Enc += ':';
// The Qualifiers should be attached to the type rather than the array.
appendQualifier(Enc, QT);
if (!appendType(Enc, AT->getElementType(), CGM, TSC))
return false;
Enc += ')';
return true;
}
/// Appends a function encoding to Enc, calling appendType for the return type
/// and the arguments.
static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT,
const CodeGen::CodeGenModule &CGM,
TypeStringCache &TSC) {
Enc += "f{";
if (!appendType(Enc, FT->getReturnType(), CGM, TSC))
return false;
Enc += "}(";
if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) {
// N.B. we are only interested in the adjusted param types.
auto I = FPT->param_type_begin();
auto E = FPT->param_type_end();
if (I != E) {
do {
if (!appendType(Enc, *I, CGM, TSC))
return false;
++I;
if (I != E)
Enc += ',';
} while (I != E);
if (FPT->isVariadic())
Enc += ",va";
} else {
if (FPT->isVariadic())
Enc += "va";
else
Enc += '0';
}
}
Enc += ')';
return true;
}
/// Handles the type's qualifier before dispatching a call to handle specific
/// type encodings.
static bool appendType(SmallStringEnc &Enc, QualType QType,
const CodeGen::CodeGenModule &CGM,
TypeStringCache &TSC) {
QualType QT = QType.getCanonicalType();
if (const ArrayType *AT = QT->getAsArrayTypeUnsafe())
// The Qualifiers should be attached to the type rather than the array.
// Thus we don't call appendQualifier() here.
return appendArrayType(Enc, QT, AT, CGM, TSC, "");
appendQualifier(Enc, QT);
if (const BuiltinType *BT = QT->getAs<BuiltinType>())
return appendBuiltinType(Enc, BT);
if (const PointerType *PT = QT->getAs<PointerType>())
return appendPointerType(Enc, PT, CGM, TSC);
if (const EnumType *ET = QT->getAs<EnumType>())
return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier());
if (const RecordType *RT = QT->getAsStructureType())
return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
if (const RecordType *RT = QT->getAsUnionType())
return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
if (const FunctionType *FT = QT->getAs<FunctionType>())
return appendFunctionType(Enc, FT, CGM, TSC);
return false;
}
static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
const CodeGen::CodeGenModule &CGM,
TypeStringCache &TSC) {
if (!D)
return false;
if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
if (FD->getLanguageLinkage() != CLanguageLinkage)
return false;
return appendType(Enc, FD->getType(), CGM, TSC);
}
if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
if (VD->getLanguageLinkage() != CLanguageLinkage)
return false;
QualType QT = VD->getType().getCanonicalType();
if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) {
// Global ArrayTypes are given a size of '*' if the size is unknown.
// The Qualifiers should be attached to the type rather than the array.
// Thus we don't call appendQualifier() here.
return appendArrayType(Enc, QT, AT, CGM, TSC, "*");
}
return appendType(Enc, QT, CGM, TSC);
}
return false;
}
//===----------------------------------------------------------------------===//
// RISCV ABI Implementation
//===----------------------------------------------------------------------===//
namespace {
class RISCVABIInfo : public DefaultABIInfo {
private:
// Size of the integer ('x') registers in bits.
unsigned XLen;
// Size of the floating point ('f') registers in bits. Note that the target
// ISA might have a wider FLen than the selected ABI (e.g. an RV32IF target
// with soft float ABI has FLen==0).
unsigned FLen;
static const int NumArgGPRs = 8;
static const int NumArgFPRs = 8;
bool detectFPCCEligibleStructHelper(QualType Ty, CharUnits CurOff,
llvm::Type *&Field1Ty,
CharUnits &Field1Off,
llvm::Type *&Field2Ty,
CharUnits &Field2Off) const;
public:
RISCVABIInfo(CodeGen::CodeGenTypes &CGT, unsigned XLen, unsigned FLen)
: DefaultABIInfo(CGT), XLen(XLen), FLen(FLen) {}
// DefaultABIInfo's classifyReturnType and classifyArgumentType are
// non-virtual, but computeInfo is virtual, so we overload it.
void computeInfo(CGFunctionInfo &FI) const override;
ABIArgInfo classifyArgumentType(QualType Ty, bool IsFixed, int &ArgGPRsLeft,
int &ArgFPRsLeft) const;
ABIArgInfo classifyReturnType(QualType RetTy) const;
Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
QualType Ty) const override;
ABIArgInfo extendType(QualType Ty) const;
bool detectFPCCEligibleStruct(QualType Ty, llvm::Type *&Field1Ty,
CharUnits &Field1Off, llvm::Type *&Field2Ty,
CharUnits &Field2Off, int &NeededArgGPRs,
int &NeededArgFPRs) const;
ABIArgInfo coerceAndExpandFPCCEligibleStruct(llvm::Type *Field1Ty,
CharUnits Field1Off,
llvm::Type *Field2Ty,
CharUnits Field2Off) const;
};
} // end anonymous namespace
void RISCVABIInfo::computeInfo(CGFunctionInfo &FI) const {
QualType RetTy = FI.getReturnType();
if (!getCXXABI().classifyReturnType(FI))
FI.getReturnInfo() = classifyReturnType(RetTy);
// IsRetIndirect is true if classifyArgumentType indicated the value should
// be passed indirect, or if the type size is a scalar greater than 2*XLen
// and not a complex type with elements <= FLen. e.g. fp128 is passed direct
// in LLVM IR, relying on the backend lowering code to rewrite the argument
// list and pass indirectly on RV32.
bool IsRetIndirect = FI.getReturnInfo().getKind() == ABIArgInfo::Indirect;
if (!IsRetIndirect && RetTy->isScalarType() &&
getContext().getTypeSize(RetTy) > (2 * XLen)) {
if (RetTy->isComplexType() && FLen) {
QualType EltTy = RetTy->castAs<ComplexType>()->getElementType();
IsRetIndirect = getContext().getTypeSize(EltTy) > FLen;
} else {
// This is a normal scalar > 2*XLen, such as fp128 on RV32.
IsRetIndirect = true;
}
}
// We must track the number of GPRs used in order to conform to the RISC-V
// ABI, as integer scalars passed in registers should have signext/zeroext
// when promoted, but are anyext if passed on the stack. As GPR usage is
// different for variadic arguments, we must also track whether we are
// examining a vararg or not.
int ArgGPRsLeft = IsRetIndirect ? NumArgGPRs - 1 : NumArgGPRs;
int ArgFPRsLeft = FLen ? NumArgFPRs : 0;
int NumFixedArgs = FI.getNumRequiredArgs();
int ArgNum = 0;
for (auto &ArgInfo : FI.arguments()) {
bool IsFixed = ArgNum < NumFixedArgs;
ArgInfo.info =
classifyArgumentType(ArgInfo.type, IsFixed, ArgGPRsLeft, ArgFPRsLeft);
ArgNum++;
}
}
// Returns true if the struct is a potential candidate for the floating point
// calling convention. If this function returns true, the caller is
// responsible for checking that if there is only a single field then that
// field is a float.
bool RISCVABIInfo::detectFPCCEligibleStructHelper(QualType Ty, CharUnits CurOff,
llvm::Type *&Field1Ty,
CharUnits &Field1Off,
llvm::Type *&Field2Ty,
CharUnits &Field2Off) const {
bool IsInt = Ty->isIntegralOrEnumerationType();
bool IsFloat = Ty->isRealFloatingType();
if (IsInt || IsFloat) {
uint64_t Size = getContext().getTypeSize(Ty);
if (IsInt && Size > XLen)
return false;
// Can't be eligible if larger than the FP registers. Half precision isn't
// currently supported on RISC-V and the ABI hasn't been confirmed, so
// default to the integer ABI in that case.
if (IsFloat && (Size > FLen || Size < 32))
return false;
// Can't be eligible if an integer type was already found (int+int pairs
// are not eligible).
if (IsInt && Field1Ty && Field1Ty->isIntegerTy())
return false;
if (!Field1Ty) {
Field1Ty = CGT.ConvertType(Ty);
Field1Off = CurOff;
return true;
}
if (!Field2Ty) {
Field2Ty = CGT.ConvertType(Ty);
Field2Off = CurOff;
return true;
}
return false;
}
if (auto CTy = Ty->getAs<ComplexType>()) {
if (Field1Ty)
return false;
QualType EltTy = CTy->getElementType();
if (getContext().getTypeSize(EltTy) > FLen)
return false;
Field1Ty = CGT.ConvertType(EltTy);
Field1Off = CurOff;
Field2Ty = Field1Ty;
Field2Off = Field1Off + getContext().getTypeSizeInChars(EltTy);
return true;
}
if (const ConstantArrayType *ATy = getContext().getAsConstantArrayType(Ty)) {
uint64_t ArraySize = ATy->getSize().getZExtValue();
QualType EltTy = ATy->getElementType();
CharUnits EltSize = getContext().getTypeSizeInChars(EltTy);
for (uint64_t i = 0; i < ArraySize; ++i) {
bool Ret = detectFPCCEligibleStructHelper(EltTy, CurOff, Field1Ty,
Field1Off, Field2Ty, Field2Off);
if (!Ret)
return false;
CurOff += EltSize;
}
return true;
}
if (const auto *RTy = Ty->getAs<RecordType>()) {
// Structures with either a non-trivial destructor or a non-trivial
// copy constructor are not eligible for the FP calling convention.
if (getRecordArgABI(Ty, CGT.getCXXABI()))
return false;
if (isEmptyRecord(getContext(), Ty, true))
return true;
const RecordDecl *RD = RTy->getDecl();
// Unions aren't eligible unless they're empty (which is caught above).
if (RD->isUnion())
return false;
int ZeroWidthBitFieldCount = 0;
for (const FieldDecl *FD : RD->fields()) {
const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
uint64_t FieldOffInBits = Layout.getFieldOffset(FD->getFieldIndex());
QualType QTy = FD->getType();
if (FD->isBitField()) {
unsigned BitWidth = FD->getBitWidthValue(getContext());
// Allow a bitfield with a type greater than XLen as long as the
// bitwidth is XLen or less.
if (getContext().getTypeSize(QTy) > XLen && BitWidth <= XLen)
QTy = getContext().getIntTypeForBitwidth(XLen, false);
if (BitWidth == 0) {
ZeroWidthBitFieldCount++;
continue;
}
}
bool Ret = detectFPCCEligibleStructHelper(
QTy, CurOff + getContext().toCharUnitsFromBits(FieldOffInBits),
Field1Ty, Field1Off, Field2Ty, Field2Off);
if (!Ret)
return false;
// As a quirk of the ABI, zero-width bitfields aren't ignored for fp+fp
// or int+fp structs, but are ignored for a struct with an fp field and
// any number of zero-width bitfields.
if (Field2Ty && ZeroWidthBitFieldCount > 0)
return false;
}
return Field1Ty != nullptr;
}
return false;
}
// Determine if a struct is eligible for passing according to the floating
// point calling convention (i.e., when flattened it contains a single fp
// value, fp+fp, or int+fp of appropriate size). If so, NeededArgFPRs and
// NeededArgGPRs are incremented appropriately.
bool RISCVABIInfo::detectFPCCEligibleStruct(QualType Ty, llvm::Type *&Field1Ty,
CharUnits &Field1Off,
llvm::Type *&Field2Ty,
CharUnits &Field2Off,
int &NeededArgGPRs,
int &NeededArgFPRs) const {
Field1Ty = nullptr;
Field2Ty = nullptr;
NeededArgGPRs = 0;
NeededArgFPRs = 0;
bool IsCandidate = detectFPCCEligibleStructHelper(
Ty, CharUnits::Zero(), Field1Ty, Field1Off, Field2Ty, Field2Off);
// Not really a candidate if we have a single int but no float.
if (Field1Ty && !Field2Ty && !Field1Ty->isFloatingPointTy())
return false;
if (!IsCandidate)
return false;
if (Field1Ty && Field1Ty->isFloatingPointTy())
NeededArgFPRs++;
else if (Field1Ty)
NeededArgGPRs++;
if (Field2Ty && Field2Ty->isFloatingPointTy())
NeededArgFPRs++;
else if (Field2Ty)
NeededArgGPRs++;
return true;
}
// Call getCoerceAndExpand for the two-element flattened struct described by
// Field1Ty, Field1Off, Field2Ty, Field2Off. This method will create an
// appropriate coerceToType and unpaddedCoerceToType.
ABIArgInfo RISCVABIInfo::coerceAndExpandFPCCEligibleStruct(
llvm::Type *Field1Ty, CharUnits Field1Off, llvm::Type *Field2Ty,
CharUnits Field2Off) const {
SmallVector<llvm::Type *, 3> CoerceElts;
SmallVector<llvm::Type *, 2> UnpaddedCoerceElts;
if (!Field1Off.isZero())
CoerceElts.push_back(llvm::ArrayType::get(
llvm::Type::getInt8Ty(getVMContext()), Field1Off.getQuantity()));
CoerceElts.push_back(Field1Ty);
UnpaddedCoerceElts.push_back(Field1Ty);
if (!Field2Ty) {
return ABIArgInfo::getCoerceAndExpand(
llvm::StructType::get(getVMContext(), CoerceElts, !Field1Off.isZero()),
UnpaddedCoerceElts[0]);
}
CharUnits Field2Align =
CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(Field2Ty));
CharUnits Field1End = Field1Off +
CharUnits::fromQuantity(getDataLayout().getTypeStoreSize(Field1Ty));
CharUnits Field2OffNoPadNoPack = Field1End.alignTo(Field2Align);
CharUnits Padding = CharUnits::Zero();
if (Field2Off > Field2OffNoPadNoPack)
Padding = Field2Off - Field2OffNoPadNoPack;
else if (Field2Off != Field2Align && Field2Off > Field1End)
Padding = Field2Off - Field1End;
bool IsPacked = !Field2Off.isMultipleOf(Field2Align);
if (!Padding.isZero())
CoerceElts.push_back(llvm::ArrayType::get(
llvm::Type::getInt8Ty(getVMContext()), Padding.getQuantity()));
CoerceElts.push_back(Field2Ty);
UnpaddedCoerceElts.push_back(Field2Ty);
auto CoerceToType =
llvm::StructType::get(getVMContext(), CoerceElts, IsPacked);
auto UnpaddedCoerceToType =
llvm::StructType::get(getVMContext(), UnpaddedCoerceElts, IsPacked);
return ABIArgInfo::getCoerceAndExpand(CoerceToType, UnpaddedCoerceToType);
}
ABIArgInfo RISCVABIInfo::classifyArgumentType(QualType Ty, bool IsFixed,
int &ArgGPRsLeft,
int &ArgFPRsLeft) const {
assert(ArgGPRsLeft <= NumArgGPRs && "Arg GPR tracking underflow");
Ty = useFirstFieldIfTransparentUnion(Ty);
// Structures with either a non-trivial destructor or a non-trivial
// copy constructor are always passed indirectly.
if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
if (ArgGPRsLeft)
ArgGPRsLeft -= 1;
return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
CGCXXABI::RAA_DirectInMemory);
}
// Ignore empty structs/unions.
if (isEmptyRecord(getContext(), Ty, true))
return ABIArgInfo::getIgnore();
uint64_t Size = getContext().getTypeSize(Ty);
// Pass floating point values via FPRs if possible.
if (IsFixed && Ty->isFloatingType() && !Ty->isComplexType() &&
FLen >= Size && ArgFPRsLeft) {
ArgFPRsLeft--;
return ABIArgInfo::getDirect();
}
// Complex types for the hard float ABI must be passed direct rather than
// using CoerceAndExpand.
if (IsFixed && Ty->isComplexType() && FLen && ArgFPRsLeft >= 2) {
QualType EltTy = Ty->castAs<ComplexType>()->getElementType();
if (getContext().getTypeSize(EltTy) <= FLen) {
ArgFPRsLeft -= 2;
return ABIArgInfo::getDirect();
}
}
if (IsFixed && FLen && Ty->isStructureOrClassType()) {
llvm::Type *Field1Ty = nullptr;
llvm::Type *Field2Ty = nullptr;
CharUnits Field1Off = CharUnits::Zero();
CharUnits Field2Off = CharUnits::Zero();
int NeededArgGPRs = 0;
int NeededArgFPRs = 0;
bool IsCandidate =
detectFPCCEligibleStruct(Ty, Field1Ty, Field1Off, Field2Ty, Field2Off,
NeededArgGPRs, NeededArgFPRs);
if (IsCandidate && NeededArgGPRs <= ArgGPRsLeft &&
NeededArgFPRs <= ArgFPRsLeft) {
ArgGPRsLeft -= NeededArgGPRs;
ArgFPRsLeft -= NeededArgFPRs;
return coerceAndExpandFPCCEligibleStruct(Field1Ty, Field1Off, Field2Ty,
Field2Off);
}
}
uint64_t NeededAlign = getContext().getTypeAlign(Ty);
bool MustUseStack = false;
// Determine the number of GPRs needed to pass the current argument
// according to the ABI. 2*XLen-aligned varargs are passed in "aligned"
// register pairs, so may consume 3 registers.
int NeededArgGPRs = 1;
if (!IsFixed && NeededAlign == 2 * XLen)
NeededArgGPRs = 2 + (ArgGPRsLeft % 2);
else if (Size > XLen && Size <= 2 * XLen)
NeededArgGPRs = 2;
if (NeededArgGPRs > ArgGPRsLeft) {
MustUseStack = true;
NeededArgGPRs = ArgGPRsLeft;
}
ArgGPRsLeft -= NeededArgGPRs;
if (!isAggregateTypeForABI(Ty) && !Ty->isVectorType()) {
// Treat an enum type as its underlying type.
if (const EnumType *EnumTy = Ty->getAs<EnumType>())
Ty = EnumTy->getDecl()->getIntegerType();
// All integral types are promoted to XLen width, unless passed on the
// stack.
if (Size < XLen && Ty->isIntegralOrEnumerationType() && !MustUseStack) {
return extendType(Ty);
}
if (const auto *EIT = Ty->getAs<ExtIntType>()) {
if (EIT->getNumBits() < XLen && !MustUseStack)
return extendType(Ty);
if (EIT->getNumBits() > 128 ||
(!getContext().getTargetInfo().hasInt128Type() &&
EIT->getNumBits() > 64))
return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
}
return ABIArgInfo::getDirect();
}
// Aggregates which are <= 2*XLen will be passed in registers if possible,
// so coerce to integers.
if (Size <= 2 * XLen) {
unsigned Alignment = getContext().getTypeAlign(Ty);
// Use a single XLen int if possible, 2*XLen if 2*XLen alignment is
// required, and a 2-element XLen array if only XLen alignment is required.
if (Size <= XLen) {
return ABIArgInfo::getDirect(
llvm::IntegerType::get(getVMContext(), XLen));
} else if (Alignment == 2 * XLen) {
return ABIArgInfo::getDirect(
llvm::IntegerType::get(getVMContext(), 2 * XLen));
} else {
return ABIArgInfo::getDirect(llvm::ArrayType::get(
llvm::IntegerType::get(getVMContext(), XLen), 2));
}
}
return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
}
ABIArgInfo RISCVABIInfo::classifyReturnType(QualType RetTy) const {
if (RetTy->isVoidType())
return ABIArgInfo::getIgnore();
int ArgGPRsLeft = 2;
int ArgFPRsLeft = FLen ? 2 : 0;
// The rules for return and argument types are the same, so defer to
// classifyArgumentType.
return classifyArgumentType(RetTy, /*IsFixed=*/true, ArgGPRsLeft,
ArgFPRsLeft);
}
Address RISCVABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
QualType Ty) const {
CharUnits SlotSize = CharUnits::fromQuantity(XLen / 8);
// Empty records are ignored for parameter passing purposes.
if (isEmptyRecord(getContext(), Ty, true)) {
Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize);
Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
return Addr;
}
auto TInfo = getContext().getTypeInfoInChars(Ty);
// Arguments bigger than 2*Xlen bytes are passed indirectly.
bool IsIndirect = TInfo.Width > 2 * SlotSize;
return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TInfo,
SlotSize, /*AllowHigherAlign=*/true);
}
ABIArgInfo RISCVABIInfo::extendType(QualType Ty) const {
int TySize = getContext().getTypeSize(Ty);
// RV64 ABI requires unsigned 32 bit integers to be sign extended.
if (XLen == 64 && Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
return ABIArgInfo::getSignExtend(Ty);
return ABIArgInfo::getExtend(Ty);
}
namespace {
class RISCVTargetCodeGenInfo : public TargetCodeGenInfo {
public:
RISCVTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, unsigned XLen,
unsigned FLen)
: TargetCodeGenInfo(std::make_unique<RISCVABIInfo>(CGT, XLen, FLen)) {}
void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
CodeGen::CodeGenModule &CGM) const override {
const auto *FD = dyn_cast_or_null<FunctionDecl>(D);
if (!FD) return;
const auto *Attr = FD->getAttr<RISCVInterruptAttr>();
if (!Attr)
return;
const char *Kind;
switch (Attr->getInterrupt()) {
case RISCVInterruptAttr::user: Kind = "user"; break;
case RISCVInterruptAttr::supervisor: Kind = "supervisor"; break;
case RISCVInterruptAttr::machine: Kind = "machine"; break;
}
auto *Fn = cast<llvm::Function>(GV);
Fn->addFnAttr("interrupt", Kind);
}
};
} // namespace
//===----------------------------------------------------------------------===//
// VE ABI Implementation.
//
namespace {
class VEABIInfo : public DefaultABIInfo {
public:
VEABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
private:
ABIArgInfo classifyReturnType(QualType RetTy) const;
ABIArgInfo classifyArgumentType(QualType RetTy) const;
void computeInfo(CGFunctionInfo &FI) const override;
};
} // end anonymous namespace
ABIArgInfo VEABIInfo::classifyReturnType(QualType Ty) const {
if (Ty->isAnyComplexType())
return ABIArgInfo::getDirect();
uint64_t Size = getContext().getTypeSize(Ty);
if (Size < 64 && Ty->isIntegerType())
return ABIArgInfo::getExtend(Ty);
return DefaultABIInfo::classifyReturnType(Ty);
}
ABIArgInfo VEABIInfo::classifyArgumentType(QualType Ty) const {
if (Ty->isAnyComplexType())
return ABIArgInfo::getDirect();
uint64_t Size = getContext().getTypeSize(Ty);
if (Size < 64 && Ty->isIntegerType())
return ABIArgInfo::getExtend(Ty);
return DefaultABIInfo::classifyArgumentType(Ty);
}
void VEABIInfo::computeInfo(CGFunctionInfo &FI) const {
FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
for (auto &Arg : FI.arguments())
Arg.info = classifyArgumentType(Arg.type);
}
namespace {
class VETargetCodeGenInfo : public TargetCodeGenInfo {
public:
VETargetCodeGenInfo(CodeGenTypes &CGT)
: TargetCodeGenInfo(std::make_unique<VEABIInfo>(CGT)) {}
// VE ABI requires the arguments of variadic and prototype-less functions
// are passed in both registers and memory.
bool isNoProtoCallVariadic(const CallArgList &args,
const FunctionNoProtoType *fnType) const override {
return true;
}
};
} // end anonymous namespace
//===----------------------------------------------------------------------===//
// Driver code
//===----------------------------------------------------------------------===//
bool CodeGenModule::supportsCOMDAT() const {
return getTriple().supportsCOMDAT();
}
const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
if (TheTargetCodeGenInfo)
return *TheTargetCodeGenInfo;
// Helper to set the unique_ptr while still keeping the return value.
auto SetCGInfo = [&](TargetCodeGenInfo *P) -> const TargetCodeGenInfo & {
this->TheTargetCodeGenInfo.reset(P);
return *P;
};
const llvm::Triple &Triple = getTarget().getTriple();
switch (Triple.getArch()) {
default:
return SetCGInfo(new DefaultTargetCodeGenInfo(Types));
case llvm::Triple::le32:
return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
case llvm::Triple::m68k:
return SetCGInfo(new M68kTargetCodeGenInfo(Types));
case llvm::Triple::mips:
case llvm::Triple::mipsel:
if (Triple.getOS() == llvm::Triple::NaCl)
return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
return SetCGInfo(new MIPSTargetCodeGenInfo(Types, true));
case llvm::Triple::mips64:
case llvm::Triple::mips64el:
return SetCGInfo(new MIPSTargetCodeGenInfo(Types, false));
case llvm::Triple::avr:
return SetCGInfo(new AVRTargetCodeGenInfo(Types));
case llvm::Triple::aarch64:
case llvm::Triple::aarch64_32:
case llvm::Triple::aarch64_be: {
AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS;
if (getTarget().getABI() == "darwinpcs")
Kind = AArch64ABIInfo::DarwinPCS;
else if (Triple.isOSWindows())
return SetCGInfo(
new WindowsAArch64TargetCodeGenInfo(Types, AArch64ABIInfo::Win64));
return SetCGInfo(new AArch64TargetCodeGenInfo(Types, Kind));
}
case llvm::Triple::wasm32:
case llvm::Triple::wasm64: {
WebAssemblyABIInfo::ABIKind Kind = WebAssemblyABIInfo::MVP;
if (getTarget().getABI() == "experimental-mv")
Kind = WebAssemblyABIInfo::ExperimentalMV;
return SetCGInfo(new WebAssemblyTargetCodeGenInfo(Types, Kind));
}
case llvm::Triple::arm:
case llvm::Triple::armeb:
case llvm::Triple::thumb:
case llvm::Triple::thumbeb: {
if (Triple.getOS() == llvm::Triple::Win32) {
return SetCGInfo(
new WindowsARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS_VFP));
}
ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
StringRef ABIStr = getTarget().getABI();
if (ABIStr == "apcs-gnu")
Kind = ARMABIInfo::APCS;
else if (ABIStr == "aapcs16")
Kind = ARMABIInfo::AAPCS16_VFP;
else if (CodeGenOpts.FloatABI == "hard" ||
(CodeGenOpts.FloatABI != "soft" &&
(Triple.getEnvironment() == llvm::Triple::GNUEABIHF ||
Triple.getEnvironment() == llvm::Triple::MuslEABIHF ||
Triple.getEnvironment() == llvm::Triple::EABIHF)))
Kind = ARMABIInfo::AAPCS_VFP;
return SetCGInfo(new ARMTargetCodeGenInfo(Types, Kind));
}
case llvm::Triple::ppc: {
if (Triple.isOSAIX())
return SetCGInfo(new AIXTargetCodeGenInfo(Types, /*Is64Bit*/ false));
bool IsSoftFloat =
CodeGenOpts.FloatABI == "soft" || getTarget().hasFeature("spe");
bool RetSmallStructInRegABI =
PPC32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
return SetCGInfo(
new PPC32TargetCodeGenInfo(Types, IsSoftFloat, RetSmallStructInRegABI));
}
case llvm::Triple::ppcle: {
bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
bool RetSmallStructInRegABI =
PPC32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
return SetCGInfo(
new PPC32TargetCodeGenInfo(Types, IsSoftFloat, RetSmallStructInRegABI));
}
case llvm::Triple::ppc64:
if (Triple.isOSAIX())
return SetCGInfo(new AIXTargetCodeGenInfo(Types, /*Is64Bit*/ true));
if (Triple.isOSBinFormatELF()) {
PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1;
if (getTarget().getABI() == "elfv2")
Kind = PPC64_SVR4_ABIInfo::ELFv2;
bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
return SetCGInfo(
new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, IsSoftFloat));
}
return SetCGInfo(new PPC64TargetCodeGenInfo(Types));
case llvm::Triple::ppc64le: {
assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2;
if (getTarget().getABI() == "elfv1")
Kind = PPC64_SVR4_ABIInfo::ELFv1;
bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
return SetCGInfo(
new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, IsSoftFloat));
}
case llvm::Triple::nvptx:
case llvm::Triple::nvptx64:
return SetCGInfo(new NVPTXTargetCodeGenInfo(Types));
case llvm::Triple::msp430:
return SetCGInfo(new MSP430TargetCodeGenInfo(Types));
case llvm::Triple::riscv32:
case llvm::Triple::riscv64: {
StringRef ABIStr = getTarget().getABI();
unsigned XLen = getTarget().getPointerWidth(0);
unsigned ABIFLen = 0;
if (ABIStr.endswith("f"))
ABIFLen = 32;
else if (ABIStr.endswith("d"))
ABIFLen = 64;
return SetCGInfo(new RISCVTargetCodeGenInfo(Types, XLen, ABIFLen));
}
case llvm::Triple::systemz: {
bool SoftFloat = CodeGenOpts.FloatABI == "soft";
bool HasVector = !SoftFloat && getTarget().getABI() == "vector";
return SetCGInfo(new SystemZTargetCodeGenInfo(Types, HasVector, SoftFloat));
}
case llvm::Triple::tce:
case llvm::Triple::tcele:
return SetCGInfo(new TCETargetCodeGenInfo(Types));
case llvm::Triple::x86: {
bool IsDarwinVectorABI = Triple.isOSDarwin();
bool RetSmallStructInRegABI =
X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
if (Triple.getOS() == llvm::Triple::Win32) {
return SetCGInfo(new WinX86_32TargetCodeGenInfo(
Types, IsDarwinVectorABI, RetSmallStructInRegABI,
IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters));
} else {
return SetCGInfo(new X86_32TargetCodeGenInfo(
Types, IsDarwinVectorABI, RetSmallStructInRegABI,
IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters,
CodeGenOpts.FloatABI == "soft"));
}
}
case llvm::Triple::x86_64: {
StringRef ABI = getTarget().getABI();
X86AVXABILevel AVXLevel =
(ABI == "avx512"
? X86AVXABILevel::AVX512
: ABI == "avx" ? X86AVXABILevel::AVX : X86AVXABILevel::None);
switch (Triple.getOS()) {
case llvm::Triple::Win32:
return SetCGInfo(new WinX86_64TargetCodeGenInfo(Types, AVXLevel));
default:
return SetCGInfo(new X86_64TargetCodeGenInfo(Types, AVXLevel));
}
}
case llvm::Triple::hexagon:
return SetCGInfo(new HexagonTargetCodeGenInfo(Types));
case llvm::Triple::lanai:
return SetCGInfo(new LanaiTargetCodeGenInfo(Types));
case llvm::Triple::r600:
return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
case llvm::Triple::amdgcn:
return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
case llvm::Triple::sparc:
return SetCGInfo(new SparcV8TargetCodeGenInfo(Types));
case llvm::Triple::sparcv9:
return SetCGInfo(new SparcV9TargetCodeGenInfo(Types));
case llvm::Triple::xcore:
return SetCGInfo(new XCoreTargetCodeGenInfo(Types));
case llvm::Triple::arc:
return SetCGInfo(new ARCTargetCodeGenInfo(Types));
case llvm::Triple::spir:
case llvm::Triple::spir64:
return SetCGInfo(new SPIRTargetCodeGenInfo(Types));
case llvm::Triple::ve:
return SetCGInfo(new VETargetCodeGenInfo(Types));
}
}
/// Create an OpenCL kernel for an enqueued block.
///
/// The kernel has the same function type as the block invoke function. Its
/// name is the name of the block invoke function postfixed with "_kernel".
/// It simply calls the block invoke function then returns.
llvm::Function *
TargetCodeGenInfo::createEnqueuedBlockKernel(CodeGenFunction &CGF,
llvm::Function *Invoke,
llvm::Value *BlockLiteral) const {
auto *InvokeFT = Invoke->getFunctionType();
llvm::SmallVector<llvm::Type *, 2> ArgTys;
for (auto &P : InvokeFT->params())
ArgTys.push_back(P);
auto &C = CGF.getLLVMContext();
std::string Name = Invoke->getName().str() + "_kernel";
auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C), ArgTys, false);
auto *F = llvm::Function::Create(FT, llvm::GlobalValue::InternalLinkage, Name,
&CGF.CGM.getModule());
auto IP = CGF.Builder.saveIP();
auto *BB = llvm::BasicBlock::Create(C, "entry", F);
auto &Builder = CGF.Builder;
Builder.SetInsertPoint(BB);
llvm::SmallVector<llvm::Value *, 2> Args;
for (auto &A : F->args())
Args.push_back(&A);
llvm::CallInst *call = Builder.CreateCall(Invoke, Args);
call->setCallingConv(Invoke->getCallingConv());
Builder.CreateRetVoid();
Builder.restoreIP(IP);
return F;
}
/// Create an OpenCL kernel for an enqueued block.
///
/// The type of the first argument (the block literal) is the struct type
/// of the block literal instead of a pointer type. The first argument
/// (block literal) is passed directly by value to the kernel. The kernel
/// allocates the same type of struct on stack and stores the block literal
/// to it and passes its pointer to the block invoke function. The kernel
/// has "enqueued-block" function attribute and kernel argument metadata.
llvm::Function *AMDGPUTargetCodeGenInfo::createEnqueuedBlockKernel(
CodeGenFunction &CGF, llvm::Function *Invoke,
llvm::Value *BlockLiteral) const {
auto &Builder = CGF.Builder;
auto &C = CGF.getLLVMContext();
auto *BlockTy = BlockLiteral->getType()->getPointerElementType();
auto *InvokeFT = Invoke->getFunctionType();
llvm::SmallVector<llvm::Type *, 2> ArgTys;
llvm::SmallVector<llvm::Metadata *, 8> AddressQuals;
llvm::SmallVector<llvm::Metadata *, 8> AccessQuals;
llvm::SmallVector<llvm::Metadata *, 8> ArgTypeNames;
llvm::SmallVector<llvm::Metadata *, 8> ArgBaseTypeNames;
llvm::SmallVector<llvm::Metadata *, 8> ArgTypeQuals;
llvm::SmallVector<llvm::Metadata *, 8> ArgNames;
ArgTys.push_back(BlockTy);
ArgTypeNames.push_back(llvm::MDString::get(C, "__block_literal"));
AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(0)));
ArgBaseTypeNames.push_back(llvm::MDString::get(C, "__block_literal"));
ArgTypeQuals.push_back(llvm::MDString::get(C, ""));
AccessQuals.push_back(llvm::MDString::get(C, "none"));
ArgNames.push_back(llvm::MDString::get(C, "block_literal"));
for (unsigned I = 1, E = InvokeFT->getNumParams(); I < E; ++I) {
ArgTys.push_back(InvokeFT->getParamType(I));
ArgTypeNames.push_back(llvm::MDString::get(C, "void*"));
AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(3)));
AccessQuals.push_back(llvm::MDString::get(C, "none"));
ArgBaseTypeNames.push_back(llvm::MDString::get(C, "void*"));
ArgTypeQuals.push_back(llvm::MDString::get(C, ""));
ArgNames.push_back(
llvm::MDString::get(C, (Twine("local_arg") + Twine(I)).str()));
}
std::string Name = Invoke->getName().str() + "_kernel";
auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C), ArgTys, false);
auto *F = llvm::Function::Create(FT, llvm::GlobalValue::InternalLinkage, Name,
&CGF.CGM.getModule());
F->addFnAttr("enqueued-block");
auto IP = CGF.Builder.saveIP();
auto *BB = llvm::BasicBlock::Create(C, "entry", F);
Builder.SetInsertPoint(BB);
const auto BlockAlign = CGF.CGM.getDataLayout().getPrefTypeAlign(BlockTy);
auto *BlockPtr = Builder.CreateAlloca(BlockTy, nullptr);
BlockPtr->setAlignment(BlockAlign);
Builder.CreateAlignedStore(F->arg_begin(), BlockPtr, BlockAlign);
auto *Cast = Builder.CreatePointerCast(BlockPtr, InvokeFT->getParamType(0));
llvm::SmallVector<llvm::Value *, 2> Args;
Args.push_back(Cast);
for (auto I = F->arg_begin() + 1, E = F->arg_end(); I != E; ++I)
Args.push_back(I);
llvm::CallInst *call = Builder.CreateCall(Invoke, Args);
call->setCallingConv(Invoke->getCallingConv());
Builder.CreateRetVoid();
Builder.restoreIP(IP);
F->setMetadata("kernel_arg_addr_space", llvm::MDNode::get(C, AddressQuals));
F->setMetadata("kernel_arg_access_qual", llvm::MDNode::get(C, AccessQuals));
F->setMetadata("kernel_arg_type", llvm::MDNode::get(C, ArgTypeNames));
F->setMetadata("kernel_arg_base_type",
llvm::MDNode::get(C, ArgBaseTypeNames));
F->setMetadata("kernel_arg_type_qual", llvm::MDNode::get(C, ArgTypeQuals));
if (CGF.CGM.getCodeGenOpts().EmitOpenCLArgMetadata)
F->setMetadata("kernel_arg_name", llvm::MDNode::get(C, ArgNames));
return F;
}
|
#include "WorkerData.h"
#include "MacroAct.h"
#include "Micro.h"
#include "The.h"
using namespace UAlbertaBot;
WorkerData::WorkerPost::WorkerPost()
: location(MacroLocation::Anywhere)
, position(the.placer.getMacroLocationPos(MacroLocation::Anywhere))
{
}
WorkerData::WorkerPost::WorkerPost(MacroLocation loc)
: location(loc)
, position(the.placer.getMacroLocationPos(loc))
{
}
// -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
WorkerData::WorkerData()
{
for (BWAPI::Unit unit : BWAPI::Broodwar->getAllUnits())
{
if (unit->getType() == BWAPI::UnitTypes::Resource_Mineral_Field)
{
workersOnMineralPatch[unit] = 0;
}
}
}
void WorkerData::workerDestroyed(BWAPI::Unit unit)
{
if (!unit) { return; }
clearPreviousJob(unit);
workers.erase(unit);
}
void WorkerData::addWorker(BWAPI::Unit unit)
{
if (!unit || !unit->exists()) { return; }
workers.insert(unit);
workerJobMap[unit] = Idle;
}
void WorkerData::addWorker(BWAPI::Unit unit, WorkerJob job, BWAPI::Unit jobUnit)
{
if (!unit || !unit->exists() || !jobUnit || !jobUnit->exists()) { return; }
assert(workers.find(unit) == workers.end());
workers.insert(unit);
setWorkerJob(unit, job, jobUnit);
}
void WorkerData::addWorker(BWAPI::Unit unit, WorkerJob job, BWAPI::UnitType jobUnitType)
{
if (!unit || !unit->exists()) { return; }
assert(workers.find(unit) == workers.end());
workers.insert(unit);
setWorkerJob(unit, job);
}
void WorkerData::removeDepot(BWAPI::Unit unit)
{
if (!unit) { return; }
depotWorkerCount.erase(unit);
// re-balance workers in here
for (BWAPI::Unit worker : workers)
{
// if a worker was working at this depot
if (workerDepotMap[worker] == unit)
{
setWorkerJob(worker, Idle, nullptr);
}
}
}
void WorkerData::addToMineralPatch(BWAPI::Unit unit, int num)
{
if (workersOnMineralPatch.find(unit) == workersOnMineralPatch.end())
{
workersOnMineralPatch[unit] = num;
}
else
{
workersOnMineralPatch[unit] += num;
}
}
void WorkerData::setWorkerJob(BWAPI::Unit unit, WorkerJob job, BWAPI::Unit jobUnit)
{
if (!unit) { return; }
//BWAPI::Broodwar->printf("set worker job (%d %c)", unit->getID(), getJobCode(job));
clearPreviousJob(unit);
workerJobMap[unit] = job;
if (job == Minerals)
{
depotWorkerCount[jobUnit] += 1;
workerDepotMap[unit] = jobUnit;
BWAPI::Unit mineralToMine = getMineralToMine(unit);
if (!mineralToMine)
{
// The worker cannot be assigned. Give up and do nothing more.
// BWAPI::Broodwar->printf("no mineral to mine for worker %d", unit->getID());
return;
}
workerMineralAssignment[unit] = mineralToMine;
addToMineralPatch(mineralToMine, 1);
if (mineralToMine->isVisible())
{
// Start mining.
the.micro.RightClick(unit, mineralToMine);
}
else
{
// First we have to move close enough to see it.
the.micro.MoveNear(unit, mineralToMine->getInitialPosition());
}
}
else if (job == Gas)
{
refineryWorkerCount[jobUnit] += 1;
workerRefineryMap[unit] = jobUnit;
// Start harvesting.
the.micro.RightClick(unit, jobUnit);
}
else if (job == Repair)
{
UAB_ASSERT(unit->getType() == BWAPI::UnitTypes::Terran_SCV, "bad job");
workerRepairMap[unit] = jobUnit;
if (!unit->isRepairing())
{
the.micro.Repair(unit, jobUnit);
}
}
}
// Give the worker a Build job.
void WorkerData::setWorkerJob(BWAPI::Unit unit, WorkerJob job)
{
if (!unit) { return; }
UAB_ASSERT(job == Build, "bad job");
// BWAPI::Broodwar->printf("Setting worker job to build");
clearPreviousJob(unit);
workerJobMap[unit] = job;
}
// Give the worker an Unblock job to mine out blocking minerals.
void WorkerData::setWorkerJob(BWAPI::Unit unit, const BWAPI::TilePosition & tile)
{
if (!unit) { return; }
//BWAPI::Broodwar->printf("assigning worker to unblock");
clearPreviousJob(unit);
workerJobMap[unit] = Unblock;
workerUnblockMap[unit] = tile;
}
// Post the worker: Give it a Posted job.
// Calculate the map position from the macro location and remember it.
void WorkerData::setWorkerPost(BWAPI::Unit unit, MacroLocation loc)
{
if (!unit) { return; }
// BWAPI::Broodwar->printf("Posting worker to location");
clearPreviousJob(unit);
workerJobMap[unit] = Posted;
workerPostMap[unit] = WorkerData::WorkerPost(loc);
}
// Give it a Posted or BuildPosted job without updating the map position.
void WorkerData::resetWorkerPost(BWAPI::Unit unit, WorkerJob job)
{
if (!unit) { return; }
UAB_ASSERT(job == Posted || job == PostedBuild, "bad job");
UAB_ASSERT(workerJobMap[unit] == Posted || workerJobMap[unit] == PostedBuild, "bad job");
workerJobMap[unit] = job;
// Do not update the worker post map. It stays the same.
}
void WorkerData::clearPreviousJob(BWAPI::Unit unit)
{
if (!unit) { return; }
WorkerJob previousJob = getWorkerJob(unit);
if (previousJob == Minerals)
{
depotWorkerCount[workerDepotMap[unit]] -= 1;
workerDepotMap.erase(unit);
// remove a worker from this unit's assigned mineral patch
addToMineralPatch(workerMineralAssignment[unit], -1);
// erase the association from the map
workerMineralAssignment.erase(unit);
}
else if (previousJob == Gas)
{
refineryWorkerCount[workerRefineryMap[unit]] -= 1;
workerRefineryMap.erase(unit);
}
else if (previousJob == Repair)
{
workerRepairMap.erase(unit);
}
else if (previousJob == Unblock)
{
workerUnblockMap.erase(unit);
}
else if (previousJob == Posted || previousJob == PostedBuild)
{
workerPostMap.erase(unit);
}
workerJobMap.erase(unit);
}
int WorkerData::getNumWorkers() const
{
return workers.size();
}
int WorkerData::getNumMineralWorkers() const
{
size_t num = 0;
for (BWAPI::Unit unit : workers)
{
if (workerJobMap.at(unit) == WorkerData::Minerals)
{
num++;
}
}
return num;
}
int WorkerData::getNumGasWorkers() const
{
size_t num = 0;
for (BWAPI::Unit unit : workers)
{
if (workerJobMap.at(unit) == WorkerData::Gas)
{
num++;
}
}
return num;
}
int WorkerData::getNumReturnCargoWorkers() const
{
size_t num = 0;
for (BWAPI::Unit unit : workers)
{
if (workerJobMap.at(unit) == WorkerData::ReturnCargo)
{
num++;
}
}
return num;
}
int WorkerData::getNumCombatWorkers() const
{
size_t num = 0;
for (BWAPI::Unit unit : workers)
{
if (workerJobMap.at(unit) == WorkerData::Combat)
{
num++;
}
}
return num;
}
int WorkerData::getNumRepairWorkers() const
{
size_t num = 0;
for (BWAPI::Unit unit : workers)
{
if (workerJobMap.at(unit) == WorkerData::Repair)
{
num++;
}
}
return num;
}
int WorkerData::getNumIdleWorkers() const
{
size_t num = 0;
for (BWAPI::Unit unit : workers)
{
if (workerJobMap.at(unit) == WorkerData::Idle)
{
num++;
}
}
return num;
}
int WorkerData::getNumPostedWorkers() const
{
return workerPostMap.size();
}
bool WorkerData::anyUnblocker() const
{
for (BWAPI::Unit unit : workers)
{
if (workerJobMap.at(unit) == WorkerData::Unblock)
{
return true;
}
}
return false;
}
enum WorkerData::WorkerJob WorkerData::getWorkerJob(BWAPI::Unit unit) const
{
if (!unit) { return Idle; }
std::map<BWAPI::Unit, enum WorkerJob>::const_iterator it = workerJobMap.find(unit);
if (it != workerJobMap.end())
{
return it->second;
}
return Idle;
}
// No more workers are needed for full mineral mining.
bool WorkerData::depotIsFull(BWAPI::Unit depot)
{
if (!depot) { return false; }
int assignedWorkers = getNumAssignedWorkers(depot);
int mineralsNearDepot = getMineralsNearDepot(depot);
// Mineral locking ensures that 2 workers per mineral patch are always enough (on normal maps).
// The configuration file may specify a different limit.
return
assignedWorkers >= 2 * mineralsNearDepot ||
assignedWorkers >= int (Config::Macro::WorkersPerPatch * mineralsNearDepot + 0.5);
}
BWAPI::Unitset WorkerData::getMineralPatchesNearDepot(BWAPI::Unit depot)
{
BWAPI::Unitset mineralsNearDepot;
int radius = 300;
// NOTE getNeutralUnits() returns visible units only. Visibility is needed for the distance check to work.
for (BWAPI::Unit unit : BWAPI::Broodwar->getNeutralUnits())
{
if (unit->getType() == BWAPI::UnitTypes::Resource_Mineral_Field && unit->getDistance(depot) < radius)
{
mineralsNearDepot.insert(unit);
}
}
// If we didn't find any, then include visible mineral patches everywhere on the map.
if (mineralsNearDepot.empty())
{
for (BWAPI::Unit unit : BWAPI::Broodwar->getNeutralUnits())
{
if (unit->getType() == BWAPI::UnitTypes::Resource_Mineral_Field)
{
mineralsNearDepot.insert(unit);
}
}
}
return mineralsNearDepot;
}
int WorkerData::getMineralsNearDepot(BWAPI::Unit depot)
{
if (!depot) { return 0; }
int mineralsNearDepot = 0;
for (BWAPI::Unit unit : BWAPI::Broodwar->getAllUnits())
{
if ((unit->getType() == BWAPI::UnitTypes::Resource_Mineral_Field) && unit->getDistance(depot) < 200)
{
mineralsNearDepot++;
}
}
return mineralsNearDepot;
}
BWAPI::Unit WorkerData::getWorkerResource(BWAPI::Unit unit)
{
if (!unit) { return nullptr; }
// create the iterator
std::map<BWAPI::Unit, BWAPI::Unit>::iterator it;
// if the worker is mining, set the iterator to the mineral map
if (getWorkerJob(unit) == Minerals)
{
it = workerMineralAssignment.find(unit);
if (it != workerMineralAssignment.end())
{
return it->second;
}
}
else if (getWorkerJob(unit) == Gas)
{
it = workerRefineryMap.find(unit);
if (it != workerRefineryMap.end())
{
return it->second;
}
}
return nullptr;
}
BWAPI::Unit WorkerData::getMineralToMine(BWAPI::Unit worker)
{
if (!worker) { return nullptr; }
// get the depot associated with this unit
BWAPI::Unit depot = getWorkerDepot(worker);
BWAPI::Unit bestMineral = nullptr;
int bestDist = INT_MAX;
int bestNumAssigned = 1; // mineral locking implies <= 2 workers per patch
if (depot)
{
BWAPI::Unitset mineralPatches = getMineralPatchesNearDepot(depot);
for (BWAPI::Unit mineral : mineralPatches)
{
int dist = mineral->getDistance(depot);
int numAssigned = workersOnMineralPatch[mineral];
if (numAssigned < bestNumAssigned ||
numAssigned == bestNumAssigned && dist < bestDist)
{
bestMineral = mineral;
bestDist = dist;
bestNumAssigned = numAssigned;
}
}
}
return bestMineral;
}
BWAPI::Unit WorkerData::getWorkerRepairUnit(BWAPI::Unit unit)
{
std::map<BWAPI::Unit, BWAPI::Unit>::iterator it = workerRepairMap.find(unit);
if (it != workerRepairMap.end())
{
return it->second;
}
return nullptr;
}
BWAPI::TilePosition WorkerData::getWorkerTile(BWAPI::Unit unit)
{
std::map<BWAPI::Unit, BWAPI::TilePosition>::iterator it = workerUnblockMap.find(unit);
if (it != workerUnblockMap.end())
{
return it->second;
}
return BWAPI::TilePositions::None;
}
MacroLocation WorkerData::getWorkerPostLocation(BWAPI::Unit unit)
{
std::map<BWAPI::Unit, WorkerData::WorkerPost>::iterator it = workerPostMap.find(unit);
if (it != workerPostMap.end())
{
return it->second.location;
}
return MacroLocation::Anywhere;
}
BWAPI::Position WorkerData::getWorkerPostPosition(BWAPI::Unit unit)
{
std::map<BWAPI::Unit, WorkerData::WorkerPost>::iterator it = workerPostMap.find(unit);
if (it != workerPostMap.end())
{
return it->second.position;
}
return BWAPI::Positions::None;
}
BWAPI::Unit WorkerData::getWorkerDepot(BWAPI::Unit unit)
{
if (!unit) { return nullptr; }
std::map<BWAPI::Unit, BWAPI::Unit>::iterator it = workerDepotMap.find(unit);
if (it != workerDepotMap.end())
{
return it->second;
}
return nullptr;
}
int WorkerData::getNumAssignedWorkers(BWAPI::Unit unit) const
{
if (!unit) { return 0; }
if (unit->getType().isResourceDepot())
{
auto it = depotWorkerCount.find(unit);
// if there is an entry, return it
if (it != depotWorkerCount.end())
{
return it->second;
}
}
else if (unit->getType().isRefinery())
{
auto it = refineryWorkerCount.find(unit);
// if there is an entry, return it
if (it != refineryWorkerCount.end())
{
return it->second;
}
}
return 0;
}
// Add all gas workers to the given set.
void WorkerData::getGasWorkers(std::set<BWAPI::Unit> & mw)
{
for (const auto & kv : workerRefineryMap)
{
mw.insert(kv.first);
}
}
char WorkerData::getJobCode(BWAPI::Unit unit)
{
if (!unit) { return 'X'; }
return getJobCode(getWorkerJob(unit));
}
char WorkerData::getJobCode(WorkerJob j) const
{
if (j == WorkerData::Minerals) return 'M';
if (j == WorkerData::Gas) return 'G';
if (j == WorkerData::Build) return 'B';
if (j == WorkerData::Combat) return 'C';
if (j == WorkerData::Idle) return 'I';
if (j == WorkerData::Repair) return 'R';
if (j == WorkerData::Scout) return 'S';
if (j == WorkerData::ReturnCargo) return '$';
if (j == WorkerData::Unblock) return 'U';
if (j == WorkerData::Posted) return 'P';
if (j == WorkerData::PostedBuild) return 'Q';
return 'X';
}
void WorkerData::drawDepotDebugInfo()
{
if (!Config::Debug::DrawWorkerInfo)
{
return;
}
for (const auto & depotCount : depotWorkerCount)
{
BWAPI::Unit depot = depotCount.first;
int nDepotWorkers = depotCount.second;
int x = depot->getPosition().x - 64;
int y = depot->getPosition().y - 32;
BWAPI::Broodwar->drawBoxMap(x-2, y-1, x+75, y+14, BWAPI::Colors::Black, true);
BWAPI::Broodwar->drawTextMap(x, y, "%c Workers: %d", white, nDepotWorkers);
for (BWAPI::Unit mineral : getMineralPatchesNearDepot(depot))
{
BWAPI::Position xy = mineral->getPosition() + BWAPI::Position(-16, -16);
if (workersOnMineralPatch.find(mineral) != workersOnMineralPatch.end())
{
BWAPI::Broodwar->drawBoxMap(xy, xy + BWAPI::Position(18, 16), BWAPI::Colors::Black, true);
BWAPI::Broodwar->drawTextMap(xy.x+2, xy.y+1, "%c %d", white, workersOnMineralPatch[mineral]);
}
}
}
for (const auto & gasCount : refineryWorkerCount)
{
BWAPI::Unit gas = gasCount.first;
int n = gasCount.second;
BWAPI::Position xy = gas->getPosition() + BWAPI::Position(-8, -16);
BWAPI::Broodwar->drawBoxMap(xy, xy + BWAPI::Position(18, 16), BWAPI::Colors::Black, true);
BWAPI::Broodwar->drawTextMap(xy.x + 2, xy.y + 1, "%c %d", white, n);
}
}
|
#include <cstdlib>
#include <iostream>
#include <cucumber-cpp/generic.hpp>
#include <cucumber-cpp/autodetect.hpp>
using cucumber::ScenarioScope;
struct MyContext {
int result;
};
GIVEN("^Given value (\\d+)$") {
REGEX_PARAM(int, val);
ScenarioScope<MyContext> context;
context->result = val;
}
WHEN("^When I add (\\d+)$") {
REGEX_PARAM(int, val);
ScenarioScope<MyContext> context;
context->result += val;
}
THEN("^Then it equals (\\d+)$") {
REGEX_PARAM(int, val);
ScenarioScope<MyContext> context;
//EXPECT_EQ(context->result, val);
}
int main()
{
std::cout << "Bincrafters\n";
return EXIT_SUCCESS;
}
|
///////////////////////////////////////////////////////////////////////////////
// Authors: Hyein Lee and Jiajia Li
// (Ph.D. advisor: Andrew B. Kahng)
//
// Many subsequent improvements were made by Minsoo Kim
// leading up to the initial release.
//
// BSD 3-Clause License
//
// Copyright (c) 2018, The Regents of the University of California
// 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 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 <stdlib.h>
#include <sstream>
#include "sizer.h"
#define GLOBAL 0
#define LEGALIZE 1
#define DETAIL 2
#define FINESWAP 3
#define FINEFIX 4
#define UPSIZE 0
#define UPTYPE 1
#define DNSIZE 2
#define DNTYPE 3
#define SAME_SS_LIMIT 2
void Sizer::TimerTest(int timerTestCnt, unsigned view)
{
cout << "[TimerTest] Evalulate STA..." << endl;
if (slack_margin != 0.0) SetGB(slack_margin);
bool ifDelete = true;
cells = new CELL[numcells];
for(unsigned i=0 ; i<numcells ; i++) {
cells[i] = g_cells[i];
cout << i << " " << cells[i].name << endl;
}
pins= new PIN*[numViews];
for (unsigned i = 0; i < numViews; ++i ) {
pins[i] = new PIN[numpins];
for(unsigned j=0 ; j<numpins ; j++)
pins[i][j]=g_pins[i][j];
}
nets= new NET*[numCorners];
for (unsigned i = 0; i < numCorners; ++i ) {
nets[i] = new NET[numnets];
for(unsigned j=0 ; j<numnets ; j++)
nets[i][j]=g_nets[i][j];
}
ifDelete = true;
PTimer = new designTiming** [1];
for (int i=0; i < 1; i++ ) {
PTimer[i] = new designTiming*[numViews];
for (int view=0; view < numViews; view++) {
cout << "Launch " << i*numViews+view << "th PT" << endl;
PTimer[i][view] = LaunchPTimer(i*numViews+view, view);
}
}
T = PTimer[0];
cout << "Verify Timer..." << endl;
//SizeIn("gtr");
UpdateCapsFromCells();
CallTimer(view);
CorrelatePT();
CalcStats(view);
//ReportWireTiming(view);
UpdatePTSizes();
//CompareWithPT();
double TMR=cpuTime();
CallTimer(view);
TMR=(cpuTime()-TMR);
cout << "full_STA_time : " << TMR << endl;
unsigned count=0;
unsigned false_count=0;
double max_rslk_diff=0.;
double max_fslk_diff=0.;
vector<double> one_rslk;
vector<double> one_fslk;
vector<double> one_rtran;
vector<double> one_ftran;
vector<double> one_rAAT;
vector<double> one_fAAT;
vector<double> one_rRAT;
vector<double> one_fRAT;
double time_total = 0;
double time_max = 0;
unsigned cellidx_max = 0;
if ( true ) {
cout << "=====BEFORE==================================================" << endl;
unsigned l = 0;
unsigned k = 0;
for (unsigned i=0; i<topolist.size(); ++i) {
for (unsigned j=0; j<cells[topolist[i]].inpins.size(); ++j) {
l = cells[topolist[i]].inpins[j];
cout << getFullPinName(pins[view][l]) << " rslk\t"
<< pins[view][l].rslk << endl;
cout << getFullPinName(pins[view][l]) << " fslk\t"
<< pins[view][l].fslk << endl;
cout << getFullPinName(pins[view][l]) << " rtran\t"
<< pins[view][l].rtran << endl;
cout << getFullPinName(pins[view][l]) << " ftran\t"
<< pins[view][l].ftran << endl;
cout << getFullPinName(pins[view][l]) << " rAAT\t"
<< pins[view][l].rAAT << endl;
cout << getFullPinName(pins[view][l]) << " fAAT\t"
<< pins[view][l].fAAT << endl;
cout << getFullPinName(pins[view][l]) << " rRAT\t"
<< pins[view][l].rRAT << endl;
cout << getFullPinName(pins[view][l]) << " fRAT\t"
<< pins[view][l].fRAT << endl;
}
for (unsigned j=0; j<cells[topolist[i]].outpins.size(); ++j) {
l = cells[topolist[i]].outpins[j];
cout << getFullPinName(pins[view][l]) << " rslk\t"
<< pins[view][l].rslk << endl;
cout << getFullPinName(pins[view][l]) << " fslk\t"
<< pins[view][l].fslk << endl;
cout << getFullPinName(pins[view][l]) << " rtran\t"
<< pins[view][l].rtran << endl;
cout << getFullPinName(pins[view][l]) << " ftran\t"
<< pins[view][l].ftran << endl;
cout << getFullPinName(pins[view][l]) << " rAAT\t"
<< pins[view][l].rAAT << endl;
cout << getFullPinName(pins[view][l]) << " fAAT\t"
<< pins[view][l].fAAT << endl;
cout << getFullPinName(pins[view][l]) << " rRAT\t"
<< pins[view][l].rRAT << endl;
cout << getFullPinName(pins[view][l]) << " fRAT\t"
<< pins[view][l].fRAT << endl;
k++;
}
}
cout << "=======================================================" << endl;
}
if ( timerTestCell != 0 ) {
unsigned k = timerTestCell;
unsigned i = timerTestMove;
PIN &pin = pins[view][cells[k].outpins[0]];
cout << "PREV TIMING - ORIG " << getFullPinName(pin)
<< " (" << pin.rslk << "/" << pin.fslk << ")"
<< " (" << pin.rRAT << "/" << pin.fRAT << ")"
<< " (" << pin.rAAT << "/" << pin.fAAT << ")"
<< " (" << pin.rslk_ofs << "/" << pin.fslk_ofs << ")"
<< " (" << pin.totcap << "," << pin.slk_gb << ")"
<< endl;
if(i == 0) {
cell_resize(cells[k], 1, true);
cout << cells[k].type << " upsized " << endl ;
OneTimer(cells[k], STA_MARGIN);
cout << "AFTER SIZING TIMING - ORIG " << getFullPinName(pin)
<< " (" << pin.rslk << "/" << pin.fslk << ")"
<< " (" << pin.rRAT << "/" << pin.fRAT << ")"
<< " (" << pin.rAAT << "/" << pin.fAAT << ")"
<< " (" << pin.rslk_ofs << "/" << pin.fslk_ofs << ")"
<< " (" << pin.totcap << "," << pin.slk_gb << ")"
<< endl;
cout << cells[k].name << " " << cells[k].type << " --> ";
cell_resize(cells[k], -1, true);
cout << cells[k].type << " downsized " << endl ;
OneTimer(cells[k], STA_MARGIN);
cout << "AFTER REVERT TIMING - ORIG " << getFullPinName(pin)
<< " (" << pin.rslk << "/" << pin.fslk << ")"
<< " (" << pin.rRAT << "/" << pin.fRAT << ")"
<< " (" << pin.rAAT << "/" << pin.fAAT << ")"
<< " (" << pin.rslk_ofs << "/" << pin.fslk_ofs << ")"
<< " (" << pin.totcap << "," << pin.slk_gb << ")"
<< endl;
} else if (i == 1) {
cell_resize(cells[k], -1, true);
cout << cells[k].type << " downsized " << endl ;
OneTimer(cells[k], STA_MARGIN);
cout << "AFTER SIZING TIMING - ORIG " << getFullPinName(pin)
<< " (" << pin.rslk << "/" << pin.fslk << ")"
<< " (" << pin.rRAT << "/" << pin.fRAT << ")"
<< " (" << pin.rAAT << "/" << pin.fAAT << ")"
<< " (" << pin.rslk_ofs << "/" << pin.fslk_ofs << ")"
<< " (" << pin.totcap << "," << pin.slk_gb << ")"
<< endl;
cout << cells[k].name << " " << cells[k].type << " --> ";
cell_resize(cells[k], 1, true);
cout << cells[k].type << " upsized " << endl ;
OneTimer(cells[k], STA_MARGIN);
cout << "AFTER REVERT TIMING - ORIG " << getFullPinName(pin)
<< " (" << pin.rslk << "/" << pin.fslk << ")"
<< " (" << pin.rRAT << "/" << pin.fRAT << ")"
<< " (" << pin.rAAT << "/" << pin.fAAT << ")"
<< " (" << pin.rslk_ofs << "/" << pin.fslk_ofs << ")"
<< " (" << pin.totcap << "," << pin.slk_gb << ")"
<< endl;
} else if(i == 2) {
cell_retype(cells[k], 1, true);
cout << cells[k].type << " uptyped " << endl ;
OneTimer(cells[k], STA_MARGIN);
cout << "AFTER SIZING TIMING - ORIG " << getFullPinName(pin)
<< " (" << pin.rslk << "/" << pin.fslk << ")"
<< " (" << pin.rRAT << "/" << pin.fRAT << ")"
<< " (" << pin.rAAT << "/" << pin.fAAT << ")"
<< " (" << pin.rslk_ofs << "/" << pin.fslk_ofs << ")"
<< " (" << pin.totcap << "," << pin.slk_gb << ")"
<< endl;
cout << cells[k].name << " " << cells[k].type << " --> ";
cell_retype(cells[k], -1, true);
cout << cells[k].type << " downtyped " << endl ;
OneTimer(cells[k], STA_MARGIN);
cout << "AFTER REVERT TIMING - ORIG " << getFullPinName(pin)
<< " (" << pin.rslk << "/" << pin.fslk << ")"
<< " (" << pin.rRAT << "/" << pin.fRAT << ")"
<< " (" << pin.rAAT << "/" << pin.fAAT << ")"
<< " (" << pin.rslk_ofs << "/" << pin.fslk_ofs << ")"
<< " (" << pin.totcap << "," << pin.slk_gb << ")"
<< endl;
} else {
cell_retype(cells[k], -1, true);
cout << cells[k].type << " downtyped " << endl ;
OneTimer(cells[k], STA_MARGIN, true);
cout << "AFTER SIZING TIMING - ORIG " << getFullPinName(pin)
<< " (" << pin.rslk << "/" << pin.fslk << ")"
<< " (" << pin.rRAT << "/" << pin.fRAT << ")"
<< " (" << pin.rAAT << "/" << pin.fAAT << ")"
<< " (" << pin.rslk_ofs << "/" << pin.fslk_ofs << ")"
<< " (" << pin.totcap << "," << pin.slk_gb << ")"
<< endl;
cout << cells[k].name << " " << cells[k].type << " --> ";
cell_retype(cells[k], 1, true);
cout << cells[k].type << " uptyped " << endl ;
OneTimer(cells[k], STA_MARGIN);
cout << "AFTER REVERT TIMING - ORIG " << getFullPinName(pin)
<< " (" << pin.rslk << "/" << pin.fslk << ")"
<< " (" << pin.rRAT << "/" << pin.fRAT << ")"
<< " (" << pin.rAAT << "/" << pin.fAAT << ")"
<< " (" << pin.rslk_ofs << "/" << pin.fslk_ofs << ")"
<< " (" << pin.totcap << "," << pin.slk_gb << ")"
<< endl;
}
TMR=cpuTime();
count = 1;
} else {
for(unsigned j=0 ; j<numcells*100 ; j++)
{
unsigned i = (unsigned) (rand()%4);
unsigned k = j%numcells;
if(isff(cells[k])) continue;
if(cells[k].isClockCell) continue;
if(i == 0) {
if(isMax(cells[k])) continue;
cout << cells[k].name << " " << cells[k].type << " --> ";
cell_resize(cells[k], 1);
cout << cells[k].type << " upsized " << endl ;
} else if (i == 1) {
if(cells[k].c_size == 0) continue;
cout << cells[k].name << " " << cells[k].type << " --> ";
cell_resize(cells[k], -1);
cout << cells[k].type << " downsized " << endl ;
} else if(i == 2) {
if(r_type(cells[k])==f) continue;
cout << cells[k].name << " " << cells[k].type << " --> ";
cell_retype(cells[k], 1);
cout << cells[k].type << " uptyped " << endl;
} else {
if(r_type(cells[k])==s) continue;
cout << cells[k].name << " " << cells[k].type << " --> ";
cell_retype(cells[k], -1);
cout << cells[k].type << " downtyped " << endl;
}
TMR=cpuTime();
OneTimer (cells[k], STA_MARGIN, view);
cout << "TIMER " << k << " " << cells[k].name << " " << cells[k].type << endl;
//UpdatePTSizes();
TMR=(cpuTime()-TMR);
time_total += TMR;
if (TMR > time_max) {
time_max = TMR;
cellidx_max = i;
}
if (++count >= timerTestCnt) break;
}
}
CalcStats(view);
// cout << count << " cells changed" << endl;
double time_avg = time_total / (double) count;
for (unsigned i=0; i<topolist.size(); ++i) {
for (unsigned j=0; j<cells[topolist[i]].inpins.size(); ++j) {
one_rslk.push_back(pins[view][cells[topolist[i]].inpins[j]].rslk);
one_fslk.push_back(pins[view][cells[topolist[i]].inpins[j]].fslk);
one_rtran.push_back(pins[view][cells[topolist[i]].inpins[j]].rtran);
one_ftran.push_back(pins[view][cells[topolist[i]].inpins[j]].ftran);
one_rAAT.push_back(pins[view][cells[topolist[i]].inpins[j]].rAAT);
one_fAAT.push_back(pins[view][cells[topolist[i]].inpins[j]].fAAT);
one_rRAT.push_back(pins[view][cells[topolist[i]].inpins[j]].rRAT);
one_fRAT.push_back(pins[view][cells[topolist[i]].inpins[j]].fRAT);
}
for (unsigned j=0; j<cells[topolist[i]].outpins.size(); ++j) {
one_rslk.push_back(pins[view][cells[topolist[i]].outpins[j]].rslk);
one_fslk.push_back(pins[view][cells[topolist[i]].outpins[j]].fslk);
one_rtran.push_back(pins[view][cells[topolist[i]].outpins[j]].rtran);
one_ftran.push_back(pins[view][cells[topolist[i]].outpins[j]].ftran);
one_rAAT.push_back(pins[view][cells[topolist[i]].outpins[j]].rAAT);
one_fAAT.push_back(pins[view][cells[topolist[i]].outpins[j]].fAAT);
one_rRAT.push_back(pins[view][cells[topolist[i]].outpins[j]].rRAT);
one_fRAT.push_back(pins[view][cells[topolist[i]].outpins[j]].fRAT);
}
}
//UpdatePTSizes();
UpdateCapsFromCells();
CallTimer(view);
CalcStats(view);
if ( true ) {
cout << "=======================================================" << endl;
unsigned l = 0;
unsigned k = 0;
for (unsigned i=0; i<topolist.size(); ++i) {
for (unsigned j=0; j<cells[topolist[i]].inpins.size(); ++j) {
l = cells[topolist[i]].inpins[j];
cout << getFullPinName(pins[view][l]) << " rslk\t"
<< one_rslk[k] << "\t"
<< pins[view][l].rslk
<< "\t" << T[view]->getRiseSlack(getFullPinName(pins[view][l]))
<< endl;
cout << getFullPinName(pins[view][l]) << " fslk\t"
<< one_fslk[k] << "\t"
<< pins[view][l].fslk
<< "\t" << T[view]->getFallSlack(getFullPinName(pins[view][l]))
<< endl;
cout << getFullPinName(pins[view][l]) << " rtran\t"
<< one_rtran[k] << "\t"
<< pins[view][l].rtran << endl;
cout << getFullPinName(pins[view][l]) << " ftran\t"
<< one_ftran[k] << "\t"
<< pins[view][l].ftran << endl;
cout << getFullPinName(pins[view][l]) << " rAAT\t"
<< one_rAAT[k] << "\t"
<< pins[view][l].rAAT << endl;
cout << getFullPinName(pins[view][l]) << " fAAT\t"
<< one_fAAT[k] << "\t"
<< pins[view][l].fAAT << endl;
cout << getFullPinName(pins[view][l]) << " rRAT\t"
<< one_rRAT[k] << "\t"
<< pins[view][l].rRAT << endl;
cout << getFullPinName(pins[view][l]) << " fRAT\t"
<< one_fRAT[k] << "\t"
<< pins[view][l].fRAT << endl;
k++;
}
for (unsigned j=0; j<cells[topolist[i]].outpins.size(); ++j) {
l = cells[topolist[i]].outpins[j];
cout << getFullPinName(pins[view][l]) << " rslk\t"
<< one_rslk[k] << "\t"
<< pins[view][l].rslk << endl;
cout << getFullPinName(pins[view][l]) << " fslk\t"
<< one_fslk[k] << "\t"
<< pins[view][l].fslk << endl;
cout << getFullPinName(pins[view][l]) << " rtran\t"
<< one_rtran[k] << "\t"
<< pins[view][l].rtran << endl;
cout << getFullPinName(pins[view][l]) << " ftran\t"
<< one_ftran[k] << "\t"
<< pins[view][l].ftran << endl;
cout << getFullPinName(pins[view][l]) << " rAAT\t"
<< one_rAAT[k] << "\t"
<< pins[view][l].rAAT << endl;
cout << getFullPinName(pins[view][l]) << " fAAT\t"
<< one_fAAT[k] << "\t"
<< pins[view][l].fAAT << endl;
cout << getFullPinName(pins[view][l]) << " rRAT\t"
<< one_rRAT[k] << "\t"
<< pins[view][l].rRAT << endl;
cout << getFullPinName(pins[view][l]) << " fRAT\t"
<< one_fRAT[k] << "\t"
<< pins[view][l].fRAT << endl;
k++;
}
}
cout << "=======================================================" << endl;
}
false_count = 0;
unsigned k = 0;
unsigned l =0;
for (unsigned i=0; i<topolist.size(); ++i) {
for (unsigned j=0; j<cells[topolist[i]].inpins.size(); ++j) {
l = cells[topolist[i]].inpins[j];
if ( one_rslk[k] != pins[view][cells[topolist[i]].inpins[j]].rslk ) {
cout << getFullPinName(pins[view][cells[topolist[i]].inpins[j]]) << " rslk\t"
<< one_rslk[k] << "\t"
<< pins[view][cells[topolist[i]].inpins[j]].rslk
<< "\t" << T[view]->getRiseSlack(getFullPinName(pins[view][l]))
<< endl;
++false_count;
}
if ( one_fslk[k] != pins[view][cells[topolist[i]].inpins[j]].fslk ) {
cout << getFullPinName(pins[view][cells[topolist[i]].inpins[j]]) << " fslk\t"
<< one_fslk[k] << "\t"
<< pins[view][cells[topolist[i]].inpins[j]].fslk
<< "\t" << T[view]->getFallSlack(getFullPinName(pins[view][l]))
<< endl;
++false_count;
}
if ( one_rtran[k] != pins[view][cells[topolist[i]].inpins[j]].rtran ) {
cout << getFullPinName(pins[view][cells[topolist[i]].inpins[j]]) << " rtran\t"
<< one_rtran[k] << "\t"
<< pins[view][cells[topolist[i]].inpins[j]].rtran
<< "\t" << T[view]->getRiseTran(getFullPinName(pins[view][l]))
<< endl;
++false_count;
}
if ( one_ftran[k] != pins[view][cells[topolist[i]].inpins[j]].ftran ) {
cout << getFullPinName(pins[view][cells[topolist[i]].inpins[j]]) << " ftran\t"
<< one_ftran[k] << "\t"
<< pins[view][cells[topolist[i]].inpins[j]].ftran
<< "\t" << T[view]->getFallTran(getFullPinName(pins[view][l]))
<< endl;
++false_count;
}
if ( one_rAAT[k] != pins[view][cells[topolist[i]].inpins[j]].rAAT ) {
cout << getFullPinName(pins[view][cells[topolist[i]].inpins[j]]) << " rAAT\t"
<< one_rAAT[k] << "\t"
<< pins[view][cells[topolist[i]].inpins[j]].rAAT
<< "\t" << T[view]->getRiseArrival(getFullPinName(pins[view][l]))
<< endl;
++false_count;
}
if ( one_fAAT[k] != pins[view][cells[topolist[i]].inpins[j]].fAAT ) {
cout << getFullPinName(pins[view][cells[topolist[i]].inpins[j]]) << " fAAT\t"
<< one_fAAT[k] << "\t"
<< pins[view][cells[topolist[i]].inpins[j]].fAAT
<< "\t" << T[view]->getFallArrival(getFullPinName(pins[view][l]))
<< endl;
++false_count;
}
if ( one_rRAT[k] != pins[view][cells[topolist[i]].inpins[j]].rRAT ) {
cout << getFullPinName(pins[view][cells[topolist[i]].inpins[j]]) << " rRAT\t"
<< one_rRAT[k] << "\t"
<< pins[view][cells[topolist[i]].inpins[j]].rRAT
<< "\t" << T[view]->getRiseArrival(getFullPinName(pins[view][l])) + T[view]->getRiseSlack(getFullPinName(pins[view][l]))
<< endl;
++false_count;
}
if ( one_fRAT[k] != pins[view][cells[topolist[i]].inpins[j]].fRAT ) {
cout << getFullPinName(pins[view][cells[topolist[i]].inpins[j]]) << " fRAT\t"
<< one_fRAT[k] << "\t"
<< pins[view][cells[topolist[i]].inpins[j]].fRAT
<< "\t" << T[view]->getFallArrival(getFullPinName(pins[view][l])) + T[view]->getFallSlack(getFullPinName(pins[view][l]))
<< endl;
++false_count;
}
++k;
}
for (unsigned j=0; j<cells[topolist[i]].outpins.size(); ++j) {
l = cells[topolist[i]].outpins[j];
if ( one_rslk[k] != pins[view][cells[topolist[i]].outpins[j]].rslk ) {
cout << getFullPinName(pins[view][cells[topolist[i]].outpins[j]]) << " rslk\t"
<< one_rslk[k] << "\t"
<< pins[view][cells[topolist[i]].outpins[j]].rslk
<< "\t" << T[view]->getRiseSlack(getFullPinName(pins[view][l]))
<< endl;
++false_count;
}
if ( one_fslk[k] != pins[view][cells[topolist[i]].outpins[j]].fslk ) {
cout << getFullPinName(pins[view][cells[topolist[i]].outpins[j]]) << " fslk\t"
<< one_fslk[k] << "\t"
<< pins[view][cells[topolist[i]].outpins[j]].fslk
<< "\t" << T[view]->getFallSlack(getFullPinName(pins[view][l]))
<< endl;
++false_count;
}
if ( one_rtran[k] != pins[view][cells[topolist[i]].outpins[j]].rtran ) {
cout << getFullPinName(pins[view][cells[topolist[i]].outpins[j]]) << " rtran\t"
<< one_rtran[k] << "\t"
<< pins[view][cells[topolist[i]].outpins[j]].rtran
<< "\t" << T[view]->getRiseTran(getFullPinName(pins[view][l]))
<< endl;
++false_count;
}
if ( one_ftran[k] != pins[view][cells[topolist[i]].outpins[j]].ftran ) {
cout << getFullPinName(pins[view][cells[topolist[i]].outpins[j]]) << " ftran\t"
<< one_ftran[k] << "\t"
<< pins[view][cells[topolist[i]].outpins[j]].ftran
<< "\t" << T[view]->getFallTran(getFullPinName(pins[view][l]))
<< endl;
++false_count;
}
if ( one_rAAT[k] != pins[view][cells[topolist[i]].outpins[j]].rAAT ) {
cout << getFullPinName(pins[view][cells[topolist[i]].outpins[j]]) << " rAAT\t"
<< one_rAAT[k] << "\t"
<< pins[view][cells[topolist[i]].outpins[j]].rAAT
<< "\t" << T[view]->getRiseArrival(getFullPinName(pins[view][l]))
<< endl;
++false_count;
}
if ( one_fAAT[k] != pins[view][cells[topolist[i]].outpins[j]].fAAT ) {
cout << getFullPinName(pins[view][cells[topolist[i]].outpins[j]]) << " fAAT\t"
<< one_fAAT[k] << "\t"
<< pins[view][cells[topolist[i]].outpins[j]].fAAT
<< "\t" << T[view]->getFallArrival(getFullPinName(pins[view][l]))
<< endl;
++false_count;
}
if ( one_rRAT[k] != pins[view][cells[topolist[i]].outpins[j]].rRAT ) {
cout << getFullPinName(pins[view][cells[topolist[i]].outpins[j]]) << " rRAT\t"
<< one_rRAT[k] << "\t"
<< pins[view][cells[topolist[i]].outpins[j]].rRAT
<< "\t" << T[view]->getRiseArrival(getFullPinName(pins[view][l])) + T[view]->getRiseSlack(getFullPinName(pins[view][l]))
<< endl;
++false_count;
}
if ( one_fRAT[k] != pins[view][cells[topolist[i]].outpins[j]].fRAT ) {
cout << getFullPinName(pins[view][cells[topolist[i]].outpins[j]]) << " fRAT\t"
<< one_fRAT[k] << "\t"
<< pins[view][cells[topolist[i]].outpins[j]].fRAT
<< "\t" << T[view]->getFallArrival(getFullPinName(pins[view][l])) + T[view]->getFallSlack(getFullPinName(pins[view][l]))
<< endl;
++false_count;
}
++k;
}
}
cout << "-------------------------------------------------" << endl;
k = 0;
unsigned false_count2 = 0;
for (unsigned i=0; i<topolist.size(); ++i) {
for (unsigned j=0; j<cells[topolist[i]].inpins.size(); ++j) {
if ( abs(one_rslk[k]-pins[view][cells[topolist[i]].inpins[j]].rslk) > 0.001 ||
abs(one_fslk[k]-pins[view][cells[topolist[i]].inpins[j]].fslk) > 0.001 ||
abs(one_rRAT[k]-pins[view][cells[topolist[i]].inpins[j]].rRAT) > 0.001 ||
abs(one_fRAT[k]-pins[view][cells[topolist[i]].inpins[j]].fRAT) > 0.001 ||
abs(one_rAAT[k]-pins[view][cells[topolist[i]].inpins[j]].rAAT) > 0.001 ||
abs(one_fAAT[k]-pins[view][cells[topolist[i]].inpins[j]].fAAT) > 0.001) {
++false_count2;
cout << getFullPinName(pins[view][cells[topolist[i]].inpins[j]]) << " rslk\t"
<< one_rslk[k] << "\t"
<< pins[view][cells[topolist[i]].inpins[j]].rslk
<< "\t" << T[view]->getRiseSlack(getFullPinName(pins[view][cells[topolist[i]].inpins[j]]))
<< "\t" << pins[view][cells[topolist[i]].inpins[j]].rslk_ofs
<< endl;
cout << getFullPinName(pins[view][cells[topolist[i]].inpins[j]]) << " fslk\t"
<< one_fslk[k] << "\t"
<< pins[view][cells[topolist[i]].inpins[j]].fslk
<< "\t" << T[view]->getFallSlack(getFullPinName(pins[view][cells[topolist[i]].inpins[j]]))
<< "\t" << pins[view][cells[topolist[i]].inpins[j]].fslk_ofs
<< endl;
cout << getFullPinName(pins[view][cells[topolist[i]].inpins[j]]) << " rtran\t"
<< one_rtran[k] << "\t"
<< pins[view][cells[topolist[i]].inpins[j]].rtran
<< "\t" << T[view]->getRiseSlack(getFullPinName(pins[view][cells[topolist[i]].inpins[j]]))
<< "\t" << pins[view][cells[topolist[i]].inpins[j]].rtran_ofs
<< endl;
cout << getFullPinName(pins[view][cells[topolist[i]].inpins[j]]) << " ftran\t"
<< one_ftran[k] << "\t"
<< pins[view][cells[topolist[i]].inpins[j]].ftran
<< "\t" << T[view]->getFallSlack(getFullPinName(pins[view][cells[topolist[i]].inpins[j]]))
<< "\t" << pins[view][cells[topolist[i]].inpins[j]].ftran_ofs
<< endl;
cout << getFullPinName(pins[view][cells[topolist[i]].inpins[j]]) << " rAAT\t"
<< one_rAAT[k] << "\t"
<< pins[view][cells[topolist[i]].inpins[j]].rAAT
<< "\t" << T[view]->getRiseArrival(getFullPinName(pins[view][cells[topolist[i]].inpins[j]]))
<< "\t" << pins[view][cells[topolist[i]].inpins[j]].rAAT_ofs
<< endl;
cout << getFullPinName(pins[view][cells[topolist[i]].inpins[j]]) << " fAAT\t"
<< one_fAAT[k] << "\t"
<< pins[view][cells[topolist[i]].inpins[j]].fAAT
<< "\t" << T[view]->getFallArrival(getFullPinName(pins[view][cells[topolist[i]].inpins[j]]))
<< "\t" << pins[view][cells[topolist[i]].inpins[j]].fAAT_ofs
<< endl;
cout << getFullPinName(pins[view][cells[topolist[i]].inpins[j]]) << " rRAT\t"
<< one_rRAT[k] << "\t"
<< pins[view][cells[topolist[i]].inpins[j]].rRAT
<< "\t" << T[view]->getRiseArrival(getFullPinName(pins[view][cells[topolist[i]].inpins[j]]))
+ T[view]->getRiseSlack(getFullPinName(pins[view][cells[topolist[i]].inpins[j]]))
<< "\t" << pins[view][cells[topolist[i]].inpins[j]].rRAT_ofs
<< endl;
cout << getFullPinName(pins[view][cells[topolist[i]].inpins[j]]) << " fRAT\t"
<< one_fRAT[k] << "\t"
<< pins[view][cells[topolist[i]].inpins[j]].fRAT
<< "\t" << T[view]->getFallArrival(getFullPinName(pins[view][cells[topolist[i]].inpins[j]]))
+ T[view]->getFallSlack(getFullPinName(pins[view][cells[topolist[i]].inpins[j]]))
<< "\t" << pins[view][cells[topolist[i]].inpins[j]].fRAT_ofs
<< endl;
cout << "-------------------------------------------------" << endl;
}
++k;
}
for (unsigned j=0; j<cells[topolist[i]].outpins.size(); ++j) {
if ( abs(one_rslk[k]-pins[view][cells[topolist[i]].outpins[j]].rslk) > 0.001 ||
abs(one_fslk[k]-pins[view][cells[topolist[i]].outpins[j]].fslk) > 0.001 ||
abs(one_rRAT[k]-pins[view][cells[topolist[i]].outpins[j]].rRAT) > 0.001 ||
abs(one_fRAT[k]-pins[view][cells[topolist[i]].outpins[j]].fRAT) > 0.001 ||
abs(one_rAAT[k]-pins[view][cells[topolist[i]].outpins[j]].rAAT) > 0.001 ||
abs(one_fAAT[k]-pins[view][cells[topolist[i]].outpins[j]].fAAT) > 0.001) {
++false_count2;
cout << getFullPinName(pins[view][cells[topolist[i]].outpins[j]]) << " rslk\t"
<< one_rslk[k] << "\t"
<< pins[view][cells[topolist[i]].outpins[j]].rslk
<< "\t" << T[view]->getRiseSlack(getFullPinName(pins[view][cells[topolist[i]].outpins[j]]))
<< "\t" << pins[view][cells[topolist[i]].outpins[j]].rslk_ofs
<< endl;
cout << getFullPinName(pins[view][cells[topolist[i]].outpins[j]]) << " fslk\t"
<< one_fslk[k] << "\t"
<< pins[view][cells[topolist[i]].outpins[j]].fslk
<< "\t" << T[view]->getFallSlack(getFullPinName(pins[view][cells[topolist[i]].outpins[j]]))
<< "\t" << pins[view][cells[topolist[i]].outpins[j]].fslk_ofs
<< endl;
cout << getFullPinName(pins[view][cells[topolist[i]].outpins[j]]) << " rtran\t"
<< one_rtran[k] << "\t"
<< pins[view][cells[topolist[i]].outpins[j]].rtran
<< "\t" << T[view]->getRiseSlack(getFullPinName(pins[view][cells[topolist[i]].outpins[j]]))
<< "\t" << pins[view][cells[topolist[i]].outpins[j]].rtran_ofs
<< endl;
cout << getFullPinName(pins[view][cells[topolist[i]].outpins[j]]) << " ftran\t"
<< one_ftran[k] << "\t"
<< pins[view][cells[topolist[i]].outpins[j]].ftran
<< "\t" << T[view]->getFallSlack(getFullPinName(pins[view][cells[topolist[i]].outpins[j]]))
<< "\t" << pins[view][cells[topolist[i]].outpins[j]].ftran_ofs
<< endl;
cout << getFullPinName(pins[view][cells[topolist[i]].outpins[j]]) << " rAAT\t"
<< one_rAAT[k] << "\t"
<< pins[view][cells[topolist[i]].outpins[j]].rAAT
<< "\t" << T[view]->getRiseArrival(getFullPinName(pins[view][cells[topolist[i]].outpins[j]]))
<< "\t" << pins[view][cells[topolist[i]].outpins[j]].rAAT_ofs
<< endl;
cout << getFullPinName(pins[view][cells[topolist[i]].outpins[j]]) << " fAAT\t"
<< one_fAAT[k] << "\t"
<< pins[view][cells[topolist[i]].outpins[j]].fAAT
<< "\t" << T[view]->getFallArrival(getFullPinName(pins[view][cells[topolist[i]].outpins[j]]))
<< "\t" << pins[view][cells[topolist[i]].outpins[j]].fAAT_ofs
<< endl;
cout << getFullPinName(pins[view][cells[topolist[i]].outpins[j]]) << " rRAT\t"
<< one_rRAT[k] << "\t"
<< pins[view][cells[topolist[i]].outpins[j]].rRAT
<< "\t" << T[view]->getRiseArrival(getFullPinName(pins[view][cells[topolist[i]].outpins[j]]))
+ T[view]->getRiseSlack(getFullPinName(pins[view][cells[topolist[i]].outpins[j]]))
<< "\t" << pins[view][cells[topolist[i]].outpins[j]].rRAT_ofs
<< endl;
cout << getFullPinName(pins[view][cells[topolist[i]].outpins[j]]) << " fRAT\t"
<< one_fRAT[k] << "\t"
<< pins[view][cells[topolist[i]].outpins[j]].fRAT
<< "\t" << T[view]->getFallArrival(getFullPinName(pins[view][cells[topolist[i]].outpins[j]]))
+ T[view]->getFallSlack(getFullPinName(pins[view][cells[topolist[i]].outpins[j]]))
<< "\t" << pins[view][cells[topolist[i]].outpins[j]].fRAT_ofs
<< endl;
cout << "-------------------------------------------------" << endl;
}
++k;
}
}
//CompareWithPT();
ExitPTimer();
one_rslk.clear();
one_fslk.clear();
one_rtran.clear();
one_ftran.clear();
one_rAAT.clear();
one_rRAT.clear();
cout << "Timer Evalulation 1---------------"<<endl;
cout << "False Count : "<< false_count<< "/" << false_count2 << " ( "<<count << " )"<< endl;
cout << "Max Rslk Diff : "<<max_rslk_diff <<endl;
cout << "Max Fslk Diff : "<<max_fslk_diff <<endl;
cout << "ISTA Avg. time : "<<time_avg <<endl;
cout << "ISTA Max. time : "<<time_max <<endl;
cout << "ISTA Max. cell : "<< cells[cellidx_max].name <<endl;
/*
SizeOut(false,"test");
ExitPTimer();
*/
printMemoryUsage();
if (ifDelete) {
for ( unsigned i=0; i < numViews; ++i ) {
delete [] pins[i];
}
for ( unsigned i=0; i < numCorners; ++i ) {
delete [] nets[i];
}
delete [] cells;
delete [] pins;
delete [] nets;
cells = NULL;
pins = NULL;
nets = NULL;
}
//if (CORR_PT) ExitPTimer();
}
//PT correlation test. report slack error at every cell changes.
void Sizer::PTCorrTest(unsigned view)
{
cout << "[PTCorrTest] ..." << endl;
bool ifDelete = true;
cells = new CELL[numcells];
for(unsigned i=0 ; i<numcells ; i++) {
cells[i] = g_cells[i];
}
pins= new PIN*[numViews];
for (unsigned i = 0; i < numViews; ++i ) {
pins[i] = new PIN[numpins];
for(unsigned j=0 ; j<numpins ; j++)
pins[i][j]=g_pins[i][j];
}
nets= new NET*[numCorners];
for (unsigned i = 0; i < numCorners; ++i ) {
nets[i] = new NET[numnets];
for(unsigned j=0 ; j<numnets ; j++)
nets[i][j]=g_nets[i][j];
}
ifDelete = true;
cout << "Verify Timer..." << endl;
//SizeIn("gtr");
PTimer = new designTiming** [1];
for (int i=0; i < 1; i++ ) {
PTimer[i] = new designTiming*[numViews];
for (int view=0; view < numViews; view++) {
cout << "Launch " << i*numViews+view << "th PT" << endl;
PTimer[i][view] = LaunchPTimer(i*numViews+view, view);
}
}
T = PTimer[0];
UpdatePTSizes();
UpdateCapsFromCells();
#ifdef USE_CEFF
CalcCeff();
#endif
double TMR=cpuTime();
CallTimer();
TMR=(cpuTime()-TMR);
cout << "full_STA_time : " << TMR << endl;
CalcStats();
unsigned count=0;
unsigned count_tmp=0;
vector<double> one_rslk;
vector<double> one_fslk;
vector<double> one_rtran;
vector<double> one_ftran;
vector<double> one_rAAT;
vector<double> one_rRAT;
double time_total = 0;
double time_max = 0;
CallTimer();
ReportSlackErr();
CallTimer();
ReportSlackErr();
CallTimer();
ReportSlackErr();
CallTimer();
ReportSlackErr();
/*
CompareWithPT();
CompareWithPT();
CallTimer();
CompareWithPT();
CallTimer();
CompareWithPT();
*/
cout << "# changed cells: " << count << "\t";
ReportSlackErr();
for(unsigned j=0 ; j<numcells*10 ; j++)
{
unsigned i = (unsigned) (rand()%4);
unsigned k = j%numcells;
if(isff(cells[k])) continue;
if(i == 0) {
if(r_size(cells[k])==128) continue;
cell_resize(cells[k], 1, true);
//cout << cells[k].name << " upsized " << endl ;
} else if (i == 1) {
if(r_size(cells[k])==1) continue;
cell_resize(cells[k], -1, true);
//cout << cells[k].name << " downsized " << endl;
} else if(i == 2) {
if(r_type(cells[k])==f) continue;
cell_retype(cells[k], 1, true);
//cout << cells[k].name << " uptyped " << endl;
} else {
if(r_type(cells[k])==s) continue;
cell_retype(cells[k], -1, true);
//cout << cells[k].name << " downtyped " << endl;
}
TMR=cpuTime();
#ifdef USE_CEFF
calc_pin_ceff(pins[view][cells[k].outpin]);
#endif
OneTimer (cells[k], .0, view);
//CallTimer();
//UpdatePTSizes();
TMR=(cpuTime()-TMR);
time_total += TMR;
if (TMR > time_max) {
time_max = TMR;
//cellidx_max = i;
}
if (count++ > numcells * 0.1) break;
if (count_tmp++ > numcells*0.01) {
cout << "# changed cells: " << count << "\t";
//UpdatePTSizes();
ReportSlackErr();
count_tmp = 0;
}
}
cout << "# changed cells: " << count << "\t";
//UpdatePTSizes();
ReportSlackErr();
ExitPTimer();
printMemoryUsage();
if (ifDelete) {
for ( unsigned i=0; i < numViews; ++i ) {
delete [] pins[i];
}
for ( unsigned i=0; i < numCorners; ++i ) {
delete [] nets[i];
}
delete [] cells;
delete [] pins;
delete [] nets;
cells = NULL;
pins = NULL;
nets = NULL;
}
}
void Sizer::TimerOffsetTest(unsigned view)
{
cout << "[TimerOffsetTest] Evalulate STA..." << endl;
bool ifDelete = true;
cells = new CELL[numcells];
for(unsigned i=0 ; i<numcells ; i++)
cells[i] = g_cells[i];
pins= new PIN*[numViews];
for (unsigned i = 0; i < numViews; ++i ) {
pins[i] = new PIN[numpins];
for(unsigned j=0 ; j<numpins ; j++)
pins[i][j]=g_pins[i][j];
}
nets= new NET*[numCorners];
for (unsigned i = 0; i < numCorners; ++i ) {
nets[i] = new NET[numnets];
for(unsigned j=0 ; j<numnets ; j++)
nets[i][j]=g_nets[i][j];
}
ifDelete = true;
cout << "Verify Timer..." << endl;
SizeIn("gtr");
UpdateCapsFromCells();
CallTimer();
CalcStats();
double TMR=cpuTime();
CalcCeff();
LaunchPTimer(0);
UpdatePTSizes();
// initial correlation with PT
TMR=(cpuTime()-TMR);
cout << "full_STA_time : " << TMR << endl;
unsigned count=0;
//unsigned false_count=0;
//double max_rslk_diff=0.;
//double max_fslk_diff=0.;
unsigned numChange = numcells*10;
unsigned step = 1;
cout << "== Cell Change Test ==" << endl;
ReportTimingErr();
for(unsigned j=0 ; j<numChange ; j++)
{
unsigned i = (unsigned) (rand()%4);
unsigned k = rand()%numcells;
if(isff(cells[k])) continue;
if(i == 0) {
if(r_size(cells[k])==128) continue;
cell_resize(cells[k], 1);
//cout << cells[k].name << " upsized " << endl ;
} else if (i == 1) {
if(r_size(cells[k])==1) continue;
cell_resize(cells[k], -1);
//cout << cells[k].name << " downsized " << endl;
} else if(i == 2) {
if(r_type(cells[k])==f) continue;
cell_retype(cells[k], 1);
//cout << cells[k].name << " uptyped " << endl;
} else {
if(r_type(cells[k])==s) continue;
cell_retype(cells[k], -1);
//cout << cells[k].name << " downtyped " << endl;
}
count++;
if (CAP_METRIC == CEFFMC)
calc_pin_ceff_MC(pins[view][cells[k].outpin]);
else if (CAP_METRIC == CEFFKM)
// TODO: To be updated
calc_pin_ceff_MC(pins[view][cells[k].outpin]);
else if (CAP_METRIC == CTOT)
pins[view][cells[k].outpin].ceff = pins[view][cells[k].outpin].totcap;
OneTimer (cells[k], .0, view);
ReportTimingErr();
// if ( (unsigned)count*100/numcells==step ) {
// cout << fixed << step << "(%) ";
// step++;
// }
if (step > 10) break;
}
ExitPTimer();
if (ifDelete) {
for ( unsigned i=0; i < numViews; ++i ) {
delete [] pins[i];
}
for ( unsigned i=0; i < numCorners; ++i ) {
delete [] nets[i];
}
delete [] cells;
delete [] pins;
delete [] nets;
cells = NULL;
pins = NULL;
nets = NULL;
}
}
void Sizer::WireDelayTest(unsigned view)
{
unsigned corner = mmmcViewList[view].corner;
cout << "[Test] Wire delay test..." << endl;
cells = new CELL[numcells];
for(unsigned i=0 ; i<numcells ; i++) {
cells[i] = g_cells[i];
}
pins= new PIN*[numViews];
for (unsigned i = 0; i < numViews; ++i ) {
pins[i] = new PIN[numpins];
for(unsigned j=0 ; j<numpins ; j++)
pins[i][j]=g_pins[i][j];
}
nets= new NET*[numCorners];
for (unsigned i = 0; i < numCorners; ++i ) {
nets[i] = new NET[numnets];
for(unsigned j=0 ; j<numnets ; j++)
nets[i][j]=g_nets[i][j];
}
UpdateCapsFromCells();
CallTimer();
LaunchPTimer(0);
UpdatePTSizes();
cout << setw(8) << "NetName" \
<< " " << setw(8) << "InPin" \
<< " " << setw(8) << "OutPin" \
<< " " << setw(8) << fixed << "PtDelayR" \
<< " " << setw(8) << fixed << "PtDelayF" \
<< " " << setw(8) << fixed << "EMDelay" \
<< " " << setw(8) << fixed << "D2MDelay" \
<< " " << setw(8) << fixed << "TriDelay" \
<< " " << setw(8) << fixed << "Err" \
<< " " << setw(8) << fixed << "InSlew" \
<< " " << setw(8) << "NumFanout" \
<< " " << setw(8) << fixed << "InCap" \
<< " " << setw(8) << "Ceff" \
<< endl;
double maxErr = 0.0;
for (unsigned i = 0; i < numnets; i++) {
vector<SUB_NODE>& snv = nets[corner][i].subNodeVec;
if ( snv.size() == 0 ) continue;
for (unsigned j = 0; j < nets[corner][i].outpins.size(); j++) {
timing_lookup triDelay;
string in_pin_name;
string out_pin_name;
if (pins[view][nets[corner][i].inpin].owner != UINT_MAX) {
in_pin_name = cells[pins[view][nets[corner][i].inpin].owner].name+"/"+pins[view][nets[corner][i].inpin].name;
} else {
in_pin_name = pins[view][nets[corner][i].inpin].name;
}
if (pins[view][nets[corner][i].outpins[j]].owner != UINT_MAX) {
out_pin_name = cells[pins[view][nets[corner][i].outpins[j]].owner].name+"/"+pins[view][nets[corner][i].outpins[j]].name;
} else {
out_pin_name = pins[view][nets[corner][i].outpins[j]].name;
}
triDelay = get_wire_delay(i,nets[corner][i].outpins[j]);
// EM and D2M
double emDelay, d2mDelay;
emDelay = d2mDelay = 0.0;
for (unsigned k = 0; k < nets[corner][i].subNodeVec.size(); k++) {
if (nets[corner][i].subNodeVec[k].isSink && \
nets[corner][i].subNodeVec[k].pinId == nets[corner][i].outpins[j] ) {
emDelay = -nets[corner][i].subNodeVec[k].m1;
d2mDelay = nets[corner][i].subNodeVec[k].delay;
}
}
//T[view]->getNetDelay(ptDelay,in_pin_name,out_pin_name);
double ptDelayR, ptDelayF;
ptDelayR = ptDelayF = 0.0;
//T[view]->getNetDelay(ptDelay,in_pin_name,out_pin_name);
ptDelayR = T[view]->getRiseArrival(out_pin_name) - T[view]->getRiseArrival(in_pin_name);
ptDelayF = T[view]->getFallArrival(out_pin_name) - T[view]->getFallArrival(in_pin_name);
cout.precision(4);
cout << setw(8) << nets[corner][i].name \
<< " " << setw(8) << in_pin_name \
<< " " << setw(8) << out_pin_name \
<< " " << setw(8) << fixed << ptDelayR \
<< " " << setw(8) << fixed << ptDelayF \
<< " " << setw(8) << fixed << emDelay \
<< " " << setw(8) << fixed << d2mDelay \
<< " " << setw(8) << fixed << triDelay.rise \
<< " " << setw(8) << fixed << triDelay.rise-ptDelayR \
<< " " << setw(8) << fixed << T[view]->getRiseTran(in_pin_name) \
<< " " << setw(8) << nets[corner][i].outpins.size() \
<< " " << setw(8) << fixed << pins[view][nets[corner][i].inpin].totcap \
<< " " << setw(8) << fixed << T[view]->getCeff(in_pin_name) \
<< endl;
if (abs(maxErr) < abs(triDelay.rise-ptDelayR) ) maxErr=triDelay.rise - ptDelayR;
}
}
cout << setw(8) << "MaxErr" \
<< " " << setw(8) << "" \
<< " " << setw(8) << "" \
<< " " << setw(8) << fixed << "" \
<< " " << setw(8) << fixed << "" \
<< " " << setw(8) << fixed << "" \
<< " " << setw(8) << fixed << "" \
<< " " << setw(8) << fixed << maxErr \
<< " " << setw(8) << fixed << "" \
<< " " << setw(8) << "" \
<< " " << setw(8) << "" \
<< " " << setw(8) << fixed << "" \
<< " " << setw(8) << fixed << "" \
<< endl;
ExitPTimer();
printMemoryUsage();
}
void Sizer::ReportWireTiming(unsigned view)
{
unsigned corner = mmmcViewList[view].corner;
cout << "------------------------------------------------------------" << endl;
cout << " Wire Timing Report " << endl;
cout << "------------------------------------------------------------" << endl;
cout << "NetName\t" \
<< " " << setw(8) << "InPin" \
<< " " << setw(8) << "OutPin" \
<< " " << setw(8) << fixed << "PtSlkR" \
<< " " << setw(8) << fixed << "PtSlkF" \
<< " " << setw(8) << fixed << "TriSlkR" \
<< " " << setw(8) << fixed << "TriSlkF" \
<< " " << setw(8) << fixed << "ErrSlkR" \
<< " " << setw(8) << fixed << "ErrSlkF" \
<< " " << setw(8) << fixed << "PtTranR" \
<< " " << setw(8) << fixed << "PtTranF" \
<< " " << setw(8) << fixed << "TriTranR" \
<< " " << setw(8) << fixed << "TriTranF" \
<< " " << setw(8) << fixed << "ErrTranR" \
<< " " << setw(8) << fixed << "ErrTranF" \
<< " " << setw(8) << fixed << "PtDelayR" \
<< " " << setw(8) << fixed << "PtDelayF" \
<< " " << setw(8) << fixed << "TriDelayR" \
<< " " << setw(8) << fixed << "TriDelayF" \
<< " " << setw(8) << fixed << "ErrDelayR" \
<< " " << setw(8) << fixed << "ErrDelayF" \
<< endl;
double ptDelay;
timing_lookup triDelay;
double triDelayR, triDelayF, triSlkR, triSlkF, triTranR, triTranF, ptSlkR, ptSlkF, ptTranR, ptTranF;
double maxErrDelay, avgErrDelay, maxErrSlk, avgErrSlk, maxErrTran, avgErrTran;
unsigned count = 0;
maxErrDelay = avgErrDelay = maxErrSlk = avgErrSlk = maxErrTran = avgErrTran = 0.0;
for (unsigned i = 0; i < numnets; i++) {
string in_pin_name;
if (pins[view][nets[corner][i].inpin].owner != UINT_MAX) {
in_pin_name = cells[pins[view][nets[corner][i].inpin].owner].name+"/"+pins[view][nets[corner][i].inpin].name;
} else {
in_pin_name = pins[view][nets[corner][i].inpin].name;
}
triDelayR = triDelayF = triSlkR = triSlkF = triTranR = triTranF =0.0;
ptDelay = ptTranR = ptTranF = ptSlkR = ptSlkF = 0.0;
triSlkR = pins[view][nets[corner][i].inpin].rslk;
triSlkF = pins[view][nets[corner][i].inpin].fslk;
triTranR = pins[view][nets[corner][i].inpin].rtran;
triTranF = pins[view][nets[corner][i].inpin].ftran;
ptSlkR = T[view]->getRiseSlack(in_pin_name);
ptSlkF = T[view]->getFallSlack(in_pin_name);
ptTranR = T[view]->getRiseTran(in_pin_name);
ptTranF = T[view]->getFallTran(in_pin_name);
cout.precision(4);
cout << nets[corner][i].name \
<< "\t " << setw(8) << "*"+in_pin_name \
<< " " << setw(8) << "" \
<< " " << setw(8) << fixed << ptSlkR \
<< " " << setw(8) << fixed << ptSlkF \
<< " " << setw(8) << fixed << triSlkR \
<< " " << setw(8) << fixed << triSlkF \
<< " " << setw(8) << fixed << triSlkR - ptSlkR \
<< " " << setw(8) << fixed << triSlkF - ptSlkF\
<< " " << setw(8) << fixed << ptTranR \
<< " " << setw(8) << fixed << ptTranF \
<< " " << setw(8) << fixed << triTranR \
<< " " << setw(8) << fixed << triTranF \
<< " " << setw(8) << fixed << triTranR - ptTranR \
<< " " << setw(8) << fixed << triTranF - ptTranF\
<< " " << setw(8) << fixed << ptDelay \
<< " " << setw(8) << fixed << ptDelay \
<< " " << setw(8) << fixed << triDelayR \
<< " " << setw(8) << fixed << triDelayF \
<< " " << setw(8) << fixed << triDelayR - ptDelay \
<< " " << setw(8) << fixed << triDelayF - ptDelay \
<< endl;
if ( abs(maxErrDelay) < abs(triDelayR - ptDelay) ) maxErrDelay = triDelayR - ptDelay;
if ( abs(maxErrDelay) < abs(triDelayF - ptDelay) ) maxErrDelay = triDelayF - ptDelay;
avgErrDelay += triDelayR - ptDelay;
avgErrDelay += triDelayF - ptDelay;
if ( abs(maxErrTran) < abs(triTranR - ptTranR) ) maxErrTran = triTranR - ptTranR;
if ( abs(maxErrTran) < abs(triTranF - ptTranF) ) maxErrTran = triTranF - ptTranF;
avgErrTran += triTranR - ptTranR;
avgErrTran += triTranF - ptTranF;
if ( abs(maxErrSlk) < abs(triSlkR - ptSlkR) ) maxErrSlk = triSlkR - ptSlkR;
if ( abs(maxErrSlk) < abs(triSlkF - ptSlkF) ) maxErrSlk = triSlkF - ptSlkF;
avgErrSlk += triSlkR - ptSlkR;
avgErrSlk += triSlkF - ptSlkF;
for (unsigned j = 0; j < nets[corner][i].outpins.size(); j++) {
triDelayR = triDelayF = triSlkR = triSlkF = triTranR = triTranF =0.0;
ptDelay = ptTranR = ptTranF = ptSlkR = ptSlkF = 0.0;
string out_pin_name;
if (pins[view][nets[corner][i].outpins[j]].owner != UINT_MAX) {
out_pin_name = cells[pins[view][nets[corner][i].outpins[j]].owner].name+"/"+pins[view][nets[corner][i].outpins[j]].name;
} else {
out_pin_name = pins[view][nets[corner][i].outpins[j]].name;
}
triDelay = get_wire_delay(i,nets[corner][i].outpins[j]);
triDelayR = triDelay.rise;
triDelayF = triDelay.fall;
triSlkR = pins[view][nets[corner][i].outpins[j]].rslk;
triSlkF = pins[view][nets[corner][i].outpins[j]].fslk;
triTranR = pins[view][nets[corner][i].outpins[j]].rtran;
triTranF = pins[view][nets[corner][i].outpins[j]].ftran;
T[view]->getNetDelay(ptDelay,in_pin_name,out_pin_name);
ptSlkR = T[view]->getRiseSlack(out_pin_name);
ptSlkF = T[view]->getFallSlack(out_pin_name);
ptTranR = T[view]->getRiseTran(out_pin_name);
ptTranF = T[view]->getFallTran(out_pin_name);
cout.precision(4);
cout << nets[corner][i].name \
<< "\t " << setw(8) << in_pin_name \
<< " " << setw(8) << "*"+out_pin_name \
<< " " << setw(8) << fixed << ptSlkR \
<< " " << setw(8) << fixed << ptSlkF \
<< " " << setw(8) << fixed << triSlkR \
<< " " << setw(8) << fixed << triSlkF \
<< " " << setw(8) << fixed << triSlkR - ptSlkR \
<< " " << setw(8) << fixed << triSlkF - ptSlkF\
<< " " << setw(8) << fixed << ptTranR \
<< " " << setw(8) << fixed << ptTranF \
<< " " << setw(8) << fixed << triTranR \
<< " " << setw(8) << fixed << triTranF \
<< " " << setw(8) << fixed << triTranR - ptTranR \
<< " " << setw(8) << fixed << triTranF - ptTranF\
<< " " << setw(8) << fixed << ptDelay \
<< " " << setw(8) << fixed << ptDelay \
<< " " << setw(8) << fixed << triDelayR \
<< " " << setw(8) << fixed << triDelayF \
<< " " << setw(8) << fixed << triDelayR - ptDelay \
<< " " << setw(8) << fixed << triDelayF - ptDelay \
<< endl;
if ( abs(maxErrDelay) < abs(triDelayR - ptDelay) ) maxErrDelay = triDelayR - ptDelay;
if ( abs(maxErrDelay) < abs(triDelayF - ptDelay) ) maxErrDelay = triDelayF - ptDelay;
avgErrDelay += triDelayR - ptDelay;
avgErrDelay += triDelayF - ptDelay;
if ( abs(maxErrTran) < abs(triTranR - ptTranR) ) maxErrTran = triTranR - ptTranR;
if ( abs(maxErrTran) < abs(triTranF - ptTranF) ) maxErrTran = triTranF - ptTranF;
avgErrTran += triTranR - ptTranR;
avgErrTran += triTranF - ptTranF;
if ( abs(maxErrSlk) < abs(triSlkR - ptSlkR) ) maxErrSlk = triSlkR - ptSlkR;
if ( abs(maxErrSlk) < abs(triSlkF - ptSlkF) ) maxErrSlk = triSlkF - ptSlkF;
avgErrSlk += triSlkR - ptSlkR;
avgErrSlk += triSlkF - ptSlkF;
count +=2;
}
}
cout << "Summary\t" \
<< " " << setw(8) << "" \
<< " " << setw(8) << "" \
<< " " << setw(8) << fixed << "MaxSlkErr" \
<< " " << setw(8) << fixed << maxErrSlk \
<< " " << setw(8) << fixed << "AvgSlkErr" \
<< " " << setw(8) << fixed << avgErrSlk/(count+2*numnets) \
<< " " << setw(8) << fixed << "" \
<< " " << setw(8) << fixed << "" \
<< " " << setw(8) << fixed << "MaxTranErr" \
<< " " << setw(8) << fixed << maxErrTran \
<< " " << setw(8) << fixed << "AvgTranErr" \
<< " " << setw(8) << fixed << avgErrTran/(count+2*numnets) \
<< " " << setw(8) << fixed << "" \
<< " " << setw(8) << fixed << "" \
<< " " << setw(8) << fixed << "MaxDelayErr" \
<< " " << setw(8) << fixed << maxErrDelay \
<< " " << setw(8) << fixed << "AvgDelayErr" \
<< " " << setw(8) << fixed << avgErrDelay/count \
<< " " << setw(8) << fixed << "" \
<< " " << setw(8) << fixed << "" \
<< endl;
}
void Sizer::ReportTimingErr(unsigned view)
{
double absavgSlkErr, avgSlkErr, maxSlkErr;
avgSlkErr = 0.0;
absavgSlkErr = 0.0;
maxSlkErr = 0.0;
double diff = 0.0;
unsigned count = 0;
for(unsigned i=0 ; i<numcells ; i++)
{
diff = pins[view][cells[i].outpin].rslk - T[view]->getRiseSlack(cells[i].name+"/"+pins[view][cells[i].outpin].name);
avgSlkErr += diff;
absavgSlkErr += abs(diff);
count ++;
if ( abs(maxSlkErr) < abs(diff) )
maxSlkErr = diff;
diff = pins[view][cells[i].outpin].fslk - T[view]->getFallSlack(cells[i].name+"/"+pins[view][cells[i].outpin].name);
avgSlkErr += diff;
absavgSlkErr += abs(diff);
count ++;
if ( abs(maxSlkErr) < abs(diff) )
maxSlkErr = diff;
for(unsigned j=0 ; j<cells[i].inpins.size() ; j++) {
if(isff(cells[i]) && pins[view][cells[i].inpins[j]].name == "ck") continue;
diff = pins[view][cells[i].inpins[j]].rslk - T[view]->getRiseSlack(cells[i].name+"/"+pins[view][cells[i].inpins[j]].name);
avgSlkErr += diff;
absavgSlkErr += abs(diff);
count ++;
if ( abs(maxSlkErr) < abs(diff) )
maxSlkErr = diff;
diff = pins[view][cells[i].inpins[j]].fslk - T[view]->getFallSlack(cells[i].name+"/"+pins[view][cells[i].inpins[j]].name);
avgSlkErr += diff;
absavgSlkErr += abs(diff);
count ++;
if ( abs(maxSlkErr) < abs(diff) )
maxSlkErr = diff;
}
}
for(unsigned i=0 ; i<PIs.size() ; i++) {
if ( pins[view][PIs[i]].name == "ispd_clk" ) continue;
diff = pins[view][PIs[i]].rslk - T[view]->getRiseSlack(pins[view][PIs[i]].name);
avgSlkErr += diff;
absavgSlkErr += abs(diff);
count ++;
if ( abs(maxSlkErr) < abs(diff) )
maxSlkErr = diff;
diff = pins[view][PIs[i]].fslk - T[view]->getFallSlack(pins[view][PIs[i]].name);
avgSlkErr += diff;
absavgSlkErr += abs(diff);
count ++;
if ( abs(maxSlkErr) < abs(diff) )
maxSlkErr = diff;
}
for(unsigned i=0 ; i<POs.size() ; i++) {
diff = pins[view][POs[i]].rslk - T[view]->getRiseSlack(pins[view][POs[i]].name);
avgSlkErr += diff;
absavgSlkErr += abs(diff);
count ++;
if ( abs(maxSlkErr) < abs(diff) )
maxSlkErr = diff;
diff = pins[view][POs[i]].fslk - T[view]->getFallSlack(pins[view][POs[i]].name);
avgSlkErr += diff;
absavgSlkErr += abs(diff);
count ++;
if ( abs(maxSlkErr) < abs(diff) )
maxSlkErr = diff;
}
avgSlkErr = avgSlkErr/count;
absavgSlkErr = absavgSlkErr/count;
cout.precision(4);
cout << setw(8) << fixed << avgSlkErr \
<< " " << setw(8) << fixed << absavgSlkErr \
<< " " << setw(8) << fixed << maxSlkErr << endl;
}
void Sizer::CompareWithPT(unsigned view)
{
cout << endl << "# pin timing" << endl << endl;
for(unsigned i=0 ; i<numcells ; i++)
{
cout << "Trident : " << cells[i].name << "/"
<< pins[view][cells[i].outpin].name << " "
<< pins[view][cells[i].outpin].rslk << " "
<< pins[view][cells[i].outpin].fslk << " "
<< pins[view][cells[i].outpin].rtran << " "
<< pins[view][cells[i].outpin].ftran << " "
<< pins[view][cells[i].outpin].rAAT << " "
<< pins[view][cells[i].outpin].fAAT << " "
<< pins[view][cells[i].outpin].rRAT << " "
<< pins[view][cells[i].outpin].fRAT << " "
<< pins[view][cells[i].outpin].ceff << endl;
cout << "PrimeTime : " << cells[i].name << "/"
<< pins[view][cells[i].outpin].name << " "
<< T[view]->getRiseSlack(cells[i].name+"/"+pins[view][cells[i].outpin].name) << " "
<< T[view]->getFallSlack(cells[i].name+"/"+pins[view][cells[i].outpin].name) << " "
<< T[view]->getRiseTran(cells[i].name+"/"+pins[view][cells[i].outpin].name) << " "
<< T[view]->getFallTran(cells[i].name+"/"+pins[view][cells[i].outpin].name) << " "
<< T[view]->getRiseArrival(cells[i].name+"/"+pins[view][cells[i].outpin].name) << " "
<< T[view]->getFallArrival(cells[i].name+"/"+pins[view][cells[i].outpin].name) << " "
<< T[view]->getRiseArrival(cells[i].name+"/"+pins[view][cells[i].outpin].name) + T[view]->getRiseSlack(cells[i].name+"/"+pins[view][cells[i].outpin].name) << " "
<< T[view]->getFallArrival(cells[i].name+"/"+pins[view][cells[i].outpin].name) + T[view]->getFallSlack(cells[i].name+"/"+pins[view][cells[i].outpin].name) << " "
<< T[view]->getCeff(cells[i].name+"/"+pins[view][cells[i].outpin].name) << endl;
for(unsigned j=0 ; j<cells[i].inpins.size() ; j++) {
//if(isff(cells[i]) && pins[view][cells[i].inpins[j]].name == "ck") continue;
cout << "Trident : " << cells[i].name << "/" << pins[view][cells[i].inpins[j]].name << " "
<< pins[view][cells[i].inpins[j]].rslk << " "
<< pins[view][cells[i].inpins[j]].fslk << " "
<< pins[view][cells[i].inpins[j]].rtran << " "
<< pins[view][cells[i].inpins[j]].ftran << " "
<< pins[view][cells[i].inpins[j]].rAAT << " "
<< pins[view][cells[i].inpins[j]].fAAT << " "
<< pins[view][cells[i].inpins[j]].rRAT << " "
<< pins[view][cells[i].inpins[j]].fRAT
<< endl;
cout << "PrimeTime : " << cells[i].name << "/" << pins[view][cells[i].inpins[j]].name << " "
<< T[view]->getRiseSlack(cells[i].name+"/"+pins[view][cells[i].inpins[j]].name) << " "
<< T[view]->getFallSlack(cells[i].name+"/"+pins[view][cells[i].inpins[j]].name) << " "
<< T[view]->getRiseTran(cells[i].name+"/"+pins[view][cells[i].inpins[j]].name) << " "
<< T[view]->getFallTran(cells[i].name+"/"+pins[view][cells[i].inpins[j]].name) << " "
<< T[view]->getRiseArrival(cells[i].name+"/"+pins[view][cells[i].inpins[j]].name) << " "
<< T[view]->getFallArrival(cells[i].name+"/"+pins[view][cells[i].inpins[j]].name) << " "
<< T[view]->getRiseArrival(cells[i].name+"/"+pins[view][cells[i].inpins[j]].name) + T[view]->getRiseSlack(cells[i].name+"/"+pins[view][cells[i].inpins[j]].name) << " "
<< T[view]->getFallArrival(cells[i].name+"/"+pins[view][cells[i].inpins[j]].name) + T[view]->getFallSlack(cells[i].name+"/"+pins[view][cells[i].inpins[j]].name) << " "
<< endl;
}
}
cout << endl << "# port timing" << endl << endl;
for(unsigned i=0 ; i<PIs.size() ; i++) {
//if ( pins[view][PIs[i]].name == "ispd_clk" ) continue;
cout << "Trident : "
<< pins[view][PIs[i]].name << " "
<< pins[view][PIs[i]].rslk << " "
<< pins[view][PIs[i]].fslk << " "
<< pins[view][PIs[i]].rtran << " "
<< pins[view][PIs[i]].ftran << " "
<< pins[view][PIs[i]].rAAT << " "
<< pins[view][PIs[i]].fAAT << " " << pins[view][PIs[i]].ceff << endl;
cout << "PrimeTime : "
<< pins[view][PIs[i]].name << " "
<< T[view]->getRiseSlack(pins[view][PIs[i]].name) << " "
<< T[view]->getFallSlack(pins[view][PIs[i]].name) << " "
<< T[view]->getRiseTran(pins[view][PIs[i]].name) << " "
<< T[view]->getFallTran(pins[view][PIs[i]].name) << " "
<< T[view]->getRiseArrival(pins[view][PIs[i]].name) << " "
<< T[view]->getFallArrival(pins[view][PIs[i]].name) << " "
<< T[view]->getCeff(pins[view][PIs[i]].name) << endl;
}
for(unsigned i=0 ; i<POs.size() ; i++) {
cout << "Trident : "
<< pins[view][POs[i]].name << " "
<< pins[view][POs[i]].rslk << " "
<< pins[view][POs[i]].fslk << " "
<< pins[view][POs[i]].rtran << " "
<< pins[view][POs[i]].ftran << " "
<< pins[view][POs[i]].rAAT << " "
<< pins[view][POs[i]].fAAT << endl;
cout << "PrimeTime : "
<< pins[view][POs[i]].name << " "
<< T[view]->getRiseSlack(pins[view][POs[i]].name) << " "
<< T[view]->getFallSlack(pins[view][POs[i]].name) << " "
<< T[view]->getRiseTran(pins[view][POs[i]].name) << " "
<< T[view]->getFallTran(pins[view][POs[i]].name) << " "
<< T[view]->getRiseArrival(pins[view][POs[i]].name) << " "
<< T[view]->getFallArrival(pins[view][POs[i]].name) << endl;
}
}
void Sizer::ReportTiming(unsigned view)
{
cout << endl << "# pin timing" << endl << endl;
for(unsigned i=0 ; i<numcells ; i++)
{
cout << "Trident : " << cells[i].name << "/"
<< pins[view][cells[i].outpin].name << " "
<< pins[view][cells[i].outpin].rslk << " "
<< pins[view][cells[i].outpin].fslk << " "
<< pins[view][cells[i].outpin].rtran << " "
<< pins[view][cells[i].outpin].ftran << " "
<< pins[view][cells[i].outpin].rAAT << " "
<< pins[view][cells[i].outpin].fAAT << " "
<< pins[view][cells[i].outpin].ceff << endl;
for(unsigned j=0 ; j<cells[i].inpins.size() ; j++) {
//if(isff(cells[i]) && pins[view][cells[i].inpins[j]].name == "ck") continue;
cout << "Trident : " << cells[i].name << "/" << pins[view][cells[i].inpins[j]].name << " " << pins[view][cells[i].inpins[j]].rslk << " " << pins[view][cells[i].inpins[j]].fslk <<" " << pins[view][cells[i].inpins[j]].rtran << " " << pins[view][cells[i].inpins[j]].ftran << " " << pins[view][cells[i].inpins[j]].rAAT << " " << pins[view][cells[i].inpins[j]].fAAT << endl;
}
}
cout << endl << "# port timing" << endl << endl;
for(unsigned i=0 ; i<PIs.size() ; i++) {
//if ( pins[view][PIs[i]].name == "ispd_clk" ) continue;
cout << "Trident : " << pins[view][PIs[i]].name << " " << pins[view][PIs[i]].rslk << " " << pins[view][PIs[i]].fslk << " " << pins[view][PIs[i]].rtran << " " << pins[view][PIs[i]].ftran << " " << pins[view][PIs[i]].rAAT << " " << pins[view][PIs[i]].fAAT << " " << pins[view][PIs[i]].ceff << endl;
}
for(unsigned i=0 ; i<POs.size() ; i++) {
cout << "Trident : " << pins[view][POs[i]].name << " " << pins[view][POs[i]].rslk << " " << pins[view][POs[i]].fslk << " " << pins[view][POs[i]].rtran << " " << pins[view][POs[i]].ftran << " " << pins[view][POs[i]].rAAT << " " << pins[view][POs[i]].fAAT << endl;
}
}
void Sizer::ReportTimingStat(bool verbose, unsigned max_num_test, unsigned view)
{
unsigned corner = mmmcViewList[view].corner;
#ifdef WORST_TEST
vector<string> wst_pin_list;
string filename = benchname+"."+"wst_wire_delay"+".list";
string pin;
ifstream infile(filename.c_str());
if (!infile) {
cout << "-E-: Could not open '" << filename << "'" << endl;
ExitPTimer();
exit(1);
}
// Read the entire file
while (!infile.eof()) {
infile >> pin;
wst_pin_list.push_back(pin);
}
infile.close();
#endif
cout << "------------------------------" << endl;
cout << "| Timing Error Statistics |" << endl;
cout << "------------------------------" << endl;
cout << endl;
if ( verbose ) {
cout << setw(4) << "R/F" \
//<< " " << setw(8) << "CellName" \
//
<< " " << setw(8) << "CellDPt" \
<< " " << setw(8) << "CellDTri" \
<< " " << setw(8) << "CellDErr" \
<< " " << setw(8) << "CellTrPt" \
<< " " << setw(8) << "CellTrTri" \
<< " " << setw(8) << "CellTrErr" \
<< " " << setw(8) << "WireDPt" \
<< " " << setw(8) << "WireDTri" \
<< " " << setw(8) << "WireDErr" \
<< " " << setw(8) << "WireTrPt" \
<< " " << setw(8) << "WireTrTri" \
<< " " << setw(8) << "WireTrErr" \
<< " " << setw(8) << "CeffErr" \
<< endl;
} else {
cout << setw(8) << "CellDAvg" \
<< " " << setw(8) << "CellDAAvg" \
<< " " << setw(8) << "CellDMax" \
<< " " << setw(8) << "CellTrAvg" \
<< " " << setw(8) << "CellTrAAvg" \
<< " " << setw(8) << "CellTrMax" \
<< " " << setw(8) << "WireDAvg" \
<< " " << setw(8) << "WireDAAvg" \
<< " " << setw(8) << "WireDMax" \
<< " " << setw(8) << "WireTrAvg" \
<< " " << setw(8) << "WireTrAAvg" \
<< " " << setw(8) << "WireTrMax" \
<< " " << setw(8) << "CeffErr" \
<< " " << setw(8) << "TotCap/PtCeff" \
<< endl;
}
double maxErrCellDelay, avgErrCellDelay, maxErrCellTran, avgErrCellTran, maxErrWireDelay, avgErrWireDelay, maxErrWireTran, avgErrWireTran;
double absAvgErrCellDelay, absAvgErrCellTran, absAvgErrWireDelay, absAvgErrWireTran;
double avgErrCeff, triCeff, ptCeff;
avgErrCeff = triCeff = ptCeff = 0.0;
unsigned count = 0;
unsigned cell_count = 0;
maxErrCellDelay = avgErrCellDelay = maxErrCellTran = avgErrCellTran = maxErrWireDelay = avgErrWireDelay = maxErrWireTran = avgErrWireTran = 0.0;
absAvgErrCellDelay = absAvgErrCellTran = absAvgErrWireDelay = absAvgErrWireTran = 0.0;
unsigned numtest = 0;
if ( max_num_test < numnets) {
numtest = max_num_test;
} else {
numtest = numnets;
}
for (unsigned i_test = 0; i_test < numtest; i_test++) {
unsigned i = 0;
if ( max_num_test > 0 ) {
i = (unsigned) rand() % numnets;
} else {
i = i_test;
}
if ( nets[corner][i].name == clk_port[0] ) continue;
for (unsigned j = 0; j < nets[corner][i].outpins.size(); j++) {
timing_lookup triWireDelay, triWireTran, ptWireDelay, ptWireTran;
vector <timing_lookup> triCellDelay, ptCellDelay, triCellTran, ptCellTran, triInTran, ptInTran;
vector <string> triCellName;
string in_pin_name;
string out_pin_name;
if (pins[view][nets[corner][i].inpin].owner != UINT_MAX) {
in_pin_name = cells[pins[view][nets[corner][i].inpin].owner].name+"/"+pins[view][nets[corner][i].inpin].name;
} else {
in_pin_name = pins[view][nets[corner][i].inpin].name;
}
if (pins[view][nets[corner][i].outpins[j]].owner != UINT_MAX) {
out_pin_name = cells[pins[view][nets[corner][i].outpins[j]].owner].name+"/"+pins[view][nets[corner][i].outpins[j]].name;
} else {
out_pin_name = pins[view][nets[corner][i].outpins[j]].name;
}
#ifdef WORST_TEST
bool found = false;
for(unsigned k=0; k<wst_pin_list.size(); k++) {
if ( out_pin_name == wst_pin_list[k] ) {
found = true;
break;
}
}
if (!found) continue;
#endif
// Report
if ( pins[view][nets[corner][i].inpin].owner != UINT_MAX && !isff(cells[pins[view][nets[corner][i].inpin].owner])) {
getCellDelaySlew(cells[pins[view][nets[corner][i].inpin].owner],triCellDelay,triCellTran,triInTran,0);
getCellDelaySlew(cells[pins[view][nets[corner][i].inpin].owner],ptCellDelay,ptCellTran,ptInTran,1);
} else {
timing_lookup triCellDelayTmp, ptCellDelayTmp;
timing_lookup triCellTranTmp, ptCellTranTmp;
//triCellName.push_back(cells[pins[view][nets[corner][i].inpin].owner].name);
triCellDelay.push_back(triCellDelayTmp);
ptCellDelay.push_back(ptCellDelayTmp);
triCellTran.push_back(triCellTranTmp);
ptCellTran.push_back(ptCellTranTmp);
}
triCeff = pins[view][nets[corner][i].inpin].ceff;
ptCeff = T[view]->getCeff(in_pin_name);
triWireDelay = get_wire_delay(i,nets[corner][i].outpins[j]);
triWireTran.rise = pins[view][nets[corner][i].outpins[j]].rtran;
triWireTran.fall = pins[view][nets[corner][i].outpins[j]].ftran;
ptWireDelay.rise = T[view]->getRiseArrival(out_pin_name) - T[view]->getRiseArrival(in_pin_name);
ptWireDelay.fall = T[view]->getFallArrival(out_pin_name) - T[view]->getFallArrival(in_pin_name);
ptWireTran.rise = T[view]->getRiseTran(out_pin_name);
ptWireTran.fall = T[view]->getFallTran(out_pin_name);
for (unsigned k = 0; k < triCellDelay.size(); k++ ) {
if ( verbose ) {
cout.precision(4);
cout << setw(4) << "R" \
//<< " " << setw(8) << fixed << triCellName[k] \
//
<< " " << setw(8) << fixed << ptCellDelay[k].rise \
<< " " << setw(8) << fixed << triCellDelay[k].rise \
<< " " << setw(8) << fixed << triCellDelay[k].rise - ptCellDelay[k].rise \
<< " " << setw(8) << fixed << ptCellTran[k].rise \
<< " " << setw(8) << fixed << triCellTran[k].rise \
<< " " << setw(8) << fixed << triCellTran[k].rise - ptCellTran[k].rise \
<< " " << setw(8) << fixed << ptWireDelay.rise \
<< " " << setw(8) << fixed << triWireDelay.rise \
<< " " << setw(8) << fixed << triWireDelay.rise - ptWireDelay.rise \
<< " " << setw(8) << fixed << ptWireTran.rise \
<< " " << setw(8) << fixed << triWireTran.rise \
<< " " << setw(8) << fixed << triWireTran.rise - ptWireTran.rise \
<< " " << setw(8) << fixed << triCeff/ptCeff \
<< " " << setw(8) << fixed << pins[view][nets[corner][i].inpin].totcap/ptCeff \
<< endl;
cout << setw(4) << "F" \
//<< " " << setw(8) << fixed << triCellName[k] \
//
<< " " << setw(8) << fixed << ptCellDelay[k].fall \
<< " " << setw(8) << fixed << triCellDelay[k].fall \
<< " " << setw(8) << fixed << triCellDelay[k].fall - ptCellDelay[k].fall \
<< " " << setw(8) << fixed << ptCellTran[k].fall \
<< " " << setw(8) << fixed << triCellTran[k].fall \
<< " " << setw(8) << fixed << triCellTran[k].fall - ptCellTran[k].fall \
<< " " << setw(8) << fixed << ptWireDelay.fall \
<< " " << setw(8) << fixed << triWireDelay.fall \
<< " " << setw(8) << fixed << triWireDelay.fall - ptWireDelay.fall \
<< " " << setw(8) << fixed << ptWireTran.fall \
<< " " << setw(8) << fixed << triWireTran.fall \
<< " " << setw(8) << fixed << triWireTran.fall - ptWireTran.fall \
<< " " << setw(8) << fixed << triCeff/ptCeff \
<< " " << setw(8) << fixed << pins[view][nets[corner][i].inpin].totcap/ptCeff \
<< endl;
}
if ( abs(maxErrCellDelay) < abs(triCellDelay[k].rise - ptCellDelay[k].rise) ) {
maxErrCellDelay = triCellDelay[k].rise - ptCellDelay[k].rise;
}
if ( abs(maxErrCellDelay) < abs(triCellDelay[k].fall - ptCellDelay[k].fall) ) {
maxErrCellDelay = triCellDelay[k].fall - ptCellDelay[k].fall;
}
avgErrCellDelay += triCellDelay[k].rise - ptCellDelay[k].rise;
avgErrCellDelay += triCellDelay[k].fall - ptCellDelay[k].fall;
absAvgErrCellDelay += abs(triCellDelay[k].rise - ptCellDelay[k].rise);
absAvgErrCellDelay += abs(triCellDelay[k].fall - ptCellDelay[k].fall);
if ( abs(maxErrCellTran) < abs(triCellTran[k].rise - ptCellTran[k].rise) ) {
maxErrCellTran = triCellTran[k].rise - ptCellTran[k].rise;
}
if ( abs(maxErrCellTran) < abs(triCellTran[k].fall - ptCellTran[k].fall) ) {
maxErrCellTran = triCellTran[k].fall - ptCellTran[k].fall;
}
avgErrCellTran += triCellTran[k].rise - ptCellTran[k].rise;
avgErrCellTran += triCellTran[k].fall - ptCellTran[k].fall;
absAvgErrCellTran += abs(triCellTran[k].rise - ptCellTran[k].rise);
absAvgErrCellTran += abs(triCellTran[k].fall - ptCellTran[k].fall);
cell_count += 2;
}
avgErrCeff += triCeff/ptCeff;
if ( abs(maxErrWireDelay) < abs(triWireDelay.rise - ptWireDelay.rise) ) {
maxErrWireDelay = triWireDelay.rise - ptWireDelay.rise;
}
if ( abs(maxErrWireDelay) < abs(triWireDelay.fall - ptWireDelay.fall) ) {
maxErrWireDelay = triWireDelay.fall - ptWireDelay.fall;
}
avgErrWireDelay += triWireDelay.rise - ptWireDelay.rise;
avgErrWireDelay += triWireDelay.fall - ptWireDelay.fall;
absAvgErrWireDelay += abs(triWireDelay.rise - ptWireDelay.rise);
absAvgErrWireDelay += abs(triWireDelay.fall - ptWireDelay.fall);
if ( abs(maxErrWireTran) < abs(triWireTran.rise - ptWireTran.rise) ) {
maxErrWireTran = triWireTran.rise - ptWireTran.rise;
}
if ( abs(maxErrWireTran) < abs(triWireTran.fall - ptWireTran.fall) ) {
maxErrWireTran = triWireTran.fall - ptWireTran.fall;
}
avgErrWireTran += triWireTran.rise - ptWireTran.rise;
avgErrWireTran += triWireTran.fall - ptWireTran.fall;
absAvgErrWireTran += abs(triWireTran.rise - ptWireTran.rise);
absAvgErrWireTran += abs(triWireTran.fall - ptWireTran.fall);
count +=2;
} //each arc
} //each net
cout.precision(4);
cout << "Summary\t" \
<< " " << setw(8) << fixed << maxErrCellDelay \
<< " " << setw(8) << fixed << avgErrCellDelay/(double)(cell_count) \
<< " " << setw(8) << fixed << absAvgErrCellDelay/(double)(cell_count) \
<< " " << setw(8) << fixed << maxErrCellTran \
<< " " << setw(8) << fixed << avgErrCellTran/(double)(cell_count) \
<< " " << setw(8) << fixed << absAvgErrCellTran/(double)(cell_count) \
<< " " << setw(8) << fixed << maxErrWireDelay \
<< " " << setw(8) << fixed << avgErrWireDelay/(double)count \
<< " " << setw(8) << fixed << absAvgErrWireDelay/(double)count \
<< " " << setw(8) << fixed << maxErrWireTran \
<< " " << setw(8) << fixed << absAvgErrWireTran/(double)(count) \
<< " " << setw(8) << fixed << absAvgErrWireTran/(double)(count) \
<< " " << setw(8) << fixed << avgErrCeff/(double)(count/2) \
<< endl;
}
void Sizer::ReportTimingStat(unsigned view)
{
cout << "[Test] report timing statistics ..." << endl;
cells = new CELL[numcells];
for(unsigned i=0 ; i<numcells ; i++)
cells[i]=g_cells[i];
pins= new PIN*[numViews];
for (unsigned i = 0; i < numViews; ++i ) {
pins[i] = new PIN[numpins];
for(unsigned j=0 ; j<numpins ; j++)
pins[i][j]=g_pins[i][j];
}
nets= new NET*[numCorners];
for (unsigned i = 0; i < numCorners; ++i ) {
nets[i] = new NET[numnets];
for(unsigned j=0 ; j<numnets ; j++)
nets[i][j]=g_nets[i][j];
}
SizeIn("gtr");
UpdateCapsFromCells();
CalcStats();
PTimer = new designTiming** [1];
for (int i=0; i < 1; i++ ) {
PTimer[i] = new designTiming*[numViews];
for (int view=0; view < numViews; view++) {
cout << "Launch " << i*numViews+view << "th PT" << endl;
PTimer[i][view] = LaunchPTimer(i*numViews+view, view);
}
}
T = PTimer[0];
UpdatePTSizes();
cout << "WNS(PT): " << T[view]->getWorstSlack("mclk") << endl;
//CallTimerTest();
/*
unsigned clock_index = 0;
for (unsigned i=0 ; i <numcells; ++i) {
if (isff(cells[i])) {
for(unsigned j=0 ; j<cells[i].inpins.size() ; j++)
{
clock_index = UINT_MAX;
if (libs[cells[i].type].pins[view][pins[view][cells[i].inpins[j]].name].isClock) {
clock_index = j;
break;
}
}
double rtran_PT, ftran_PT;
T[view]->getPinTran(rtran_PT, ftran_PT, getFullPinName(pins[view][cells[i].inpins[clock_index]]));
pins[view][cells[i].inpins[clock_index]].rtran = rtran_PT;
pins[view][cells[i].inpins[clock_index]].ftran = ftran_PT;
PIN & pin = pins[view][cells[i].inpins[clock_index]];
cout << "CP PIN TRAN UPDATE " << getFullPinName(pin) << " " << pin.rtran << "/" << pin.ftran << "--" << T[view]->getRiseTran(getFullPinName(pins[view][cells[i].inpins[clock_index]])) <<"/" << T[view]->getFallTran(getFullPinName(pins[view][cells[i].inpins[clock_index]]))<< endl;
}
}
*/
CallTimer();
CompareWithPT();
//ReportTimingStat(false);
ReportTimingStat(true,2000);
ExitPTimer();
for ( unsigned i=0; i < numViews; ++i ) {
delete [] pins[i];
}
for ( unsigned i=0; i < numCorners; ++i ) {
delete [] nets[i];
}
delete [] cells;
delete [] pins;
delete [] nets;
}
// TEST5
void Sizer::ReportDeltaTimingStat(unsigned view)
{
cout << "[Test] report timing statistics ..." << endl;
double begin = cpuTime();
cells = new CELL[numcells];
for(unsigned i=0 ; i<numcells ; i++)
cells[i]=g_cells[i];
pins= new PIN*[numViews];
for (unsigned i = 0; i < numViews; ++i ) {
pins[i] = new PIN[numpins];
for(unsigned j=0 ; j<numpins ; j++)
pins[i][j]=g_pins[i][j];
}
nets= new NET*[numCorners];
for (unsigned i = 0; i < numCorners; ++i ) {
nets[i] = new NET[numnets];
for(unsigned j=0 ; j<numnets ; j++)
nets[i][j]=g_nets[i][j];
}
SizeIn("gtr");
UpdateCapsFromCells();
CallTimer();
CalcStats();
LaunchPTimer(0);
UpdatePTSizes();
// cout << "WNS(PT): " << T[view]->getWorstSlack("mclk") << endl;
// cell move starts
//
int count = 0;
for(unsigned j=0 ; j<numcells*10 ; j++)
{
unsigned i = (unsigned) (rand()%4);
unsigned k = j%numcells;
if(isff(cells[k])) continue;
if(i == 0) {
if(r_size(cells[k])==128) continue;
cell_resize(cells[k], 1);
//cout << cells[k].name << " upsized " << endl ;
} else if (i == 1) {
if(r_size(cells[k])==1) continue;
cell_resize(cells[k], -1);
//cout << cells[k].name << " downsized " << endl;
} else if(i == 2) {
if(r_type(cells[k])==f) continue;
cell_retype(cells[k], 1);
//cout << cells[k].name << " uptyped " << endl;
} else {
if(r_type(cells[k])==s) continue;
cell_retype(cells[k], -1);
//cout << cells[k].name << " downtyped " << endl;
}
#ifdef USE_CEFF
calc_pin_ceff(pins[view][cells[i].outpin]);
#endif
//OneTimer(cells[k], STA_MARGIN);
OneTimer (cells[k], .0, view);
if (count++ > numcells * 0.01) break;
//if (count++ > 200) break;
}
double cpu_time=cpuTime()-begin;
cout << count << " cells changed" << endl;
//CompareWithPT();
//ReportTimingStat(false);
ReportTimingStat(true, 1000);
cout << "cpu time : " << cpu_time << endl;
ExitPTimer();
for ( unsigned i=0; i < numViews; ++i ) {
delete [] pins[i];
}
for ( unsigned i=0; i < numCorners; ++i ) {
delete [] nets[i];
}
delete [] cells;
delete [] pins;
delete [] nets;
}
void Sizer::Test2(unsigned view)
{
cells = new CELL[numcells];
for(unsigned i=0 ; i<numcells ; i++)
cells[i]=g_cells[i];
pins= new PIN*[numViews];
for (unsigned i = 0; i < numViews; ++i ) {
pins[i] = new PIN[numpins];
for(unsigned j=0 ; j<numpins ; j++)
pins[i][j]=g_pins[i][j];
}
nets= new NET*[numCorners];
for (unsigned i = 0; i < numCorners; ++i ) {
nets[i] = new NET[numnets];
for(unsigned j=0 ; j<numnets ; j++)
nets[i][j]=g_nets[i][j];
}
double WNS = 0.0;
SizeIn("gtr");
LaunchPTimer(0);
UpdatePTSizes(0);
UpdateCapsFromCells();
CallTimer();
CalcStats();
WNS = T[view]->getWorstSlack("mclk");
cout << "w/o file: wns/TNS/PWR : " << WNS << " " << skew_violation << " " << power << endl;
ExitPTimer();
CORR_PT_FILE = true;
SizeIn("gtr");
LaunchPTimer(0);
UpdatePTSizes(0);
UpdateCapsFromCells();
CallTimer();
CalcStats();
WNS = T[view]->getWorstSlack("mclk");
cout << "w/ file: wns/TNS/PWR : " << WNS << " " << skew_violation << " " << power << endl;
double begin, cpu_time1, cpu_time2;
begin = cpu_time1 = cpu_time2 = 0.0;
begin=cpuTime();
for(unsigned i=0 ; i<numpins ; i++) {
double rslk_PT, fslk_PT;
if (pins[view][i].owner == UINT_MAX) // PI, PO
T[view]->getPinSlack(rslk_PT, fslk_PT, pins[view][i].name);
else
T[view]->getPinSlack(rslk_PT, fslk_PT, cells[pins[view][i].owner].name+"/"+pins[view][i].name);
pins[view][i].rslk_ofs += rslk_PT - pins[view][i].rslk;
pins[view][i].fslk_ofs += fslk_PT - pins[view][i].fslk;
pins[view][i].rslk = rslk_PT;
pins[view][i].fslk = fslk_PT;
}
cpu_time1=cpuTime()-begin;
vector <timing_lookup> slack_org_list;
for(unsigned i=0 ; i<numpins ; i++) {
timing_lookup slack;
slack.rise = pins[view][i].rslk;
slack.fall = pins[view][i].fslk;
slack_org_list.push_back(slack);
}
// pin list file --
string pt_out_file="pt_slack.timing";
string pin_file="pin_list";
ofstream ofp(pin_file.c_str());
for(unsigned i=0 ; i<numpins ; i++) {
ofp << getFullPinName(pins[view][i]) << endl;
}
ofp.close();
begin=cpuTime();
cout << "Reading slack timing... " <<endl;
T[view]->writePinSlack(pin_file,pt_out_file);
ifstream infile(pt_out_file.c_str());
vector <timing_lookup> slack_list;
string pin_name, rise, fall;
while (infile >> pin_name >> rise >> fall) {
timing_lookup slack;
if ( rise == "INFINITY" ) slack.rise = std::numeric_limits<double>::infinity();
else slack.rise = atof(rise.c_str());
if ( fall == "INFINITY" ) slack.fall = std::numeric_limits<double>::infinity();
else slack.fall = atof(fall.c_str());
slack_list.push_back(slack);
}
infile.close();
for(unsigned i=0 ; i<numpins ; i++) {
pins[view][i].rslk_ofs += slack_list[i].rise - pins[view][i].rslk;
pins[view][i].fslk_ofs += slack_list[i].fall - pins[view][i].fslk;
pins[view][i].rslk = slack_list[i].rise;
pins[view][i].fslk = slack_list[i].fall;
}
cpu_time2=cpuTime()-begin;
cout.precision(15);
int err = 0;
for(unsigned i=0 ; i<numpins ; i++) {
if ( slack_org_list[i].rise !=slack_list[i].rise ) {
err ++;
cout << "rise error " << slack_org_list[i].rise <<" " << slack_list[i].rise<< endl;
}
if ( slack_org_list[i].fall != slack_list[i].fall ) {
err ++;
cout << "fall error " << slack_org_list[i].fall <<" " << slack_list[i].fall<< endl;
}
}
if ( err > 0 )
cout << "Error " << err << endl;
else
cout << "All timings are matched. :-)" << endl;
cout << "Pin update timing " << cpu_time1 << " " << cpu_time2 << endl;
ExitPTimer();
printMemoryUsage();
for ( unsigned i=0; i < numViews; ++i ) {
delete [] pins[i];
}
for ( unsigned i=0; i < numCorners; ++i ) {
delete [] nets[i];
}
delete [] cells;
delete [] pins;
delete [] nets;
}
void Sizer::ReportSlackErr(unsigned view)
{
double absavgSlkErr, avgSlkErr, maxSlkErr;
avgSlkErr = 0.0;
absavgSlkErr = 0.0;
maxSlkErr = 0.0;
double diff = 0.0;
unsigned count = 0;
for(unsigned i=0 ; i<POs.size() ; i++) {
diff = pins[view][POs[i]].rslk - T[view]->getRiseSlack(pins[view][POs[i]].name);
avgSlkErr += diff;
absavgSlkErr += abs(diff);
count ++;
// cout << pins[view][POs[i]].name << "R\t" << diff << endl;
if ( abs(maxSlkErr) < abs(diff) )
maxSlkErr = diff;
diff = pins[view][POs[i]].fslk - T[view]->getFallSlack(pins[view][POs[i]].name);
avgSlkErr += diff;
absavgSlkErr += abs(diff);
count ++;
// cout << pins[view][POs[i]].name << "F\t" << diff << endl;
if ( abs(maxSlkErr) < abs(diff) )
maxSlkErr = diff;
}
for(unsigned i=0 ; i<FFs.size() ; i++)
{
unsigned curpin=cells[FFs[i]].pinchar["d"];
diff = pins[view][curpin].rslk - T[view]->getRiseSlack(cells[FFs[i]].name+"/"+pins[view][curpin].name);
avgSlkErr += diff;
absavgSlkErr += abs(diff);
count ++;
// cout << cells[FFs[i]].name << "R\t" << diff << endl;
if ( abs(maxSlkErr) < abs(diff) )
maxSlkErr = diff;
diff = pins[view][curpin].rslk - T[view]->getRiseSlack(cells[FFs[i]].name+"/"+pins[view][curpin].name);
avgSlkErr += diff;
absavgSlkErr += abs(diff);
count ++;
// cout << cells[FFs[i]].name << "F\t" << diff << endl;
if ( abs(maxSlkErr) < abs(diff) )
maxSlkErr = diff;
}
avgSlkErr = avgSlkErr/ (double) count;
absavgSlkErr = absavgSlkErr/ (double) count;
cout << "MAX: " << maxSlkErr << "\t";
cout << "AVG: " << avgSlkErr << "\t";
cout << "AAVG: " << absavgSlkErr << endl;
}
void Sizer::getCellDelaySlew (CELL &cell, vector <timing_lookup> &cell_delays, vector <timing_lookup> &cell_otrans, vector <timing_lookup> &cell_itrans, bool isPT, unsigned view)
{
if (isff(cell)) return;
string outPinName = cell.name+"/"+pins[view][cell.outpin].name;
// CellDelay and OutSlew
double WstAATR, WstAATF;
double WstTranR, WstTranF;
double AATF, AATR;
double TranF, TranR;
WstAATR = WstAATF = 0.0;
WstTranR = WstTranF = 0.0;
AATR = AATF = 0.0;
TranR = TranF = 0.0;
timing_lookup outAAT, outTran;
if (isPT) {
outAAT.rise = T[view]->getRiseArrival(outPinName);
outAAT.fall = T[view]->getFallArrival(outPinName);
outTran.rise = T[view]->getRiseTran(outPinName);
outTran.fall = T[view]->getFallTran(outPinName);
} else {
outAAT.rise = pins[view][cell.outpin].rAAT;
outAAT.fall = pins[view][cell.outpin].fAAT;
outTran.rise = pins[view][cell.outpin].rtran;
outTran.fall = pins[view][cell.outpin].ftran;
}
for(unsigned j=0 ; j<cell.inpins.size() ; j++) {
string inPinName = cell.name+"/"+pins[view][cell.inpins[j]].name;
timing_lookup cell_delay;
if (isPT) {
AATF = T[view]->getFallArrival(inPinName);
AATR = T[view]->getRiseArrival(inPinName);
TranF = T[view]->getFallTran(inPinName);
TranR = T[view]->getRiseTran(inPinName);
string riseFall;
T[view]->getCellDelay(cell_delay.rise, riseFall, inPinName, outPinName);
cell_delay.fall = cell_delay.rise;
} else {
string riseFall;
T[view]->getCellDelay(cell_delay.rise, riseFall, inPinName, outPinName);
cell_delay.rise = pins[view][cell.inpins[j]].rdelay[0];
cell_delay.fall = pins[view][cell.inpins[j]].fdelay[0];
if (riseFall == "rise" ) {
//cout << "rise " << cell_delay.rise << " " << cell_delay.fall << endl;
cell_delay.fall = cell_delay.rise;
} else if (riseFall == "fall" ) {
//cout << "fall " << cell_delay.rise << " " << cell_delay.fall << endl;
cell_delay.rise = cell_delay.fall;
}
TranF = pins[view][cell.inpins[j]].ftran;
TranR = pins[view][cell.inpins[j]].rtran;
}
// store delay for every input to output arc
timing_lookup cell_itran;
cell_itran.rise = TranR;
cell_itran.fall = TranF;
double ceff = 0.0;
if (isPT) ceff = T[view]->getCeff(outPinName);
else ceff = pins[view][cell.outpin].ceff;
string master;
if (isPT) master= T[view]->getLibCell(cell.name);
else master = cell.type;
// cout <<isPT << master <<" "<< inPinName << "->" << outPinName << ":" << cell_delay.rise <<" " <<cell_itran.rise <<" "<< ceff<< endl;
cell_delays.push_back(cell_delay);
cell_itrans.push_back(cell_itran);
cell_otrans.push_back(outTran);
}
}
void Sizer::ReportDelayAllParam(unsigned view)
{
unsigned corner = mmmcViewList[view].corner;
unsigned mode = mmmcViewList[view].mode;
double begin=cpuTime();
cout << "[Test] report all parameters ..." << endl;
cells = new CELL[numcells];
for(unsigned i=0 ; i<numcells ; i++)
cells[i]=g_cells[i];
pins= new PIN*[numViews];
for (unsigned i = 0; i < numViews; ++i ) {
pins[i] = new PIN[numpins];
for(unsigned j=0 ; j<numpins ; j++)
pins[i][j]=g_pins[i][j];
}
nets= new NET*[numCorners];
for (unsigned i = 0; i < numCorners; ++i ) {
nets[i] = new NET[numnets];
for(unsigned j=0 ; j<numnets ; j++)
nets[i][j]=g_nets[i][j];
}
SizeIn("GTR");
PTimer = new designTiming** [1];
for (int i=0; i < 1; i++ ) {
PTimer[i] = new designTiming*[numViews];
for (int view=0; view < numViews; view++) {
cout << "Launch " << i*numViews+view << "th PT" << endl;
PTimer[i][view] = LaunchPTimer(i*numViews+view, view);
}
}
T = PTimer[0];
UpdatePTSizes();
CallTimer();
UpdateCapsFromCells();
CalcStats();
#ifdef WORST_TEST
string filename = benchname+"."+"wst_wire_delay"+".list";
ifstream infile(filename.c_str());
if (!infile) {
cout << "-E-: Could not open '" << filename << "'" << endl;
exit(1);
}
vector<string> wst_pin_list;
string pin;
// Read the entire file
while (!infile.eof()) {
infile >> pin;
wst_pin_list.push_back(pin);
}
infile.close();
#endif
cout << "NetName\t" \
<< " " << setw(8) << "InPin" \
<< " " << setw(8) << "OutPin" \
<< " " << setw(3) << "R/F" \
<< " " << setw(8) << fixed << "PtDelay" \
<< " " << setw(8) << fixed << "EMDelay" \
<< " " << setw(8) << fixed << "D2M" \
<< " " << setw(8) << fixed << "DM1" \
<< " " << setw(8) << fixed << "DM2" \
<< " " << setw(8) << fixed << "TriInSlew" \
<< " " << setw(8) << "NumStage" \
<< " " << setw(8) << "NumFanout" \
<< " " << setw(8) << fixed << "InCap" \
<< " " << setw(8) << fixed << "OutCap" \
<< " " << setw(8) << fixed << "TotalRes" \
<< " " << setw(8) << fixed << "TriCeff" \
<< " " << setw(8) << fixed << "TriOutSlew" \
<< " " << setw(8) << fixed << "LE" \
<< " " << setw(8) << fixed << "TriCD" \
<< " " << setw(8) << fixed << "PtCD" \
<< " " << setw(8) << fixed << "TriCTr" \
<< " " << setw(8) << fixed << "PtCTr" \
<< " " << setw(8) << fixed << "PtInSlew" \
<< " " << setw(8) << fixed << "PtOutSlew" \
<< endl;
for (unsigned i = 0; i < numnets; i++) {
if ( debug_net != "" ) {
if ( nets[corner][i].name != debug_net ) {
continue;
}
}
vector<SUB_NODE>& snv = nets[corner][i].subNodeVec;
if ( snv.size() == 0 ) continue;
for (unsigned int j = 0; j < snv.size(); j++) {
if (snv[j].isSink) {
DelayAllParam(i,snv[j].pinId);
}
}
}
ExitPTimer();
for ( unsigned i=0; i < numViews; ++i ) {
delete [] pins[i];
}
for ( unsigned i=0; i < numCorners; ++i ) {
delete [] nets[i];
}
delete [] cells;
delete [] pins;
delete [] nets;
printMemoryUsage();
double cpu_time=cpuTime()-begin;
cout << "cpu time : " << cpu_time << endl;
}
void Sizer::DelayAllParam(unsigned netID, unsigned sinkPinID, string prefix, unsigned view)
{
unsigned corner = mmmcViewList[view].corner;
unsigned mode = mmmcViewList[view].mode;
unsigned subNodeID = 0;
vector<SUB_NODE>& snv = nets[corner][netID].subNodeVec;
if ( snv.size() == 0 ) return;
for (unsigned j = 0; j < nets[corner][netID].subNodeVec.size(); j++) {
if (nets[corner][netID].subNodeVec[j].isSink && \
nets[corner][netID].subNodeVec[j].pinId == sinkPinID ) {
subNodeID = j;
break;
}
}
double DelayEM;
double DelayDM0;
double DelayDM1;
double DelayDM2;
vector <timing_lookup> triCellDelay,triCellTran,triInTran;
vector <timing_lookup> ptCellDelay,ptCellTran,ptInTran;
calc_net_moment(snv, nets[corner][netID].subNodeResVec); // m1, m2 calculation
DelayEM = -snv[subNodeID].m1;
calc_net_delay(netID,DM0);
DelayDM0 = snv[subNodeID].delay;
calc_net_delay(netID,DM1);
DelayDM1 = snv[subNodeID].delay;
calc_net_delay(netID,DM2);
DelayDM2 = snv[subNodeID].delay;
string in_pin_name;
string out_pin_name;
if (pins[view][nets[corner][netID].inpin].owner != UINT_MAX) {
in_pin_name = cells[pins[view][nets[corner][netID].inpin].owner].name+"/"+pins[view][nets[corner][netID].inpin].name;
} else {
in_pin_name = pins[view][nets[corner][netID].inpin].name;
}
if (pins[view][snv[subNodeID].pinId].owner != UINT_MAX) {
out_pin_name = cells[pins[view][snv[subNodeID].pinId].owner].name+"/"+pins[view][snv[subNodeID].pinId].name;
} else {
out_pin_name = pins[view][snv[subNodeID].pinId].name;
}
// CellDelay and OutSlew
if (pins[view][nets[corner][netID].inpin].owner != UINT_MAX && !isff(cells[pins[view][nets[corner][netID].inpin].owner])) {
getCellDelaySlew(cells[pins[view][nets[corner][netID].inpin].owner],triCellDelay,triCellTran,triInTran,0);
getCellDelaySlew(cells[pins[view][nets[corner][netID].inpin].owner],ptCellDelay,ptCellTran,ptInTran,1);
}
double ptDelayR, ptDelayF;
ptDelayR = ptDelayF = 0.0;
double ptAATout, ptAATin;
ptAATout = ptAATin = 0.0;
ptDelayR = T[view]->getRiseArrival(out_pin_name) - T[view]->getRiseArrival(in_pin_name);
ptDelayF = T[view]->getFallArrival(out_pin_name) - T[view]->getFallArrival(in_pin_name);
timing_lookup G;
for (unsigned i = 0; i < triCellDelay.size(); i++ ) {
cout.precision(4);
cout << prefix \
<< " " << nets[corner][netID].name \
<< " " << setw(8) << in_pin_name \
<< " " << setw(8) << out_pin_name \
<< " " << setw(3) << "R" \
<< " " << setw(8) << fixed << ptDelayR \
<< " " << setw(8) << fixed << DelayEM \
<< " " << setw(8) << fixed << DelayDM0 \
<< " " << setw(8) << fixed << DelayDM1 \
<< " " << setw(8) << fixed << DelayDM2 \
<< " " << setw(8) << fixed << pins[view][nets[corner][netID].inpin].rtran \
<< " " << setw(8) << getNumRCStage(snv,subNodeID) \
<< " " << setw(8) << nets[corner][netID].outpins.size() \
<< " " << setw(8) << fixed << pins[view][nets[corner][netID].inpin].totcap \
<< " " << setw(8) << fixed << pins[view][snv[subNodeID].pinId].cap \
<< " " << setw(8) << fixed << snv[subNodeID].totres \
<< " " << setw(8) << fixed << pins[view][nets[corner][netID].inpin].ceff \
<< " " << setw(8) << fixed << pins[view][snv[subNodeID].pinId].rtran \
<< " " << setw(8) << fixed << G.rise \
<< " " << setw(8) << fixed << triCellDelay[i].rise \
<< " " << setw(8) << fixed << ptCellDelay[i].rise \
<< " " << setw(8) << fixed << triCellTran[i].rise \
<< " " << setw(8) << fixed << ptCellTran[i].rise \
<< " " << setw(8) << fixed << T[view]->getRiseTran(in_pin_name) \
<< " " << setw(8) << fixed << T[view]->getRiseTran(out_pin_name) \
<< endl;
cout.precision(4);
cout << prefix \
<< " " << nets[corner][netID].name \
<< " " << setw(8) << in_pin_name \
<< " " << setw(8) << out_pin_name \
<< " " << setw(3) << "F" \
<< " " << setw(8) << fixed << ptDelayF \
<< " " << setw(8) << fixed << DelayEM \
<< " " << setw(8) << fixed << DelayDM0 \
<< " " << setw(8) << fixed << DelayDM1 \
<< " " << setw(8) << fixed << DelayDM2 \
<< " " << setw(8) << fixed << pins[view][nets[corner][netID].inpin].ftran \
<< " " << setw(8) << getNumRCStage(snv,subNodeID) \
<< " " << setw(8) << nets[corner][netID].outpins.size() \
<< " " << setw(8) << fixed << pins[view][nets[corner][netID].inpin].totcap \
<< " " << setw(8) << fixed << pins[view][snv[subNodeID].pinId].cap \
<< " " << setw(8) << fixed << snv[subNodeID].totres \
<< " " << setw(8) << fixed << pins[view][nets[corner][netID].inpin].ceff \
<< " " << setw(8) << fixed << pins[view][snv[subNodeID].pinId].ftran \
<< " " << setw(8) << fixed << G.fall \
<< " " << setw(8) << fixed << triCellDelay[i].fall \
<< " " << setw(8) << fixed << ptCellDelay[i].fall \
<< " " << setw(8) << fixed << triCellTran[i].fall \
<< " " << setw(8) << fixed << ptCellTran[i].fall \
<< " " << setw(8) << fixed << T[view]->getFallTran(in_pin_name) \
<< " " << setw(8) << fixed << T[view]->getFallTran(out_pin_name) \
<< endl;
}
if ( triCellDelay.size() == 0 ) {
cout.precision(4);
cout << prefix \
<< " " << nets[corner][netID].name \
<< " " << setw(8) << in_pin_name \
<< " " << setw(8) << out_pin_name \
<< " " << setw(3) << "R" \
<< " " << setw(8) << fixed << ptDelayR \
<< " " << setw(8) << fixed << DelayEM \
<< " " << setw(8) << fixed << DelayDM0 \
<< " " << setw(8) << fixed << DelayDM1 \
<< " " << setw(8) << fixed << DelayDM2 \
<< " " << setw(8) << fixed << pins[view][nets[corner][netID].inpin].rtran \
<< " " << setw(8) << getNumRCStage(snv,subNodeID) \
<< " " << setw(8) << nets[corner][netID].outpins.size() \
<< " " << setw(8) << fixed << pins[view][nets[corner][netID].inpin].totcap \
<< " " << setw(8) << fixed << pins[view][snv[subNodeID].pinId].cap \
<< " " << setw(8) << fixed << snv[subNodeID].totres \
<< " " << setw(8) << fixed << pins[view][nets[corner][netID].inpin].ceff \
<< " " << setw(8) << fixed << pins[view][snv[subNodeID].pinId].rtran \
<< " " << setw(8) << fixed << G.rise \
<< " " << setw(8) << fixed << 0.0 \
<< " " << setw(8) << fixed << 0.0\
<< " " << setw(8) << fixed << 0.0\
<< " " << setw(8) << fixed << 0.0
<< " " << setw(8) << fixed << T[view]->getRiseTran(in_pin_name) \
<< " " << setw(8) << fixed << T[view]->getRiseTran(out_pin_name) \
<< endl;
cout.precision(4);
cout << prefix \
<< " " << nets[corner][netID].name \
<< " " << setw(8) << in_pin_name \
<< " " << setw(8) << out_pin_name \
<< " " << setw(3) << "F" \
<< " " << setw(8) << fixed << ptDelayF \
<< " " << setw(8) << fixed << DelayEM \
<< " " << setw(8) << fixed << DelayDM0 \
<< " " << setw(8) << fixed << DelayDM1 \
<< " " << setw(8) << fixed << DelayDM2 \
<< " " << setw(8) << fixed << pins[view][nets[corner][netID].inpin].ftran \
<< " " << setw(8) << getNumRCStage(snv,subNodeID) \
<< " " << setw(8) << nets[corner][netID].outpins.size() \
<< " " << setw(8) << fixed << pins[view][nets[corner][netID].inpin].totcap \
<< " " << setw(8) << fixed << pins[view][snv[subNodeID].pinId].cap \
<< " " << setw(8) << fixed << snv[subNodeID].totres \
<< " " << setw(8) << fixed << pins[view][nets[corner][netID].inpin].ceff \
<< " " << setw(8) << fixed << pins[view][snv[subNodeID].pinId].ftran \
<< " " << setw(8) << fixed << G.fall \
<< " " << setw(8) << fixed << 0.0 \
<< " " << setw(8) << fixed << 0.0 \
<< " " << setw(8) << fixed << 0.0 \
<< " " << setw(8) << fixed << 0.0\
<< " " << setw(8) << fixed << T[view]->getFallTran(in_pin_name) \
<< " " << setw(8) << fixed << T[view]->getFallTran(out_pin_name) \
<< endl;
}
}
void Sizer::ReportDeltaTimingAll(unsigned view)
{
unsigned corner = mmmcViewList[view].corner;
unsigned mode = mmmcViewList[view].mode;
bool ifDelete = true;
cells = new CELL[numcells];
for(unsigned i=0 ; i<numcells ; i++)
cells[i] = g_cells[i];
pins= new PIN*[numViews];
for (unsigned i = 0; i < numViews; ++i ) {
pins[i] = new PIN[numpins];
for(unsigned j=0 ; j<numpins ; j++)
pins[i][j]=g_pins[i][j];
}
nets= new NET*[numCorners];
for (unsigned i = 0; i < numCorners; ++i ) {
nets[i] = new NET[numnets];
for(unsigned j=0 ; j<numnets ; j++)
nets[i][j]=g_nets[i][j];
}
ifDelete = true;
SizeIn("GTR");
UpdateCapsFromCells();
CalcStats();
LaunchPTimer(0);
UpdatePTSizes();
CallTimer();
#ifdef WORST_TEST
vector<string> wst_pin_list;
string filename = benchname+"."+"wst_wire_delay"+".list";
string pin;
ifstream infile(filename.c_str());
if (!infile) {
cout << "-E-: Could not open '" << filename << "'" << endl;
ExitPTimer();
exit(1);
}
// Read the entire file
while (!infile.eof()) {
infile >> pin;
wst_pin_list.push_back(pin);
}
infile.close();
#endif
cout << "------------------------------" << endl;
cout << "| Delta Timing Report |" << endl;
cout << "------------------------------" << endl;
cout << endl;
cout << "move" \
<< " " << "NetName\t" \
<< " " << setw(8) << "InPin" \
<< " " << setw(8) << "OutPin" \
<< " " << setw(3) << "R/F" \
<< " " << setw(8) << fixed << "PtDelay" \
<< " " << setw(8) << fixed << "EMDelay" \
<< " " << setw(8) << fixed << "D2M" \
<< " " << setw(8) << fixed << "DM1" \
<< " " << setw(8) << fixed << "DM2" \
<< " " << setw(8) << fixed << "TriInSlew" \
<< " " << setw(8) << "NumStage" \
<< " " << setw(8) << "NumFanout" \
<< " " << setw(8) << fixed << "InCap" \
<< " " << setw(8) << fixed << "OutCap" \
<< " " << setw(8) << fixed << "TotalRes" \
<< " " << setw(8) << fixed << "TriCeff" \
<< " " << setw(8) << fixed << "TriOutSlew" \
<< " " << setw(8) << fixed << "LE" \
<< " " << setw(8) << fixed << "TriCD" \
<< " " << setw(8) << fixed << "PtCD" \
<< " " << setw(8) << fixed << "TriCTr" \
<< " " << setw(8) << fixed << "PtCTr" \
<< " " << setw(8) << fixed << "PtInSlew" \
<< " " << setw(8) << fixed << "PtOutSlew" \
<< endl;
for (unsigned i = 0; i < numnets; i++) {
if ( nets[corner][i].name == "ispd_clk" ) continue;
for (unsigned j = 0; j < nets[corner][i].outpins.size(); j++) {
string out_pin_name;
if (pins[view][nets[corner][i].outpins[j]].owner != UINT_MAX) {
out_pin_name = cells[pins[view][nets[corner][i].outpins[j]].owner].name+"/"+pins[view][nets[corner][i].outpins[j]].name;
} else {
out_pin_name = pins[view][nets[corner][i].outpins[j]].name;
}
#ifdef WORST_TEST
bool found = false;
for(unsigned k=0; k<wst_pin_list.size(); k++) {
if ( out_pin_name == wst_pin_list[k] ) {
found = true;
break;
}
}
if (!found) continue;
#endif
// report org
DelayAllParam(i,nets[corner][i].outpins[j],"org");
// size up
DeltaCellTest(i,nets[corner][i].outpins[j],1,true,true);
// driver size down
DeltaCellTest(i,nets[corner][i].outpins[j],-1,true,true);
// driver vth up
DeltaCellTest(i,nets[corner][i].outpins[j],1,false,true);
// driver vth down
DeltaCellTest(i,nets[corner][i].outpins[j],-1,false,true);
// load size up
DeltaCellTest(i,nets[corner][i].outpins[j],1,true,false);
// load size down
DeltaCellTest(i,nets[corner][i].outpins[j],-1,true,false);
}
}
ExitPTimer();
}
void Sizer::ReportDeltaCellTranTimingAll(unsigned view)
{
unsigned corner = mmmcViewList[view].corner;
unsigned mode = mmmcViewList[view].mode;
bool ifDelete = true;
cells = new CELL[numcells];
for(unsigned i=0 ; i<numcells ; i++)
cells[i] = g_cells[i];
pins= new PIN*[numViews];
for (unsigned i = 0; i < numViews; ++i ) {
pins[i] = new PIN[numpins];
for(unsigned j=0 ; j<numpins ; j++)
pins[i][j]=g_pins[i][j];
}
nets= new NET*[numCorners];
for (unsigned i = 0; i < numCorners; ++i ) {
nets[i] = new NET[numnets];
for(unsigned j=0 ; j<numnets ; j++)
nets[i][j]=g_nets[i][j];
}
ifDelete = true;
SizeIn("GTR");
UpdateCapsFromCells();
CalcStats();
LaunchPTimer(0);
UpdatePTSizes();
CallTimer();
#ifdef WORST_TEST
vector<string> wst_pin_list;
string filename = benchname+"."+"wst_wire_delay"+".list";
string pin;
ifstream infile(filename.c_str());
if (!infile) {
cout << "-E-: Could not open '" << filename << "'" << endl;
ExitPTimer();
exit(1);
}
// Read the entire file
while (!infile.eof()) {
infile >> pin;
wst_pin_list.push_back(pin);
}
infile.close();
#endif
cout << "------------------------------" << endl;
cout << "| Delta Timing Report |" << endl;
cout << "------------------------------" << endl;
cout << endl;
cout << "move"
<< " " << "Cell"
<< " " << "InPin"
<< " " << "R"
<< " " << setw(8) << fixed << "LE"
<< " " << setw(8) << fixed << "InTran"
<< " " << setw(8) << fixed << "Ceff"
<< " " << setw(8) << fixed << "Ctot"
<< " " << setw(8) << fixed << "PtOutTran"
<< " " << setw(8) << fixed << "TriOutTran" << endl;
for(unsigned i=0 ; i<numcells ; i++) {
if (isff(cells[i])) continue;
// report org
ReportCellTran(i, "org");
// size up
DeltaCellTranTest(i,1,true);
// driver size down
DeltaCellTranTest(i,-1,true);
// driver vth up
DeltaCellTranTest(i,1,false);
// driver vth down
DeltaCellTranTest(i,-1,false);
}
ExitPTimer();
}
void Sizer::DeltaCellTest (unsigned netID, unsigned sinkPinID, int step, bool isSize, bool isDrv, unsigned view)
{
unsigned corner = mmmcViewList[view].corner;
unsigned mode = mmmcViewList[view].mode;
unsigned outpinID = 0;
vector<SUB_NODE>& snv = nets[corner][netID].subNodeVec;
if ( snv.size() == 0 ) return;
for (unsigned j = 0; j < nets[corner][netID].outpins.size(); j++) {
if (nets[corner][netID].outpins[j] == sinkPinID ) {
outpinID = j;
break;
}
}
string in_pin_name;
string out_pin_name;
string prefix;
int changed_cell_id = -1;
string org_cell_type;
if (pins[view][nets[corner][netID].inpin].owner != UINT_MAX) {
in_pin_name = cells[pins[view][nets[corner][netID].inpin].owner].name+"/"+pins[view][nets[corner][netID].inpin].name;
} else {
in_pin_name = pins[view][nets[corner][netID].inpin].name;
if (isDrv) return;
}
if (pins[view][nets[corner][netID].outpins[outpinID]].owner != UINT_MAX) {
out_pin_name = cells[pins[view][nets[corner][netID].outpins[outpinID]].owner].name+"/"+pins[view][nets[corner][netID].outpins[outpinID]].name;
} else {
out_pin_name = pins[view][nets[corner][netID].outpins[outpinID]].name;
if (!isDrv) return;
}
if ( !isDrv ) {
// load cell
//
if (isff(cells[pins[view][nets[corner][netID].outpins[outpinID]].owner])) return;
org_cell_type = cells[pins[view][nets[corner][netID].outpins[outpinID]].owner].type;
if ( isSize ) {
// sizing
if(step < 0 && r_size(cells[pins[view][nets[corner][netID].outpins[outpinID]].owner])!=1) {
changed_cell_id = pins[view][nets[corner][netID].outpins[outpinID]].owner;
cell_resize(cells[pins[view][nets[corner][netID].outpins[outpinID]].owner],step);
prefix = "sink_size_down";
} else if(step > 0 && r_size(cells[pins[view][nets[corner][netID].outpins[outpinID]].owner])!=80) {
changed_cell_id = pins[view][nets[corner][netID].outpins[outpinID]].owner;
cell_resize(cells[pins[view][nets[corner][netID].outpins[outpinID]].owner],step);
prefix = "sink_size_up";
}
} else {
// vt swap
if(step < 0 && r_type(cells[pins[view][nets[corner][netID].outpins[outpinID]].owner])!=s) {
changed_cell_id = pins[view][nets[corner][netID].outpins[outpinID]].owner;
cell_retype(cells[pins[view][nets[corner][netID].outpins[outpinID]].owner],step);
prefix = "sink_vth_down";
} else if(step > 0 && r_type(cells[pins[view][nets[corner][netID].outpins[outpinID]].owner])!=f) {
changed_cell_id = pins[view][nets[corner][netID].outpins[outpinID]].owner;
cell_retype(cells[pins[view][nets[corner][netID].outpins[outpinID]].owner],step);
prefix = "sink_vth_up";
}
}
} else {
// driver cell change
if (isff(cells[pins[view][nets[corner][netID].inpin].owner])) return;
org_cell_type = cells[pins[view][nets[corner][netID].inpin].owner].type;
if ( isSize ) {
// sizing
if(step < 0 && r_size(cells[pins[view][nets[corner][netID].inpin].owner])!=1) {
changed_cell_id = pins[view][nets[corner][netID].inpin].owner;
cell_resize(cells[pins[view][nets[corner][netID].inpin].owner],step);
prefix = "driver_size_down";
} else if(step > 0 && r_size(cells[pins[view][nets[corner][netID].inpin].owner])!=80) {
changed_cell_id = pins[view][nets[corner][netID].inpin].owner;
cell_resize(cells[pins[view][nets[corner][netID].inpin].owner],step);
prefix = "driver_size_up";
}
} else {
// vt swap
if(step < 0 && r_type(cells[pins[view][nets[corner][netID].inpin].owner])!='s') {
changed_cell_id = pins[view][nets[corner][netID].inpin].owner;
cell_retype(cells[pins[view][nets[corner][netID].inpin].owner],step);
prefix = "driver_vth_down";
} else if(step > 0 && r_type(cells[pins[view][nets[corner][netID].inpin].owner])!='f') {
changed_cell_id = pins[view][nets[corner][netID].inpin].owner;
cell_retype(cells[pins[view][nets[corner][netID].inpin].owner],step);
prefix = "driver_vth_up";
}
}
}
if ( changed_cell_id == -1 ) {
return;
}
// iSTA
OneTimer (cells[changed_cell_id], .0, view);
// PtUpdate
T[view]->sizeCell(cells[changed_cell_id].name, cells[changed_cell_id].type);
// report
DelayAllParam(netID,sinkPinID,prefix);
// revert
if ( isSize ) {
cell_resize(cells[changed_cell_id], -step);
// iSTA
OneTimer (cells[changed_cell_id], .0, view);
// PT restore
T[view]->sizeCell(cells[changed_cell_id].name, org_cell_type);
} else {
cell_retype(cells[changed_cell_id], -step);
// iSTA
OneTimer (cells[changed_cell_id], .0, view);
T[view]->sizeCell(cells[changed_cell_id].name, org_cell_type);
}
}
void Sizer::DeltaCellTranTest (unsigned cellID, int step, bool isSize, unsigned view)
{
unsigned corner = mmmcViewList[view].corner;
unsigned mode = mmmcViewList[view].mode;
string prefix;
string org_cell_type;
int changed_cell_id = -1;
// load cell
//
if (isff(cells[cellID])) return;
org_cell_type = cells[cellID].type;
if ( isSize ) {
// sizing
if(step < 0 && r_size(cells[cellID])!=1) {
changed_cell_id = cellID;
cell_resize(cells[cellID],step);
prefix = "size_down";
} else if(step > 0 && r_size(cells[cellID])!=80) {
changed_cell_id = cellID;
cell_resize(cells[cellID],step);
prefix = "size_up";
}
} else {
// vt swap
if(step < 0 && r_type(cells[cellID])!=s) {
changed_cell_id = cellID;
cell_retype(cells[cellID],step);
prefix = "vth_down";
} else if(step > 0 && r_type(cells[cellID])!=f) {
changed_cell_id = cellID;
cell_retype(cells[cellID],step);
prefix = "vth_up";
}
}
if ( changed_cell_id == -1 ) {
return;
}
// iSTA
OneTimer (cells[changed_cell_id], .0, view);
// PtUpdate
T[view]->sizeCell(cells[changed_cell_id].name, cells[changed_cell_id].type);
// report
ReportCellTran(changed_cell_id, prefix);
// revert
if ( isSize ) {
cell_resize(cells[changed_cell_id], -step);
// iSTA
OneTimer (cells[changed_cell_id], .0, view);
// PT restore
T[view]->sizeCell(cells[changed_cell_id].name, org_cell_type);
} else {
cell_retype(cells[changed_cell_id], -step);
// iSTA
OneTimer (cells[changed_cell_id], .0, view);
T[view]->sizeCell(cells[changed_cell_id].name, org_cell_type);
}
}
void Sizer::DeltaCellTestSum (int step, bool isSize, bool isDrv, unsigned view)
{
unsigned corner = mmmcViewList[view].corner;
unsigned mode = mmmcViewList[view].mode;
vector<unsigned> changed_net_list;
#ifdef WORST_TEST
vector<string> wst_pin_list;
string filename = benchname+"."+"wst_wire_delay"+".list";
string pin;
ifstream infile(filename.c_str());
if (!infile) {
cout << "-E-: Could not open '" << filename << "'" << endl;
ExitPTimer();
exit(1);
}
// Read the entire file
while (!infile.eof()) {
infile >> pin;
wst_pin_list.push_back(pin);
}
infile.close();
#endif
cout << "------------------------------" << endl;
cout << "| Delta Timing Report |" << endl;
cout << "------------------------------" << endl;
cout << endl;
cout << "NetName\t" \
<< " " << setw(8) << "InPin" \
<< " " << setw(8) << "OutPin" \
<< " " << setw(4) << "R/F" \
<< " " << setw(8) << fixed << "OrgCellType" \
<< " " << setw(8) << fixed << "NewCellType" \
<< " " << setw(8) << fixed << "PtCDly" \
<< " " << setw(8) << fixed << "TriCD" \
<< " " << setw(8) << fixed << "ErrCD" \
<< " " << setw(8) << fixed << "PtCTr" \
<< " " << setw(8) << fixed << "TriCTr" \
<< " " << setw(8) << fixed << "ErrCTr" \
<< " " << setw(8) << fixed << "PtWD" \
<< " " << setw(8) << fixed << "TriWD" \
<< " " << setw(8) << fixed << "ErrWD" \
<< " " << setw(8) << fixed << "PtWTr" \
<< " " << setw(8) << fixed << "TriWTr" \
<< " " << setw(8) << fixed << "ErrWTr" \
<< endl;
double maxErrCellDelay, avgErrCellDelay, maxErrCellTran, avgErrCellTran, maxErrWireDelay, avgErrWireDelay, maxErrWireTran, avgErrWireTran;
double absAvgErrCellDelay, absAvgErrCellTran, absAvgErrWireDelay, absAvgErrWireTran;
unsigned count = 0;
unsigned cell_count = 0;
maxErrCellDelay = avgErrCellDelay = maxErrCellTran = avgErrCellTran = maxErrWireDelay = avgErrWireDelay = maxErrWireTran = avgErrWireTran = 0.0;
absAvgErrCellDelay = absAvgErrCellTran = absAvgErrWireDelay = absAvgErrWireTran = 0.0;
double maxPtDeltaCellDelay, maxTriDeltaCellDelay, avgPtDeltaCellDelay, avgTriDeltaCellDelay;
double maxPtDeltaCellTran, maxTriDeltaCellTran, avgPtDeltaCellTran, avgTriDeltaCellTran;
double maxPtDeltaWireDelay, maxTriDeltaWireDelay, avgPtDeltaWireDelay, avgTriDeltaWireDelay;
double maxPtDeltaWireTran, maxTriDeltaWireTran, avgPtDeltaWireTran, avgTriDeltaWireTran;
maxPtDeltaCellDelay = maxTriDeltaCellDelay = avgPtDeltaCellDelay = avgTriDeltaCellDelay = 0.0;
maxPtDeltaCellTran = maxTriDeltaCellTran = avgPtDeltaCellTran = avgTriDeltaCellTran = 0.0;
maxPtDeltaWireDelay = maxTriDeltaWireDelay = avgPtDeltaWireDelay = avgTriDeltaWireDelay = 0.0;
maxPtDeltaWireTran = maxTriDeltaWireTran = avgPtDeltaWireTran = avgTriDeltaWireTran = 0.0;
unsigned arc_index = 0;
for (unsigned i = 0; i < numnets; i++) {
if ( nets[corner][i].name == "ispd_clk" ) continue;
for (unsigned j = 0; j < nets[corner][i].outpins.size(); j++) {
timing_lookup triWireDelay, triWireTran, ptWireDelay, ptWireTran;
vector <timing_lookup> triCellDelay, ptCellDelay, triCellTran, ptCellTran, triInTran, ptInTran;
timing_lookup triWireDelayOrg, triWireTranOrg, ptWireDelayOrg, ptWireTranOrg;
vector <timing_lookup> triCellDelayOrg, ptCellDelayOrg, triCellTranOrg, ptCellTranOrg, triInTranOrg, ptInTranOrg;
string in_pin_name;
string out_pin_name;
int changed_cell_id = -1;
string org_type;
if (pins[view][nets[corner][i].inpin].owner != UINT_MAX) {
in_pin_name = cells[pins[view][nets[corner][i].inpin].owner].name+"/"+pins[view][nets[corner][i].inpin].name;
} else {
in_pin_name = pins[view][nets[corner][i].inpin].name;
if (isDrv) { if ( i !=0 || j !=0) arc_index++; continue; }
}
if (pins[view][nets[corner][i].outpins[j]].owner != UINT_MAX) {
out_pin_name = cells[pins[view][nets[corner][i].outpins[j]].owner].name+"/"+pins[view][nets[corner][i].outpins[j]].name;
} else {
out_pin_name = pins[view][nets[corner][i].outpins[j]].name;
if (!isDrv) { if ( i !=0 || j !=0) arc_index++; continue; }
}
#ifdef WORST_TEST
bool found = false;
for(unsigned k=0; k<wst_pin_list.size(); k++) {
if ( out_pin_name == wst_pin_list[k] ) {
found = true;
break;
}
}
if (!found) continue;
#endif
// CellDelay and OutSlew
if (pins[view][nets[corner][i].inpin].owner != UINT_MAX && !isff(cells[pins[view][nets[corner][i].inpin].owner])) {
getCellDelaySlew(cells[pins[view][nets[corner][i].inpin].owner],triCellDelayOrg,triCellTranOrg,triInTranOrg,0);
getCellDelaySlew(cells[pins[view][nets[corner][i].inpin].owner],ptCellDelayOrg,ptCellTranOrg,ptInTranOrg,1);
} else {
timing_lookup triCellDelayTmp, ptCellDelayTmp;
timing_lookup triCellTranTmp, ptCellTranTmp;
triCellDelayOrg.push_back(triCellDelayTmp);
ptCellDelayOrg.push_back(ptCellDelayTmp);
triCellTranOrg.push_back(triCellTranTmp);
ptCellTranOrg.push_back(ptCellTranTmp);
}
triWireDelayOrg = get_wire_delay(i,nets[corner][i].outpins[j]);
triWireTranOrg.rise = pins[view][nets[corner][i].outpins[j]].rtran;
triWireTranOrg.fall = pins[view][nets[corner][i].outpins[j]].ftran;
ptWireDelayOrg.rise = T[view]->getRiseArrival(out_pin_name) - T[view]->getRiseArrival(in_pin_name);
ptWireDelayOrg.fall = T[view]->getFallArrival(out_pin_name) - T[view]->getFallArrival(in_pin_name);
ptWireTranOrg.rise = T[view]->getRiseTran(out_pin_name);
ptWireTranOrg.fall = T[view]->getFallTran(out_pin_name);
string org_cell_type;
/////////// make moves
if ( !isDrv ) {
// load cell
//
if (isff(cells[pins[view][nets[corner][i].outpins[j]].owner])) continue;
org_cell_type = cells[pins[view][nets[corner][i].outpins[j]].owner].type;
if ( isSize ) {
// sizing
if(step < 0 && r_size(cells[pins[view][nets[corner][i].outpins[j]].owner])!=1) {
changed_cell_id = pins[view][nets[corner][i].outpins[j]].owner;
cell_resize(cells[pins[view][nets[corner][i].outpins[j]].owner],step);
} else if(step > 0 && r_size(cells[pins[view][nets[corner][i].outpins[j]].owner])!=80) {
changed_cell_id = pins[view][nets[corner][i].outpins[j]].owner;
cell_resize(cells[pins[view][nets[corner][i].outpins[j]].owner],step);
changed_net_list.push_back(arc_index);
}
} else {
// vt swap
if(step < 0 && r_type(cells[pins[view][nets[corner][i].outpins[j]].owner])!=s) {
changed_cell_id = pins[view][nets[corner][i].outpins[j]].owner;
cell_retype(cells[pins[view][nets[corner][i].outpins[j]].owner],step);
changed_net_list.push_back(arc_index);
} else if(step > 0 && r_type(cells[pins[view][nets[corner][i].outpins[j]].owner])!=f) {
changed_cell_id = pins[view][nets[corner][i].outpins[j]].owner;
cell_retype(cells[pins[view][nets[corner][i].outpins[j]].owner],step);
changed_net_list.push_back(arc_index);
}
}
} else {
// driver cell change
if (isff(cells[pins[view][nets[corner][i].inpin].owner])) continue;
org_cell_type = cells[pins[view][nets[corner][i].inpin].owner].type;
if ( isSize ) {
// sizing
if(step < 0 && r_size(cells[pins[view][nets[corner][i].inpin].owner])!=1) {
changed_cell_id = pins[view][nets[corner][i].inpin].owner;
cell_resize(cells[pins[view][nets[corner][i].inpin].owner],step);
changed_net_list.push_back(arc_index);
} else if(step > 0 && r_size(cells[pins[view][nets[corner][i].inpin].owner])!=80) {
changed_cell_id = pins[view][nets[corner][i].inpin].owner;
cell_resize(cells[pins[view][nets[corner][i].inpin].owner],step);
changed_net_list.push_back(arc_index);
}
} else {
// vt swap
if(step < 0 && r_type(cells[pins[view][nets[corner][i].inpin].owner])!=s) {
changed_cell_id = pins[view][nets[corner][i].inpin].owner;
cell_retype(cells[pins[view][nets[corner][i].inpin].owner],step);
cout << cells[pins[view][nets[corner][i].inpin].owner].type << endl;
changed_net_list.push_back(arc_index);
} else if(step > 0 && r_type(cells[pins[view][nets[corner][i].inpin].owner])!=f) {
changed_cell_id = pins[view][nets[corner][i].inpin].owner;
cell_retype(cells[pins[view][nets[corner][i].inpin].owner],step);
changed_net_list.push_back(arc_index);
}
}
}
if ( changed_cell_id == -1 ) {
continue;
}
// iSTA
OneTimer (cells[changed_cell_id], .0, view);
// PtUpdate
T[view]->sizeCell(cells[changed_cell_id].name, cells[changed_cell_id].type);
// Report
if (pins[view][nets[corner][i].inpin].owner != UINT_MAX && !isff(cells[pins[view][nets[corner][i].inpin].owner])) {
getCellDelaySlew(cells[pins[view][nets[corner][i].inpin].owner],triCellDelay,triCellTran,triInTran,0);
getCellDelaySlew(cells[pins[view][nets[corner][i].inpin].owner],ptCellDelay,ptCellTran,ptInTran,1);
} else {
timing_lookup triCellDelayTmp, ptCellDelayTmp;
timing_lookup triCellTranTmp, ptCellTranTmp;
triCellDelay.push_back(triCellDelayTmp);
ptCellDelay.push_back(ptCellDelayTmp);
triCellTran.push_back(triCellTranTmp);
ptCellTran.push_back(ptCellTranTmp);
}
triWireDelay = get_wire_delay(i,nets[corner][i].outpins[j]);
triWireTran.rise = pins[view][nets[corner][i].outpins[j]].rtran;
triWireTran.fall = pins[view][nets[corner][i].outpins[j]].ftran;
ptWireDelay.rise = T[view]->getRiseArrival(out_pin_name) - T[view]->getRiseArrival(in_pin_name);
ptWireDelay.fall = T[view]->getFallArrival(out_pin_name) - T[view]->getFallArrival(in_pin_name);
ptWireTran.rise = T[view]->getRiseTran(out_pin_name);
ptWireTran.fall = T[view]->getFallTran(out_pin_name);
timing_lookup ptDeltaCellDelay;
timing_lookup triDeltaCellDelay;
timing_lookup ptDeltaCellTran;
timing_lookup triDeltaCellTran;
timing_lookup ptDeltaWireDelay;
timing_lookup triDeltaWireDelay;
timing_lookup ptDeltaWireTran;
timing_lookup triDeltaWireTran;
for (unsigned k = 0; k < ptCellDelay.size(); k++) {
ptDeltaCellDelay.rise = ptCellDelay[k].rise - ptCellDelayOrg[k].rise;
ptDeltaCellDelay.fall = ptCellDelay[k].fall - ptCellDelayOrg[k].fall;
ptDeltaCellTran.rise = ptCellTran[k].rise - ptCellTranOrg[k].rise;
ptDeltaCellTran.fall = ptCellTran[k].fall - ptCellTranOrg[k].fall;
ptDeltaWireDelay.rise = ptWireDelay.rise - ptWireDelayOrg.rise;
ptDeltaWireDelay.fall = ptWireDelay.fall - ptWireDelayOrg.fall;
ptDeltaWireTran.rise = ptWireTran.rise - ptWireTranOrg.rise;
ptDeltaWireTran.fall = ptWireTran.fall - ptWireTranOrg.fall;
triDeltaCellDelay.rise = triCellDelay[k].rise - triCellDelayOrg[k].rise;
triDeltaCellDelay.fall = triCellDelay[k].fall - triCellDelayOrg[k].fall;
triDeltaCellTran.rise = triCellTran[k].rise - triCellTranOrg[k].rise;
triDeltaCellTran.fall = triCellTran[k].fall - triCellTranOrg[k].fall;
triDeltaWireDelay.rise = triWireDelay.rise - triWireDelayOrg.rise;
triDeltaWireDelay.fall = triWireDelay.fall - triWireDelayOrg.fall;
triDeltaWireTran.rise = triWireTran.rise - triWireTranOrg.rise;
triDeltaWireTran.fall = triWireTran.fall - triWireTranOrg.fall;
cout.precision(4);
cout << nets[corner][i].name \
<< "\t " << setw(8) << in_pin_name \
<< " " << setw(8) << out_pin_name \
<< " " << setw(4) << "R" \
<< " " << setw(8) << org_cell_type \
<< " " << setw(8) << cells[changed_cell_id].type \
<< " " << setw(8) << fixed << ptDeltaCellDelay.rise \
<< " " << setw(8) << fixed << triDeltaCellDelay.rise \
<< " " << setw(8) << fixed << triDeltaCellDelay.rise - ptDeltaCellDelay.rise \
<< " " << setw(8) << fixed << ptDeltaCellTran.rise \
<< " " << setw(8) << fixed << triDeltaCellTran.rise \
<< " " << setw(8) << fixed << triDeltaCellTran.rise - ptDeltaCellTran.rise \
<< " " << setw(8) << fixed << ptDeltaWireDelay.rise \
<< " " << setw(8) << fixed << triDeltaWireDelay.rise \
<< " " << setw(8) << fixed << triDeltaWireDelay.rise - ptDeltaWireDelay.rise \
<< " " << setw(8) << fixed << ptDeltaWireTran.rise \
<< " " << setw(8) << fixed << triDeltaWireTran.rise \
<< " " << setw(8) << fixed << triDeltaWireTran.rise - ptDeltaWireTran.rise \
<< endl;
cout << nets[corner][i].name \
<< "\t " << setw(8) << in_pin_name \
<< " " << setw(8) << out_pin_name \
<< " " << setw(4) << "F" \
<< " " << setw(8) << org_cell_type \
<< " " << setw(8) << cells[changed_cell_id].type \
<< " " << setw(8) << fixed << ptDeltaCellDelay.fall \
<< " " << setw(8) << fixed << triDeltaCellDelay.fall \
<< " " << setw(8) << fixed << triDeltaCellDelay.fall - ptDeltaCellDelay.fall \
<< " " << setw(8) << fixed << ptDeltaCellTran.fall \
<< " " << setw(8) << fixed << triDeltaCellTran.fall \
<< " " << setw(8) << fixed << triDeltaCellTran.fall - ptDeltaCellTran.fall \
<< " " << setw(8) << fixed << ptDeltaWireDelay.fall \
<< " " << setw(8) << fixed << triDeltaWireDelay.fall \
<< " " << setw(8) << fixed << triDeltaWireDelay.fall - ptDeltaWireDelay.fall \
<< " " << setw(8) << fixed << ptDeltaWireTran.fall \
<< " " << setw(8) << fixed << triDeltaWireTran.fall \
<< " " << setw(8) << fixed << triDeltaWireTran.fall - ptDeltaWireTran.fall \
<< endl;
if ( abs(maxErrCellDelay) < abs(triDeltaCellDelay.rise - ptDeltaCellDelay.rise) ) {
maxErrCellDelay = triDeltaCellDelay.rise - ptDeltaCellDelay.rise;
maxPtDeltaCellDelay = ptDeltaCellDelay.rise;
maxTriDeltaCellDelay = triDeltaCellDelay.rise;
}
if ( abs(maxErrCellDelay) < abs(triDeltaCellDelay.fall - ptDeltaCellDelay.fall) ) {
maxErrCellDelay = triDeltaCellDelay.fall - ptDeltaCellDelay.fall;
maxPtDeltaCellDelay = ptDeltaCellDelay.fall;
maxTriDeltaCellDelay = triDeltaCellDelay.fall;
}
avgErrCellDelay += triDeltaCellDelay.rise - ptDeltaCellDelay.rise;
avgErrCellDelay += triDeltaCellDelay.fall - ptDeltaCellDelay.fall;
absAvgErrCellDelay += abs(triDeltaCellDelay.rise - ptDeltaCellDelay.rise);
absAvgErrCellDelay += abs(triDeltaCellDelay.fall - ptDeltaCellDelay.fall);
avgPtDeltaCellDelay += ptDeltaCellDelay.rise + ptDeltaCellDelay.fall;
avgTriDeltaCellDelay += triDeltaCellDelay.rise + triDeltaCellDelay.fall;
if ( abs(maxErrCellTran) < abs(triDeltaCellTran.rise - ptDeltaCellTran.rise) ) {
maxErrCellTran = triDeltaCellTran.rise - ptDeltaCellTran.rise;
maxPtDeltaCellTran = ptDeltaCellTran.rise;
maxTriDeltaCellTran = triDeltaCellTran.rise;
}
if ( abs(maxErrCellTran) < abs(triDeltaCellTran.fall - ptDeltaCellTran.fall) ) {
maxErrCellTran = triDeltaCellTran.fall - ptDeltaCellTran.fall;
maxPtDeltaCellTran = ptDeltaCellTran.fall;
maxTriDeltaCellTran = triDeltaCellTran.fall;
}
avgErrCellTran += triDeltaCellTran.rise - ptDeltaCellTran.rise;
avgErrCellTran += triDeltaCellTran.fall - ptDeltaCellTran.fall;
absAvgErrCellTran += abs(triDeltaCellTran.rise - ptDeltaCellTran.rise);
absAvgErrCellTran += abs(triDeltaCellTran.fall - ptDeltaCellTran.fall);
avgPtDeltaCellTran += ptDeltaCellTran.rise + ptDeltaCellTran.fall;
avgTriDeltaCellTran += triDeltaCellTran.rise + triDeltaCellTran.fall;
cell_count += 2;
}
if ( abs(maxErrWireDelay) < abs(triDeltaWireDelay.rise - ptDeltaWireDelay.rise) ) {
maxErrWireDelay = triDeltaWireDelay.rise - ptDeltaWireDelay.rise;
maxPtDeltaWireDelay = ptDeltaWireDelay.rise;
maxTriDeltaWireDelay = triDeltaWireDelay.rise;
}
if ( abs(maxErrWireDelay) < abs(triDeltaWireDelay.fall - ptDeltaWireDelay.fall) ) {
maxErrWireDelay = triDeltaWireDelay.fall - ptDeltaWireDelay.fall;
maxPtDeltaWireDelay = ptDeltaWireDelay.fall;
maxTriDeltaWireDelay = triDeltaWireDelay.fall;
}
avgErrWireDelay += triDeltaWireDelay.rise - ptDeltaWireDelay.rise;
avgErrWireDelay += triDeltaWireDelay.fall - ptDeltaWireDelay.fall;
absAvgErrWireDelay += abs(triDeltaWireDelay.rise - ptDeltaWireDelay.rise);
absAvgErrWireDelay += abs(triDeltaWireDelay.fall - ptDeltaWireDelay.fall);
avgPtDeltaWireDelay += ptDeltaWireDelay.rise + ptDeltaWireDelay.fall;
avgTriDeltaWireDelay += triDeltaWireDelay.rise + triDeltaWireDelay.fall;
if ( abs(maxErrWireTran) < abs(triDeltaWireTran.rise - ptDeltaWireTran.rise) ) {
maxErrWireTran = triDeltaWireTran.rise - ptDeltaWireTran.rise;
maxPtDeltaWireTran = ptDeltaWireTran.rise;
maxTriDeltaWireTran = triDeltaWireTran.rise;
}
if ( abs(maxErrWireTran) < abs(triDeltaWireTran.fall - ptDeltaWireTran.fall) ) {
maxErrWireTran = triDeltaWireTran.fall - ptDeltaWireTran.fall;
maxPtDeltaWireTran = ptDeltaWireTran.fall;
maxTriDeltaWireTran = triDeltaWireTran.fall;
}
avgErrWireTran += triDeltaWireTran.rise - ptDeltaWireTran.rise;
avgErrWireTran += triDeltaWireTran.fall - ptDeltaWireTran.fall;
absAvgErrWireTran += abs(triDeltaWireTran.rise - ptDeltaWireTran.rise);
absAvgErrWireTran += abs(triDeltaWireTran.fall - ptDeltaWireTran.fall);
avgPtDeltaWireTran += ptDeltaWireTran.rise + ptDeltaWireTran.fall;
avgTriDeltaWireTran += triDeltaWireTran.rise + triDeltaWireTran.fall;
count +=2;
// revert
//
if ( isSize ) {
cell_resize(cells[changed_cell_id], -step);
// iSTA
OneTimer (cells[changed_cell_id], .0, view);
// PT restore
T[view]->sizeCell(cells[changed_cell_id].name, org_cell_type);
} else {
cell_retype(cells[changed_cell_id], -step);
// iSTA
OneTimer (cells[changed_cell_id], .0, view);
T[view]->sizeCell(cells[changed_cell_id].name, org_cell_type);
}
} //each arc
} //each net
cout << "Summary\t" \
<< " " << setw(8) << "" \
<< " " << setw(8) << fixed << maxPtDeltaCellDelay \
<< " " << setw(8) << fixed << maxTriDeltaCellDelay \
<< " " << setw(8) << fixed << maxErrCellDelay \
<< " " << setw(8) << fixed << avgPtDeltaCellDelay/count \
<< " " << setw(8) << fixed << avgTriDeltaCellDelay/count \
<< " " << setw(8) << fixed << avgErrCellDelay/(count) \
<< " " << setw(8) << fixed << absAvgErrCellDelay/(count) \
\
<< " " << setw(8) << fixed << maxPtDeltaCellTran \
<< " " << setw(8) << fixed << maxTriDeltaCellTran \
<< " " << setw(8) << fixed << maxErrCellTran \
<< " " << setw(8) << fixed << avgPtDeltaCellTran/count \
<< " " << setw(8) << fixed << avgTriDeltaCellTran/count \
<< " " << setw(8) << fixed << avgErrCellTran/(count) \
<< " " << setw(8) << fixed << absAvgErrCellTran/(count) \
\
<< " " << setw(8) << fixed << maxPtDeltaWireDelay \
<< " " << setw(8) << fixed << maxTriDeltaWireDelay \
<< " " << setw(8) << fixed << maxErrWireDelay \
<< " " << setw(8) << fixed << avgPtDeltaWireDelay/count \
<< " " << setw(8) << fixed << avgTriDeltaWireDelay/count \
<< " " << setw(8) << fixed << avgErrWireDelay/count \
<< " " << setw(8) << fixed << absAvgErrWireDelay/count \
\
<< " " << setw(8) << fixed << maxPtDeltaWireTran \
<< " " << setw(8) << fixed << maxTriDeltaWireTran \
<< " " << setw(8) << fixed << maxErrWireTran \
<< " " << setw(8) << fixed << avgPtDeltaWireTran/count \
<< " " << setw(8) << fixed << avgTriDeltaWireTran/count \
<< " " << setw(8) << fixed << avgErrWireTran/(count) \
<< " " << setw(8) << fixed << absAvgErrWireTran/(count) \
<< endl;
}
void Sizer::ReportDeltaTiming(unsigned view)
{
unsigned corner = mmmcViewList[view].corner;
unsigned mode = mmmcViewList[view].mode;
bool ifDelete = true;
cells = new CELL[numcells];
for(unsigned i=0 ; i<numcells ; i++)
cells[i] = g_cells[i];
pins= new PIN*[numViews];
for (unsigned i = 0; i < numViews; ++i ) {
pins[i] = new PIN[numpins];
for(unsigned j=0 ; j<numpins ; j++)
pins[i][j]=g_pins[i][j];
}
nets= new NET*[numCorners];
for (unsigned i = 0; i < numCorners; ++i ) {
nets[i] = new NET[numnets];
for(unsigned j=0 ; j<numnets ; j++)
nets[i][j]=g_nets[i][j];
}
ifDelete = true;
SizeIn("GTR");
UpdateCapsFromCells();
CalcStats();
LaunchPTimer(0);
UpdatePTSizes();
CallTimer();
cout << "=== DRIVER SIZE UP ===" << endl;
// driver size up
DeltaCellTestSum(1, true, true);
cout << "=== DRIVER SIZE DOWN ===" << endl;
// driver size down
DeltaCellTestSum(-1, true, true);
cout << "=== DRIVER VTH UP ===" << endl;
// driver vth up
DeltaCellTestSum(1,false,true);
cout << "=== DRIVER VTH DOWN ===" << endl;
// driver vth down
DeltaCellTestSum(-1,false,true);
cout << "=== SINK SIZE UP ===" << endl;
// load size up
DeltaCellTestSum(1,true,false);
cout << "=== SINK SIZE DOWN ===" << endl;
// load size down
DeltaCellTestSum(-1,true,false);
ExitPTimer();
}
void Sizer::DelaySearchTest(unsigned view)
{
unsigned corner = mmmcViewList[view].corner;
unsigned mode = mmmcViewList[view].mode;
cells = new CELL[numcells];
for(unsigned i=0 ; i<numcells ; i++)
cells[i]=g_cells[i];
pins= new PIN*[numViews];
for (unsigned i = 0; i < numViews; ++i ) {
pins[i] = new PIN[numpins];
for(unsigned j=0 ; j<numpins ; j++)
pins[i][j]=g_pins[i][j];
}
nets= new NET*[numCorners];
for (unsigned i = 0; i < numCorners; ++i ) {
nets[i] = new NET[numnets];
for(unsigned j=0 ; j<numnets ; j++)
nets[i][j]=g_nets[i][j];
}
UpdateCapsFromCells();
CallTimer();
CalcStats();
unsigned num_size = 9;
unsigned pi = 0;
double min_delay = 1000000.0;
if ( pins[view][PIs[0]].name == "ispd_clk") {
pi = 1;
} else {
pi = 0;
}
cout << "***" << pins[view][pi].name << endl;
cell_retype(cells[0],1);
cell_retype(cells[1],1);
cell_retype(cells[2],1);
cell_retype(cells[3],1);
cell_retype(cells[4],1);
cell_retype(cells[0],1);
cell_retype(cells[1],1);
cell_retype(cells[2],1);
cell_retype(cells[3],1);
cell_retype(cells[4],1);
for ( unsigned i = 0; i < num_size; i++ ) {
for ( unsigned j = 0; j < num_size; j++ ) {
for ( unsigned k = 0; k < num_size; k++ ) {
for ( unsigned l = 0; l < num_size; l++ ) {
for ( unsigned m = 0; m < num_size; m++ ) {
for ( unsigned ii = 0; ii < i; ii++ ) cell_resize(cells[0],1);
for ( unsigned jj = 0; jj < j; jj++ ) cell_resize(cells[1],1);
for ( unsigned kk = 0; kk < k; kk++ ) cell_resize(cells[2],1);
for ( unsigned ll = 0; ll < l; ll++ ) cell_resize(cells[3],1);
for ( unsigned mm = 0; mm < m; mm++ ) cell_resize(cells[4],1);
CallTimer();
double rdelay = pins[view][POs[0]].rAAT;
double fdelay = pins[view][POs[0]].fAAT;
double delay = max(rdelay, fdelay);
if (min_delay > delay) {
min_delay = delay;
cout << "Min Delay: " << min_delay << endl;
cout << "Solution: " << i << " " << j << " " << k << " " << l << " " << m << endl;
}
cout << delay << " : " << i << " " << j << " " << k << " " << l << " " << m << endl;
cout << delay << " : "
<< r_size(cells[0]) << ":" << r_type(cells[0])\
<< " " << r_size(cells[1]) << ":" << r_type(cells[1])\
<< " " << r_size(cells[2]) << ":" << r_type(cells[2])\
<< " " << r_size(cells[3]) << ":" << r_type(cells[3])\
<< " " << r_size(cells[4]) << ":" << r_type(cells[4])<< endl;
cout << delay << " : " << pins[view][cells[0].outpin].rAAT \
<< " " << pins[view][cells[1].outpin].rAAT \
<< " " << pins[view][cells[2].outpin].rAAT \
<< " " << pins[view][cells[3].outpin].rAAT \
<< " " << pins[view][cells[4].outpin].rAAT << endl;
for ( unsigned ii = 0; ii < i; ii++ ) cell_resize(cells[0],-1);
for ( unsigned jj = 0; jj < j; jj++ ) cell_resize(cells[1],-1);
for ( unsigned kk = 0; kk < k; kk++ ) cell_resize(cells[2],-1);
for ( unsigned ll = 0; ll < l; ll++ ) cell_resize(cells[3],-1);
for ( unsigned mm = 0; mm < m; mm++ ) cell_resize(cells[4],-1);
}}}}}
}
string Sizer::getFullPinName(PIN &pin)
{
string full_pin_name;
if (pin.owner != UINT_MAX) {
full_pin_name = g_cells[pin.owner].name+"/"+pin.name;
} else {
full_pin_name = pin.name;
}
return full_pin_name;
}
void Sizer::ZeroDelayTest()
{
cells = new CELL[numcells];
for(unsigned i=0 ; i<numcells ; i++)
cells[i]=g_cells[i];
pins= new PIN*[numViews];
for (unsigned i = 0; i < numViews; ++i ) {
pins[i] = new PIN[numpins];
for(unsigned j=0 ; j<numpins ; j++)
pins[i][j]=g_pins[i][j];
}
nets= new NET*[numCorners];
for (unsigned i = 0; i < numCorners; ++i ) {
nets[i] = new NET[numnets];
for(unsigned j=0 ; j<numnets ; j++) {
nets[i][j]=g_nets[i][j];
}
}
PTimer = new designTiming** [1];
for (int i=0; i < 1; i++ ) {
PTimer[i] = new designTiming*[numViews];
for (int view=0; view < numViews; view++) {
cout << "Launch " << i*numViews+view << "th PT" << endl;
PTimer[i][view] = LaunchPTimer(i*numViews+view, view);
}
}
T = PTimer[0];
unsigned view = 0;
UpdateCapsFromCells();
CallTimer(view);
CorrelatePT(view);
for (unsigned i = 0; i < numcells; ++i) {
double delta_delay = EstDeltaDelay(cells[i], -1, 0, view);
if ( delta_delay <= 0 ) {
string old_type = cells[i].type;
vector <double> old_in_tran1, old_in_tran2;
vector <double> old_out_tran1, old_out_tran2;
vector <double> new_in_tran1, new_in_tran2;
vector <double> new_out_tran1, new_out_tran2;
for ( unsigned j = 0; j < cells[i].inpins.size(); ++j ) {
old_in_tran1.push_back(pins[view][cells[i].inpins[j]].rtran);
old_in_tran1.push_back(pins[view][cells[i].inpins[j]].ftran);
double r_rtran, r_ftran;
T[view]->getPinTran(r_rtran, r_ftran, getFullPinName(pins[view][cells[i].inpins[j]]));
old_in_tran2.push_back(r_rtran);
old_in_tran2.push_back(r_ftran);
}
for ( unsigned j = 0; j < cells[i].outpins.size(); ++j ) {
old_out_tran1.push_back(pins[view][cells[i].outpins[j]].rtran);
old_out_tran1.push_back(pins[view][cells[i].outpins[j]].ftran);
double r_rtran, r_ftran;
T[view]->getPinTran(r_rtran, r_ftran, getFullPinName(pins[view][cells[i].outpins[j]]));
old_out_tran2.push_back(r_rtran);
old_out_tran2.push_back(r_ftran);
}
bool change_step = cell_resize(cells[i], -1, true);
OneTimer(cells[i], STA_MARGIN, view);
if ( change_step ) {
cout << cells[i].name << " " << old_type<< " --> " << cells[i].type << endl;
for ( unsigned j = 0; j < cells[i].inpins.size(); ++j ) {
new_in_tran1.push_back(pins[view][cells[i].inpins[j]].rtran);
new_in_tran1.push_back(pins[view][cells[i].inpins[j]].ftran);
double r_rtran, r_ftran;
T[view]->getPinTran(r_rtran, r_ftran, getFullPinName(pins[view][cells[i].inpins[j]]));
new_in_tran2.push_back(r_rtran);
new_in_tran2.push_back(r_ftran);
}
for ( unsigned j = 0; j < cells[i].outpins.size(); ++j ) {
new_out_tran1.push_back(pins[view][cells[i].outpins[j]].rtran);
new_out_tran1.push_back(pins[view][cells[i].outpins[j]].ftran);
double r_rtran, r_ftran;
T[view]->getPinTran(r_rtran, r_ftran, getFullPinName(pins[view][cells[i].outpins[j]]));
new_out_tran2.push_back(r_rtran);
new_out_tran2.push_back(r_ftran);
}
for ( unsigned j = 0; j < cells[i].inpins.size(); ++j ) {
cout << "IN TRAN "
<< old_in_tran1[j] << " " << new_in_tran1[j] << " "
<< old_in_tran2[j] << " " << new_in_tran2[j] << endl;
}
for ( unsigned j = 0; j < cells[i].outpins.size(); ++j ) {
cout << "OUT TRAN "
<< old_out_tran1[j] << " " << new_out_tran1[j] << " "
<< old_out_tran2[j] << " " << new_out_tran2[j] << endl;
}
cell_resize(cells[i], 1, true);
OneTimer(cells[i], STA_MARGIN, view);
}
}
}
ExitPTimer();
for ( unsigned i=0; i < numViews; ++i ) {
delete [] pins[i];
}
for ( unsigned i=0; i < numCorners; ++i ) {
delete [] nets[i];
}
delete [] cells;
delete [] pins;
delete [] nets;
}
void Sizer::AllCorrSTATest()
{
cells = new CELL[numcells];
for(unsigned i=0 ; i<numcells ; i++)
cells[i]=g_cells[i];
pins= new PIN*[numViews];
for (unsigned i = 0; i < numViews; ++i ) {
pins[i] = new PIN[numpins];
for(unsigned j=0 ; j<numpins ; j++)
pins[i][j]=g_pins[i][j];
}
nets= new NET*[numCorners];
for (unsigned i = 0; i < numCorners; ++i ) {
nets[i] = new NET[numnets];
for(unsigned j=0 ; j<numnets ; j++) {
nets[i][j]=g_nets[i][j];
}
}
PTimer = new designTiming** [1];
for (int i=0; i < 1; i++ ) {
PTimer[i] = new designTiming*[numViews];
for (int view=0; view < numViews; view++) {
cout << "Launch " << i*numViews+view << "th PT" << endl;
PTimer[i][view] = LaunchPTimer(i*numViews+view, view);
}
}
T = PTimer[0];
unsigned view = 0;
UpdateCapsFromCells();
string pt_in_file = benchname+".pin_list";
string pt_out_file = benchname+"_0.pt.tran";
T[view]->writePinAll(pt_in_file,pt_out_file);
ifstream infile(pt_out_file.c_str());
vector <timing_lookup> slack_list;
vector <timing_lookup> ceff_list;
vector <timing_lookup> tran_list;
vector <timing_lookup> aat_list;
string pin_name, slack_rise, slack_fall,
tran_rise, tran_fall, aat_rise, aat_fall;
while (infile >> pin_name >> slack_rise >> slack_fall
>> tran_rise >> tran_fall >> aat_rise >> aat_fall ) {
timing_lookup slack;
if ( slack_rise == "INFINITY" ) slack.rise = DBL_MAX;
else slack.rise = atof(slack_rise.c_str());
if ( slack_fall == "INFINITY" ) slack.fall = DBL_MAX;
else slack.fall = atof(slack_fall.c_str());
slack_list.push_back(slack);
timing_lookup tran;
if ( tran_rise == "INFINITY" ) tran.rise = DBL_MAX;
else tran.rise = atof(tran_rise.c_str());
if ( tran_fall == "INFINITY" ) tran.fall = DBL_MAX;
else tran.fall = atof(tran_fall.c_str());
tran_list.push_back(tran);
timing_lookup aat;
if ( aat_rise == "INFINITY" ) aat.rise = DBL_MAX;
else aat.rise = atof(aat_rise.c_str());
if ( aat_fall == "INFINITY" ) aat.fall = DBL_MAX;
else aat.fall = atof(aat_fall.c_str());
aat_list.push_back(aat);
}
infile.close();
CallTimer(view);
for (unsigned i = 0; i < numpins; ++i) {
cout << "before corr " << getFullPinName(pins[view][i])
<< " " << pins[view][i].rtran << "/" << tran_list[i].rise << " "
<< " " << pins[view][i].ftran << "/" << tran_list[i].fall << " "
<< " " << pins[view][i].rAAT << "/" << aat_list[i].rise << " "
<< " " << pins[view][i].fAAT << "/" << aat_list[i].fall << " "
<< " " << pins[view][i].rRAT << "/" << aat_list[i].rise + slack_list[i].rise << " "
<< " " << pins[view][i].fRAT << "/" << aat_list[i].fall + slack_list[i].fall << " "
<< " " << pins[view][i].rslk << "/" << slack_list[i].rise << " "
<< " " << pins[view][i].fslk << "/" << slack_list[i].fall << " "
<< endl;
if ( !isEqual(pins[view][i].rtran, tran_list[i].rise) ||
!isEqual(pins[view][i].ftran, tran_list[i].fall) ||
//!isEqual(pins[view][i].rAAT, aat_list[i].rise) ||
//!isEqual(pins[view][i].fAAT, aat_list[i].fall) ||
!isEqual(pins[view][i].rslk, slack_list[i].rise) ||
!isEqual(pins[view][i].fslk, slack_list[i].fall) ) {
cout << "before corr mismatch " << getFullPinName(pins[view][i])
<< " " << pins[view][i].rtran << "/" << tran_list[i].rise << " "
<< " " << pins[view][i].ftran << "/" << tran_list[i].fall << " "
<< " " << pins[view][i].rAAT << "/" << aat_list[i].rise << " "
<< " " << pins[view][i].fAAT << "/" << aat_list[i].fall << " "
<< " " << pins[view][i].rRAT << "/" << aat_list[i].rise + slack_list[i].rise << " "
<< " " << pins[view][i].fRAT << "/" << aat_list[i].fall + slack_list[i].fall << " "
<< " " << pins[view][i].rslk << "/" << slack_list[i].rise << " "
<< " " << pins[view][i].fslk << "/" << slack_list[i].fall << " "
<< endl;
}
}
CorrelatePT(view);
for (unsigned i = 0; i < numpins; ++i) {
cout << "after corr " << getFullPinName(pins[view][i])
<< " " << pins[view][i].rtran << "/" << tran_list[i].rise << " "
<< " " << pins[view][i].ftran << "/" << tran_list[i].fall << " "
<< " " << pins[view][i].rAAT << "/" << aat_list[i].rise << " "
<< " " << pins[view][i].fAAT << "/" << aat_list[i].fall << " "
<< " " << pins[view][i].rRAT << "/" << aat_list[i].rise + slack_list[i].rise << " "
<< " " << pins[view][i].fRAT << "/" << aat_list[i].fall + slack_list[i].fall << " "
<< " " << pins[view][i].rslk << "/" << slack_list[i].rise << " "
<< " " << pins[view][i].fslk << "/" << slack_list[i].fall << " "
<< endl;
if ( !isEqual(pins[view][i].rtran, tran_list[i].rise) ||
!isEqual(pins[view][i].ftran, tran_list[i].fall) ||
//!isEqual(pins[view][i].rAAT, aat_list[i].rise) ||
//!isEqual(pins[view][i].fAAT, aat_list[i].fall) ||
!isEqual(pins[view][i].rslk, slack_list[i].rise) ||
!isEqual(pins[view][i].fslk, slack_list[i].fall) ) {
cout << "after corr mismatch " << getFullPinName(pins[view][i])
<< " " << pins[view][i].rtran << "/" << tran_list[i].rise << " "
<< " " << pins[view][i].ftran << "/" << tran_list[i].fall << " "
<< " " << pins[view][i].rAAT << "/" << aat_list[i].rise << " "
<< " " << pins[view][i].fAAT << "/" << aat_list[i].fall << " "
<< " " << pins[view][i].rRAT << "/" << aat_list[i].rise + slack_list[i].rise << " "
<< " " << pins[view][i].fRAT << "/" << aat_list[i].fall + slack_list[i].fall << " "
<< " " << pins[view][i].rslk << "/" << slack_list[i].rise << " "
<< " " << pins[view][i].fslk << "/" << slack_list[i].fall << " "
<< endl;
}
}
CallTimer(view);
for (unsigned i = 0; i < numpins; ++i) {
cout << "after timer " << getFullPinName(pins[view][i])
<< " " << pins[view][i].rtran << "/" << tran_list[i].rise << " "
<< " " << pins[view][i].ftran << "/" << tran_list[i].fall << " "
<< " " << pins[view][i].rAAT << "/" << aat_list[i].rise << " "
<< " " << pins[view][i].fAAT << "/" << aat_list[i].fall << " "
<< " " << pins[view][i].rRAT << "/" << aat_list[i].rise + slack_list[i].rise << " "
<< " " << pins[view][i].fRAT << "/" << aat_list[i].fall + slack_list[i].fall << " "
<< " " << pins[view][i].rslk << "/" << slack_list[i].rise << " "
<< " " << pins[view][i].fslk << "/" << slack_list[i].fall << " "
<< endl;
if ( !isEqual(pins[view][i].rtran, tran_list[i].rise) ||
!isEqual(pins[view][i].ftran, tran_list[i].fall) ||
//!isEqual(pins[view][i].rAAT, aat_list[i].rise) ||
//!isEqual(pins[view][i].fAAT, aat_list[i].fall) ||
!isEqual(pins[view][i].rslk, slack_list[i].rise) ||
!isEqual(pins[view][i].fslk, slack_list[i].fall) ) {
cout << "after timer mismatch " << getFullPinName(pins[view][i])
<< " " << pins[view][i].rtran << "/" << tran_list[i].rise << " "
<< " " << pins[view][i].ftran << "/" << tran_list[i].fall << " "
<< " " << pins[view][i].rAAT << "/" << aat_list[i].rise << " "
<< " " << pins[view][i].fAAT << "/" << aat_list[i].fall << " "
<< " " << pins[view][i].rRAT << "/" << aat_list[i].rise + slack_list[i].rise << " "
<< " " << pins[view][i].fRAT << "/" << aat_list[i].fall + slack_list[i].fall << " "
<< " " << pins[view][i].rslk << "/" << slack_list[i].rise << " "
<< " " << pins[view][i].fslk << "/" << slack_list[i].fall << " "
<< endl;
}
}
unsigned cnt = 0;
for (unsigned i = 0; i < numcells; ++i) {
if (cells[i].isClockCell)
continue;
if (cells[i].isDontTouch)
continue;
string old_type = cells[i].type;
bool change = cell_retype(cells[i], -1, true);
if ( change ) {
cout << "CHANGE " << cells[i].name << " " << old_type << " --> " << cells[i].type << endl;
OneTimer(cells[i], STA_MARGIN);
++cnt;
} else {
bool change1 = cell_resize(cells[i], -1, true);
if ( change1 ) {
cout << "CHANGE " << cells[i].name << " " << old_type << " --> " << cells[i].type << endl;
OneTimer(cells[i], STA_MARGIN);
++cnt;
}
}
if ( cnt > CORR_RATIO*numcells ) {
break;
}
}
slack_list.clear();
ceff_list.clear();
tran_list.clear();
aat_list.clear();
T[view]->writePinAll(pt_in_file,pt_out_file);
infile.open(pt_out_file.c_str());
while (infile >> pin_name >> slack_rise >> slack_fall
>> tran_rise >> tran_fall >> aat_rise >> aat_fall ) {
timing_lookup slack;
if ( slack_rise == "INFINITY" ) slack.rise = DBL_MAX;
else slack.rise = atof(slack_rise.c_str());
if ( slack_fall == "INFINITY" ) slack.fall = DBL_MAX;
else slack.fall = atof(slack_fall.c_str());
slack_list.push_back(slack);
timing_lookup tran;
if ( tran_rise == "INFINITY" ) tran.rise = DBL_MAX;
else tran.rise = atof(tran_rise.c_str());
if ( tran_fall == "INFINITY" ) tran.fall = DBL_MAX;
else tran.fall = atof(tran_fall.c_str());
tran_list.push_back(tran);
timing_lookup aat;
if ( aat_rise == "INFINITY" ) aat.rise = DBL_MAX;
else aat.rise = atof(aat_rise.c_str());
if ( aat_fall == "INFINITY" ) aat.fall = DBL_MAX;
else aat.fall = atof(aat_fall.c_str());
aat_list.push_back(aat);
}
infile.close();
for (unsigned i = 0; i < numpins; ++i) {
cout << "after one timer " << getFullPinName(pins[view][i])
<< " " << pins[view][i].rtran << "/" << tran_list[i].rise << " "
<< " " << pins[view][i].ftran << "/" << tran_list[i].fall << " "
<< " " << pins[view][i].rAAT << "/" << aat_list[i].rise << " "
<< " " << pins[view][i].fAAT << "/" << aat_list[i].fall << " "
<< " " << pins[view][i].rRAT << "/" << aat_list[i].rise + slack_list[i].rise << " "
<< " " << pins[view][i].fRAT << "/" << aat_list[i].fall + slack_list[i].fall << " "
<< " " << pins[view][i].rslk << "/" << slack_list[i].rise << " "
<< " " << pins[view][i].fslk << "/" << slack_list[i].fall << " "
<< endl;
if ( !isEqual(pins[view][i].rtran, tran_list[i].rise) ||
!isEqual(pins[view][i].ftran, tran_list[i].fall) ||
//!isEqual(pins[view][i].rAAT, aat_list[i].rise) ||
//!isEqual(pins[view][i].fAAT, aat_list[i].fall) ||
!isEqual(pins[view][i].rslk, slack_list[i].rise) ||
!isEqual(pins[view][i].fslk, slack_list[i].fall) ) {
cout << "after one timer mismatch " << getFullPinName(pins[view][i])
<< " " << pins[view][i].rtran << "/" << tran_list[i].rise << " "
<< " " << pins[view][i].ftran << "/" << tran_list[i].fall << " "
<< " " << pins[view][i].rAAT << "/" << aat_list[i].rise << " "
<< " " << pins[view][i].fAAT << "/" << aat_list[i].fall << " "
<< " " << pins[view][i].rRAT << "/" << aat_list[i].rise + slack_list[i].rise << " "
<< " " << pins[view][i].fRAT << "/" << aat_list[i].fall + slack_list[i].fall << " "
<< " " << pins[view][i].rslk << "/" << slack_list[i].rise << " "
<< " " << pins[view][i].fslk << "/" << slack_list[i].fall << " "
<< endl;
}
}
ExitPTimer();
for ( unsigned i=0; i < numViews; ++i ) {
delete [] pins[i];
}
for ( unsigned i=0; i < numCorners; ++i ) {
delete [] nets[i];
}
delete [] cells;
delete [] pins;
delete [] nets;
}
void Sizer::AllCorrTest()
{
cells = new CELL[numcells];
for(unsigned i=0 ; i<numcells ; i++)
cells[i]=g_cells[i];
pins= new PIN*[numViews];
for (unsigned i = 0; i < numViews; ++i ) {
pins[i] = new PIN[numpins];
for(unsigned j=0 ; j<numpins ; j++)
pins[i][j]=g_pins[i][j];
}
nets= new NET*[numCorners];
for (unsigned i = 0; i < numCorners; ++i ) {
nets[i] = new NET[numnets];
for(unsigned j=0 ; j<numnets ; j++) {
nets[i][j]=g_nets[i][j];
}
}
PTimer = new designTiming** [1];
for (int i=0; i < 1; i++ ) {
PTimer[i] = new designTiming*[numViews];
for (int view=0; view < numViews; view++) {
cout << "Launch " << i*numViews+view << "th PT" << endl;
PTimer[i][view] = LaunchPTimer(i*numViews+view, view);
}
}
T = PTimer[0];
unsigned view = 0;
UpdateCapsFromCells();
string pt_in_file = benchname+".pin_list";
string pt_out_file = benchname+"_0.pt.tran";
T[view]->writePinAll(pt_in_file,pt_out_file);
ifstream infile(pt_out_file.c_str());
vector <timing_lookup> slack_list;
vector <timing_lookup> ceff_list;
vector <timing_lookup> tran_list;
vector <timing_lookup> aat_list;
string pin_name, slack_rise, slack_fall,
tran_rise, tran_fall, aat_rise, aat_fall;
while (infile >> pin_name >> slack_rise >> slack_fall
>> tran_rise >> tran_fall >> aat_rise >> aat_fall ) {
timing_lookup slack;
if ( slack_rise == "INFINITY" ) slack.rise = DBL_MAX;
else slack.rise = atof(slack_rise.c_str());
if ( slack_fall == "INFINITY" ) slack.fall = DBL_MAX;
else slack.fall = atof(slack_fall.c_str());
slack_list.push_back(slack);
timing_lookup tran;
if ( tran_rise == "INFINITY" ) tran.rise = DBL_MAX;
else tran.rise = atof(tran_rise.c_str());
if ( tran_fall == "INFINITY" ) tran.fall = DBL_MAX;
else tran.fall = atof(tran_fall.c_str());
tran_list.push_back(tran);
timing_lookup aat;
if ( aat_rise == "INFINITY" ) aat.rise = DBL_MAX;
else aat.rise = atof(aat_rise.c_str());
if ( aat_fall == "INFINITY" ) aat.fall = DBL_MAX;
else aat.fall = atof(aat_fall.c_str());
aat_list.push_back(aat);
}
infile.close();
CallTimer(view);
for (unsigned i = 0; i < numpins; ++i) {
cout << "before corr " << getFullPinName(pins[view][i])
<< " " << pins[view][i].rtran << "/" << tran_list[i].rise << " "
<< " " << pins[view][i].ftran << "/" << tran_list[i].fall << " "
<< " " << pins[view][i].rAAT << "/" << aat_list[i].rise << " "
<< " " << pins[view][i].fAAT << "/" << aat_list[i].fall << " "
<< " " << pins[view][i].rRAT << "/" << aat_list[i].rise + slack_list[i].rise << " "
<< " " << pins[view][i].fRAT << "/" << aat_list[i].fall + slack_list[i].fall << " "
<< " " << pins[view][i].rslk << "/" << slack_list[i].rise << " "
<< " " << pins[view][i].fslk << "/" << slack_list[i].fall << " "
<< endl;
if ( !isEqual(pins[view][i].rtran, tran_list[i].rise) ||
!isEqual(pins[view][i].ftran, tran_list[i].fall) ||
//!isEqual(pins[view][i].rAAT, aat_list[i].rise) ||
//!isEqual(pins[view][i].fAAT, aat_list[i].fall) ||
!isEqual(pins[view][i].rslk, slack_list[i].rise) ||
!isEqual(pins[view][i].fslk, slack_list[i].fall) ) {
cout << "before corr mismatch " << getFullPinName(pins[view][i])
<< " " << pins[view][i].rtran << "/" << tran_list[i].rise << " "
<< " " << pins[view][i].ftran << "/" << tran_list[i].fall << " "
<< " " << pins[view][i].rAAT << "/" << aat_list[i].rise << " "
<< " " << pins[view][i].fAAT << "/" << aat_list[i].fall << " "
<< " " << pins[view][i].rRAT << "/" << aat_list[i].rise + slack_list[i].rise << " "
<< " " << pins[view][i].fRAT << "/" << aat_list[i].fall + slack_list[i].fall << " "
<< " " << pins[view][i].rslk << "/" << slack_list[i].rise << " "
<< " " << pins[view][i].fslk << "/" << slack_list[i].fall << " "
<< endl;
}
}
CorrelatePT(view);
for (unsigned i = 0; i < numpins; ++i) {
cout << "after corr " << getFullPinName(pins[view][i])
<< " " << pins[view][i].rtran << "/" << tran_list[i].rise << " "
<< " " << pins[view][i].ftran << "/" << tran_list[i].fall << " "
<< " " << pins[view][i].rAAT << "/" << aat_list[i].rise << " "
<< " " << pins[view][i].fAAT << "/" << aat_list[i].fall << " "
<< " " << pins[view][i].rRAT << "/" << aat_list[i].rise + slack_list[i].rise << " "
<< " " << pins[view][i].fRAT << "/" << aat_list[i].fall + slack_list[i].fall << " "
<< " " << pins[view][i].rslk << "/" << slack_list[i].rise << " "
<< " " << pins[view][i].fslk << "/" << slack_list[i].fall << " "
<< endl;
if ( !isEqual(pins[view][i].rtran, tran_list[i].rise) ||
!isEqual(pins[view][i].ftran, tran_list[i].fall) ||
//!isEqual(pins[view][i].rAAT, aat_list[i].rise) ||
//!isEqual(pins[view][i].fAAT, aat_list[i].fall) ||
!isEqual(pins[view][i].rslk, slack_list[i].rise) ||
!isEqual(pins[view][i].fslk, slack_list[i].fall) ) {
cout << "after corr mismatch " << getFullPinName(pins[view][i])
<< " " << pins[view][i].rtran << "/" << tran_list[i].rise << " "
<< " " << pins[view][i].ftran << "/" << tran_list[i].fall << " "
<< " " << pins[view][i].rAAT << "/" << aat_list[i].rise << " "
<< " " << pins[view][i].fAAT << "/" << aat_list[i].fall << " "
<< " " << pins[view][i].rRAT << "/" << aat_list[i].rise + slack_list[i].rise << " "
<< " " << pins[view][i].fRAT << "/" << aat_list[i].fall + slack_list[i].fall << " "
<< " " << pins[view][i].rslk << "/" << slack_list[i].rise << " "
<< " " << pins[view][i].fslk << "/" << slack_list[i].fall << " "
<< endl;
}
}
CallTimer(view);
for (unsigned i = 0; i < numpins; ++i) {
cout << "after timer " << getFullPinName(pins[view][i])
<< " " << pins[view][i].rtran << "/" << tran_list[i].rise << " "
<< " " << pins[view][i].ftran << "/" << tran_list[i].fall << " "
<< " " << pins[view][i].rAAT << "/" << aat_list[i].rise << " "
<< " " << pins[view][i].fAAT << "/" << aat_list[i].fall << " "
<< " " << pins[view][i].rRAT << "/" << aat_list[i].rise + slack_list[i].rise << " "
<< " " << pins[view][i].fRAT << "/" << aat_list[i].fall + slack_list[i].fall << " "
<< " " << pins[view][i].rslk << "/" << slack_list[i].rise << " "
<< " " << pins[view][i].fslk << "/" << slack_list[i].fall << " "
<< endl;
if ( !isEqual(pins[view][i].rtran, tran_list[i].rise) ||
!isEqual(pins[view][i].ftran, tran_list[i].fall) ||
//!isEqual(pins[view][i].rAAT, aat_list[i].rise) ||
//!isEqual(pins[view][i].fAAT, aat_list[i].fall) ||
!isEqual(pins[view][i].rslk, slack_list[i].rise) ||
!isEqual(pins[view][i].fslk, slack_list[i].fall) ) {
cout << "after timer mismatch " << getFullPinName(pins[view][i])
<< " " << pins[view][i].rtran << "/" << tran_list[i].rise << " "
<< " " << pins[view][i].ftran << "/" << tran_list[i].fall << " "
<< " " << pins[view][i].rAAT << "/" << aat_list[i].rise << " "
<< " " << pins[view][i].fAAT << "/" << aat_list[i].fall << " "
<< " " << pins[view][i].rRAT << "/" << aat_list[i].rise + slack_list[i].rise << " "
<< " " << pins[view][i].fRAT << "/" << aat_list[i].fall + slack_list[i].fall << " "
<< " " << pins[view][i].rslk << "/" << slack_list[i].rise << " "
<< " " << pins[view][i].fslk << "/" << slack_list[i].fall << " "
<< endl;
}
}
for (unsigned i = 0; i < numcells; ++i) {
OneTimer(cells[i], STA_MARGIN);
}
for (unsigned i = 0; i < numpins; ++i) {
cout << "after one timer " << getFullPinName(pins[view][i])
<< " " << pins[view][i].rtran << "/" << tran_list[i].rise << " "
<< " " << pins[view][i].ftran << "/" << tran_list[i].fall << " "
<< " " << pins[view][i].rAAT << "/" << aat_list[i].rise << " "
<< " " << pins[view][i].fAAT << "/" << aat_list[i].fall << " "
<< " " << pins[view][i].rRAT << "/" << aat_list[i].rise + slack_list[i].rise << " "
<< " " << pins[view][i].fRAT << "/" << aat_list[i].fall + slack_list[i].fall << " "
<< " " << pins[view][i].rslk << "/" << slack_list[i].rise << " "
<< " " << pins[view][i].fslk << "/" << slack_list[i].fall << " "
<< endl;
if ( !isEqual(pins[view][i].rtran, tran_list[i].rise) ||
!isEqual(pins[view][i].ftran, tran_list[i].fall) ||
//!isEqual(pins[view][i].rAAT, aat_list[i].rise) ||
//!isEqual(pins[view][i].fAAT, aat_list[i].fall) ||
!isEqual(pins[view][i].rslk, slack_list[i].rise) ||
!isEqual(pins[view][i].fslk, slack_list[i].fall) ) {
cout << "after one timer mismatch " << getFullPinName(pins[view][i])
<< " " << pins[view][i].rtran << "/" << tran_list[i].rise << " "
<< " " << pins[view][i].ftran << "/" << tran_list[i].fall << " "
<< " " << pins[view][i].rAAT << "/" << aat_list[i].rise << " "
<< " " << pins[view][i].fAAT << "/" << aat_list[i].fall << " "
<< " " << pins[view][i].rRAT << "/" << aat_list[i].rise + slack_list[i].rise << " "
<< " " << pins[view][i].fRAT << "/" << aat_list[i].fall + slack_list[i].fall << " "
<< " " << pins[view][i].rslk << "/" << slack_list[i].rise << " "
<< " " << pins[view][i].fslk << "/" << slack_list[i].fall << " "
<< endl;
}
}
ExitPTimer();
for ( unsigned i=0; i < numViews; ++i ) {
delete [] pins[i];
}
for ( unsigned i=0; i < numCorners; ++i ) {
delete [] nets[i];
}
delete [] cells;
delete [] pins;
delete [] nets;
}
void Sizer::TranCorrTest()
{
cells = new CELL[numcells];
for(unsigned i=0 ; i<numcells ; i++)
cells[i]=g_cells[i];
pins= new PIN*[numViews];
for (unsigned i = 0; i < numViews; ++i ) {
pins[i] = new PIN[numpins];
for(unsigned j=0 ; j<numpins ; j++)
pins[i][j]=g_pins[i][j];
}
nets= new NET*[numCorners];
for (unsigned i = 0; i < numCorners; ++i ) {
nets[i] = new NET[numnets];
for(unsigned j=0 ; j<numnets ; j++) {
nets[i][j]=g_nets[i][j];
}
}
PTimer = new designTiming** [1];
for (int i=0; i < 1; i++ ) {
PTimer[i] = new designTiming*[numViews];
for (int view=0; view < numViews; view++) {
cout << "Launch " << i*numViews+view << "th PT" << endl;
PTimer[i][view] = LaunchPTimer(i*numViews+view, view);
}
}
T = PTimer[0];
unsigned view = 0;
UpdateCapsFromCells();
string pt_in_file = benchname+".pin_list";
string pt_out_file = benchname+"_0.pt.tran";
T[view]->writePinTran(pt_in_file,pt_out_file);
ifstream infile(pt_out_file.c_str());
vector <timing_lookup> tran_list;
string pin_name, rise, fall;
unsigned num = 0;
while (infile >> pin_name >> rise >> fall) {
timing_lookup tran;
if ( rise == "INFINITY" ) tran.rise = std::numeric_limits<double>::infinity();
else tran.rise = atof(rise.c_str());
if ( fall == "INFINITY" ) tran.fall = std::numeric_limits<double>::infinity();
else tran.fall = atof(fall.c_str());
tran_list.push_back(tran);
cout << "tran list" << getFullPinName(pins[view][num])
<< " " << tran_list[num].rise
<< " " << tran_list[num].fall
<< endl;
++num;
}
infile.close();
CallTimer(view);
for (unsigned i = 0; i < numpins; ++i) {
cout << "slew before corr " << getFullPinName(pins[view][i])
<< " " << pins[view][i].rtran << " " << tran_list[i].rise << " "
<< " " << pins[view][i].ftran << " " << tran_list[i].fall << " "
<< endl;
if ( !isEqual(pins[view][i].rtran, tran_list[i].rise) ||
!isEqual(pins[view][i].ftran, tran_list[i].fall) ) {
cout << "slew before corr mismatch " << getFullPinName(pins[view][i])
<< " " << pins[view][i].rtran << " " << tran_list[i].rise << " "
<< " " << pins[view][i].ftran << " " << tran_list[i].fall << " "
<< endl;
}
}
CorrelatePT(view);
for (unsigned i = 0; i < numpins; ++i) {
cout << "slew after corr " << getFullPinName(pins[view][i])
<< " " << pins[view][i].rtran << " " << pins[view][i].rtran_ofs << " " << tran_list[i].rise << " "
<< " " << pins[view][i].ftran << " " << pins[view][i].ftran_ofs << " " << tran_list[i].fall << " "
<< endl;
if ( !isEqual(pins[view][i].rtran, tran_list[i].rise) ||
!isEqual(pins[view][i].ftran, tran_list[i].fall) ) {
cout << "slew after corr mismatch " << getFullPinName(pins[view][i])
<< " " << pins[view][i].rtran << " " << pins[view][i].rtran_ofs << " " << tran_list[i].rise << " "
<< " " << pins[view][i].ftran << " " << pins[view][i].ftran_ofs << " " << tran_list[i].fall << " "
<< endl;
}
}
CallTimer(view);
for (unsigned i = 0; i < numpins; ++i) {
cout << "slew after timer " << getFullPinName(pins[view][i])
<< " " << pins[view][i].rtran << " " << pins[view][i].rtran_ofs << " " << tran_list[i].rise << " "
<< " " << pins[view][i].ftran << " " << pins[view][i].ftran_ofs << " " << tran_list[i].fall << " "
<< endl;
if ( !isEqual(pins[view][i].rtran, tran_list[i].rise) ||
!isEqual(pins[view][i].ftran, tran_list[i].fall) ) {
cout << "slew after timer mismatch " << getFullPinName(pins[view][i])
<< " " << pins[view][i].rtran << " " << pins[view][i].rtran_ofs << " " << tran_list[i].rise << " "
<< " " << pins[view][i].ftran << " " << pins[view][i].ftran_ofs << " " << tran_list[i].fall << " "
<< endl;
}
}
ExitPTimer();
for ( unsigned i=0; i < numViews; ++i ) {
delete [] pins[i];
}
for ( unsigned i=0; i < numCorners; ++i ) {
delete [] nets[i];
}
delete [] cells;
delete [] pins;
delete [] nets;
}
void Sizer::HLTest()
{
cells = new CELL[numcells];
for(unsigned i=0 ; i<numcells ; i++)
cells[i]=g_cells[i];
pins= new PIN*[numViews];
for (unsigned i = 0; i < numViews; ++i ) {
pins[i] = new PIN[numpins];
for(unsigned j=0 ; j<numpins ; j++)
pins[i][j]=g_pins[i][j];
}
nets= new NET*[numCorners];
for (unsigned i = 0; i < numCorners; ++i ) {
nets[i] = new NET[numnets];
for(unsigned j=0 ; j<numnets ; j++) {
nets[i][j]=g_nets[i][j];
}
}
for(unsigned i=0 ; i<_ckt->numnets ; i++) {
cout << "--------- all sub node list (" << nets[0][i].name << ")--------" << endl;
vector <SUB_NODE> *subNodeVecPtr = &nets[0][i].subNodeVec;
std::vector<SUB_NODE>::iterator subNodeIter;
for (subNodeIter = subNodeVecPtr->begin(); subNodeIter != subNodeVecPtr->end(); ++subNodeIter) {
cout << "Id: " << subNodeIter->id << ", Cap: " << subNodeIter->cap << " " << subNodeIter->isSink << endl;
for (unsigned int i=0; i < subNodeIter->adj.size(); ++i) {
cout << "Id: " << subNodeIter->id << ", Res: " << subNodeIter->res[i] << " Adj :" << subNodeIter->adj[i] << endl;
}
}
cout << endl ;
}
cout << "HL Test ---- " << endl;
PTimer = new designTiming** [1];
for (int i=0; i < 1; i++ ) {
PTimer[i] = new designTiming*[numViews];
for (int view=0; view < numViews; view++) {
cout << "Launch " << i*numViews+view << "th PT" << endl;
PTimer[i][view] = LaunchPTimer(i*numViews+view, view);
}
}
T = PTimer[0];
unsigned view = 0;
UpdateCapsFromCells();
CallTimer(view);
CalcStats();
UpdatePTSizes();
cout << "WNS(PT): " << T[view]->getWorstSlack(clk_name[0]) << endl;
CompareWithPT();
for(unsigned i=0 ; i< numcells ; i++) {
if(isff(cells[i]))
continue;
EstDeltaTNSNEW(cells[i], 0, 1);
//cout << "EST DELTA DELAY " << EstDeltaDelay(cells[i], 0, 1) << endl;
EstDeltaTNSNEW(cells[i], 1, 0);
//cout << "EST DELTA DELAY " << EstDeltaDelay(cells[i], 1, 0) << endl;
}
//CorrelatePT();
//CallTimer(view);
// CalcStats(0, false, "view1", view);
//
//unsigned k = timerTestCell;
// unsigned k = 0;
//
//
// PIN &pin = pins[view][cells[k].outpins[0]];
// cout << "PREV TIMING - ORIG " << getFullPinName(pin)
// << " (" << pin.rslk << "/" << pin.fslk << ")"
// << " (" << pin.rRAT << "/" << pin.fRAT << ")"
// << " (" << pin.rAAT << "/" << pin.fAAT << ")"
// << " (" << pin.rslk_ofs << "/" << pin.fslk_ofs << ")"
// << " (" << pin.totcap << "," << pin.slk_gb << ")"
// << endl;
// cell_resize(cells[k], 1);
// cout << cells[k].type << " upsized " << endl ;
// OneTimer(cells[k], STA_MARGIN);
//
// cout << "AFTER SIZING TIMING - ORIG " << getFullPinName(pin)
// << " (" << pin.rslk << "/" << pin.fslk << ")"
// << " (" << pin.rRAT << "/" << pin.fRAT << ")"
// << " (" << pin.rAAT << "/" << pin.fAAT << ")"
// << " (" << pin.rslk_ofs << "/" << pin.fslk_ofs << ")"
// << " (" << pin.totcap << "," << pin.slk_gb << ")"
// << endl;
//
// cout << cells[k].name << " " << cells[k].type << " --> ";
// cell_resize(cells[k], -1);
// cout << cells[k].type << " downsized " << endl ;
// OneTimer(cells[k], STA_MARGIN);
//
// cout << "AFTER REVERT TIMING - ORIG " << getFullPinName(pin)
// << " (" << pin.rslk << "/" << pin.fslk << ")"
// << " (" << pin.rRAT << "/" << pin.fRAT << ")"
// << " (" << pin.rAAT << "/" << pin.fAAT << ")"
// << " (" << pin.rslk_ofs << "/" << pin.fslk_ofs << ")"
// << " (" << pin.totcap << "," << pin.slk_gb << ")"
// << endl;
//
//
// cell_retype(cells[k], 1);
// cout << cells[k].type << " uptyped " << endl ;
// OneTimer(cells[k], STA_MARGIN);
//
// cout << "AFTER SIZING TIMING - ORIG " << getFullPinName(pin)
// << " (" << pin.rslk << "/" << pin.fslk << ")"
// << " (" << pin.rRAT << "/" << pin.fRAT << ")"
// << " (" << pin.rAAT << "/" << pin.fAAT << ")"
// << " (" << pin.rslk_ofs << "/" << pin.fslk_ofs << ")"
// << " (" << pin.totcap << "," << pin.slk_gb << ")"
// << endl;
//
// cout << cells[k].name << " " << cells[k].type << " --> ";
// cell_retype(cells[k], -1);
// cout << cells[k].type << " downtyped " << endl ;
// OneTimer(cells[k], STA_MARGIN);
//
// cout << "AFTER REVERT TIMING - ORIG " << getFullPinName(pin)
// << " (" << pin.rslk << "/" << pin.fslk << ")"
// << " (" << pin.rRAT << "/" << pin.fRAT << ")"
// << " (" << pin.rAAT << "/" << pin.fAAT << ")"
// << " (" << pin.rslk_ofs << "/" << pin.fslk_ofs << ")"
// << " (" << pin.totcap << "," << pin.slk_gb << ")"
// << endl;
//
// CallTimer();
// cout << "AFTER REVERT TIMING FULL STA - ORIG " << getFullPinName(pin)
// << " (" << pin.rslk << "/" << pin.fslk << ")"
// << " (" << pin.rRAT << "/" << pin.fRAT << ")"
// << " (" << pin.rAAT << "/" << pin.fAAT << ")"
// << " (" << pin.rslk_ofs << "/" << pin.fslk_ofs << ")"
// << " (" << pin.totcap << "," << pin.slk_gb << ")"
// << endl;
ExitPTimer();
for ( unsigned i=0; i < numViews; ++i ) {
delete [] pins[i];
}
for ( unsigned i=0; i < numCorners; ++i ) {
delete [] nets[i];
}
delete [] cells;
delete [] pins;
delete [] nets;
}
void Sizer::ReportCellTran(unsigned view)
{
unsigned corner = mmmcViewList[view].corner;
unsigned mode = mmmcViewList[view].mode;
cells = new CELL[numcells];
for(unsigned i=0 ; i<numcells ; i++)
cells[i]=g_cells[i];
pins= new PIN*[numViews];
for (unsigned i = 0; i < numViews; ++i ) {
pins[i] = new PIN[numpins];
for(unsigned j=0 ; j<numpins ; j++)
pins[i][j]=g_pins[i][j];
}
nets= new NET*[numCorners];
for (unsigned i = 0; i < numCorners; ++i ) {
nets[i] = new NET[numnets];
for(unsigned j=0 ; j<numnets ; j++)
nets[i][j]=g_nets[i][j];
}
SizeIn("gtr");
UpdateCapsFromCells();
CallTimer();
LaunchPTimer(0);
UpdatePTSizes();
cout << "Cell"
<< " " << "InPin"
<< " " << "R"
<< " " << setw(8) << fixed << "LE"
<< " " << setw(8) << fixed << "InTran"
<< " " << setw(8) << fixed << "Ceff"
<< " " << setw(8) << fixed << "Ctot"
<< " " << setw(8) << fixed << "PtOutTran"
<< " " << setw(8) << fixed << "TriOutTran" << endl;
for(unsigned i=0 ; i<numcells ; i++) {
double max_rise_tran, max_fall_tran;
max_rise_tran = max_fall_tran = 0.0;
unsigned max_rise_pin, max_fall_pin;
max_rise_pin = max_fall_pin = UINT_MAX;
if (isff(cells[i])) continue;
for (unsigned j=0; j < cells[i].inpins.size(); j++) {
double rise_tran, fall_tran;
rise_tran = fall_tran = 0.0;
T[view]->getPinTran(rise_tran, fall_tran, getFullPinName(pins[view][cells[i].inpins[j]]));
pins[view][cells[i].inpins[j]].rtran = rise_tran;
pins[view][cells[i].inpins[j]].ftran = fall_tran;
if (max_rise_tran < rise_tran) {
max_rise_tran = rise_tran;
max_rise_pin = cells[i].inpins[j];
}
if (max_fall_tran < fall_tran) {
max_fall_tran = fall_tran;
max_fall_pin = cells[i].inpins[j];
}
}
double ceff = T[view]->getCeff(getFullPinName(pins[view][cells[i].outpin]));
pins[view][cells[i].outpin].ceff = ceff;
double pt_rise_tran, pt_fall_tran;
double tri_rise_tran, tri_fall_tran;
pt_rise_tran = pt_fall_tran = 0.0;
tri_rise_tran = tri_fall_tran = 0.0;
T[view]->getPinTran(pt_rise_tran, pt_fall_tran, getFullPinName(pins[view][cells[i].outpin]));
timing_lookup G;
LookupST(cells[i], 0, &tri_rise_tran, &tri_fall_tran, 0, 0.0);
cout.precision(4);
cout << cells[i].type
<< " " << pins[view][max_fall_pin].name
<< " " << "R"
<< " " << setw(8) << fixed << G.fall
<< " " << setw(8) << fixed << max_fall_tran
<< " " << setw(8) << fixed << ceff
<< " " << setw(8) << fixed << pins[view][cells[i].outpin].totcap
<< " " << setw(8) << fixed << pt_rise_tran
<< " " << setw(8) << fixed << tri_rise_tran << endl;
cout << cells[i].type
<< " " << pins[view][max_rise_pin].name
<< " " << "F"
<< " " << setw(8) << fixed << G.rise
<< " " << setw(8) << fixed << max_rise_tran
<< " " << setw(8) << fixed << ceff
<< " " << setw(8) << fixed << pins[view][cells[i].outpin].totcap
<< " " << setw(8) << fixed << pt_fall_tran
<< " " << setw(8) << fixed << tri_fall_tran << endl;
}
ExitPTimer();
}
void Sizer::ReportCellTran(unsigned cellID, string prefix, unsigned view)
{
unsigned corner = mmmcViewList[view].corner;
unsigned mode = mmmcViewList[view].mode;
double max_rise_tran, max_fall_tran;
max_rise_tran = max_fall_tran = 0.0;
unsigned max_rise_pin, max_fall_pin;
max_rise_pin = max_fall_pin = UINT_MAX;
if (isff(cells[cellID])) return;
for (unsigned j=0; j < cells[cellID].inpins.size(); j++) {
double rise_tran, fall_tran;
rise_tran = fall_tran = 0.0;
T[view]->getPinTran(rise_tran, fall_tran, getFullPinName(pins[view][cells[cellID].inpins[j]]));
pins[view][cells[cellID].inpins[j]].rtran = rise_tran;
pins[view][cells[cellID].inpins[j]].ftran = fall_tran;
if (max_rise_tran < rise_tran) {
max_rise_tran = rise_tran;
max_rise_pin = cells[cellID].inpins[j];
}
if (max_fall_tran < fall_tran) {
max_fall_tran = fall_tran;
max_fall_pin = cells[cellID].inpins[j];
}
}
double ceff = T[view]->getCeff(getFullPinName(pins[view][cells[cellID].outpin]));
pins[view][cells[cellID].outpin].ceff = ceff;
double pt_rise_tran, pt_fall_tran;
double tri_rise_tran, tri_fall_tran;
pt_rise_tran = pt_fall_tran = 0.0;
tri_rise_tran = tri_fall_tran = 0.0;
T[view]->getPinTran(pt_rise_tran, pt_fall_tran, getFullPinName(pins[view][cells[cellID].outpin]));
timing_lookup G;
LookupST(cells[cellID], 0, &tri_rise_tran, &tri_fall_tran, 0, 0.0);
cout.precision(4);
cout << prefix
<< " " << cells[cellID].type
<< " " << pins[view][max_fall_pin].name
<< " " << "R"
<< " " << setw(8) << fixed << G.fall
<< " " << setw(8) << fixed << max_fall_tran
<< " " << setw(8) << fixed << ceff
<< " " << setw(8) << fixed << pins[view][cells[cellID].outpin].totcap
<< " " << setw(8) << fixed << pt_rise_tran
<< " " << setw(8) << fixed << tri_rise_tran << endl;
cout << prefix
<< " " << cells[cellID].type
<< " " << pins[view][max_rise_pin].name
<< " " << "F"
<< " " << setw(8) << fixed << G.rise
<< " " << setw(8) << fixed << max_rise_tran
<< " " << setw(8) << fixed << ceff
<< " " << setw(8) << fixed << pins[view][cells[cellID].outpin].totcap
<< " " << setw(8) << fixed << pt_fall_tran
<< " " << setw(8) << fixed << tri_fall_tran << endl;
}
|
// 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 "ppl/nn/engines/arm/optimizer/ops/onnx/less_op.h"
#include "ppl/nn/engines/arm/kernels/onnx/less_kernel.h"
#include "ppl/nn/oputils/onnx/reshape_less.h"
using namespace std;
using namespace ppl::common;
namespace ppl { namespace nn { namespace arm {
LessOp::LessOp(const ir::Node* node) : ArmOptKernel(node) {
infer_dims_func_ = [](InputOutputInfo* info) -> RetCode {
if (info->GetInput<TensorImpl>(0)->GetShape()->GetDataFormat() != DATAFORMAT_NDARRAY) {
return RC_UNSUPPORTED;
}
return onnx::ReshapeLess(info, nullptr);
};
infer_type_func_ = [](InputOutputInfo* info) -> void {
info->GetOutput<TensorImpl>(0)->GetShape()->SetDataType(DATATYPE_BOOL);
};
}
RetCode LessOp::Init(const OptKernelOptions& options) {
return RC_SUCCESS;
}
KernelImpl* LessOp::CreateKernelImpl() const {
return CreateKernelImplWithoutParam<LessKernel>();
}
}}} // namespace ppl::nn::arm
|
// -*- C++ -*-
//
// ======================================================================
//
// Brad T. Aagaard, U.S. Geological Survey
// Charles A. Williams, GNS Science
// Matthew G. Knepley, University of Chicago
//
// This code was developed as part of the Computational Infrastructure
// for Geodynamics (http://geodynamics.org).
//
// Copyright (c) 2010-2017 University of California, Davis
//
// See COPYING for license information.
//
// ======================================================================
//
#include "DataWriterHDF5DataPointsTri3.hh"
#include <assert.h> // USES assert()
const char* pylith::meshio::DataWriterHDF5DataPointsTri3::_meshFilename =
"data/tri3.mesh";
const char* pylith::meshio::DataWriterHDF5DataPointsTri3::_faultLabel =
"fault";
const int pylith::meshio::DataWriterHDF5DataPointsTri3::_faultId = 100;
const char* pylith::meshio::DataWriterHDF5DataPointsTri3::_timestepFilename =
"tri3_points.h5";
const char* pylith::meshio::DataWriterHDF5DataPointsTri3::_vertexFilename =
"tri3_points_vertex.h5";
const PylithScalar pylith::meshio::DataWriterHDF5DataPointsTri3::_time = 1.0;
const int pylith::meshio::DataWriterHDF5DataPointsTri3::_numVertices = 6;
const pylith::meshio::DataWriterData::FieldStruct
pylith::meshio::DataWriterHDF5DataPointsTri3::_vertexFields[4] = {
{ "pressure", topology::FieldBase::SCALAR, 1 },
{ "displacement", topology::FieldBase::VECTOR, 2 },
{ "stress", topology::FieldBase::TENSOR, 3 },
{ "other", topology::FieldBase::OTHER, 2 },
};
const PylithScalar pylith::meshio::DataWriterHDF5DataPointsTri3::_vertexFieldScalar[6*1] = {
2.1, // 0
3.2, // 1
4.3, // 2
5.4, // 3
6.5, // 4
7.6, // 5
};
const PylithScalar pylith::meshio::DataWriterHDF5DataPointsTri3::_vertexFieldVector[6*2] = {
1.1, 2.2, // 0
3.3, 4.4, // 1
5.5, 6.6, // 2
7.7, 8.8, // 3
9.9, 10.0, // 4
11.1, 12.2, // 5
};
const PylithScalar pylith::meshio::DataWriterHDF5DataPointsTri3::_vertexFieldTensor[6*3] = {
1.1, 1.2, 1.3,
2.1, 2.2, 2.3,
3.1, 3.2, 3.3,
4.1, 4.2, 4.3,
5.1, 5.2, 5.3,
6.1, 6.2, 6.3,
};
const PylithScalar pylith::meshio::DataWriterHDF5DataPointsTri3::_vertexFieldOther[6*2] = {
1.2, 2.3, // 0
3.4, 4.5, // 1
5.6, 6.7, // 2
7.8, 8.9, // 3
9.0, 10.1, // 4
11.2, 12.3, // 5
};
const int pylith::meshio::DataWriterHDF5DataPointsTri3::_numPoints = 3;
const int pylith::meshio::DataWriterHDF5DataPointsTri3::_spaceDim = 2;
const PylithScalar pylith::meshio::DataWriterHDF5DataPointsTri3::_points[3*2] = {
-0.3333333, 0.0,
0.0000001, 0.0,
0.9999999, 0.0,
};
const char* const pylith::meshio::DataWriterHDF5DataPointsTri3::_names[3] = {
"ZZ.A",
"ZZ.B",
"ZZ.C",
};
pylith::meshio::DataWriterHDF5DataPointsTri3::DataWriterHDF5DataPointsTri3(void)
{ // constructor
meshFilename = const_cast<char*>(_meshFilename);
faultLabel = const_cast<char*>(_faultLabel);
faultId = _faultId;
timestepFilename = const_cast<char*>(_timestepFilename);
vertexFilename = const_cast<char*>(_vertexFilename);
time = _time;
numVertices = _numVertices;
assert(DataWriterData::numVertexFields == numVertexFields);
vertexFieldsInfo = const_cast<DataWriterData::FieldStruct*>(_vertexFields);
vertexFields[0] = const_cast<PylithScalar*>(_vertexFieldScalar);
vertexFields[1] = const_cast<PylithScalar*>(_vertexFieldVector);
vertexFields[2] = const_cast<PylithScalar*>(_vertexFieldTensor);
vertexFields[3] = const_cast<PylithScalar*>(_vertexFieldOther);
numPoints = _numPoints;
spaceDim = _spaceDim;
points = const_cast<PylithScalar*>(_points);
names = _names;
} // constructor
pylith::meshio::DataWriterHDF5DataPointsTri3::~DataWriterHDF5DataPointsTri3(void)
{}
// End of file
|
/*
* Copyright (c) 2019, Intel Corporation
*
* 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.
*/
//!
//! \file decode_av1_pipeline.cpp
//! \brief Defines the interface for av1 decode pipeline
//!
#include "decode_av1_pipeline.h"
#include "decode_utils.h"
#include "media_user_settings_mgr_g12.h"
#include "codechal_setting.h"
#include "decode_av1_feature_manager.h"
namespace decode {
Av1Pipeline::Av1Pipeline(
CodechalHwInterface * hwInterface,
CodechalDebugInterface *debugInterface)
: DecodePipeline(hwInterface, debugInterface)
{
}
MOS_STATUS Av1Pipeline::Initialize(void *settings)
{
DECODE_FUNC_CALL();
DECODE_CHK_STATUS(DecodePipeline::Initialize(settings));
m_cdfCopyPkt = MOS_New(HucCopyPkt, this, m_task, m_hwInterface);
DECODE_CHK_NULL(m_cdfCopyPkt);
DECODE_CHK_STATUS(RegisterPacket(DecodePacketId(this, defaultCdfBufCopyPacketId), m_cdfCopyPkt));
DECODE_CHK_STATUS(m_cdfCopyPkt->Init());
auto *codecSettings = (CodechalSetting*)settings;
DECODE_CHK_NULL(codecSettings);
MOS_USER_FEATURE_VALUE_DATA userFeatureData;
MOS_ZeroMemory(&userFeatureData, sizeof(userFeatureData));
#if (_DEBUG || _RELEASE_INTERNAL)
MOS_UserFeature_ReadValue_ID(
nullptr,
__MEDIA_USER_FEATURE_VALUE_FORCE_AV1_TILE_BASED_DECODE_ID,
&userFeatureData,
m_osInterface ? m_osInterface->pOsContext : nullptr);
#endif
m_forceTileBasedDecoding = userFeatureData.i32Data;
return MOS_STATUS_SUCCESS;
}
MOS_STATUS Av1Pipeline::Prepare(void *params)
{
DECODE_FUNC_CALL();
DECODE_CHK_NULL(params);
auto basicFeature = dynamic_cast<Av1BasicFeature*>(m_featureManager->GetFeature(FeatureIDs::basicFeature));
DECODE_CHK_NULL(basicFeature);
DECODE_CHK_STATUS(DecodePipeline::Prepare(params));
if (basicFeature->m_frameNum == 0)
{
for (uint8_t i = 0; i < av1DefaultCdfTableNum; i++)
{
HucCopyPkt::HucCopyParams copyParams = {};
copyParams.srcBuffer = &(basicFeature->m_tmpCdfBuffers[i]->OsResource);
copyParams.srcOffset = 0;
copyParams.destBuffer = &(basicFeature->m_defaultCdfBuffers[i]->OsResource);
copyParams.destOffset = 0;
copyParams.copyLength = basicFeature->m_cdfMaxNumBytes;
m_cdfCopyPkt->PushCopyParams(copyParams);
}
}
return MOS_STATUS_SUCCESS;
}
MOS_STATUS Av1Pipeline::Uninitialize()
{
DECODE_FUNC_CALL();
return DecodePipeline::Uninitialize();
}
MOS_STATUS Av1Pipeline::UserFeatureReport()
{
DECODE_FUNC_CALL();
DECODE_CHK_STATUS(DecodePipeline::UserFeatureReport());
#if (_DEBUG || _RELEASE_INTERNAL)
WriteUserFeature(__MEDIA_USER_FEATURE_VALUE_APOGEIOS_AV1D_ENABLE_ID_G12, 1, m_osInterface->pOsContext);
#endif
return MOS_STATUS_SUCCESS;
}
MOS_STATUS Av1Pipeline::ActivateDecodePackets()
{
DECODE_FUNC_CALL();
bool immediateSubmit = true;
if (m_isFirstTileInFrm)
{
DECODE_CHK_STATUS(ActivatePacket(DecodePacketId(this, defaultCdfBufCopyPacketId), immediateSubmit, 0, 0));
m_isFirstTileInFrm = false;
}
if (!m_forceTileBasedDecoding)
{
immediateSubmit = false;
}
for (uint8_t curPass = 0; curPass < GetPassNum(); curPass++)
{
DECODE_CHK_STATUS(ActivatePacket(DecodePacketId(this, av1DecodePacketId), immediateSubmit, curPass, 0));
}
return MOS_STATUS_SUCCESS;
}
bool Av1Pipeline::FrameBasedDecodingInUse()
{
auto basicFeature = dynamic_cast<Av1BasicFeature*>(m_featureManager->GetFeature(FeatureIDs::basicFeature));
bool isframeBasedDecodingUsed = false;
if (basicFeature != nullptr)
{
isframeBasedDecodingUsed = ((basicFeature->m_av1PicParams->m_loopRestorationFlags.m_fields.m_yframeRestorationType > 0) &
((basicFeature->m_av1PicParams->m_loopRestorationFlags.m_fields.m_cbframeRestorationType |
basicFeature->m_av1PicParams->m_loopRestorationFlags.m_fields.m_crframeRestorationType) > 0) &&
basicFeature->m_av1PicParams->m_picInfoFlags.m_fields.m_useSuperres && MEDIA_IS_WA(GetWaTable(), Wa_1409820462)
|| !m_forceTileBasedDecoding);
}
return isframeBasedDecodingUsed;
}
MOS_STATUS Av1Pipeline::CreateFeatureManager()
{
DECODE_FUNC_CALL();
m_featureManager = MOS_New(DecodeAv1FeatureManager, m_allocator, m_hwInterface);
DECODE_CHK_NULL(m_featureManager);
return MOS_STATUS_SUCCESS;
}
Av1Pipeline::Av1DecodeMode Av1Pipeline::GetDecodeMode()
{
return m_decodeMode;
}
}
|
#include "Icons.h"
gui::Icons::Icons()
{
}
gui::Icons::~Icons()
{
}
std::pair<unsigned char*, unsigned int> gui::Icons::get(Icon icon)
{
switch (icon)
{
case gui::Icons::CHECKBOX:
return { _checkbox_icon, _checkbox_icon_size };
break;
case gui::Icons::RADIO_BUTTON_MARK:
return { _radio_button_mark_icon, _radio_button_mark_icon_size };
break;
case gui::Icons::RADIO_BUTTON_OUTLINE:
return { _radio_button_outline_icon, _radio_button_outline_icon_size };
break;
default:
return { nullptr, 0 };
break;
}
}
unsigned char gui::Icons::_checkbox_icon[] =
{
137,80,78,71,13,10,26,10,0,0,0,13,73,72,68,82,0,0,0,50,0,0,0,50,8,6,0,0,0,30,63,136,177,0,0,0,4,115,66,73,84,8,8,8,8,124,8,100,136,0,0,0,9,112,72,89,115,0,0,13,215,0,0,13,215,1,66,40,155,120,0,0,0,25,116,
69,88,116,83,111,102,116,119,97,114,101,0,119,119,119,46,105,110,107,115,99,97,112,101,46,111,114,103,155,238,60,26,0,0,1,9,73,68,65,84,104,129,237,209,193,105,2,81,20,133,225,223,201,202,2,2,113,149,14,
172,67,177,11,59,72,27,65,178,12,1,177,5,59,72,27,105,192,157,235,128,217,132,201,66,47,72,112,102,222,155,17,238,121,204,253,225,110,223,156,143,129,40,138,70,209,131,247,128,204,150,192,20,56,122,15,
25,210,2,56,113,70,204,157,183,244,206,16,245,229,138,196,252,71,20,137,105,66,20,133,89,1,63,52,35,236,62,189,6,166,212,245,39,236,190,128,39,167,141,157,5,66,165,64,168,20,8,149,2,161,82,32,84,10,132,
74,129,184,71,107,224,117,224,27,18,136,223,203,71,222,122,190,33,133,176,203,197,72,34,114,49,210,136,84,140,59,2,96,155,48,160,6,54,202,8,128,9,240,158,48,228,214,159,145,65,88,125,48,114,8,43,7,179,
87,69,88,57,24,89,132,117,15,140,59,194,26,130,145,65,88,125,48,114,8,171,2,118,164,33,14,192,163,207,204,180,38,192,7,237,136,111,224,217,107,96,78,109,152,98,16,214,45,76,113,8,235,26,83,44,194,170,128,
23,96,230,61,36,138,162,145,245,7,158,86,180,127,7,179,93,255,0,0,0,0,73,69,78,68,174,66,96,130,0
};
unsigned char gui::Icons::_radio_button_mark_icon[] =
{
137,80,78,71,13,10,26,10,0,0,0,13,73,72,68,82,0,0,0,50,0,0,0,50,8,6,0,0,0,30,63,136,177,0,0,0,4,115,66,73,84,8,8,8,8,124,8,100,136,0,0,0,9,112,72,89,115,0,0,13,215,0,0,13,215,1,66,40,155,120,0,0,0,25,116,
69,88,116,83,111,102,116,119,97,114,101,0,119,119,119,46,105,110,107,115,99,97,112,101,46,111,114,103,155,238,60,26,0,0,2,15,73,68,65,84,104,129,237,153,187,74,3,65,20,134,63,163,177,16,109,188,20,18,181,
84,251,136,96,105,222,65,20,125,2,193,231,80,123,149,40,214,214,22,94,26,193,7,16,125,0,237,212,160,224,165,210,34,105,162,197,100,32,44,115,66,54,115,217,17,247,131,211,76,72,242,127,217,205,204,236,25,
200,201,201,249,23,244,57,252,172,126,96,17,88,6,202,192,60,48,9,12,183,94,255,6,94,128,123,224,14,184,6,110,128,166,195,12,86,76,3,187,64,13,248,73,89,207,192,14,48,21,60,117,27,19,192,17,208,32,189,64,
178,26,64,21,24,15,106,0,172,3,159,22,193,165,250,0,214,66,8,20,129,99,15,2,201,58,108,125,151,23,134,128,203,0,18,186,46,90,223,233,148,98,96,9,93,87,192,160,75,145,16,183,147,84,85,87,18,27,25,74,232,
90,181,149,24,3,222,35,16,249,196,114,106,62,138,64,66,215,65,175,18,83,184,89,236,92,85,3,152,145,194,22,58,136,108,225,120,198,176,100,16,216,76,251,166,2,106,31,148,245,85,72,86,13,181,57,237,154,165,
8,66,75,181,104,10,44,221,90,203,105,172,3,83,49,13,74,34,11,30,131,216,82,54,13,74,34,179,30,131,216,50,103,26,148,68,38,61,6,177,197,152,77,18,25,22,198,99,96,196,52,216,105,29,249,83,72,34,223,65,83,
164,227,203,52,40,137,188,122,12,98,139,49,155,36,242,224,49,136,45,247,166,65,73,228,214,99,16,91,140,217,36,145,107,143,65,108,73,149,173,0,60,145,253,190,42,89,143,8,63,190,116,69,154,192,73,26,243,
64,156,208,67,139,53,182,7,171,58,80,74,43,161,169,70,32,160,107,175,87,9,128,81,226,104,62,124,224,160,47,188,22,129,200,138,173,132,230,48,67,137,125,87,18,160,158,147,79,51,144,56,7,6,92,138,128,106,
40,95,4,148,56,195,67,19,91,83,36,204,76,182,143,135,43,97,98,21,63,179,217,27,14,255,216,221,50,134,106,99,214,45,130,235,170,163,214,137,209,160,6,9,74,168,3,205,94,246,102,79,192,54,22,43,182,198,229,
241,116,1,213,70,170,160,90,54,115,168,128,237,199,211,53,212,179,206,45,106,23,123,71,68,199,211,57,57,57,127,128,95,118,237,244,21,64,231,25,42,0,0,0,0,73,69,78,68,174,66,96,130,0
};
unsigned char gui::Icons::_radio_button_outline_icon[] =
{
137,80,78,71,13,10,26,10,0,0,0,13,73,72,68,82,0,0,0,55,0,0,0,55,8,6,0,0,0,168,219,210,70,0,0,0,4,115,66,73,84,8,8,8,8,124,8,100,136,0,0,0,9,112,72,89,115,0,0,13,215,0,0,13,215,1,66,40,155,120,0,0,0,25,
116,69,88,116,83,111,102,116,119,97,114,101,0,119,119,119,46,105,110,107,115,99,97,112,101,46,111,114,103,155,238,60,26,0,0,4,76,73,68,65,84,104,129,221,218,77,111,21,85,24,7,240,31,35,132,22,69,19,74,
98,164,93,40,34,80,22,134,2,98,99,4,137,38,2,209,24,12,59,216,249,25,52,18,87,190,66,19,87,4,34,224,135,80,49,134,16,23,26,55,136,82,49,193,96,160,70,93,26,19,68,160,8,45,47,173,139,51,147,51,94,110,161,
189,115,238,157,214,127,50,153,59,247,204,61,207,255,220,243,242,188,206,147,30,75,177,5,235,177,18,171,176,4,247,227,65,92,193,63,184,136,243,24,193,48,190,193,133,54,240,169,140,62,236,193,143,152,192,
100,11,215,109,156,198,155,232,77,65,106,94,197,223,15,226,45,188,132,172,161,237,38,126,195,57,252,137,203,194,192,51,60,132,135,177,26,203,177,160,225,183,19,248,2,123,241,93,69,142,51,198,26,124,233,
206,127,255,12,222,193,115,88,56,205,190,186,132,101,252,46,126,106,210,231,113,244,167,163,126,119,34,67,184,81,18,126,29,135,176,54,145,140,1,28,198,88,73,198,56,246,153,254,31,54,99,172,20,246,84,33,
240,38,246,227,145,54,201,91,134,3,185,156,66,230,105,60,145,90,208,118,225,148,43,132,124,139,39,83,11,153,2,107,113,178,36,251,50,182,165,234,124,151,184,12,39,132,217,106,60,0,218,141,249,120,91,56,
81,139,85,243,90,213,78,119,151,58,188,134,87,170,118,88,17,175,10,123,188,80,29,187,91,237,104,187,56,99,127,227,217,20,236,18,96,19,46,9,188,110,96,235,76,59,88,33,172,237,98,198,54,165,100,151,0,131,
184,42,240,27,21,172,160,105,161,75,60,21,111,171,127,41,78,133,29,162,53,116,90,224,125,79,12,137,39,211,222,182,81,75,131,50,215,125,247,122,121,141,184,207,78,8,167,212,108,198,124,81,77,140,187,135,
37,83,152,84,55,117,78,143,85,197,90,220,18,77,181,166,24,20,167,120,127,103,120,37,195,65,145,251,198,102,47,124,46,218,138,237,50,169,218,133,94,209,22,61,218,216,216,39,42,235,67,157,229,149,12,71,4,
254,183,52,248,131,123,196,105,77,101,221,119,26,27,196,49,188,81,110,40,244,218,153,26,72,165,196,89,97,28,195,4,175,120,169,120,50,126,90,19,169,84,248,36,191,15,96,73,38,120,193,69,136,224,171,58,24,
37,196,215,249,61,195,150,76,136,82,17,116,219,201,90,40,165,195,9,225,64,129,245,153,16,164,129,95,5,45,63,151,49,134,223,243,207,171,50,209,109,31,169,135,79,114,156,207,239,43,51,244,228,15,127,212,
68,38,53,138,113,244,100,120,32,127,24,173,137,76,106,20,227,88,156,161,59,127,24,171,137,76,106,92,203,239,139,50,193,150,100,154,206,222,28,192,162,252,126,45,19,220,117,88,92,19,153,212,40,198,49,154,
137,153,149,185,230,9,76,133,98,28,23,50,252,146,63,76,59,200,50,203,81,232,237,145,76,212,11,203,205,253,125,215,141,71,243,207,35,153,220,130,22,162,200,131,117,48,74,136,103,196,184,207,112,38,100,52,
39,242,47,158,175,133,82,58,20,252,39,132,113,33,196,253,38,133,252,216,92,198,207,194,56,78,149,191,44,123,226,3,53,144,74,129,178,39,254,122,185,161,87,140,161,28,238,60,175,36,248,88,140,161,44,107,
108,60,154,55,142,53,107,156,229,232,19,163,95,159,53,123,225,105,113,90,15,116,142,87,18,124,36,114,127,106,170,151,142,139,17,231,185,18,5,91,39,70,156,143,221,237,197,126,193,27,159,20,66,14,179,61,
87,176,0,223,139,185,130,213,119,127,61,100,75,138,41,30,106,43,181,234,248,208,12,51,82,11,69,189,55,33,164,106,103,35,118,138,249,185,97,51,40,227,40,103,86,175,99,115,59,216,85,192,102,49,55,126,69,
11,70,255,54,49,87,119,201,236,73,29,111,22,115,226,227,120,177,213,142,26,171,25,118,164,96,87,1,59,253,183,154,97,87,213,14,255,183,117,40,5,182,138,123,176,80,19,157,210,131,235,196,227,190,216,34,45,
47,197,169,176,66,60,69,11,27,238,160,68,181,145,77,208,39,88,30,133,130,158,196,15,120,188,77,242,116,9,122,176,80,244,133,45,122,68,204,57,84,197,6,193,8,46,203,24,23,244,88,219,170,246,202,232,23,77,
181,242,117,22,239,9,78,227,116,67,22,221,120,1,239,139,254,88,249,58,166,197,248,78,213,74,217,141,66,165,236,203,184,175,161,237,150,144,148,56,39,132,184,71,243,239,230,11,225,183,101,2,233,199,220,
105,230,221,22,42,101,63,208,224,120,214,129,94,33,85,59,44,158,104,173,212,56,159,18,28,205,36,46,87,213,153,107,134,37,98,117,250,42,161,8,181,71,200,73,20,213,233,87,241,151,59,171,211,47,166,36,242,
47,34,28,92,114,250,16,170,169,0,0,0,0,73,69,78,68,174,66,96,130,0
};
|
/*
* Copyright (c) 2021, Andreas Kling <kling@serenityos.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include "ConnectionFromClient.h"
#include <ConfigServer/ConfigClientEndpoint.h>
#include <LibCore/ConfigFile.h>
#include <LibCore/FileWatcher.h>
#include <LibCore/Timer.h>
namespace ConfigServer {
static HashMap<int, RefPtr<ConnectionFromClient>> s_connections;
struct CachedDomain {
String domain;
NonnullRefPtr<Core::ConfigFile> config;
RefPtr<Core::FileWatcher> watcher;
};
static HashMap<String, NonnullOwnPtr<CachedDomain>> s_cache;
static constexpr int s_disk_sync_delay_ms = 5'000;
static void for_each_monitoring_connection(String const& domain, ConnectionFromClient* excluded_connection, Function<void(ConnectionFromClient&)> callback)
{
for (auto& it : s_connections) {
if (it.value->is_monitoring_domain(domain) && (!excluded_connection || it.value != excluded_connection))
callback(*it.value);
}
}
static Core::ConfigFile& ensure_domain_config(String const& domain)
{
auto it = s_cache.find(domain);
if (it != s_cache.end())
return *it->value->config;
auto config = Core::ConfigFile::open_for_app(domain, Core::ConfigFile::AllowWriting::Yes).release_value_but_fixme_should_propagate_errors();
// FIXME: Use a single FileWatcher with multiple watches inside.
auto watcher_or_error = Core::FileWatcher::create(InodeWatcherFlags::Nonblock);
VERIFY(!watcher_or_error.is_error());
auto result = watcher_or_error.value()->add_watch(config->filename(), Core::FileWatcherEvent::Type::ContentModified);
VERIFY(!result.is_error());
watcher_or_error.value()->on_change = [config, domain](auto&) {
auto new_config = Core::ConfigFile::open(config->filename(), Core::ConfigFile::AllowWriting::Yes).release_value_but_fixme_should_propagate_errors();
for (auto& group : config->groups()) {
for (auto& key : config->keys(group)) {
if (!new_config->has_key(group, key)) {
for_each_monitoring_connection(domain, nullptr, [&domain, &group, &key](ConnectionFromClient& connection) {
connection.async_notify_removed_key(domain, group, key);
});
}
}
}
// FIXME: Detect type of keys.
for (auto& group : new_config->groups()) {
for (auto& key : new_config->keys(group)) {
auto old_value = config->read_entry(group, key);
auto new_value = new_config->read_entry(group, key);
if (old_value != new_value) {
for_each_monitoring_connection(domain, nullptr, [&domain, &group, &key, &new_value](ConnectionFromClient& connection) {
connection.async_notify_changed_string_value(domain, group, key, new_value);
});
}
}
}
// FIXME: Refactor this whole thing so that we don't need a cache lookup here.
s_cache.get(domain).value()->config = new_config;
};
auto cache_entry = make<CachedDomain>(domain, config, watcher_or_error.release_value());
s_cache.set(domain, move(cache_entry));
return *config;
}
ConnectionFromClient::ConnectionFromClient(NonnullOwnPtr<Core::Stream::LocalSocket> client_socket, int client_id)
: IPC::ConnectionFromClient<ConfigClientEndpoint, ConfigServerEndpoint>(*this, move(client_socket), client_id)
, m_sync_timer(Core::Timer::create_single_shot(s_disk_sync_delay_ms, [this]() { sync_dirty_domains_to_disk(); }))
{
s_connections.set(client_id, *this);
}
ConnectionFromClient::~ConnectionFromClient()
{
}
void ConnectionFromClient::die()
{
s_connections.remove(client_id());
m_sync_timer->stop();
sync_dirty_domains_to_disk();
}
void ConnectionFromClient::pledge_domains(Vector<String> const& domains)
{
if (m_has_pledged) {
did_misbehave("Tried to pledge domains twice.");
return;
}
m_has_pledged = true;
for (auto& domain : domains)
m_pledged_domains.set(domain);
}
void ConnectionFromClient::monitor_domain(String const& domain)
{
if (m_has_pledged && !m_pledged_domains.contains(domain)) {
did_misbehave("Attempt to monitor non-pledged domain");
return;
}
m_monitored_domains.set(domain);
}
bool ConnectionFromClient::validate_access(String const& domain, String const& group, String const& key)
{
if (!m_has_pledged)
return true;
if (m_pledged_domains.contains(domain))
return true;
did_misbehave(String::formatted("Blocked attempt to access domain '{}', group={}, key={}", domain, group, key).characters());
return false;
}
void ConnectionFromClient::sync_dirty_domains_to_disk()
{
if (m_dirty_domains.is_empty())
return;
auto dirty_domains = move(m_dirty_domains);
dbgln("Syncing {} dirty domains to disk", dirty_domains.size());
for (auto domain : dirty_domains) {
auto& config = ensure_domain_config(domain);
if (auto result = config.sync(); result.is_error()) {
dbgln("Failed to write config '{}' to disk: {}", domain, result.error());
// Put it back in the list since it's still dirty.
m_dirty_domains.set(domain);
}
}
}
Messages::ConfigServer::ListConfigKeysResponse ConnectionFromClient::list_config_keys(String const& domain, String const& group)
{
if (!validate_access(domain, group, ""))
return Vector<String> {};
auto& config = ensure_domain_config(domain);
return { config.keys(group) };
}
Messages::ConfigServer::ListConfigGroupsResponse ConnectionFromClient::list_config_groups(String const& domain)
{
if (!validate_access(domain, "", ""))
return Vector<String> {};
auto& config = ensure_domain_config(domain);
return { config.groups() };
}
Messages::ConfigServer::ReadStringValueResponse ConnectionFromClient::read_string_value(String const& domain, String const& group, String const& key)
{
if (!validate_access(domain, group, key))
return nullptr;
auto& config = ensure_domain_config(domain);
if (!config.has_key(group, key))
return Optional<String> {};
return Optional<String> { config.read_entry(group, key) };
}
Messages::ConfigServer::ReadI32ValueResponse ConnectionFromClient::read_i32_value(String const& domain, String const& group, String const& key)
{
if (!validate_access(domain, group, key))
return nullptr;
auto& config = ensure_domain_config(domain);
if (!config.has_key(group, key))
return Optional<i32> {};
return Optional<i32> { config.read_num_entry(group, key) };
}
Messages::ConfigServer::ReadBoolValueResponse ConnectionFromClient::read_bool_value(String const& domain, String const& group, String const& key)
{
if (!validate_access(domain, group, key))
return nullptr;
auto& config = ensure_domain_config(domain);
if (!config.has_key(group, key))
return Optional<bool> {};
return Optional<bool> { config.read_bool_entry(group, key) };
}
void ConnectionFromClient::start_or_restart_sync_timer()
{
if (m_sync_timer->is_active())
m_sync_timer->restart();
else
m_sync_timer->start();
}
void ConnectionFromClient::write_string_value(String const& domain, String const& group, String const& key, String const& value)
{
if (!validate_access(domain, group, key))
return;
auto& config = ensure_domain_config(domain);
if (config.has_key(group, key) && config.read_entry(group, key) == value)
return;
config.write_entry(group, key, value);
m_dirty_domains.set(domain);
start_or_restart_sync_timer();
for_each_monitoring_connection(domain, this, [&domain, &group, &key, &value](ConnectionFromClient& connection) {
connection.async_notify_changed_string_value(domain, group, key, value);
});
}
void ConnectionFromClient::write_i32_value(String const& domain, String const& group, String const& key, i32 value)
{
if (!validate_access(domain, group, key))
return;
auto& config = ensure_domain_config(domain);
if (config.has_key(group, key) && config.read_num_entry(group, key) == value)
return;
config.write_num_entry(group, key, value);
m_dirty_domains.set(domain);
start_or_restart_sync_timer();
for_each_monitoring_connection(domain, this, [&domain, &group, &key, &value](ConnectionFromClient& connection) {
connection.async_notify_changed_i32_value(domain, group, key, value);
});
}
void ConnectionFromClient::write_bool_value(String const& domain, String const& group, String const& key, bool value)
{
if (!validate_access(domain, group, key))
return;
auto& config = ensure_domain_config(domain);
if (config.has_key(group, key) && config.read_bool_entry(group, key) == value)
return;
config.write_bool_entry(group, key, value);
m_dirty_domains.set(domain);
start_or_restart_sync_timer();
for_each_monitoring_connection(domain, this, [&domain, &group, &key, &value](ConnectionFromClient& connection) {
connection.async_notify_changed_bool_value(domain, group, key, value);
});
}
void ConnectionFromClient::remove_key(String const& domain, String const& group, String const& key)
{
if (!validate_access(domain, group, key))
return;
auto& config = ensure_domain_config(domain);
if (!config.has_key(group, key))
return;
config.remove_entry(group, key);
m_dirty_domains.set(domain);
start_or_restart_sync_timer();
for_each_monitoring_connection(domain, this, [&domain, &group, &key](ConnectionFromClient& connection) {
connection.async_notify_removed_key(domain, group, key);
});
}
}
|
#include "Logger.hpp"
#include "AmxDebugManager.hpp"
#include "LogManager.hpp"
#include "LogConfig.hpp"
#include "amx/amx2.h"
#include "utils.hpp"
#include <fmt/format.h>
#include <fmt/time.h>
#include <ctime>
Logger::Logger(std::string module_name) :
_moduleName(std::move(module_name)),
_logFilePath(LogConfig::Get()->GetGlobalConfig().LogsRootFolder + _moduleName + ".log"),
_logCounter(0)
{
//create possibly non-existing folders before opening log file
utils::EnsureFolders(_logFilePath);
LogConfig::Get()->SubscribeLogger(this,
std::bind(&Logger::OnConfigUpdate, this, std::placeholders::_1));
if (_config.Append == false)
{
// create file if it doesn't exist, and truncate whole content
std::ofstream logfile(_logFilePath, std::ofstream::trunc);
}
}
Logger::~Logger()
{
LogConfig::Get()->UnsubscribeLogger(this);
LogRotationManager::Get()->UnregisterLogFile(_logFilePath);
// wait until all log messages are processed, as we have this logger
// referenced in the action lambda and deleting it would be bad
while (_logCounter != 0)
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
bool Logger::Log(LogLevel level, std::string msg,
std::vector<samplog::AmxFuncCallInfo> const &call_info)
{
if (!IsLogLevel(level))
return false;
auto current_time = Clock::now();
LogManager::Get()->Queue([this, level, current_time, msg, call_info]()
{
std::string const
time_str = FormatTimestamp(current_time),
log_msg = FormatLogMessage(msg, call_info);
WriteLogString(time_str, level, log_msg);
LogManager::Get()->WriteLevelLogString(time_str, level, GetModuleName(), msg);
auto const &level_config = LogConfig::Get()->GetLogLevelConfig(level);
if (_config.PrintToConsole || level_config.PrintToConsole)
PrintLogString(time_str, level, log_msg);
--_logCounter;
});
++_logCounter;
return true;
}
bool Logger::Log(LogLevel level, std::string msg)
{
static const std::vector<samplog::AmxFuncCallInfo> empty_call_info;
return Log(level, std::move(msg), empty_call_info);
}
bool Logger::LogNativeCall(AMX * const amx, cell * const params,
std::string name, std::string params_format)
{
if (amx == nullptr)
return false;
if (params == nullptr)
return false;
if (name.empty())
return false;
if (!IsLogLevel(LogLevel::DEBUG))
return false;
fmt::memory_buffer fmt_msg;
fmt::format_to(fmt_msg, "{:s}(", name);
for (size_t i = 0; i != params_format.length(); ++i)
{
if (i != 0)
fmt::format_to(fmt_msg, ", ");
cell current_param = params[i + 1];
switch (params_format[i])
{
case 'd': //decimal
case 'i': //integer
fmt::format_to(fmt_msg, "{:d}", static_cast<int>(current_param));
break;
case 'f': //float
fmt::format_to(fmt_msg, "{:f}", amx_ctof(current_param));
break;
case 'h': //hexadecimal
case 'x': //
fmt::format_to(fmt_msg, "{:x}", current_param);
break;
case 'b': //binary
fmt::format_to(fmt_msg, "{:b}", current_param);
break;
case 's': //string
fmt::format_to(fmt_msg, "\"{:s}\"", amx_GetCppString(amx, current_param));
break;
case '*': //censored output
fmt::format_to(fmt_msg, "\"*****\"");
break;
case 'r': //reference
{
cell *addr_dest = nullptr;
amx_GetAddr(amx, current_param, &addr_dest);
fmt::format_to(fmt_msg, "{:#08x}", reinterpret_cast<unsigned int>(addr_dest));
} break;
case 'p': //pointer-value
fmt::format_to(fmt_msg, "{:#08x}", current_param);
break;
default:
return false; //unrecognized format specifier
}
}
fmt::format_to(fmt_msg, ")");
std::vector<samplog::AmxFuncCallInfo> call_info;
AmxDebugManager::Get()->GetFunctionCallTrace(amx, call_info);
return Log(LogLevel::DEBUG, fmt::to_string(fmt_msg), call_info);
}
void Logger::OnConfigUpdate(Logger::Config const &config)
{
_config = config;
LogRotationManager::Get()->RegisterLogFile(_logFilePath, _config.Rotation);
}
std::string Logger::FormatTimestamp(Clock::time_point time)
{
std::time_t now_c = std::chrono::system_clock::to_time_t(time);
auto const &time_format = LogConfig::Get()->GetGlobalConfig().LogTimeFormat;
return fmt::format("{:" + time_format + "}", fmt::localtime(now_c));
}
std::string Logger::FormatLogMessage(std::string message,
std::vector<samplog::AmxFuncCallInfo> call_info)
{
fmt::memory_buffer log_string_buf;
fmt::format_to(log_string_buf, "{:s}", message);
if (!call_info.empty())
{
fmt::format_to(log_string_buf, " (");
bool first = true;
for (auto const &ci : call_info)
{
if (!first)
fmt::format_to(log_string_buf, " -> ");
fmt::format_to(log_string_buf, "{:s}:{:d}", ci.file, ci.line);
first = false;
}
fmt::format_to(log_string_buf, ")");
}
return fmt::to_string(log_string_buf);
}
void Logger::WriteLogString(std::string const &time, LogLevel level, std::string const &message)
{
utils::EnsureFolders(_logFilePath);
std::ofstream logfile(_logFilePath,
std::ofstream::out | std::ofstream::app);
logfile <<
"[" << time << "] " <<
"[" << utils::GetLogLevelAsString(level) << "] " <<
message << '\n' << std::flush;
}
void Logger::PrintLogString(std::string const &time, LogLevel level, std::string const &message)
{
auto *loglevel_str = utils::GetLogLevelAsString(level);
if (LogConfig::Get()->GetGlobalConfig().EnableColors)
{
utils::EnsureTerminalColorSupport();
fmt::print("[");
fmt::print(fmt::fg(fmt::rgb(255, 255, 150)), time);
fmt::print("] [");
fmt::print(fmt::fg(fmt::color::sandy_brown), GetModuleName());
fmt::print("] [");
auto loglevel_color = utils::GetLogLevelColor(level);
if (level == LogLevel::FATAL)
fmt::print(fmt::fg(fmt::color::white) | fmt::bg(loglevel_color), loglevel_str);
else
fmt::print(fmt::fg(loglevel_color), loglevel_str);
fmt::print("] {:s}\n", message);
}
else
{
fmt::print("[{:s}] [{:s}] [{:s}] {:s}\n",
time, GetModuleName(), loglevel_str, message);
}
}
|
// Copyright 2020 The XLS Authors
//
// 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 "xls/codegen/proc_generator.h"
#include "xls/common/status/matchers.h"
#include "xls/ir/channel.h"
#include "xls/ir/channel.pb.h"
#include "xls/ir/function_builder.h"
#include "xls/ir/package.h"
#include "xls/ir/type.h"
#include "xls/ir/value.h"
#include "xls/simulation/module_simulator.h"
#include "xls/simulation/verilog_test_base.h"
namespace xls {
namespace verilog {
namespace {
using status_testing::StatusIs;
using ::testing::HasSubstr;
using ::testing::Not;
constexpr char kTestName[] = "proc_generator_test";
constexpr char kTestdataPath[] = "xls/codegen/testdata";
class ProcGeneratorTest : public VerilogTestBase {
protected:
GeneratorOptions options() {
return GeneratorOptions().use_system_verilog(UseSystemVerilog());
}
};
TEST_P(ProcGeneratorTest, APlusB) {
Package package(TestBaseName());
Type* u32 = package.GetBitsType(32);
XLS_ASSERT_OK_AND_ASSIGN(
Channel * a_ch,
package.CreatePortChannel("a", ChannelOps::kReceiveOnly, u32));
XLS_ASSERT_OK_AND_ASSIGN(
Channel * b_ch,
package.CreatePortChannel("b", ChannelOps::kReceiveOnly, u32));
XLS_ASSERT_OK_AND_ASSIGN(
Channel * output_ch,
package.CreatePortChannel("sum", ChannelOps::kSendOnly, u32));
TokenlessProcBuilder pb(TestBaseName(), /*init_value=*/Value::Tuple({}),
/*token_name=*/"tkn", /*state_name=*/"st", &package);
BValue a = pb.Receive(a_ch);
BValue b = pb.Receive(b_ch);
pb.Send(output_ch, pb.Add(a, b));
XLS_ASSERT_OK_AND_ASSIGN(Proc * proc, pb.Build(pb.GetStateParam()));
XLS_ASSERT_OK_AND_ASSIGN(auto result, GenerateModule(proc, options()));
// The block should not have a clock or reset signal.
EXPECT_FALSE(result.signature.proto().has_reset());
EXPECT_FALSE(result.signature.proto().has_clock_name());
ModuleTestbench tb(result.verilog_text, result.signature, GetSimulator());
tb.ExpectX("sum");
// The combinational module doesn't a connected clock, but the clock can still
// be used to sequence events in time.
tb.NextCycle().Set("a", 0).Set("b", 0).ExpectEq("sum", 0);
tb.NextCycle().Set("a", 100).Set("b", 42).ExpectEq("sum", 142);
XLS_ASSERT_OK(tb.Run());
}
TEST_P(ProcGeneratorTest, PipelinedAPlusB) {
Package package(TestBaseName());
Type* u32 = package.GetBitsType(32);
XLS_ASSERT_OK_AND_ASSIGN(
Channel * a_ch,
package.CreatePortChannel("a", ChannelOps::kReceiveOnly, u32));
XLS_ASSERT_OK_AND_ASSIGN(
Channel * b_ch,
package.CreatePortChannel("b", ChannelOps::kReceiveOnly, u32));
XLS_ASSERT_OK_AND_ASSIGN(
Channel * p0_a_ch,
package.CreateRegisterChannel("p0_a", u32,
/*reset_value=*/Value(UBits(0, 32))));
XLS_ASSERT_OK_AND_ASSIGN(
Channel * p0_b_ch,
package.CreateRegisterChannel("p0_b", u32,
/*reset_value=*/Value(UBits(0, 32))));
XLS_ASSERT_OK_AND_ASSIGN(
Channel * p1_sum_ch,
package.CreateRegisterChannel("p1_sum", u32,
/*reset_value=*/Value(UBits(0, 32))));
XLS_ASSERT_OK_AND_ASSIGN(
Channel * output_ch,
package.CreatePortChannel("sum", ChannelOps::kSendOnly, u32));
TokenlessProcBuilder pb(TestBaseName(), /*init_value=*/Value::Tuple({}),
/*token_name=*/"tkn", /*state_name=*/"st", &package);
BValue a = pb.Receive(a_ch);
BValue b = pb.Receive(b_ch);
// Pipeline register 0.
pb.Send(p0_a_ch, a);
BValue p0_a = pb.Receive(p0_a_ch);
pb.Send(p0_b_ch, b);
BValue p0_b = pb.Receive(p0_b_ch);
// Pipeline register 1.
pb.Send(p1_sum_ch, pb.Add(p0_a, p0_b));
BValue p1_sum = pb.Receive(p1_sum_ch);
pb.Send(output_ch, p1_sum);
XLS_ASSERT_OK_AND_ASSIGN(Proc * proc, pb.Build(pb.GetStateParam()));
XLS_ASSERT_OK_AND_ASSIGN(
auto result,
GenerateModule(proc, options()
.clock_name("the_clock")
.reset("the_reset", /*asynchronous=*/false,
/*active_low=*/false)));
// The block should have a clock or reset signal.
EXPECT_EQ(result.signature.proto().reset().name(), "the_reset");
EXPECT_EQ(result.signature.proto().clock_name(), "the_clock");
ModuleTestbench tb(result.verilog_text, result.signature, GetSimulator());
tb.ExpectX("sum");
tb.Set("a", 0).Set("b", 0);
tb.AdvanceNCycles(2).ExpectEq("sum", 0);
tb.Set("a", 100).Set("b", 42);
tb.AdvanceNCycles(2).ExpectEq("sum", 142);
tb.Set("the_reset", 1).NextCycle();
tb.ExpectEq("sum", 0);
tb.Set("the_reset", 0);
tb.AdvanceNCycles(2).ExpectEq("sum", 142);
XLS_ASSERT_OK(tb.Run());
}
TEST_P(ProcGeneratorTest, RegisteredInputNoReset) {
Package package(TestBaseName());
Type* u32 = package.GetBitsType(32);
XLS_ASSERT_OK_AND_ASSIGN(
Channel * input_ch,
package.CreatePortChannel("foo", ChannelOps::kReceiveOnly, u32));
XLS_ASSERT_OK_AND_ASSIGN(Channel * reg_ch,
package.CreateRegisterChannel("foo_reg", u32));
XLS_ASSERT_OK_AND_ASSIGN(
Channel * output_ch,
package.CreatePortChannel("out", ChannelOps::kSendOnly, u32));
TokenlessProcBuilder pb(TestBaseName(), /*init_value=*/Value::Tuple({}),
/*token_name=*/"tkn", /*state_name=*/"st", &package);
BValue data = pb.Receive(input_ch);
pb.Send(reg_ch, data);
BValue reg_data = pb.Receive(reg_ch);
pb.Send(output_ch, reg_data);
XLS_ASSERT_OK_AND_ASSIGN(Proc * proc, pb.Build(pb.GetStateParam()));
XLS_ASSERT_OK_AND_ASSIGN(
auto result, GenerateModule(proc, options().clock_name("foo_clock")));
ModuleTestbench tb(result.verilog_text, result.signature, GetSimulator());
// The block should have a clock, but no reset.
EXPECT_FALSE(result.signature.proto().has_reset());
EXPECT_EQ(result.signature.proto().clock_name(), "foo_clock");
tb.ExpectX("out");
tb.Set("foo", 42).NextCycle().ExpectEq("out", 42);
tb.Set("foo", 100).ExpectEq("out", 42).NextCycle().ExpectEq("out", 100);
XLS_ASSERT_OK(tb.Run());
}
TEST_P(ProcGeneratorTest, Accumulator) {
Package package(TestBaseName());
Type* u32 = package.GetBitsType(32);
XLS_ASSERT_OK_AND_ASSIGN(
Channel * input_ch,
package.CreatePortChannel("in", ChannelOps::kReceiveOnly, u32));
XLS_ASSERT_OK_AND_ASSIGN(
Channel * accum_ch,
package.CreateRegisterChannel("accum", u32,
/*reset_value=*/Value(UBits(10, 32))));
XLS_ASSERT_OK_AND_ASSIGN(
Channel * output_ch,
package.CreatePortChannel("out", ChannelOps::kSendOnly, u32));
TokenlessProcBuilder pb(TestBaseName(), /*init_value=*/Value::Tuple({}),
/*token_name=*/"tkn", /*state_name=*/"st", &package);
BValue input = pb.Receive(input_ch);
BValue accum = pb.Receive(accum_ch);
BValue next_accum = pb.Add(input, accum);
pb.Send(accum_ch, next_accum);
pb.Send(output_ch, accum);
XLS_ASSERT_OK_AND_ASSIGN(Proc * proc, pb.Build(pb.GetStateParam()));
XLS_ASSERT_OK_AND_ASSIGN(
auto result, GenerateModule(proc, options().clock_name("clk").reset(
"rst_n", /*asynchronous=*/false,
/*active_low=*/true)));
ExpectVerilogEqualToGoldenFile(GoldenFilePath(kTestName, kTestdataPath),
result.verilog_text);
ModuleTestbench tb(result.verilog_text, result.signature, GetSimulator());
tb.Set("in", 0).Set("rst_n", 0).NextCycle().Set("rst_n", 1);
tb.ExpectEq("out", 10);
tb.Set("in", 42).NextCycle().ExpectEq("out", 52);
tb.Set("in", 100).NextCycle().ExpectEq("out", 152);
tb.Set("in", 0).Set("rst_n", 0).NextCycle().Set("rst_n", 1);
tb.ExpectEq("out", 10);
XLS_ASSERT_OK(tb.Run());
}
TEST_P(ProcGeneratorTest, SendIfRegister) {
Package package(TestBaseName());
Type* u32 = package.GetBitsType(32);
XLS_ASSERT_OK_AND_ASSIGN(
Channel * pred_ch,
package.CreatePortChannel("pred", ChannelOps::kReceiveOnly,
package.GetBitsType(1)));
XLS_ASSERT_OK_AND_ASSIGN(
Channel * data_ch,
package.CreatePortChannel("data", ChannelOps::kReceiveOnly, u32));
XLS_ASSERT_OK_AND_ASSIGN(Channel * reg_ch,
package.CreateRegisterChannel("reg", u32));
XLS_ASSERT_OK_AND_ASSIGN(
Channel * output_ch,
package.CreatePortChannel("out", ChannelOps::kSendOnly, u32));
TokenlessProcBuilder pb(TestBaseName(),
/*init_value=*/Value::Tuple({}),
/*token_name=*/"tkn", /*state_name=*/"st", &package);
BValue pred = pb.Receive(pred_ch);
BValue data = pb.Receive(data_ch);
pb.SendIf(reg_ch, pred, data);
BValue reg_data = pb.Receive(reg_ch);
pb.Send(output_ch, reg_data);
XLS_ASSERT_OK_AND_ASSIGN(Proc * proc, pb.Build(pb.GetStateParam()));
ASSERT_THAT(
GenerateModule(proc, options().clock_name("clk")).status(),
StatusIs(absl::StatusCode::kUnimplemented,
HasSubstr("SendIf to register channels not supported yet")));
}
TEST_P(ProcGeneratorTest, ProcWithNonNilState) {
Package package(TestBaseName());
TokenlessProcBuilder pb(TestBaseName(), /*init_value=*/Value(UBits(42, 32)),
/*token_name=*/"tkn", /*state_name=*/"st", &package);
XLS_ASSERT_OK_AND_ASSIGN(Proc * proc, pb.Build(pb.GetStateParam()));
EXPECT_THAT(
GenerateModule(proc, options()).status(),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("The proc state must be an empty tuple for codegen")));
}
TEST_P(ProcGeneratorTest, ProcWithStreamingChannel) {
Package package(TestBaseName());
Type* u32 = package.GetBitsType(32);
XLS_ASSERT_OK_AND_ASSIGN(
Channel * ch,
package.CreateStreamingChannel("a", ChannelOps::kReceiveOnly, u32));
TokenlessProcBuilder pb(TestBaseName(), /*init_value=*/Value(UBits(42, 32)),
/*token_name=*/"tkn", /*state_name=*/"st", &package);
BValue sum = pb.Add(pb.GetStateParam(), pb.Receive(ch));
XLS_ASSERT_OK_AND_ASSIGN(Proc * proc, pb.Build(sum));
EXPECT_THAT(
GenerateModule(proc, options()).status(),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr(
"Only register and port channel are supported in codegen")));
}
TEST_P(ProcGeneratorTest, ResetValueWithoutResetSignal) {
Package package(TestBaseName());
Type* u32 = package.GetBitsType(32);
XLS_ASSERT_OK_AND_ASSIGN(
Channel * in_ch,
package.CreatePortChannel("in", ChannelOps::kReceiveOnly, u32));
XLS_ASSERT_OK_AND_ASSIGN(
Channel * reg_ch, package.CreateRegisterChannel(
"reg", u32, /*reset_value=*/Value(UBits(123, 32))));
TokenlessProcBuilder pb(TestBaseName(),
/*init_value=*/Value::Tuple({}),
/*token_name=*/"tkn", /*state_name=*/"st", &package);
BValue in = pb.Receive(in_ch);
BValue reg_d = pb.Receive(reg_ch);
pb.Send(reg_ch, pb.Add(in, reg_d));
XLS_ASSERT_OK_AND_ASSIGN(Proc * proc, pb.Build(pb.GetStateParam()));
EXPECT_THAT(
GenerateModule(proc, options().clock_name("clk")).status(),
StatusIs(
absl::StatusCode::kInvalidArgument,
HasSubstr(
"Must specify a reset signal if registers have a reset value")));
}
TEST_P(ProcGeneratorTest, ProcWithAssertNoLabel) {
Package package(TestBaseName());
Type* u32 = package.GetBitsType(32);
XLS_ASSERT_OK_AND_ASSIGN(
Channel * ch,
package.CreatePortChannel("a", ChannelOps::kReceiveOnly, u32));
TokenlessProcBuilder pb(TestBaseName(), /*init_value=*/Value::Tuple({}),
/*token_name=*/"tkn", /*state_name=*/"st", &package);
pb.Assert(pb.ULt(pb.Receive(ch), pb.Literal(UBits(42, 32))),
"a is not greater than 42");
XLS_ASSERT_OK_AND_ASSIGN(Proc * proc, pb.Build(pb.GetStateParam()));
{
// No format string.
XLS_ASSERT_OK_AND_ASSIGN(ModuleGeneratorResult result,
GenerateModule(proc, options()));
if (UseSystemVerilog()) {
EXPECT_THAT(
result.verilog_text,
HasSubstr(
R"(assert ($isunknown(a < 32'h0000_002a) || a < 32'h0000_002a) else $fatal(0, "a is not greater than 42"))"));
} else {
EXPECT_THAT(result.verilog_text, Not(HasSubstr("assert")));
}
}
{
// With format string, no label.
XLS_ASSERT_OK_AND_ASSIGN(
ModuleGeneratorResult result,
GenerateModule(
proc,
options()
.reset("my_rst", /*asynchronous=*/false, /*active_low=*/false)
.clock_name("my_clk")
.assert_format(
R"(`MY_ASSERT({condition}, "{message}", {clk}, {rst}))")));
if (UseSystemVerilog()) {
EXPECT_THAT(
result.verilog_text,
HasSubstr(
R"(`MY_ASSERT(a < 32'h0000_002a, "a is not greater than 42", my_clk, my_rst))"));
} else {
EXPECT_THAT(result.verilog_text, Not(HasSubstr("assert")));
}
}
// Format string with label but assert doesn't have label.
EXPECT_THAT(
GenerateModule(proc, options()
.reset("my_rst", /*asynchronous=*/false,
/*active_low=*/false)
.clock_name("my_clk")
.assert_format(R"({label} foobar)")),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("Assert format string has '{label}' placeholder, "
"but assert operation has no label")));
// Format string with clock but block doesn't have clock.
EXPECT_THAT(
GenerateModule(proc, options()
.reset("my_rst", /*asynchronous=*/false,
/*active_low=*/false)
.assert_format(R"({clk} foobar)")),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("Assert format string has '{clk}' placeholder, "
"but block has no clock signal")));
// Format string with reset but block doesn't have reset.
EXPECT_THAT(
GenerateModule(proc, options().assert_format(R"({rst} foobar)")),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("Assert format string has '{rst}' placeholder, "
"but block has no reset signal")));
// Format string with invalid placeholder.
EXPECT_THAT(
GenerateModule(proc, options().assert_format(R"({foobar} blargfoobar)")),
StatusIs(
absl::StatusCode::kInvalidArgument,
HasSubstr("Invalid placeholder '{foobar}' in assert format string. "
"Supported placeholders: {clk}, {condition}, {label}, "
"{message}, {rst}")));
}
TEST_P(ProcGeneratorTest, ProcWithAssertWithLabel) {
Package package(TestBaseName());
Type* u32 = package.GetBitsType(32);
XLS_ASSERT_OK_AND_ASSIGN(
Channel * ch,
package.CreatePortChannel("a", ChannelOps::kReceiveOnly, u32));
TokenlessProcBuilder pb(TestBaseName(), /*init_value=*/Value::Tuple({}),
/*token_name=*/"tkn", /*state_name=*/"st", &package);
pb.Assert(pb.ULt(pb.Receive(ch), pb.Literal(UBits(42, 32))),
"a is not greater than 42", "the_label");
XLS_ASSERT_OK_AND_ASSIGN(Proc * proc, pb.Build(pb.GetStateParam()));
{
// No format string.
XLS_ASSERT_OK_AND_ASSIGN(ModuleGeneratorResult result,
GenerateModule(proc, options()));
if (UseSystemVerilog()) {
EXPECT_THAT(
result.verilog_text,
HasSubstr(
R"(assert ($isunknown(a < 32'h0000_002a) || a < 32'h0000_002a) else $fatal(0, "a is not greater than 42"))"));
} else {
EXPECT_THAT(result.verilog_text, Not(HasSubstr("assert")));
}
}
{
// With format string.
XLS_ASSERT_OK_AND_ASSIGN(
ModuleGeneratorResult result,
GenerateModule(
proc,
options()
.reset("my_rst", /*asynchronous=*/false, /*active_low=*/false)
.clock_name("my_clk")
.assert_format(
R"({label}: `MY_ASSERT({condition}, "{message}", {clk}, {rst}) // {label})")));
if (UseSystemVerilog()) {
EXPECT_THAT(
result.verilog_text,
HasSubstr(
R"(the_label: `MY_ASSERT(a < 32'h0000_002a, "a is not greater than 42", my_clk, my_rst) // the_label)"));
} else {
EXPECT_THAT(result.verilog_text, Not(HasSubstr("assert")));
}
}
}
TEST_P(ProcGeneratorTest, ProcWithEmptyTupleElementInOutput) {
Package package(TestBaseName());
Type* u32 = package.GetBitsType(32);
XLS_ASSERT_OK_AND_ASSIGN(
Channel * in_ch,
package.CreatePortChannel("in", ChannelOps::kReceiveOnly, u32));
XLS_ASSERT_OK_AND_ASSIGN(
Channel * out_ch,
package.CreatePortChannel(
"result", ChannelOps::kSendOnly,
package.GetTupleType({package.GetTupleType({}), u32})));
TokenlessProcBuilder pb(TestBaseName(), /*init_value=*/Value::Tuple({}),
/*token_name=*/"tkn", /*state_name=*/"st", &package);
BValue empty_tuple = pb.Tuple({});
pb.Send(out_ch, pb.Tuple({empty_tuple, pb.Receive(in_ch)}));
XLS_ASSERT_OK_AND_ASSIGN(Proc * proc, pb.Build(pb.GetStateParam()));
XLS_ASSERT_OK_AND_ASSIGN(ModuleGeneratorResult result,
GenerateModule(proc, options()));
}
INSTANTIATE_TEST_SUITE_P(ProcGeneratorTestInstantiation, ProcGeneratorTest,
testing::ValuesIn(kDefaultSimulationTargets),
ParameterizedTestName<ProcGeneratorTest>);
} // namespace
} // namespace verilog
} // namespace xls
|
/** Solution to Programming Challenge -
to sum the elements of Array
*/
#include<iostream>
using namespace std;
int main()
{
int A[10], sum = 0, i;
cout<<"\nEnter the Elements..";
for(i=0;i<10;i++)
cin>>A[i];
for(i=0;i<10;i++)
sum += A[i];
cout<<"The Sum is.."<<sum<<endl;
return(0);
}
|
//
// Created by Shujian Qian on 2020-11-17.
//
#include "nasoq/nasoq_step.h"
#include <cstdio>
#include <iostream>
namespace nasoq {
NasoqStep::NasoqStep(size_t H_size, int *Hp, int *Hi, double *Hx, double *q_in,
size_t B_row, size_t B_col, int *Bp, int *Bi,
double *Bx, double *b_ineq) : Nasoq(H_size, Hp, Hi, Hx, q_in,
B_row, B_col, Bp, Bi,
Bx, b_ineq) {}
NasoqStep::NasoqStep(size_t H_size, int *Hp, int *Hi, double *Hx, double *q_in,
size_t A_size1, size_t A_size2, int *Ap, int *Ai, double *Ax,
double *a_eq,
size_t B_size1, size_t B_size2, int *Bp, int *Bi, double *Bx,
double *b_ineq) : Nasoq(H_size, Hp, Hi, Hx, q_in,
A_size1, A_size2, Ap, Ai, Ax,
a_eq,
B_size1, B_size2, Bp, Bi, Bx,
b_ineq) {}
int NasoqStep::solve_init() {
ret_val = nasoq_status::NotFinished;
int status = 1;
warm_start = 0;
//print_csc("BT fisrt:\n",BT->ncol,BT->p,BT->i,BT->x);
qi->tot_st = qi->tic();
if (scaling > 0) {
scale_data();
//print_csc("H scaled\n",H->ncol,H->p,H->i,H->x);
}
if (scaling < 0) {
scale_data_2();
}
if (variant == nasoq_mode::Tuned) {//TODO: reuse symbolic QP
symbolic_QP();
// the tuned solver loop is now controlled by step_tuned_iter
initialize_x();
} else { // Fixed or Auto
if (variant == nasoq_mode::AUTO) {
auto_reg_en = 2;
} else if (variant == nasoq_mode::Fixed) {
auto_reg_en = 1;
} else {
auto_reg_en = 0;
}
#ifdef CHOLROWMOD
status = symbolic_QP_cholmod();
initialize_x_cholmod();
#else
symbolic_QP();
status = initialize_x();
#endif
}
nxt_active = -1;
nxt_drop = -1;
to_add = 1;
num_violated = 0;
typ_nxt_solve = SOLVE;
step_solve_finished = 0;
step_tuned_iter = 0;
if (warm_start)
typ_nxt_solve = REFACTOR;
return status;
}
int NasoqStep::solve_step() {
if (num_iter > max_iter_nas) {
is_converged = 0;
step_solve_finished = 1;
return check_step_status(is_converged);
}
if (to_add == 1) {
num_violated = primal_feasibility(nxt_active);
if (num_violated == 0) {
is_converged = 1;
step_solve_finished = 1;
return check_step_status(is_converged);
} else if (nxt_active == -1) {//unbounded!
std::cout << "All constraints are used\n";
is_converged = 0;
step_solve_finished = 1;
return check_step_status(is_converged);
}
update_rhs(nxt_active);
}
#ifdef CHOLROWMOD
solve_kkt_cholmod(typ_nxt_solve);
#else
solve_kkt(typ_nxt_solve);
#endif
prime_step = primal_step_length(nxt_active);
dual_step = dual_step_length(nxt_drop);
step = prime_step > dual_step ? dual_step : prime_step;
if (step == std::numeric_limits<double>::max()) {
is_converged = 0;
step_solve_finished = 1;
return check_step_status(is_converged);
} else if (prime_step == std::numeric_limits<double>::max()
&& step == dual_step) { // Dual step
update_dual(step);
dual_vars[nxt_active] = dual_vars[nxt_active] + step;//==-step*-1
to_add = 0;
#ifdef CHOLROWMOD
edit_kkt_cholmod(to_add, nxt_drop);
#else
edit_kkt(to_add, nxt_drop);
#endif
typ_nxt_solve = UPDATE;
int is_up = update_active_set(to_add, nxt_drop);
assert(is_up == 1);
} else { // Full step
update_primal(step);// solution = step*descent + solution
update_dual(step);// dual_vars = step*descent + dual_vars
dual_vars[nxt_active] = dual_vars[nxt_active] + step;//==-step*-1
if (step == prime_step) { //update
to_add = 1;
#ifdef CHOLROWMOD
edit_kkt_cholmod(to_add, nxt_active);
#else
edit_kkt(to_add, nxt_active);
#endif
typ_nxt_solve = UPDATE;
update_active_set(to_add, nxt_active);
} else if (step == dual_step) { //downdate
to_add = 0;
#ifdef CHOLROWMOD
edit_kkt_cholmod(to_add, nxt_drop);
#else
edit_kkt(to_add, nxt_drop);
#endif
typ_nxt_solve = UPDATE;
int is_up = update_active_set(to_add, nxt_drop);
assert(is_up == 1);
}
assert(n_active == active_set.size());
}
is_converged = 0;
return check_step_status(is_converged);
}
nasoq_status NasoqStep::check_step_status(int status) {
if (!step_solve_finished) {
++num_iter;
ret_val = nasoq_status::NotFinished;
return ret_val;
}
detect_solver_name();
if (variant == nasoq_mode::Tuned) {
if (step_tuned_iter < 4) {
++step_tuned_iter;
initialize_x();
step_solve_finished = 0;
ret_val = nasoq_status::NotFinished;
return ret_val;
}
}
if (scaling > 0) {
unscale_data();
unscale_solution();
}
if (scaling < 0) {
unscale_data_2();
unscale_solution_2();
}
qi->tot_end = qi->toc();
qi->tot = qi->elapsed_time(qi->tot_st, qi->tot_end);
// ret_val = check_solve_status(status);
detect_solver_name();
// return ret_val;
if(step_solve_finished && status == 0)
return nasoq_status::Infeasible;
if(compute_norms_per_step || step_solve_finished){
compute_objective();
constraint_sat_norm();
lagrangian_residual_norm();
complementarity_norm();
non_negativity_norm();
}
if(step_solve_finished){
if (lag_res <= eps_abs && cons_sat_norm <= eps_abs &&
non_negativity_infn <= eps_abs) {//&& complementarity_infn <= eps_abs
ret_val = nasoq_status::Optimal; //converged
} else if (cons_sat_norm <= eps_abs) {//low accuracy
ret_val = nasoq_status::Inaccurate;
} else {
ret_val = nasoq_status::NotConverged; //not converged or maybe very inaccurate
}
} else{
ret_val = nasoq_status::NotFinished;
}
return ret_val;
}
int NasoqStep::solve_steps(int num_step) {
int status = nasoq_status::NotFinished;
for (int i = 0; i < num_step; i++) {
status = solve_step();
if (status != nasoq_status::NotFinished) break;
}
return status;
}
}
|
#include "fitpackpp/BSplineCurve.h"
#include "FCMangle.h"
#include <cmath>
#include <stdexcept>
extern "C"
{
void curfit(int* iopt, int* m, double* x, double* y, double* w, double* xb, double* xe, int* k,
double* s, int* nest, int* n, double* t, double* c, double* fp, double* wrk, int* lwrk,
int* iwrk, int* ier);
void splev(
double* t, int* n, double* c, int* k, double* x, double* y, int* m, int* e, int* ier);
}
namespace fitpackpp
{
BSplineCurve::BSplineCurve(int degree, const Vec& knots, const Vec& coeffs)
: mDegree(degree)
, mKnots(knots)
, mCoeffs(coeffs)
{
}
BSplineCurve BSplineCurve::splrep(Vec x, Vec y, std::optional<Vec> w, std::optional<double> xb,
std::optional<double> xe, int k, int task, std::optional<double> s, std::optional<Vec> t,
bool per)
{
int m = x.size();
if (!w)
{
w = Vec(m, 1.0);
if (!s)
s = 0.0;
}
else if (!s)
s = m - std::sqrt(2 * m);
// check if input is valid
if (static_cast<int>(w.value().size()) != m || static_cast<int>(y.size()) != m)
throw std::runtime_error("sizes of weight, x and y musts be equal");
if (m <= k)
throw std::runtime_error("m > k must hold");
if (task > 0)
throw std::runtime_error("Task must be -1, 0");
if (!xb)
xb = x.front();
if (!xe)
xe = x.back();
int nest = 0;
if (task == -1)
{
if (!t)
throw std::runtime_error("Knots must be given for task=-1");
auto numKnots = t.value().size();
Vec newT(numKnots + 2 * k + 2);
std::copy(std::begin(t.value()), std::end(t.value()), std::begin(newT) + k + 1);
t.value().swap(newT);
nest = t.value().size();
}
else if (task == 0)
{
if (per)
nest = std::max(m + 2 * k, 2 * k + 3);
else
nest = std::max(m + k + 1, 2 * k + 3);
t = Vec(nest);
}
Vec wrk;
if (per)
wrk = Vec(m * (k + 1) + nest * (8 + 5 * k));
else
wrk = Vec(m * (k + 1) + nest * (7 + 3 * k));
auto iwrk = std::vector<int>(nest);
int lwrk = wrk.size();
auto coeffs = Vec(nest);
double fp = 0.0;
int n = 0;
int ier = 0;
curfit(&task, &m, x.data(), y.data(), w.value().data(), &xb.value(), &xe.value(), &k,
&s.value(), &nest, &n, t.value().data(), coeffs.data(), &fp, wrk.data(), &lwrk, iwrk.data(),
&ier);
// truncate if needed
t.value().resize(n);
coeffs.resize(n);
return BSplineCurve(k, t.value(), coeffs);
}
Vec BSplineCurve::evaluate(Vec x, int ext)
{
Vec y(x.size(), 0.0);
int n = mKnots.size();
int m = x.size();
int ier = 0;
splev(mKnots.data(), &n, mCoeffs.data(), &mDegree, x.data(), y.data(), &m, &ext, &ier);
if (ier > 0)
{
if (ier == 1)
throw std::runtime_error("Argument out of bounds");
if (ier == 10)
throw std::runtime_error("Invalid input data");
}
return y;
}
} // namespace fitpackpp
|
///////////////////////////////////////////////////////////////////////////////
// This source file is part of Hect.
//
// Copyright (c) 2016 Colin Hill
//
// 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 "Interface.h"
#include "Hect/Scene/Systems/InterfaceSystem.h"
using namespace hect;
Interface::Interface(InterfaceSystem& interface_system, RenderTarget& render_target) :
Widget(interface_system),
_render_target(render_target)
{
// Set the default style colors
set_style_color(StyleColor::Background, Color(0.15, 0.15, 0.15, 0.9));
set_style_color(StyleColor::BackgroundSelected, Color(0.0, 122.0 / 255.0, 204.0 / 255.0, 0.9));
set_style_color(StyleColor::BackgroundPressed, Color(0.15, 0.15, 0.15, 0.9));
set_style_color(StyleColor::BackgroundMouseOver, Color(0.0, 122.0 / 255.0, 204.0 / 255.0, 0.9));
set_style_color(StyleColor::Foreground, Color(1.0, 1.0, 1.0));
set_style_color(StyleColor::ForegroundSelected, Color(1.0, 1.0, 1.0));
set_style_color(StyleColor::ForegroundPressed, Color(1.0, 1.0, 1.0));
set_style_color(StyleColor::ForegroundMouseOver, Color(1.0, 1.0, 1.0));
set_style_color(StyleColor::Border, Color(0.5, 0.5, 0.5));
set_style_color(StyleColor::BorderPressed, Color(0.5, 0.5, 0.5));
set_style_color(StyleColor::BorderMouseOver, Color(0.5, 0.5, 0.5));
// Set the dimensions of the interface to match the render target
set_dimensions(render_target.dimensions());
}
RenderTarget& Interface::render_target()
{
return _render_target;
}
|
#include "sc2api/sc2_map_info.h"
namespace sc2 {
ImageData::ImageData () :
width(0),
height(0),
bits_per_pixel(0)
{
}
GameInfo::GameInfo () :
width(0),
height(0)
{
}
}
|
// SPDX-license-identifier: Apache-2.0
// Copyright © 2021 Intel Corporation
#pragma once
#include <cassert>
#include <cstdint>
#include <memory>
#include <string>
#include <tuple>
#include <unordered_map>
#include <variant>
#include <vector>
#include <optional>
#include "locations.hpp"
namespace Frontend::AST {
class AdditiveExpression;
class Assignment;
class Boolean;
class Identifier;
class MultiplicativeExpression;
class Number;
class String;
class Subscript;
class UnaryExpression;
class Relational;
class FunctionCall;
class GetAttribute;
class Array;
class Dict;
class Ternary;
using ExpressionV =
std::variant<std::unique_ptr<AdditiveExpression>, std::unique_ptr<Boolean>,
std::unique_ptr<Identifier>, std::unique_ptr<MultiplicativeExpression>,
std::unique_ptr<UnaryExpression>, std::unique_ptr<Number>, std::unique_ptr<String>,
std::unique_ptr<Subscript>, std::unique_ptr<Relational>,
std::unique_ptr<FunctionCall>, std::unique_ptr<GetAttribute>,
std::unique_ptr<Array>, std::unique_ptr<Dict>, std::unique_ptr<Ternary>>;
using ExpressionList = std::vector<ExpressionV>;
class Location {
public:
Location(const location & l)
: column_start{l.begin.column}, column_end{l.end.column},
line_start{l.begin.line}, line_end{l.end.line}, filename{*l.begin.filename} {};
virtual ~Location(){};
const int column_start;
const int column_end;
const int line_start;
const int line_end;
const std::string filename;
};
class Number {
public:
Number(const int64_t & number, const location & l) : value{number}, loc{l} {};
Number(Number && n) noexcept : value{std::move(n.value)}, loc{std::move(n.loc)} {};
Number(const Number &) = delete;
~Number(){};
std::string as_string() const;
int64_t value;
Location loc;
};
class Boolean {
public:
Boolean(const bool & b, const location & l) : value{b}, loc{l} {};
Boolean(Boolean && b) noexcept : value{std::move(b.value)}, loc{std::move(b.loc)} {};
Boolean(const Boolean &) = delete;
~Boolean(){};
std::string as_string() const;
bool value;
Location loc;
};
class String {
public:
String(const std::string & str, const bool & t, const bool & f, const location & l)
: value{str}, is_triple{t}, is_fstring{f}, loc{l} {};
String(String && s) noexcept
: value{std::move(s.value)}, is_triple{std::move(s.is_triple)},
is_fstring{std::move(s.is_fstring)}, loc{std::move(s.loc)} {};
String(const String &) = delete;
~String(){};
std::string as_string() const;
std::string value;
bool is_triple;
bool is_fstring;
Location loc;
};
class Identifier {
public:
Identifier(const std::string & str, const location & l) : value{str}, loc{l} {};
Identifier(Identifier && s) noexcept : value{std::move(s.value)}, loc{std::move(s.loc)} {};
Identifier(const Identifier &) = delete;
~Identifier(){};
std::string as_string() const;
std::string value;
Location loc;
};
class Subscript {
public:
Subscript(ExpressionV && l, ExpressionV && r, location & lo)
: lhs{std::move(l)}, rhs{std::move(r)}, loc{lo} {};
Subscript(const Subscript &) = delete;
Subscript(Subscript && a) noexcept
: lhs{std::move(a.lhs)}, rhs{std::move(a.rhs)}, loc{std::move(a.loc)} {};
~Subscript(){};
std::string as_string() const;
ExpressionV lhs;
ExpressionV rhs;
Location loc;
};
enum class UnaryOp {
NEG,
NOT,
};
class UnaryExpression {
public:
UnaryExpression(const UnaryOp & o, ExpressionV && r, location & l)
: op{o}, rhs{std::move(r)}, loc{l} {};
UnaryExpression(UnaryExpression && a) noexcept
: op{std::move(a.op)}, rhs{std::move(a.rhs)}, loc{std::move(a.loc)} {};
UnaryExpression(const UnaryExpression &) = delete;
~UnaryExpression(){};
std::string as_string() const;
UnaryOp op;
ExpressionV rhs;
Location loc;
};
enum class MulOp {
MUL,
DIV,
MOD,
};
class MultiplicativeExpression {
public:
MultiplicativeExpression(ExpressionV && l, const MulOp & o, ExpressionV && r, location & lo)
: lhs{std::move(l)}, op{o}, rhs{std::move(r)}, loc{lo} {};
MultiplicativeExpression(MultiplicativeExpression && a) noexcept
: lhs{std::move(a.lhs)}, op{std::move(a.op)}, rhs{std::move(a.rhs)}, loc{std::move(
a.loc)} {};
MultiplicativeExpression(const MultiplicativeExpression &) = delete;
~MultiplicativeExpression(){};
std::string as_string() const;
ExpressionV lhs;
MulOp op;
ExpressionV rhs;
Location loc;
};
enum class AddOp {
ADD,
SUB,
};
class AdditiveExpression {
public:
AdditiveExpression(ExpressionV && l, const AddOp & o, ExpressionV && r, location & lo)
: lhs{std::move(l)}, op{o}, rhs{std::move(r)}, loc{lo} {};
AdditiveExpression(AdditiveExpression && a) noexcept
: lhs{std::move(a.lhs)}, op{std::move(a.op)}, rhs{std::move(a.rhs)}, loc{std::move(
a.loc)} {};
AdditiveExpression(const AdditiveExpression &) = delete;
~AdditiveExpression(){};
std::string as_string() const;
ExpressionV lhs;
AddOp op;
ExpressionV rhs;
Location loc;
};
enum class RelationalOp {
LT,
LE,
EQ,
NE,
GE,
GT,
AND,
OR,
IN,
NOT_IN,
};
// TODO: move this into the parser cpp
static AST::RelationalOp to_relop(const std::string & s) {
if (s == "<") {
return AST::RelationalOp::LT;
} else if (s == "<=") {
return AST::RelationalOp::LE;
} else if (s == "==") {
return AST::RelationalOp::EQ;
} else if (s == "!=") {
return AST::RelationalOp::NE;
} else if (s == ">=") {
return AST::RelationalOp::GE;
} else if (s == ">") {
return AST::RelationalOp::GT;
} else if (s == "and") {
return AST::RelationalOp::AND;
} else if (s == "or") {
return AST::RelationalOp::OR;
} else if (s == "in") {
return AST::RelationalOp::IN;
} else if (s == "not in") {
return AST::RelationalOp::NOT_IN;
}
assert(false);
}
class Relational {
public:
Relational(ExpressionV && l, const std::string & o, ExpressionV && r, location & lo)
: lhs{std::move(l)}, op{to_relop(o)}, rhs{std::move(r)}, loc{lo} {};
Relational(Relational && a) noexcept
: lhs{std::move(a.lhs)}, op{std::move(a.op)}, rhs{std::move(a.rhs)}, loc{std::move(
a.loc)} {};
Relational(const Relational &) = delete;
~Relational(){};
std::string as_string() const;
ExpressionV lhs;
RelationalOp op;
ExpressionV rhs;
Location loc;
};
// XXX: this isn't really true, it's really an identifier : expressionv
using KeywordPair = std::tuple<ExpressionV, ExpressionV>;
using KeywordList = std::vector<KeywordPair>;
class Arguments {
public:
Arguments(location & l) : positional{}, keyword{}, loc{l} {};
Arguments(ExpressionList && v, location & l) : positional{std::move(v)}, keyword{}, loc{l} {};
Arguments(KeywordList && k, location & l) : positional{}, keyword{std::move(k)}, loc{l} {};
Arguments(ExpressionList && v, KeywordList && k, location & l)
: positional{std::move(v)}, keyword{std::move(k)}, loc{l} {};
Arguments(Arguments && a) noexcept
: positional{std::move(a.positional)}, keyword{std::move(a.keyword)}, loc{std::move(
a.loc)} {};
Arguments(const Arguments &) = delete;
~Arguments(){};
std::string as_string() const;
ExpressionList positional;
KeywordList keyword;
Location loc;
};
class FunctionCall {
public:
FunctionCall(ExpressionV && i, std::unique_ptr<Arguments> && a, location & l)
: held{std::move(i)}, args{std::move(a)}, loc{l} {};
FunctionCall(FunctionCall && a) noexcept
: held{std::move(a.held)}, args{std::move(a.args)}, loc{std::move(a.loc)} {};
FunctionCall(const FunctionCall &) = delete;
~FunctionCall(){};
std::string as_string() const;
ExpressionV held;
std::unique_ptr<Arguments> args;
Location loc;
};
class GetAttribute {
public:
GetAttribute(ExpressionV && o, ExpressionV && i, location & l)
: holder{std::move(o)}, held{std::move(i)}, loc{l} {};
GetAttribute(GetAttribute && a) noexcept
: holder{std::move(a.holder)}, held{std::move(a.held)}, loc{std::move(a.loc)} {};
GetAttribute(const GetAttribute &) = delete;
~GetAttribute(){};
std::string as_string() const;
/// Object holding the attribute
ExpressionV holder;
/// The attribute to get (really, the method)
ExpressionV held;
Location loc;
};
class Array {
public:
Array(location & l) : elements{}, loc{l} {};
Array(ExpressionList && e, location & l) : elements{std::move(e)}, loc{l} {};
Array(Array && a) noexcept : elements{std::move(a.elements)}, loc{std::move(a.loc)} {};
Array(const Array &) = delete;
~Array(){};
std::string as_string() const;
ExpressionList elements;
Location loc;
};
class Dict {
public:
Dict(location & l) : elements{}, loc{l} {};
Dict(KeywordList && l, location & lo);
Dict(Dict && a) : elements{std::move(a.elements)}, loc{std::move(a.loc)} {};
Dict(const Dict &) = delete;
~Dict(){};
std::string as_string() const;
std::unordered_map<ExpressionV, ExpressionV> elements;
Location loc;
};
class Ternary {
public:
Ternary(ExpressionV && c, ExpressionV && l, ExpressionV && r, location & lo)
: condition{std::move(c)}, lhs{std::move(l)}, rhs{std::move(r)}, loc{lo} {};
Ternary(Ternary && t)
: condition{std::move(t.condition)}, lhs{std::move(t.lhs)}, rhs{std::move(t.rhs)},
loc{std::move(t.loc)} {};
Ternary(const Ternary &) = delete;
~Ternary(){};
std::string as_string() const;
ExpressionV condition;
ExpressionV lhs;
ExpressionV rhs;
Location loc;
};
class Statement {
public:
Statement(ExpressionV && e) : expr{std::move(e)} {};
Statement(Statement && a) noexcept : expr{std::move(a.expr)} {};
Statement(const Statement &) = delete;
~Statement(){};
std::string as_string() const;
ExpressionV expr;
};
enum class AssignOp {
EQUAL,
ADD_EQUAL,
SUB_EQUAL,
MUL_EQUAL,
DIV_EQUAL,
MOD_EQUAL,
};
class Assignment {
public:
Assignment(ExpressionV && l, AssignOp & o, ExpressionV && r)
: lhs{std::move(l)}, op{o}, rhs{std::move(r)} {};
Assignment(Assignment && a) noexcept
: lhs{std::move(a.lhs)}, op{std::move(a.op)}, rhs{std::move(a.rhs)} {};
Assignment(const Assignment &) = delete;
~Assignment(){};
std::string as_string() const;
ExpressionV lhs;
AssignOp op;
ExpressionV rhs;
};
class Break {
public:
Break(){};
~Break(){};
Break(const Break &) = delete;
std::string as_string() const;
};
class Continue {
public:
Continue(){};
~Continue(){};
Continue(const Break &) = delete;
std::string as_string() const;
};
class IfStatement;
class ForeachStatement;
using StatementV = std::variant<std::unique_ptr<Statement>, std::unique_ptr<Assignment>,
std::unique_ptr<IfStatement>, std::unique_ptr<ForeachStatement>,
std::unique_ptr<Break>, std::unique_ptr<Continue>>;
class CodeBlock {
public:
CodeBlock() : statements{} {};
CodeBlock(StatementV && stmt) : statements{} { statements.emplace_back(std::move(stmt)); };
CodeBlock(CodeBlock && b) noexcept : statements{std::move(b.statements)} {};
CodeBlock(const CodeBlock &) = delete;
~CodeBlock(){};
CodeBlock & operator=(CodeBlock &&) = default;
std::string as_string() const;
// XXX: this should probably be a statement list
std::vector<StatementV> statements;
};
class IfBlock {
public:
IfBlock(){};
IfBlock(ExpressionV && cond) : condition{std::move(cond)}, block{} {};
IfBlock(ExpressionV && cond, std::unique_ptr<CodeBlock> && b)
: condition{std::move(cond)}, block{std::move(b)} {};
IfBlock(IfBlock && i) noexcept
: condition{std::move(i.condition)}, block{std::move(i.block)} {};
IfBlock(const IfBlock &) = delete;
~IfBlock(){};
IfBlock & operator=(IfBlock &&) = default;
ExpressionV condition;
std::unique_ptr<CodeBlock> block;
};
class ElifBlock {
public:
ElifBlock() : condition{}, block{} {};
ElifBlock(ExpressionV && cond, std::unique_ptr<CodeBlock> && b)
: condition{std::move(cond)}, block{std::move(b)} {};
ElifBlock(ElifBlock && e) noexcept
: condition{std::move(e.condition)}, block{std::move(e.block)} {};
ElifBlock(const ElifBlock &) = delete;
~ElifBlock(){};
ElifBlock & operator=(ElifBlock &&) = default;
ExpressionV condition;
std::unique_ptr<CodeBlock> block;
};
class ElseBlock {
public:
ElseBlock() : block{nullptr} {};
ElseBlock(std::unique_ptr<CodeBlock> && b) : block{std::move(b)} {};
ElseBlock(ElseBlock && e) noexcept : block{std::move(e.block)} {};
ElseBlock(const ElseBlock &) = delete;
~ElseBlock(){};
ElseBlock & operator=(ElseBlock &&) = default;
std::unique_ptr<CodeBlock> block;
};
class IfStatement {
public:
IfStatement(IfBlock && ib) : ifblock{std::move(ib)}, efblock{}, eblock{} {};
IfStatement(IfBlock && ib, ElseBlock && eb)
: ifblock{std::move(ib)}, efblock{}, eblock{std::move(eb)} {};
IfStatement(IfBlock && ib, std::vector<ElifBlock> && ef)
: ifblock{std::move(ib)}, efblock{std::move(ef)}, eblock{} {};
IfStatement(IfBlock && ib, std::vector<ElifBlock> && ef, ElseBlock && eb)
: ifblock{std::move(ib)}, efblock{std::move(ef)}, eblock{std::move(eb)} {};
IfStatement(IfStatement && i)
: ifblock{std::move(i.ifblock)}, efblock{std::move(i.efblock)}, eblock{
std::move(i.eblock)} {};
IfStatement(const IfStatement &) = delete;
~IfStatement(){};
std::string as_string() const;
IfBlock ifblock;
std::vector<ElifBlock> efblock;
ElseBlock eblock;
};
class ForeachStatement {
public:
ForeachStatement(Identifier && i, ExpressionV && e, std::unique_ptr<CodeBlock> && b)
: id{std::move(i)}, id2{std::nullopt}, expr{std::move(e)}, block{std::move(b)} {};
ForeachStatement(Identifier && i, Identifier && j, ExpressionV && e,
std::unique_ptr<CodeBlock> && b)
: id{std::move(i)}, id2{std::move(j)}, expr{std::move(e)}, block{std::move(b)} {};
ForeachStatement(ForeachStatement && f) noexcept
: id{std::move(f.id)}, id2{std::move(f.id2)}, expr{std::move(f.expr)}, block{std::move(
f.block)} {};
ForeachStatement(const ForeachStatement &) = delete;
~ForeachStatement(){};
std::string as_string() const;
Identifier id;
// Used only in dictionary iteration
std::optional<Identifier> id2;
ExpressionV expr;
std::unique_ptr<CodeBlock> block;
};
} // namespace Frontend::AST
|
/**
* @file
* @author __AUTHOR_NAME__ <mail@host.com>
* @copyright 2021 __COMPANY_LTD__
* @license <a href="https://opensource.org/licenses/MIT">MIT License</a>
*/
#ifndef ZEN_CORE_CONFIG_IMAGES_HPP
#define ZEN_CORE_CONFIG_IMAGES_HPP
#include <string>
namespace Zen {
/*
* Config object containing various sound settings.
*
* @since 0.0.0
*/
struct ImagesConfig {
/**
* A base64 encoded image file to use as the 'default' texture.
*
* @since 0.0.0
*/
std::string defaults;
/**
* A base64 encoded image file to use as the 'missing' texture.
*
* @since 0.0.0
*/
std::string missing;
/**
* base64 encoded image file to use as the 'white' texture.
*
* @since 0.0.0
*/
std::string white;
};
} // namespace Zen
#endif
|
#include <lemon/syscall.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <dirent.h>
#include <limits.h>
#include <fcntl.h>
#include <string.h>
#include <bits/ensure.h>
#include <mlibc/all-sysdeps.hpp>
#include <mlibc/debug.hpp>
namespace mlibc{
typedef struct {
dev_t st_dev;
ino_t st_ino;
mode_t st_mode;
nlink_t st_nlink;
uid_t st_uid;
uid_t st_gid;
dev_t st_rdev;
off_t st_size;
int64_t st_blksize;
int64_t st_blocks;
} lemon_stat_t;
int sys_write(int fd, const void* buffer, size_t count, ssize_t* written){
long ret = syscall(SYS_WRITE, fd, (uintptr_t)buffer, count);
if(ret < 0)
return -ret;
*written = ret;
return 0;
}
int sys_read(int fd, void *buf, size_t count, ssize_t *bytes_read) {
long ret = syscall(SYS_READ, fd, (uintptr_t)buf, count);
if(ret < 0){
*bytes_read = 0;
return -ret;
}
*bytes_read = ret;
return 0;
}
int sys_pwrite(int fd, const void* buffer, size_t count, off_t off, ssize_t* written){
int ret = syscall(SYS_PWRITE, fd, (uintptr_t)buffer, count, 0, off);
if(ret < 0){
return -ret;
}
*written = ret;
return 0;
}
int sys_pread(int fd, void *buf, size_t count, off_t off, ssize_t *bytes_read) {
int ret = syscall(SYS_PREAD, fd, (uintptr_t)buf, count, 0, off);
if(ret < 0){
return -ret;
}
*bytes_read = ret;
return 0;
}
int sys_seek(int fd, off_t offset, int whence, off_t *new_offset) {
long ret = syscall(SYS_LSEEK, fd, offset, whence);
if(ret < 0){
return -ret;
}
*new_offset = ret;
return 0;
}
int sys_open(const char* filename, int flags, int* fd){
long ret = syscall(SYS_OPEN, (uintptr_t)filename, flags);
if(ret < 0)
return -ret;
*fd = ret;
return 0;
}
int sys_close(int fd){
syscall(SYS_CLOSE, fd);
return 0;
}
int sys_access(const char* filename, int mode){
int fd;
if(int e = sys_open(filename, O_RDONLY, &fd)){
return e;
}
sys_close(fd);
return 0;
}
int sys_stat(fsfd_target fsfdt, int fd, const char *path, int flags, struct stat *statbuf){
long ret = 0;
lemon_stat_t lemonStat;
switch(fsfdt){
case fsfd_target::fd:
ret = syscall(SYS_FSTAT, &lemonStat, fd);
break;
case fsfd_target::path:
ret = syscall(SYS_STAT, &lemonStat, path);
break;
default:
mlibc::infoLogger() << "mlibc warning: sys_stat: unsupported fsfd target" << frg::endlog;
return EINVAL;
}
statbuf->st_dev = lemonStat.st_dev;
statbuf->st_ino = lemonStat.st_ino;
statbuf->st_mode = lemonStat.st_mode;
statbuf->st_nlink = lemonStat.st_nlink;
statbuf->st_uid = lemonStat.st_uid;
statbuf->st_gid = lemonStat.st_gid;
statbuf->st_rdev = lemonStat.st_rdev;
statbuf->st_size = lemonStat.st_size;
statbuf->st_blksize = lemonStat.st_blksize;
statbuf->st_blocks = lemonStat.st_blocks;
return -ret;
}
int sys_ioctl(int fd, unsigned long request, void *arg, int *result){
return syscall(SYS_IOCTL, fd, request, arg, result);
}
#ifndef MLIBC_BUILDING_RTDL
#define LEMON_TIOCGATTR 0xB301
#define LEMON_TIOCSATTR 0xB302
int sys_isatty(int fd) {
struct winsize ws;
long ret = sys_ioctl(fd, TIOCGWINSZ, &ws, 0);
if(!ret) return 0;
return ENOTTY;
}
int sys_tcgetattr(int fd, struct termios *attr) {
if(int e = sys_isatty(fd))
return e;
int ret;
sys_ioctl(fd, LEMON_TIOCGATTR, attr, &ret);
if(ret)
return -ret;
return 0;
}
int sys_tcsetattr(int fd, int optional_action, const struct termios *attr) {
if(int e = sys_isatty(fd))
return e;
if(optional_action){
mlibc::infoLogger() << "mlibc warning: sys_tcsetattr ignores optional_action" << frg::endlog;
}
int ret;
sys_ioctl(fd, LEMON_TIOCSATTR, const_cast<struct termios*>(attr), &ret);
if(ret)
return -ret;
return 0;
}
int sys_poll(struct pollfd *fds, nfds_t count, int timeout, int *num_events){
long ret = syscall(SYS_POLL, fds, count, timeout);
if(ret < 0){
return -ret;
}
*num_events = ret;
return 0;
}
int sys_mkdir(const char* path){
long ret = syscall(SYS_MKDIR, path);
if(ret < 0){
return -ret;
}
return 0;
}
int sys_rmdir(const char* path){
long ret = syscall(SYS_RMDIR, path);
if(ret < 0){
return -ret;
}
return 0;
}
int sys_link(const char* srcpath, const char* destpath){
long ret = syscall(SYS_LINK, srcpath, destpath);
if(ret < 0){
return -ret;
}
return 0;
}
int sys_unlinkat(int fd, const char *path, int flags) {
long ret = syscall(SYS_UNLINK, fd, path, flags);
if(ret < 0) {
return -ret;
}
return 0;
}
typedef struct lemon_dirent {
uint32_t inode; // Inode number
uint32_t type;
char name[NAME_MAX]; // Filename
} lemon_dirent_t;
int sys_read_entries(int handle, void *buffer, size_t max_size, size_t *bytes_read){
lemon_dirent_t lemonDirent;
long ret = syscall(SYS_READDIR_NEXT, handle, &lemonDirent);
if(!ret){
*bytes_read = 0;
return 0;
} else if(ret > 0){
dirent* dir = (dirent*)buffer;
strcpy(dir->d_name, lemonDirent.name);
dir->d_ino = lemonDirent.inode;
dir->d_off = 0;
dir->d_reclen = sizeof(dirent);
dir->d_type = lemonDirent.type;
*bytes_read = sizeof(dirent);
return 0;
} else {
return -ret;
}
}
int sys_open_dir(const char* path, int* handle){
return sys_open(path, O_DIRECTORY, handle);
}
int sys_rename(const char* path, const char* new_path){
return -syscall(SYS_RENAME, path, new_path);
}
int sys_readlink(const char *path, void *buffer, size_t max_size, ssize_t *length){
long ret = syscall(SYS_READLINK, path, buffer, max_size);
if(ret < 0){
return -ret;
}
*length = ret;
return 0;
}
int sys_dup(int fd, int flags, int* newfd){
int ret = syscall(SYS_DUP, fd, flags, -1);
if(ret < 0){
return -ret;
}
*newfd = ret;
return 0;
}
int sys_dup2(int fd, int flags, int newfd){
int ret = syscall(SYS_DUP, fd, flags, newfd);
if(ret < 0){
return -ret;
}
return 0;
}
int sys_fcntl(int fd, int request, va_list args, int* result){
if(request == F_DUPFD){
return sys_dup(fd, 0, result);
} else if(request == F_GETFD){
*result = 0; // Lemon does not support O_CLOEXEC
return 0;
} else if(request == F_SETFD){
*result = 0; // Lemon does not support O_CLOEXEC
return 0;
} else if(request == F_GETFL){
int ret = syscall(SYS_GET_FILE_STATUS_FLAGS, fd);
if(ret < 0){
return -ret;
}
*result = ret;
return 0;
} else if(request == F_SETFL){
int ret = syscall(SYS_SET_FILE_STATUS_FLAGS, fd, va_arg(args, int));
return -ret;
} else {
infoLogger() << "mlibc: sys_fcntl unsupported request (" << request << ")" << frg::endlog;
return EINVAL;
}
}
int sys_pselect(int nfds, fd_set* readfds, fd_set* writefds,
fd_set *exceptfds, const struct timespec* timeout, const sigset_t* sigmask, int *num_events){
int ret = syscall(SYS_SELECT, nfds, readfds, writefds, exceptfds, timeout);
if(ret < 0){
return -ret;
}
*num_events = ret;
return 0;
}
int sys_chmod(const char *pathname, mode_t mode){
int ret = syscall(SYS_CHMOD, pathname, mode);
if(ret < 0){
return -ret;
}
return 0;
}
int sys_pipe(int *fds, int flags){
return -syscall(SYS_PIPE, fds, flags);
}
int sys_epoll_create(int flags, int *fd) {
int ret = syscall(SYS_EPOLL_CREATE, flags);
if(ret < 0){
return -ret;
}
*fd = ret;
return 0;
}
int sys_epoll_ctl(int epfd, int mode, int fd, struct epoll_event *ev) {
int ret = syscall(SYS_EPOLL_CTL, epfd, mode, fd, ev);
if(ret < 0) {
return -ret;
}
return 0;
}
int sys_epoll_pwait(int epfd, struct epoll_event *ev, int n,
int timeout, const sigset_t *sigmask, int *raised) {
int ret = syscall(SYS_EPOLL_WAIT, epfd, ev, n, timeout, sigmask);
if(ret < 0) {
return -ret;
}
*raised = ret;
return 0;
}
int sys_ttyname(int tty, char *buf, size_t size) {
char path[PATH_MAX] = {"/dev/pts/"};
struct stat stat;
if(int e = sys_stat(fsfd_target::fd, tty, nullptr, 0, &stat)) {
return e;
}
if(!S_ISCHR(stat.st_mode)) {
return ENOTTY; // Not a char device, isn't a tty
}
if(sys_isatty(tty)) {
return ENOTTY;
}
// Look for tty in /dev/pts
int ptDir = open("/dev/pts", O_DIRECTORY);
__ensure(ptDir >= 0);
struct dirent dirent;
size_t direntBytesRead;
while(!sys_read_entries(ptDir, &dirent, sizeof(dirent), &direntBytesRead) && direntBytesRead) {
// Compare the inodes
if(dirent.d_ino == stat.st_ino) {
__ensure(strlen(path) + strlen(dirent.d_name) < PATH_MAX);
strcat(path, dirent.d_name);
strncpy(buf, path, size);
return 0;
}
}
// Could not find corresponding TTY in /dev/pts
return ENODEV;
}
#endif
}
|
/*
* Comba Multiplication and Squaring
*
* This file was automatically generated by ./src/scripts/comba.py on 2021-05-01
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#include <botan/internal/mp_core.h>
namespace Botan {
/*
* Comba 4x4 Squaring
*/
void bigint_comba_sqr4(word z[8], const word x[4])
{
word w2 = 0, w1 = 0, w0 = 0;
word3_muladd (&w2, &w1, &w0, x[ 0], x[ 0]);
z[ 0] = w0; w0 = 0;
word3_muladd_2(&w0, &w2, &w1, x[ 0], x[ 1]);
z[ 1] = w1; w1 = 0;
word3_muladd_2(&w1, &w0, &w2, x[ 0], x[ 2]);
word3_muladd (&w1, &w0, &w2, x[ 1], x[ 1]);
z[ 2] = w2; w2 = 0;
word3_muladd_2(&w2, &w1, &w0, x[ 0], x[ 3]);
word3_muladd_2(&w2, &w1, &w0, x[ 1], x[ 2]);
z[ 3] = w0; w0 = 0;
word3_muladd_2(&w0, &w2, &w1, x[ 1], x[ 3]);
word3_muladd (&w0, &w2, &w1, x[ 2], x[ 2]);
z[ 4] = w1; w1 = 0;
word3_muladd_2(&w1, &w0, &w2, x[ 2], x[ 3]);
z[ 5] = w2; w2 = 0;
word3_muladd (&w2, &w1, &w0, x[ 3], x[ 3]);
z[ 6] = w0;
z[ 7] = w1;
}
/*
* Comba 4x4 Multiplication
*/
void bigint_comba_mul4(word z[8], const word x[4], const word y[4])
{
word w2 = 0, w1 = 0, w0 = 0;
word3_muladd(&w2, &w1, &w0, x[ 0], y[ 0]);
z[ 0] = w0; w0 = 0;
word3_muladd(&w0, &w2, &w1, x[ 0], y[ 1]);
word3_muladd(&w0, &w2, &w1, x[ 1], y[ 0]);
z[ 1] = w1; w1 = 0;
word3_muladd(&w1, &w0, &w2, x[ 0], y[ 2]);
word3_muladd(&w1, &w0, &w2, x[ 1], y[ 1]);
word3_muladd(&w1, &w0, &w2, x[ 2], y[ 0]);
z[ 2] = w2; w2 = 0;
word3_muladd(&w2, &w1, &w0, x[ 0], y[ 3]);
word3_muladd(&w2, &w1, &w0, x[ 1], y[ 2]);
word3_muladd(&w2, &w1, &w0, x[ 2], y[ 1]);
word3_muladd(&w2, &w1, &w0, x[ 3], y[ 0]);
z[ 3] = w0; w0 = 0;
word3_muladd(&w0, &w2, &w1, x[ 1], y[ 3]);
word3_muladd(&w0, &w2, &w1, x[ 2], y[ 2]);
word3_muladd(&w0, &w2, &w1, x[ 3], y[ 1]);
z[ 4] = w1; w1 = 0;
word3_muladd(&w1, &w0, &w2, x[ 2], y[ 3]);
word3_muladd(&w1, &w0, &w2, x[ 3], y[ 2]);
z[ 5] = w2; w2 = 0;
word3_muladd(&w2, &w1, &w0, x[ 3], y[ 3]);
z[ 6] = w0;
z[ 7] = w1;
}
/*
* Comba 6x6 Squaring
*/
void bigint_comba_sqr6(word z[12], const word x[6])
{
word w2 = 0, w1 = 0, w0 = 0;
word3_muladd (&w2, &w1, &w0, x[ 0], x[ 0]);
z[ 0] = w0; w0 = 0;
word3_muladd_2(&w0, &w2, &w1, x[ 0], x[ 1]);
z[ 1] = w1; w1 = 0;
word3_muladd_2(&w1, &w0, &w2, x[ 0], x[ 2]);
word3_muladd (&w1, &w0, &w2, x[ 1], x[ 1]);
z[ 2] = w2; w2 = 0;
word3_muladd_2(&w2, &w1, &w0, x[ 0], x[ 3]);
word3_muladd_2(&w2, &w1, &w0, x[ 1], x[ 2]);
z[ 3] = w0; w0 = 0;
word3_muladd_2(&w0, &w2, &w1, x[ 0], x[ 4]);
word3_muladd_2(&w0, &w2, &w1, x[ 1], x[ 3]);
word3_muladd (&w0, &w2, &w1, x[ 2], x[ 2]);
z[ 4] = w1; w1 = 0;
word3_muladd_2(&w1, &w0, &w2, x[ 0], x[ 5]);
word3_muladd_2(&w1, &w0, &w2, x[ 1], x[ 4]);
word3_muladd_2(&w1, &w0, &w2, x[ 2], x[ 3]);
z[ 5] = w2; w2 = 0;
word3_muladd_2(&w2, &w1, &w0, x[ 1], x[ 5]);
word3_muladd_2(&w2, &w1, &w0, x[ 2], x[ 4]);
word3_muladd (&w2, &w1, &w0, x[ 3], x[ 3]);
z[ 6] = w0; w0 = 0;
word3_muladd_2(&w0, &w2, &w1, x[ 2], x[ 5]);
word3_muladd_2(&w0, &w2, &w1, x[ 3], x[ 4]);
z[ 7] = w1; w1 = 0;
word3_muladd_2(&w1, &w0, &w2, x[ 3], x[ 5]);
word3_muladd (&w1, &w0, &w2, x[ 4], x[ 4]);
z[ 8] = w2; w2 = 0;
word3_muladd_2(&w2, &w1, &w0, x[ 4], x[ 5]);
z[ 9] = w0; w0 = 0;
word3_muladd (&w0, &w2, &w1, x[ 5], x[ 5]);
z[10] = w1;
z[11] = w2;
}
/*
* Comba 6x6 Multiplication
*/
void bigint_comba_mul6(word z[12], const word x[6], const word y[6])
{
word w2 = 0, w1 = 0, w0 = 0;
word3_muladd(&w2, &w1, &w0, x[ 0], y[ 0]);
z[ 0] = w0; w0 = 0;
word3_muladd(&w0, &w2, &w1, x[ 0], y[ 1]);
word3_muladd(&w0, &w2, &w1, x[ 1], y[ 0]);
z[ 1] = w1; w1 = 0;
word3_muladd(&w1, &w0, &w2, x[ 0], y[ 2]);
word3_muladd(&w1, &w0, &w2, x[ 1], y[ 1]);
word3_muladd(&w1, &w0, &w2, x[ 2], y[ 0]);
z[ 2] = w2; w2 = 0;
word3_muladd(&w2, &w1, &w0, x[ 0], y[ 3]);
word3_muladd(&w2, &w1, &w0, x[ 1], y[ 2]);
word3_muladd(&w2, &w1, &w0, x[ 2], y[ 1]);
word3_muladd(&w2, &w1, &w0, x[ 3], y[ 0]);
z[ 3] = w0; w0 = 0;
word3_muladd(&w0, &w2, &w1, x[ 0], y[ 4]);
word3_muladd(&w0, &w2, &w1, x[ 1], y[ 3]);
word3_muladd(&w0, &w2, &w1, x[ 2], y[ 2]);
word3_muladd(&w0, &w2, &w1, x[ 3], y[ 1]);
word3_muladd(&w0, &w2, &w1, x[ 4], y[ 0]);
z[ 4] = w1; w1 = 0;
word3_muladd(&w1, &w0, &w2, x[ 0], y[ 5]);
word3_muladd(&w1, &w0, &w2, x[ 1], y[ 4]);
word3_muladd(&w1, &w0, &w2, x[ 2], y[ 3]);
word3_muladd(&w1, &w0, &w2, x[ 3], y[ 2]);
word3_muladd(&w1, &w0, &w2, x[ 4], y[ 1]);
word3_muladd(&w1, &w0, &w2, x[ 5], y[ 0]);
z[ 5] = w2; w2 = 0;
word3_muladd(&w2, &w1, &w0, x[ 1], y[ 5]);
word3_muladd(&w2, &w1, &w0, x[ 2], y[ 4]);
word3_muladd(&w2, &w1, &w0, x[ 3], y[ 3]);
word3_muladd(&w2, &w1, &w0, x[ 4], y[ 2]);
word3_muladd(&w2, &w1, &w0, x[ 5], y[ 1]);
z[ 6] = w0; w0 = 0;
word3_muladd(&w0, &w2, &w1, x[ 2], y[ 5]);
word3_muladd(&w0, &w2, &w1, x[ 3], y[ 4]);
word3_muladd(&w0, &w2, &w1, x[ 4], y[ 3]);
word3_muladd(&w0, &w2, &w1, x[ 5], y[ 2]);
z[ 7] = w1; w1 = 0;
word3_muladd(&w1, &w0, &w2, x[ 3], y[ 5]);
word3_muladd(&w1, &w0, &w2, x[ 4], y[ 4]);
word3_muladd(&w1, &w0, &w2, x[ 5], y[ 3]);
z[ 8] = w2; w2 = 0;
word3_muladd(&w2, &w1, &w0, x[ 4], y[ 5]);
word3_muladd(&w2, &w1, &w0, x[ 5], y[ 4]);
z[ 9] = w0; w0 = 0;
word3_muladd(&w0, &w2, &w1, x[ 5], y[ 5]);
z[10] = w1;
z[11] = w2;
}
/*
* Comba 8x8 Squaring
*/
void bigint_comba_sqr8(word z[16], const word x[8])
{
word w2 = 0, w1 = 0, w0 = 0;
word3_muladd (&w2, &w1, &w0, x[ 0], x[ 0]);
z[ 0] = w0; w0 = 0;
word3_muladd_2(&w0, &w2, &w1, x[ 0], x[ 1]);
z[ 1] = w1; w1 = 0;
word3_muladd_2(&w1, &w0, &w2, x[ 0], x[ 2]);
word3_muladd (&w1, &w0, &w2, x[ 1], x[ 1]);
z[ 2] = w2; w2 = 0;
word3_muladd_2(&w2, &w1, &w0, x[ 0], x[ 3]);
word3_muladd_2(&w2, &w1, &w0, x[ 1], x[ 2]);
z[ 3] = w0; w0 = 0;
word3_muladd_2(&w0, &w2, &w1, x[ 0], x[ 4]);
word3_muladd_2(&w0, &w2, &w1, x[ 1], x[ 3]);
word3_muladd (&w0, &w2, &w1, x[ 2], x[ 2]);
z[ 4] = w1; w1 = 0;
word3_muladd_2(&w1, &w0, &w2, x[ 0], x[ 5]);
word3_muladd_2(&w1, &w0, &w2, x[ 1], x[ 4]);
word3_muladd_2(&w1, &w0, &w2, x[ 2], x[ 3]);
z[ 5] = w2; w2 = 0;
word3_muladd_2(&w2, &w1, &w0, x[ 0], x[ 6]);
word3_muladd_2(&w2, &w1, &w0, x[ 1], x[ 5]);
word3_muladd_2(&w2, &w1, &w0, x[ 2], x[ 4]);
word3_muladd (&w2, &w1, &w0, x[ 3], x[ 3]);
z[ 6] = w0; w0 = 0;
word3_muladd_2(&w0, &w2, &w1, x[ 0], x[ 7]);
word3_muladd_2(&w0, &w2, &w1, x[ 1], x[ 6]);
word3_muladd_2(&w0, &w2, &w1, x[ 2], x[ 5]);
word3_muladd_2(&w0, &w2, &w1, x[ 3], x[ 4]);
z[ 7] = w1; w1 = 0;
word3_muladd_2(&w1, &w0, &w2, x[ 1], x[ 7]);
word3_muladd_2(&w1, &w0, &w2, x[ 2], x[ 6]);
word3_muladd_2(&w1, &w0, &w2, x[ 3], x[ 5]);
word3_muladd (&w1, &w0, &w2, x[ 4], x[ 4]);
z[ 8] = w2; w2 = 0;
word3_muladd_2(&w2, &w1, &w0, x[ 2], x[ 7]);
word3_muladd_2(&w2, &w1, &w0, x[ 3], x[ 6]);
word3_muladd_2(&w2, &w1, &w0, x[ 4], x[ 5]);
z[ 9] = w0; w0 = 0;
word3_muladd_2(&w0, &w2, &w1, x[ 3], x[ 7]);
word3_muladd_2(&w0, &w2, &w1, x[ 4], x[ 6]);
word3_muladd (&w0, &w2, &w1, x[ 5], x[ 5]);
z[10] = w1; w1 = 0;
word3_muladd_2(&w1, &w0, &w2, x[ 4], x[ 7]);
word3_muladd_2(&w1, &w0, &w2, x[ 5], x[ 6]);
z[11] = w2; w2 = 0;
word3_muladd_2(&w2, &w1, &w0, x[ 5], x[ 7]);
word3_muladd (&w2, &w1, &w0, x[ 6], x[ 6]);
z[12] = w0; w0 = 0;
word3_muladd_2(&w0, &w2, &w1, x[ 6], x[ 7]);
z[13] = w1; w1 = 0;
word3_muladd (&w1, &w0, &w2, x[ 7], x[ 7]);
z[14] = w2;
z[15] = w0;
}
/*
* Comba 8x8 Multiplication
*/
void bigint_comba_mul8(word z[16], const word x[8], const word y[8])
{
word w2 = 0, w1 = 0, w0 = 0;
word3_muladd(&w2, &w1, &w0, x[ 0], y[ 0]);
z[ 0] = w0; w0 = 0;
word3_muladd(&w0, &w2, &w1, x[ 0], y[ 1]);
word3_muladd(&w0, &w2, &w1, x[ 1], y[ 0]);
z[ 1] = w1; w1 = 0;
word3_muladd(&w1, &w0, &w2, x[ 0], y[ 2]);
word3_muladd(&w1, &w0, &w2, x[ 1], y[ 1]);
word3_muladd(&w1, &w0, &w2, x[ 2], y[ 0]);
z[ 2] = w2; w2 = 0;
word3_muladd(&w2, &w1, &w0, x[ 0], y[ 3]);
word3_muladd(&w2, &w1, &w0, x[ 1], y[ 2]);
word3_muladd(&w2, &w1, &w0, x[ 2], y[ 1]);
word3_muladd(&w2, &w1, &w0, x[ 3], y[ 0]);
z[ 3] = w0; w0 = 0;
word3_muladd(&w0, &w2, &w1, x[ 0], y[ 4]);
word3_muladd(&w0, &w2, &w1, x[ 1], y[ 3]);
word3_muladd(&w0, &w2, &w1, x[ 2], y[ 2]);
word3_muladd(&w0, &w2, &w1, x[ 3], y[ 1]);
word3_muladd(&w0, &w2, &w1, x[ 4], y[ 0]);
z[ 4] = w1; w1 = 0;
word3_muladd(&w1, &w0, &w2, x[ 0], y[ 5]);
word3_muladd(&w1, &w0, &w2, x[ 1], y[ 4]);
word3_muladd(&w1, &w0, &w2, x[ 2], y[ 3]);
word3_muladd(&w1, &w0, &w2, x[ 3], y[ 2]);
word3_muladd(&w1, &w0, &w2, x[ 4], y[ 1]);
word3_muladd(&w1, &w0, &w2, x[ 5], y[ 0]);
z[ 5] = w2; w2 = 0;
word3_muladd(&w2, &w1, &w0, x[ 0], y[ 6]);
word3_muladd(&w2, &w1, &w0, x[ 1], y[ 5]);
word3_muladd(&w2, &w1, &w0, x[ 2], y[ 4]);
word3_muladd(&w2, &w1, &w0, x[ 3], y[ 3]);
word3_muladd(&w2, &w1, &w0, x[ 4], y[ 2]);
word3_muladd(&w2, &w1, &w0, x[ 5], y[ 1]);
word3_muladd(&w2, &w1, &w0, x[ 6], y[ 0]);
z[ 6] = w0; w0 = 0;
word3_muladd(&w0, &w2, &w1, x[ 0], y[ 7]);
word3_muladd(&w0, &w2, &w1, x[ 1], y[ 6]);
word3_muladd(&w0, &w2, &w1, x[ 2], y[ 5]);
word3_muladd(&w0, &w2, &w1, x[ 3], y[ 4]);
word3_muladd(&w0, &w2, &w1, x[ 4], y[ 3]);
word3_muladd(&w0, &w2, &w1, x[ 5], y[ 2]);
word3_muladd(&w0, &w2, &w1, x[ 6], y[ 1]);
word3_muladd(&w0, &w2, &w1, x[ 7], y[ 0]);
z[ 7] = w1; w1 = 0;
word3_muladd(&w1, &w0, &w2, x[ 1], y[ 7]);
word3_muladd(&w1, &w0, &w2, x[ 2], y[ 6]);
word3_muladd(&w1, &w0, &w2, x[ 3], y[ 5]);
word3_muladd(&w1, &w0, &w2, x[ 4], y[ 4]);
word3_muladd(&w1, &w0, &w2, x[ 5], y[ 3]);
word3_muladd(&w1, &w0, &w2, x[ 6], y[ 2]);
word3_muladd(&w1, &w0, &w2, x[ 7], y[ 1]);
z[ 8] = w2; w2 = 0;
word3_muladd(&w2, &w1, &w0, x[ 2], y[ 7]);
word3_muladd(&w2, &w1, &w0, x[ 3], y[ 6]);
word3_muladd(&w2, &w1, &w0, x[ 4], y[ 5]);
word3_muladd(&w2, &w1, &w0, x[ 5], y[ 4]);
word3_muladd(&w2, &w1, &w0, x[ 6], y[ 3]);
word3_muladd(&w2, &w1, &w0, x[ 7], y[ 2]);
z[ 9] = w0; w0 = 0;
word3_muladd(&w0, &w2, &w1, x[ 3], y[ 7]);
word3_muladd(&w0, &w2, &w1, x[ 4], y[ 6]);
word3_muladd(&w0, &w2, &w1, x[ 5], y[ 5]);
word3_muladd(&w0, &w2, &w1, x[ 6], y[ 4]);
word3_muladd(&w0, &w2, &w1, x[ 7], y[ 3]);
z[10] = w1; w1 = 0;
word3_muladd(&w1, &w0, &w2, x[ 4], y[ 7]);
word3_muladd(&w1, &w0, &w2, x[ 5], y[ 6]);
word3_muladd(&w1, &w0, &w2, x[ 6], y[ 5]);
word3_muladd(&w1, &w0, &w2, x[ 7], y[ 4]);
z[11] = w2; w2 = 0;
word3_muladd(&w2, &w1, &w0, x[ 5], y[ 7]);
word3_muladd(&w2, &w1, &w0, x[ 6], y[ 6]);
word3_muladd(&w2, &w1, &w0, x[ 7], y[ 5]);
z[12] = w0; w0 = 0;
word3_muladd(&w0, &w2, &w1, x[ 6], y[ 7]);
word3_muladd(&w0, &w2, &w1, x[ 7], y[ 6]);
z[13] = w1; w1 = 0;
word3_muladd(&w1, &w0, &w2, x[ 7], y[ 7]);
z[14] = w2;
z[15] = w0;
}
/*
* Comba 9x9 Squaring
*/
void bigint_comba_sqr9(word z[18], const word x[9])
{
word w2 = 0, w1 = 0, w0 = 0;
word3_muladd (&w2, &w1, &w0, x[ 0], x[ 0]);
z[ 0] = w0; w0 = 0;
word3_muladd_2(&w0, &w2, &w1, x[ 0], x[ 1]);
z[ 1] = w1; w1 = 0;
word3_muladd_2(&w1, &w0, &w2, x[ 0], x[ 2]);
word3_muladd (&w1, &w0, &w2, x[ 1], x[ 1]);
z[ 2] = w2; w2 = 0;
word3_muladd_2(&w2, &w1, &w0, x[ 0], x[ 3]);
word3_muladd_2(&w2, &w1, &w0, x[ 1], x[ 2]);
z[ 3] = w0; w0 = 0;
word3_muladd_2(&w0, &w2, &w1, x[ 0], x[ 4]);
word3_muladd_2(&w0, &w2, &w1, x[ 1], x[ 3]);
word3_muladd (&w0, &w2, &w1, x[ 2], x[ 2]);
z[ 4] = w1; w1 = 0;
word3_muladd_2(&w1, &w0, &w2, x[ 0], x[ 5]);
word3_muladd_2(&w1, &w0, &w2, x[ 1], x[ 4]);
word3_muladd_2(&w1, &w0, &w2, x[ 2], x[ 3]);
z[ 5] = w2; w2 = 0;
word3_muladd_2(&w2, &w1, &w0, x[ 0], x[ 6]);
word3_muladd_2(&w2, &w1, &w0, x[ 1], x[ 5]);
word3_muladd_2(&w2, &w1, &w0, x[ 2], x[ 4]);
word3_muladd (&w2, &w1, &w0, x[ 3], x[ 3]);
z[ 6] = w0; w0 = 0;
word3_muladd_2(&w0, &w2, &w1, x[ 0], x[ 7]);
word3_muladd_2(&w0, &w2, &w1, x[ 1], x[ 6]);
word3_muladd_2(&w0, &w2, &w1, x[ 2], x[ 5]);
word3_muladd_2(&w0, &w2, &w1, x[ 3], x[ 4]);
z[ 7] = w1; w1 = 0;
word3_muladd_2(&w1, &w0, &w2, x[ 0], x[ 8]);
word3_muladd_2(&w1, &w0, &w2, x[ 1], x[ 7]);
word3_muladd_2(&w1, &w0, &w2, x[ 2], x[ 6]);
word3_muladd_2(&w1, &w0, &w2, x[ 3], x[ 5]);
word3_muladd (&w1, &w0, &w2, x[ 4], x[ 4]);
z[ 8] = w2; w2 = 0;
word3_muladd_2(&w2, &w1, &w0, x[ 1], x[ 8]);
word3_muladd_2(&w2, &w1, &w0, x[ 2], x[ 7]);
word3_muladd_2(&w2, &w1, &w0, x[ 3], x[ 6]);
word3_muladd_2(&w2, &w1, &w0, x[ 4], x[ 5]);
z[ 9] = w0; w0 = 0;
word3_muladd_2(&w0, &w2, &w1, x[ 2], x[ 8]);
word3_muladd_2(&w0, &w2, &w1, x[ 3], x[ 7]);
word3_muladd_2(&w0, &w2, &w1, x[ 4], x[ 6]);
word3_muladd (&w0, &w2, &w1, x[ 5], x[ 5]);
z[10] = w1; w1 = 0;
word3_muladd_2(&w1, &w0, &w2, x[ 3], x[ 8]);
word3_muladd_2(&w1, &w0, &w2, x[ 4], x[ 7]);
word3_muladd_2(&w1, &w0, &w2, x[ 5], x[ 6]);
z[11] = w2; w2 = 0;
word3_muladd_2(&w2, &w1, &w0, x[ 4], x[ 8]);
word3_muladd_2(&w2, &w1, &w0, x[ 5], x[ 7]);
word3_muladd (&w2, &w1, &w0, x[ 6], x[ 6]);
z[12] = w0; w0 = 0;
word3_muladd_2(&w0, &w2, &w1, x[ 5], x[ 8]);
word3_muladd_2(&w0, &w2, &w1, x[ 6], x[ 7]);
z[13] = w1; w1 = 0;
word3_muladd_2(&w1, &w0, &w2, x[ 6], x[ 8]);
word3_muladd (&w1, &w0, &w2, x[ 7], x[ 7]);
z[14] = w2; w2 = 0;
word3_muladd_2(&w2, &w1, &w0, x[ 7], x[ 8]);
z[15] = w0; w0 = 0;
word3_muladd (&w0, &w2, &w1, x[ 8], x[ 8]);
z[16] = w1;
z[17] = w2;
}
/*
* Comba 9x9 Multiplication
*/
void bigint_comba_mul9(word z[18], const word x[9], const word y[9])
{
word w2 = 0, w1 = 0, w0 = 0;
word3_muladd(&w2, &w1, &w0, x[ 0], y[ 0]);
z[ 0] = w0; w0 = 0;
word3_muladd(&w0, &w2, &w1, x[ 0], y[ 1]);
word3_muladd(&w0, &w2, &w1, x[ 1], y[ 0]);
z[ 1] = w1; w1 = 0;
word3_muladd(&w1, &w0, &w2, x[ 0], y[ 2]);
word3_muladd(&w1, &w0, &w2, x[ 1], y[ 1]);
word3_muladd(&w1, &w0, &w2, x[ 2], y[ 0]);
z[ 2] = w2; w2 = 0;
word3_muladd(&w2, &w1, &w0, x[ 0], y[ 3]);
word3_muladd(&w2, &w1, &w0, x[ 1], y[ 2]);
word3_muladd(&w2, &w1, &w0, x[ 2], y[ 1]);
word3_muladd(&w2, &w1, &w0, x[ 3], y[ 0]);
z[ 3] = w0; w0 = 0;
word3_muladd(&w0, &w2, &w1, x[ 0], y[ 4]);
word3_muladd(&w0, &w2, &w1, x[ 1], y[ 3]);
word3_muladd(&w0, &w2, &w1, x[ 2], y[ 2]);
word3_muladd(&w0, &w2, &w1, x[ 3], y[ 1]);
word3_muladd(&w0, &w2, &w1, x[ 4], y[ 0]);
z[ 4] = w1; w1 = 0;
word3_muladd(&w1, &w0, &w2, x[ 0], y[ 5]);
word3_muladd(&w1, &w0, &w2, x[ 1], y[ 4]);
word3_muladd(&w1, &w0, &w2, x[ 2], y[ 3]);
word3_muladd(&w1, &w0, &w2, x[ 3], y[ 2]);
word3_muladd(&w1, &w0, &w2, x[ 4], y[ 1]);
word3_muladd(&w1, &w0, &w2, x[ 5], y[ 0]);
z[ 5] = w2; w2 = 0;
word3_muladd(&w2, &w1, &w0, x[ 0], y[ 6]);
word3_muladd(&w2, &w1, &w0, x[ 1], y[ 5]);
word3_muladd(&w2, &w1, &w0, x[ 2], y[ 4]);
word3_muladd(&w2, &w1, &w0, x[ 3], y[ 3]);
word3_muladd(&w2, &w1, &w0, x[ 4], y[ 2]);
word3_muladd(&w2, &w1, &w0, x[ 5], y[ 1]);
word3_muladd(&w2, &w1, &w0, x[ 6], y[ 0]);
z[ 6] = w0; w0 = 0;
word3_muladd(&w0, &w2, &w1, x[ 0], y[ 7]);
word3_muladd(&w0, &w2, &w1, x[ 1], y[ 6]);
word3_muladd(&w0, &w2, &w1, x[ 2], y[ 5]);
word3_muladd(&w0, &w2, &w1, x[ 3], y[ 4]);
word3_muladd(&w0, &w2, &w1, x[ 4], y[ 3]);
word3_muladd(&w0, &w2, &w1, x[ 5], y[ 2]);
word3_muladd(&w0, &w2, &w1, x[ 6], y[ 1]);
word3_muladd(&w0, &w2, &w1, x[ 7], y[ 0]);
z[ 7] = w1; w1 = 0;
word3_muladd(&w1, &w0, &w2, x[ 0], y[ 8]);
word3_muladd(&w1, &w0, &w2, x[ 1], y[ 7]);
word3_muladd(&w1, &w0, &w2, x[ 2], y[ 6]);
word3_muladd(&w1, &w0, &w2, x[ 3], y[ 5]);
word3_muladd(&w1, &w0, &w2, x[ 4], y[ 4]);
word3_muladd(&w1, &w0, &w2, x[ 5], y[ 3]);
word3_muladd(&w1, &w0, &w2, x[ 6], y[ 2]);
word3_muladd(&w1, &w0, &w2, x[ 7], y[ 1]);
word3_muladd(&w1, &w0, &w2, x[ 8], y[ 0]);
z[ 8] = w2; w2 = 0;
word3_muladd(&w2, &w1, &w0, x[ 1], y[ 8]);
word3_muladd(&w2, &w1, &w0, x[ 2], y[ 7]);
word3_muladd(&w2, &w1, &w0, x[ 3], y[ 6]);
word3_muladd(&w2, &w1, &w0, x[ 4], y[ 5]);
word3_muladd(&w2, &w1, &w0, x[ 5], y[ 4]);
word3_muladd(&w2, &w1, &w0, x[ 6], y[ 3]);
word3_muladd(&w2, &w1, &w0, x[ 7], y[ 2]);
word3_muladd(&w2, &w1, &w0, x[ 8], y[ 1]);
z[ 9] = w0; w0 = 0;
word3_muladd(&w0, &w2, &w1, x[ 2], y[ 8]);
word3_muladd(&w0, &w2, &w1, x[ 3], y[ 7]);
word3_muladd(&w0, &w2, &w1, x[ 4], y[ 6]);
word3_muladd(&w0, &w2, &w1, x[ 5], y[ 5]);
word3_muladd(&w0, &w2, &w1, x[ 6], y[ 4]);
word3_muladd(&w0, &w2, &w1, x[ 7], y[ 3]);
word3_muladd(&w0, &w2, &w1, x[ 8], y[ 2]);
z[10] = w1; w1 = 0;
word3_muladd(&w1, &w0, &w2, x[ 3], y[ 8]);
word3_muladd(&w1, &w0, &w2, x[ 4], y[ 7]);
word3_muladd(&w1, &w0, &w2, x[ 5], y[ 6]);
word3_muladd(&w1, &w0, &w2, x[ 6], y[ 5]);
word3_muladd(&w1, &w0, &w2, x[ 7], y[ 4]);
word3_muladd(&w1, &w0, &w2, x[ 8], y[ 3]);
z[11] = w2; w2 = 0;
word3_muladd(&w2, &w1, &w0, x[ 4], y[ 8]);
word3_muladd(&w2, &w1, &w0, x[ 5], y[ 7]);
word3_muladd(&w2, &w1, &w0, x[ 6], y[ 6]);
word3_muladd(&w2, &w1, &w0, x[ 7], y[ 5]);
word3_muladd(&w2, &w1, &w0, x[ 8], y[ 4]);
z[12] = w0; w0 = 0;
word3_muladd(&w0, &w2, &w1, x[ 5], y[ 8]);
word3_muladd(&w0, &w2, &w1, x[ 6], y[ 7]);
word3_muladd(&w0, &w2, &w1, x[ 7], y[ 6]);
word3_muladd(&w0, &w2, &w1, x[ 8], y[ 5]);
z[13] = w1; w1 = 0;
word3_muladd(&w1, &w0, &w2, x[ 6], y[ 8]);
word3_muladd(&w1, &w0, &w2, x[ 7], y[ 7]);
word3_muladd(&w1, &w0, &w2, x[ 8], y[ 6]);
z[14] = w2; w2 = 0;
word3_muladd(&w2, &w1, &w0, x[ 7], y[ 8]);
word3_muladd(&w2, &w1, &w0, x[ 8], y[ 7]);
z[15] = w0; w0 = 0;
word3_muladd(&w0, &w2, &w1, x[ 8], y[ 8]);
z[16] = w1;
z[17] = w2;
}
/*
* Comba 16x16 Squaring
*/
void bigint_comba_sqr16(word z[32], const word x[16])
{
word w2 = 0, w1 = 0, w0 = 0;
word3_muladd (&w2, &w1, &w0, x[ 0], x[ 0]);
z[ 0] = w0; w0 = 0;
word3_muladd_2(&w0, &w2, &w1, x[ 0], x[ 1]);
z[ 1] = w1; w1 = 0;
word3_muladd_2(&w1, &w0, &w2, x[ 0], x[ 2]);
word3_muladd (&w1, &w0, &w2, x[ 1], x[ 1]);
z[ 2] = w2; w2 = 0;
word3_muladd_2(&w2, &w1, &w0, x[ 0], x[ 3]);
word3_muladd_2(&w2, &w1, &w0, x[ 1], x[ 2]);
z[ 3] = w0; w0 = 0;
word3_muladd_2(&w0, &w2, &w1, x[ 0], x[ 4]);
word3_muladd_2(&w0, &w2, &w1, x[ 1], x[ 3]);
word3_muladd (&w0, &w2, &w1, x[ 2], x[ 2]);
z[ 4] = w1; w1 = 0;
word3_muladd_2(&w1, &w0, &w2, x[ 0], x[ 5]);
word3_muladd_2(&w1, &w0, &w2, x[ 1], x[ 4]);
word3_muladd_2(&w1, &w0, &w2, x[ 2], x[ 3]);
z[ 5] = w2; w2 = 0;
word3_muladd_2(&w2, &w1, &w0, x[ 0], x[ 6]);
word3_muladd_2(&w2, &w1, &w0, x[ 1], x[ 5]);
word3_muladd_2(&w2, &w1, &w0, x[ 2], x[ 4]);
word3_muladd (&w2, &w1, &w0, x[ 3], x[ 3]);
z[ 6] = w0; w0 = 0;
word3_muladd_2(&w0, &w2, &w1, x[ 0], x[ 7]);
word3_muladd_2(&w0, &w2, &w1, x[ 1], x[ 6]);
word3_muladd_2(&w0, &w2, &w1, x[ 2], x[ 5]);
word3_muladd_2(&w0, &w2, &w1, x[ 3], x[ 4]);
z[ 7] = w1; w1 = 0;
word3_muladd_2(&w1, &w0, &w2, x[ 0], x[ 8]);
word3_muladd_2(&w1, &w0, &w2, x[ 1], x[ 7]);
word3_muladd_2(&w1, &w0, &w2, x[ 2], x[ 6]);
word3_muladd_2(&w1, &w0, &w2, x[ 3], x[ 5]);
word3_muladd (&w1, &w0, &w2, x[ 4], x[ 4]);
z[ 8] = w2; w2 = 0;
word3_muladd_2(&w2, &w1, &w0, x[ 0], x[ 9]);
word3_muladd_2(&w2, &w1, &w0, x[ 1], x[ 8]);
word3_muladd_2(&w2, &w1, &w0, x[ 2], x[ 7]);
word3_muladd_2(&w2, &w1, &w0, x[ 3], x[ 6]);
word3_muladd_2(&w2, &w1, &w0, x[ 4], x[ 5]);
z[ 9] = w0; w0 = 0;
word3_muladd_2(&w0, &w2, &w1, x[ 0], x[10]);
word3_muladd_2(&w0, &w2, &w1, x[ 1], x[ 9]);
word3_muladd_2(&w0, &w2, &w1, x[ 2], x[ 8]);
word3_muladd_2(&w0, &w2, &w1, x[ 3], x[ 7]);
word3_muladd_2(&w0, &w2, &w1, x[ 4], x[ 6]);
word3_muladd (&w0, &w2, &w1, x[ 5], x[ 5]);
z[10] = w1; w1 = 0;
word3_muladd_2(&w1, &w0, &w2, x[ 0], x[11]);
word3_muladd_2(&w1, &w0, &w2, x[ 1], x[10]);
word3_muladd_2(&w1, &w0, &w2, x[ 2], x[ 9]);
word3_muladd_2(&w1, &w0, &w2, x[ 3], x[ 8]);
word3_muladd_2(&w1, &w0, &w2, x[ 4], x[ 7]);
word3_muladd_2(&w1, &w0, &w2, x[ 5], x[ 6]);
z[11] = w2; w2 = 0;
word3_muladd_2(&w2, &w1, &w0, x[ 0], x[12]);
word3_muladd_2(&w2, &w1, &w0, x[ 1], x[11]);
word3_muladd_2(&w2, &w1, &w0, x[ 2], x[10]);
word3_muladd_2(&w2, &w1, &w0, x[ 3], x[ 9]);
word3_muladd_2(&w2, &w1, &w0, x[ 4], x[ 8]);
word3_muladd_2(&w2, &w1, &w0, x[ 5], x[ 7]);
word3_muladd (&w2, &w1, &w0, x[ 6], x[ 6]);
z[12] = w0; w0 = 0;
word3_muladd_2(&w0, &w2, &w1, x[ 0], x[13]);
word3_muladd_2(&w0, &w2, &w1, x[ 1], x[12]);
word3_muladd_2(&w0, &w2, &w1, x[ 2], x[11]);
word3_muladd_2(&w0, &w2, &w1, x[ 3], x[10]);
word3_muladd_2(&w0, &w2, &w1, x[ 4], x[ 9]);
word3_muladd_2(&w0, &w2, &w1, x[ 5], x[ 8]);
word3_muladd_2(&w0, &w2, &w1, x[ 6], x[ 7]);
z[13] = w1; w1 = 0;
word3_muladd_2(&w1, &w0, &w2, x[ 0], x[14]);
word3_muladd_2(&w1, &w0, &w2, x[ 1], x[13]);
word3_muladd_2(&w1, &w0, &w2, x[ 2], x[12]);
word3_muladd_2(&w1, &w0, &w2, x[ 3], x[11]);
word3_muladd_2(&w1, &w0, &w2, x[ 4], x[10]);
word3_muladd_2(&w1, &w0, &w2, x[ 5], x[ 9]);
word3_muladd_2(&w1, &w0, &w2, x[ 6], x[ 8]);
word3_muladd (&w1, &w0, &w2, x[ 7], x[ 7]);
z[14] = w2; w2 = 0;
word3_muladd_2(&w2, &w1, &w0, x[ 0], x[15]);
word3_muladd_2(&w2, &w1, &w0, x[ 1], x[14]);
word3_muladd_2(&w2, &w1, &w0, x[ 2], x[13]);
word3_muladd_2(&w2, &w1, &w0, x[ 3], x[12]);
word3_muladd_2(&w2, &w1, &w0, x[ 4], x[11]);
word3_muladd_2(&w2, &w1, &w0, x[ 5], x[10]);
word3_muladd_2(&w2, &w1, &w0, x[ 6], x[ 9]);
word3_muladd_2(&w2, &w1, &w0, x[ 7], x[ 8]);
z[15] = w0; w0 = 0;
word3_muladd_2(&w0, &w2, &w1, x[ 1], x[15]);
word3_muladd_2(&w0, &w2, &w1, x[ 2], x[14]);
word3_muladd_2(&w0, &w2, &w1, x[ 3], x[13]);
word3_muladd_2(&w0, &w2, &w1, x[ 4], x[12]);
word3_muladd_2(&w0, &w2, &w1, x[ 5], x[11]);
word3_muladd_2(&w0, &w2, &w1, x[ 6], x[10]);
word3_muladd_2(&w0, &w2, &w1, x[ 7], x[ 9]);
word3_muladd (&w0, &w2, &w1, x[ 8], x[ 8]);
z[16] = w1; w1 = 0;
word3_muladd_2(&w1, &w0, &w2, x[ 2], x[15]);
word3_muladd_2(&w1, &w0, &w2, x[ 3], x[14]);
word3_muladd_2(&w1, &w0, &w2, x[ 4], x[13]);
word3_muladd_2(&w1, &w0, &w2, x[ 5], x[12]);
word3_muladd_2(&w1, &w0, &w2, x[ 6], x[11]);
word3_muladd_2(&w1, &w0, &w2, x[ 7], x[10]);
word3_muladd_2(&w1, &w0, &w2, x[ 8], x[ 9]);
z[17] = w2; w2 = 0;
word3_muladd_2(&w2, &w1, &w0, x[ 3], x[15]);
word3_muladd_2(&w2, &w1, &w0, x[ 4], x[14]);
word3_muladd_2(&w2, &w1, &w0, x[ 5], x[13]);
word3_muladd_2(&w2, &w1, &w0, x[ 6], x[12]);
word3_muladd_2(&w2, &w1, &w0, x[ 7], x[11]);
word3_muladd_2(&w2, &w1, &w0, x[ 8], x[10]);
word3_muladd (&w2, &w1, &w0, x[ 9], x[ 9]);
z[18] = w0; w0 = 0;
word3_muladd_2(&w0, &w2, &w1, x[ 4], x[15]);
word3_muladd_2(&w0, &w2, &w1, x[ 5], x[14]);
word3_muladd_2(&w0, &w2, &w1, x[ 6], x[13]);
word3_muladd_2(&w0, &w2, &w1, x[ 7], x[12]);
word3_muladd_2(&w0, &w2, &w1, x[ 8], x[11]);
word3_muladd_2(&w0, &w2, &w1, x[ 9], x[10]);
z[19] = w1; w1 = 0;
word3_muladd_2(&w1, &w0, &w2, x[ 5], x[15]);
word3_muladd_2(&w1, &w0, &w2, x[ 6], x[14]);
word3_muladd_2(&w1, &w0, &w2, x[ 7], x[13]);
word3_muladd_2(&w1, &w0, &w2, x[ 8], x[12]);
word3_muladd_2(&w1, &w0, &w2, x[ 9], x[11]);
word3_muladd (&w1, &w0, &w2, x[10], x[10]);
z[20] = w2; w2 = 0;
word3_muladd_2(&w2, &w1, &w0, x[ 6], x[15]);
word3_muladd_2(&w2, &w1, &w0, x[ 7], x[14]);
word3_muladd_2(&w2, &w1, &w0, x[ 8], x[13]);
word3_muladd_2(&w2, &w1, &w0, x[ 9], x[12]);
word3_muladd_2(&w2, &w1, &w0, x[10], x[11]);
z[21] = w0; w0 = 0;
word3_muladd_2(&w0, &w2, &w1, x[ 7], x[15]);
word3_muladd_2(&w0, &w2, &w1, x[ 8], x[14]);
word3_muladd_2(&w0, &w2, &w1, x[ 9], x[13]);
word3_muladd_2(&w0, &w2, &w1, x[10], x[12]);
word3_muladd (&w0, &w2, &w1, x[11], x[11]);
z[22] = w1; w1 = 0;
word3_muladd_2(&w1, &w0, &w2, x[ 8], x[15]);
word3_muladd_2(&w1, &w0, &w2, x[ 9], x[14]);
word3_muladd_2(&w1, &w0, &w2, x[10], x[13]);
word3_muladd_2(&w1, &w0, &w2, x[11], x[12]);
z[23] = w2; w2 = 0;
word3_muladd_2(&w2, &w1, &w0, x[ 9], x[15]);
word3_muladd_2(&w2, &w1, &w0, x[10], x[14]);
word3_muladd_2(&w2, &w1, &w0, x[11], x[13]);
word3_muladd (&w2, &w1, &w0, x[12], x[12]);
z[24] = w0; w0 = 0;
word3_muladd_2(&w0, &w2, &w1, x[10], x[15]);
word3_muladd_2(&w0, &w2, &w1, x[11], x[14]);
word3_muladd_2(&w0, &w2, &w1, x[12], x[13]);
z[25] = w1; w1 = 0;
word3_muladd_2(&w1, &w0, &w2, x[11], x[15]);
word3_muladd_2(&w1, &w0, &w2, x[12], x[14]);
word3_muladd (&w1, &w0, &w2, x[13], x[13]);
z[26] = w2; w2 = 0;
word3_muladd_2(&w2, &w1, &w0, x[12], x[15]);
word3_muladd_2(&w2, &w1, &w0, x[13], x[14]);
z[27] = w0; w0 = 0;
word3_muladd_2(&w0, &w2, &w1, x[13], x[15]);
word3_muladd (&w0, &w2, &w1, x[14], x[14]);
z[28] = w1; w1 = 0;
word3_muladd_2(&w1, &w0, &w2, x[14], x[15]);
z[29] = w2; w2 = 0;
word3_muladd (&w2, &w1, &w0, x[15], x[15]);
z[30] = w0;
z[31] = w1;
}
/*
* Comba 16x16 Multiplication
*/
void bigint_comba_mul16(word z[32], const word x[16], const word y[16])
{
word w2 = 0, w1 = 0, w0 = 0;
word3_muladd(&w2, &w1, &w0, x[ 0], y[ 0]);
z[ 0] = w0; w0 = 0;
word3_muladd(&w0, &w2, &w1, x[ 0], y[ 1]);
word3_muladd(&w0, &w2, &w1, x[ 1], y[ 0]);
z[ 1] = w1; w1 = 0;
word3_muladd(&w1, &w0, &w2, x[ 0], y[ 2]);
word3_muladd(&w1, &w0, &w2, x[ 1], y[ 1]);
word3_muladd(&w1, &w0, &w2, x[ 2], y[ 0]);
z[ 2] = w2; w2 = 0;
word3_muladd(&w2, &w1, &w0, x[ 0], y[ 3]);
word3_muladd(&w2, &w1, &w0, x[ 1], y[ 2]);
word3_muladd(&w2, &w1, &w0, x[ 2], y[ 1]);
word3_muladd(&w2, &w1, &w0, x[ 3], y[ 0]);
z[ 3] = w0; w0 = 0;
word3_muladd(&w0, &w2, &w1, x[ 0], y[ 4]);
word3_muladd(&w0, &w2, &w1, x[ 1], y[ 3]);
word3_muladd(&w0, &w2, &w1, x[ 2], y[ 2]);
word3_muladd(&w0, &w2, &w1, x[ 3], y[ 1]);
word3_muladd(&w0, &w2, &w1, x[ 4], y[ 0]);
z[ 4] = w1; w1 = 0;
word3_muladd(&w1, &w0, &w2, x[ 0], y[ 5]);
word3_muladd(&w1, &w0, &w2, x[ 1], y[ 4]);
word3_muladd(&w1, &w0, &w2, x[ 2], y[ 3]);
word3_muladd(&w1, &w0, &w2, x[ 3], y[ 2]);
word3_muladd(&w1, &w0, &w2, x[ 4], y[ 1]);
word3_muladd(&w1, &w0, &w2, x[ 5], y[ 0]);
z[ 5] = w2; w2 = 0;
word3_muladd(&w2, &w1, &w0, x[ 0], y[ 6]);
word3_muladd(&w2, &w1, &w0, x[ 1], y[ 5]);
word3_muladd(&w2, &w1, &w0, x[ 2], y[ 4]);
word3_muladd(&w2, &w1, &w0, x[ 3], y[ 3]);
word3_muladd(&w2, &w1, &w0, x[ 4], y[ 2]);
word3_muladd(&w2, &w1, &w0, x[ 5], y[ 1]);
word3_muladd(&w2, &w1, &w0, x[ 6], y[ 0]);
z[ 6] = w0; w0 = 0;
word3_muladd(&w0, &w2, &w1, x[ 0], y[ 7]);
word3_muladd(&w0, &w2, &w1, x[ 1], y[ 6]);
word3_muladd(&w0, &w2, &w1, x[ 2], y[ 5]);
word3_muladd(&w0, &w2, &w1, x[ 3], y[ 4]);
word3_muladd(&w0, &w2, &w1, x[ 4], y[ 3]);
word3_muladd(&w0, &w2, &w1, x[ 5], y[ 2]);
word3_muladd(&w0, &w2, &w1, x[ 6], y[ 1]);
word3_muladd(&w0, &w2, &w1, x[ 7], y[ 0]);
z[ 7] = w1; w1 = 0;
word3_muladd(&w1, &w0, &w2, x[ 0], y[ 8]);
word3_muladd(&w1, &w0, &w2, x[ 1], y[ 7]);
word3_muladd(&w1, &w0, &w2, x[ 2], y[ 6]);
word3_muladd(&w1, &w0, &w2, x[ 3], y[ 5]);
word3_muladd(&w1, &w0, &w2, x[ 4], y[ 4]);
word3_muladd(&w1, &w0, &w2, x[ 5], y[ 3]);
word3_muladd(&w1, &w0, &w2, x[ 6], y[ 2]);
word3_muladd(&w1, &w0, &w2, x[ 7], y[ 1]);
word3_muladd(&w1, &w0, &w2, x[ 8], y[ 0]);
z[ 8] = w2; w2 = 0;
word3_muladd(&w2, &w1, &w0, x[ 0], y[ 9]);
word3_muladd(&w2, &w1, &w0, x[ 1], y[ 8]);
word3_muladd(&w2, &w1, &w0, x[ 2], y[ 7]);
word3_muladd(&w2, &w1, &w0, x[ 3], y[ 6]);
word3_muladd(&w2, &w1, &w0, x[ 4], y[ 5]);
word3_muladd(&w2, &w1, &w0, x[ 5], y[ 4]);
word3_muladd(&w2, &w1, &w0, x[ 6], y[ 3]);
word3_muladd(&w2, &w1, &w0, x[ 7], y[ 2]);
word3_muladd(&w2, &w1, &w0, x[ 8], y[ 1]);
word3_muladd(&w2, &w1, &w0, x[ 9], y[ 0]);
z[ 9] = w0; w0 = 0;
word3_muladd(&w0, &w2, &w1, x[ 0], y[10]);
word3_muladd(&w0, &w2, &w1, x[ 1], y[ 9]);
word3_muladd(&w0, &w2, &w1, x[ 2], y[ 8]);
word3_muladd(&w0, &w2, &w1, x[ 3], y[ 7]);
word3_muladd(&w0, &w2, &w1, x[ 4], y[ 6]);
word3_muladd(&w0, &w2, &w1, x[ 5], y[ 5]);
word3_muladd(&w0, &w2, &w1, x[ 6], y[ 4]);
word3_muladd(&w0, &w2, &w1, x[ 7], y[ 3]);
word3_muladd(&w0, &w2, &w1, x[ 8], y[ 2]);
word3_muladd(&w0, &w2, &w1, x[ 9], y[ 1]);
word3_muladd(&w0, &w2, &w1, x[10], y[ 0]);
z[10] = w1; w1 = 0;
word3_muladd(&w1, &w0, &w2, x[ 0], y[11]);
word3_muladd(&w1, &w0, &w2, x[ 1], y[10]);
word3_muladd(&w1, &w0, &w2, x[ 2], y[ 9]);
word3_muladd(&w1, &w0, &w2, x[ 3], y[ 8]);
word3_muladd(&w1, &w0, &w2, x[ 4], y[ 7]);
word3_muladd(&w1, &w0, &w2, x[ 5], y[ 6]);
word3_muladd(&w1, &w0, &w2, x[ 6], y[ 5]);
word3_muladd(&w1, &w0, &w2, x[ 7], y[ 4]);
word3_muladd(&w1, &w0, &w2, x[ 8], y[ 3]);
word3_muladd(&w1, &w0, &w2, x[ 9], y[ 2]);
word3_muladd(&w1, &w0, &w2, x[10], y[ 1]);
word3_muladd(&w1, &w0, &w2, x[11], y[ 0]);
z[11] = w2; w2 = 0;
word3_muladd(&w2, &w1, &w0, x[ 0], y[12]);
word3_muladd(&w2, &w1, &w0, x[ 1], y[11]);
word3_muladd(&w2, &w1, &w0, x[ 2], y[10]);
word3_muladd(&w2, &w1, &w0, x[ 3], y[ 9]);
word3_muladd(&w2, &w1, &w0, x[ 4], y[ 8]);
word3_muladd(&w2, &w1, &w0, x[ 5], y[ 7]);
word3_muladd(&w2, &w1, &w0, x[ 6], y[ 6]);
word3_muladd(&w2, &w1, &w0, x[ 7], y[ 5]);
word3_muladd(&w2, &w1, &w0, x[ 8], y[ 4]);
word3_muladd(&w2, &w1, &w0, x[ 9], y[ 3]);
word3_muladd(&w2, &w1, &w0, x[10], y[ 2]);
word3_muladd(&w2, &w1, &w0, x[11], y[ 1]);
word3_muladd(&w2, &w1, &w0, x[12], y[ 0]);
z[12] = w0; w0 = 0;
word3_muladd(&w0, &w2, &w1, x[ 0], y[13]);
word3_muladd(&w0, &w2, &w1, x[ 1], y[12]);
word3_muladd(&w0, &w2, &w1, x[ 2], y[11]);
word3_muladd(&w0, &w2, &w1, x[ 3], y[10]);
word3_muladd(&w0, &w2, &w1, x[ 4], y[ 9]);
word3_muladd(&w0, &w2, &w1, x[ 5], y[ 8]);
word3_muladd(&w0, &w2, &w1, x[ 6], y[ 7]);
word3_muladd(&w0, &w2, &w1, x[ 7], y[ 6]);
word3_muladd(&w0, &w2, &w1, x[ 8], y[ 5]);
word3_muladd(&w0, &w2, &w1, x[ 9], y[ 4]);
word3_muladd(&w0, &w2, &w1, x[10], y[ 3]);
word3_muladd(&w0, &w2, &w1, x[11], y[ 2]);
word3_muladd(&w0, &w2, &w1, x[12], y[ 1]);
word3_muladd(&w0, &w2, &w1, x[13], y[ 0]);
z[13] = w1; w1 = 0;
word3_muladd(&w1, &w0, &w2, x[ 0], y[14]);
word3_muladd(&w1, &w0, &w2, x[ 1], y[13]);
word3_muladd(&w1, &w0, &w2, x[ 2], y[12]);
word3_muladd(&w1, &w0, &w2, x[ 3], y[11]);
word3_muladd(&w1, &w0, &w2, x[ 4], y[10]);
word3_muladd(&w1, &w0, &w2, x[ 5], y[ 9]);
word3_muladd(&w1, &w0, &w2, x[ 6], y[ 8]);
word3_muladd(&w1, &w0, &w2, x[ 7], y[ 7]);
word3_muladd(&w1, &w0, &w2, x[ 8], y[ 6]);
word3_muladd(&w1, &w0, &w2, x[ 9], y[ 5]);
word3_muladd(&w1, &w0, &w2, x[10], y[ 4]);
word3_muladd(&w1, &w0, &w2, x[11], y[ 3]);
word3_muladd(&w1, &w0, &w2, x[12], y[ 2]);
word3_muladd(&w1, &w0, &w2, x[13], y[ 1]);
word3_muladd(&w1, &w0, &w2, x[14], y[ 0]);
z[14] = w2; w2 = 0;
word3_muladd(&w2, &w1, &w0, x[ 0], y[15]);
word3_muladd(&w2, &w1, &w0, x[ 1], y[14]);
word3_muladd(&w2, &w1, &w0, x[ 2], y[13]);
word3_muladd(&w2, &w1, &w0, x[ 3], y[12]);
word3_muladd(&w2, &w1, &w0, x[ 4], y[11]);
word3_muladd(&w2, &w1, &w0, x[ 5], y[10]);
word3_muladd(&w2, &w1, &w0, x[ 6], y[ 9]);
word3_muladd(&w2, &w1, &w0, x[ 7], y[ 8]);
word3_muladd(&w2, &w1, &w0, x[ 8], y[ 7]);
word3_muladd(&w2, &w1, &w0, x[ 9], y[ 6]);
word3_muladd(&w2, &w1, &w0, x[10], y[ 5]);
word3_muladd(&w2, &w1, &w0, x[11], y[ 4]);
word3_muladd(&w2, &w1, &w0, x[12], y[ 3]);
word3_muladd(&w2, &w1, &w0, x[13], y[ 2]);
word3_muladd(&w2, &w1, &w0, x[14], y[ 1]);
word3_muladd(&w2, &w1, &w0, x[15], y[ 0]);
z[15] = w0; w0 = 0;
word3_muladd(&w0, &w2, &w1, x[ 1], y[15]);
word3_muladd(&w0, &w2, &w1, x[ 2], y[14]);
word3_muladd(&w0, &w2, &w1, x[ 3], y[13]);
word3_muladd(&w0, &w2, &w1, x[ 4], y[12]);
word3_muladd(&w0, &w2, &w1, x[ 5], y[11]);
word3_muladd(&w0, &w2, &w1, x[ 6], y[10]);
word3_muladd(&w0, &w2, &w1, x[ 7], y[ 9]);
word3_muladd(&w0, &w2, &w1, x[ 8], y[ 8]);
word3_muladd(&w0, &w2, &w1, x[ 9], y[ 7]);
word3_muladd(&w0, &w2, &w1, x[10], y[ 6]);
word3_muladd(&w0, &w2, &w1, x[11], y[ 5]);
word3_muladd(&w0, &w2, &w1, x[12], y[ 4]);
word3_muladd(&w0, &w2, &w1, x[13], y[ 3]);
word3_muladd(&w0, &w2, &w1, x[14], y[ 2]);
word3_muladd(&w0, &w2, &w1, x[15], y[ 1]);
z[16] = w1; w1 = 0;
word3_muladd(&w1, &w0, &w2, x[ 2], y[15]);
word3_muladd(&w1, &w0, &w2, x[ 3], y[14]);
word3_muladd(&w1, &w0, &w2, x[ 4], y[13]);
word3_muladd(&w1, &w0, &w2, x[ 5], y[12]);
word3_muladd(&w1, &w0, &w2, x[ 6], y[11]);
word3_muladd(&w1, &w0, &w2, x[ 7], y[10]);
word3_muladd(&w1, &w0, &w2, x[ 8], y[ 9]);
word3_muladd(&w1, &w0, &w2, x[ 9], y[ 8]);
word3_muladd(&w1, &w0, &w2, x[10], y[ 7]);
word3_muladd(&w1, &w0, &w2, x[11], y[ 6]);
word3_muladd(&w1, &w0, &w2, x[12], y[ 5]);
word3_muladd(&w1, &w0, &w2, x[13], y[ 4]);
word3_muladd(&w1, &w0, &w2, x[14], y[ 3]);
word3_muladd(&w1, &w0, &w2, x[15], y[ 2]);
z[17] = w2; w2 = 0;
word3_muladd(&w2, &w1, &w0, x[ 3], y[15]);
word3_muladd(&w2, &w1, &w0, x[ 4], y[14]);
word3_muladd(&w2, &w1, &w0, x[ 5], y[13]);
word3_muladd(&w2, &w1, &w0, x[ 6], y[12]);
word3_muladd(&w2, &w1, &w0, x[ 7], y[11]);
word3_muladd(&w2, &w1, &w0, x[ 8], y[10]);
word3_muladd(&w2, &w1, &w0, x[ 9], y[ 9]);
word3_muladd(&w2, &w1, &w0, x[10], y[ 8]);
word3_muladd(&w2, &w1, &w0, x[11], y[ 7]);
word3_muladd(&w2, &w1, &w0, x[12], y[ 6]);
word3_muladd(&w2, &w1, &w0, x[13], y[ 5]);
word3_muladd(&w2, &w1, &w0, x[14], y[ 4]);
word3_muladd(&w2, &w1, &w0, x[15], y[ 3]);
z[18] = w0; w0 = 0;
word3_muladd(&w0, &w2, &w1, x[ 4], y[15]);
word3_muladd(&w0, &w2, &w1, x[ 5], y[14]);
word3_muladd(&w0, &w2, &w1, x[ 6], y[13]);
word3_muladd(&w0, &w2, &w1, x[ 7], y[12]);
word3_muladd(&w0, &w2, &w1, x[ 8], y[11]);
word3_muladd(&w0, &w2, &w1, x[ 9], y[10]);
word3_muladd(&w0, &w2, &w1, x[10], y[ 9]);
word3_muladd(&w0, &w2, &w1, x[11], y[ 8]);
word3_muladd(&w0, &w2, &w1, x[12], y[ 7]);
word3_muladd(&w0, &w2, &w1, x[13], y[ 6]);
word3_muladd(&w0, &w2, &w1, x[14], y[ 5]);
word3_muladd(&w0, &w2, &w1, x[15], y[ 4]);
z[19] = w1; w1 = 0;
word3_muladd(&w1, &w0, &w2, x[ 5], y[15]);
word3_muladd(&w1, &w0, &w2, x[ 6], y[14]);
word3_muladd(&w1, &w0, &w2, x[ 7], y[13]);
word3_muladd(&w1, &w0, &w2, x[ 8], y[12]);
word3_muladd(&w1, &w0, &w2, x[ 9], y[11]);
word3_muladd(&w1, &w0, &w2, x[10], y[10]);
word3_muladd(&w1, &w0, &w2, x[11], y[ 9]);
word3_muladd(&w1, &w0, &w2, x[12], y[ 8]);
word3_muladd(&w1, &w0, &w2, x[13], y[ 7]);
word3_muladd(&w1, &w0, &w2, x[14], y[ 6]);
word3_muladd(&w1, &w0, &w2, x[15], y[ 5]);
z[20] = w2; w2 = 0;
word3_muladd(&w2, &w1, &w0, x[ 6], y[15]);
word3_muladd(&w2, &w1, &w0, x[ 7], y[14]);
word3_muladd(&w2, &w1, &w0, x[ 8], y[13]);
word3_muladd(&w2, &w1, &w0, x[ 9], y[12]);
word3_muladd(&w2, &w1, &w0, x[10], y[11]);
word3_muladd(&w2, &w1, &w0, x[11], y[10]);
word3_muladd(&w2, &w1, &w0, x[12], y[ 9]);
word3_muladd(&w2, &w1, &w0, x[13], y[ 8]);
word3_muladd(&w2, &w1, &w0, x[14], y[ 7]);
word3_muladd(&w2, &w1, &w0, x[15], y[ 6]);
z[21] = w0; w0 = 0;
word3_muladd(&w0, &w2, &w1, x[ 7], y[15]);
word3_muladd(&w0, &w2, &w1, x[ 8], y[14]);
word3_muladd(&w0, &w2, &w1, x[ 9], y[13]);
word3_muladd(&w0, &w2, &w1, x[10], y[12]);
word3_muladd(&w0, &w2, &w1, x[11], y[11]);
word3_muladd(&w0, &w2, &w1, x[12], y[10]);
word3_muladd(&w0, &w2, &w1, x[13], y[ 9]);
word3_muladd(&w0, &w2, &w1, x[14], y[ 8]);
word3_muladd(&w0, &w2, &w1, x[15], y[ 7]);
z[22] = w1; w1 = 0;
word3_muladd(&w1, &w0, &w2, x[ 8], y[15]);
word3_muladd(&w1, &w0, &w2, x[ 9], y[14]);
word3_muladd(&w1, &w0, &w2, x[10], y[13]);
word3_muladd(&w1, &w0, &w2, x[11], y[12]);
word3_muladd(&w1, &w0, &w2, x[12], y[11]);
word3_muladd(&w1, &w0, &w2, x[13], y[10]);
word3_muladd(&w1, &w0, &w2, x[14], y[ 9]);
word3_muladd(&w1, &w0, &w2, x[15], y[ 8]);
z[23] = w2; w2 = 0;
word3_muladd(&w2, &w1, &w0, x[ 9], y[15]);
word3_muladd(&w2, &w1, &w0, x[10], y[14]);
word3_muladd(&w2, &w1, &w0, x[11], y[13]);
word3_muladd(&w2, &w1, &w0, x[12], y[12]);
word3_muladd(&w2, &w1, &w0, x[13], y[11]);
word3_muladd(&w2, &w1, &w0, x[14], y[10]);
word3_muladd(&w2, &w1, &w0, x[15], y[ 9]);
z[24] = w0; w0 = 0;
word3_muladd(&w0, &w2, &w1, x[10], y[15]);
word3_muladd(&w0, &w2, &w1, x[11], y[14]);
word3_muladd(&w0, &w2, &w1, x[12], y[13]);
word3_muladd(&w0, &w2, &w1, x[13], y[12]);
word3_muladd(&w0, &w2, &w1, x[14], y[11]);
word3_muladd(&w0, &w2, &w1, x[15], y[10]);
z[25] = w1; w1 = 0;
word3_muladd(&w1, &w0, &w2, x[11], y[15]);
word3_muladd(&w1, &w0, &w2, x[12], y[14]);
word3_muladd(&w1, &w0, &w2, x[13], y[13]);
word3_muladd(&w1, &w0, &w2, x[14], y[12]);
word3_muladd(&w1, &w0, &w2, x[15], y[11]);
z[26] = w2; w2 = 0;
word3_muladd(&w2, &w1, &w0, x[12], y[15]);
word3_muladd(&w2, &w1, &w0, x[13], y[14]);
word3_muladd(&w2, &w1, &w0, x[14], y[13]);
word3_muladd(&w2, &w1, &w0, x[15], y[12]);
z[27] = w0; w0 = 0;
word3_muladd(&w0, &w2, &w1, x[13], y[15]);
word3_muladd(&w0, &w2, &w1, x[14], y[14]);
word3_muladd(&w0, &w2, &w1, x[15], y[13]);
z[28] = w1; w1 = 0;
word3_muladd(&w1, &w0, &w2, x[14], y[15]);
word3_muladd(&w1, &w0, &w2, x[15], y[14]);
z[29] = w2; w2 = 0;
word3_muladd(&w2, &w1, &w0, x[15], y[15]);
z[30] = w0;
z[31] = w1;
}
/*
* Comba 24x24 Squaring
*/
void bigint_comba_sqr24(word z[48], const word x[24])
{
word w2 = 0, w1 = 0, w0 = 0;
word3_muladd (&w2, &w1, &w0, x[ 0], x[ 0]);
z[ 0] = w0; w0 = 0;
word3_muladd_2(&w0, &w2, &w1, x[ 0], x[ 1]);
z[ 1] = w1; w1 = 0;
word3_muladd_2(&w1, &w0, &w2, x[ 0], x[ 2]);
word3_muladd (&w1, &w0, &w2, x[ 1], x[ 1]);
z[ 2] = w2; w2 = 0;
word3_muladd_2(&w2, &w1, &w0, x[ 0], x[ 3]);
word3_muladd_2(&w2, &w1, &w0, x[ 1], x[ 2]);
z[ 3] = w0; w0 = 0;
word3_muladd_2(&w0, &w2, &w1, x[ 0], x[ 4]);
word3_muladd_2(&w0, &w2, &w1, x[ 1], x[ 3]);
word3_muladd (&w0, &w2, &w1, x[ 2], x[ 2]);
z[ 4] = w1; w1 = 0;
word3_muladd_2(&w1, &w0, &w2, x[ 0], x[ 5]);
word3_muladd_2(&w1, &w0, &w2, x[ 1], x[ 4]);
word3_muladd_2(&w1, &w0, &w2, x[ 2], x[ 3]);
z[ 5] = w2; w2 = 0;
word3_muladd_2(&w2, &w1, &w0, x[ 0], x[ 6]);
word3_muladd_2(&w2, &w1, &w0, x[ 1], x[ 5]);
word3_muladd_2(&w2, &w1, &w0, x[ 2], x[ 4]);
word3_muladd (&w2, &w1, &w0, x[ 3], x[ 3]);
z[ 6] = w0; w0 = 0;
word3_muladd_2(&w0, &w2, &w1, x[ 0], x[ 7]);
word3_muladd_2(&w0, &w2, &w1, x[ 1], x[ 6]);
word3_muladd_2(&w0, &w2, &w1, x[ 2], x[ 5]);
word3_muladd_2(&w0, &w2, &w1, x[ 3], x[ 4]);
z[ 7] = w1; w1 = 0;
word3_muladd_2(&w1, &w0, &w2, x[ 0], x[ 8]);
word3_muladd_2(&w1, &w0, &w2, x[ 1], x[ 7]);
word3_muladd_2(&w1, &w0, &w2, x[ 2], x[ 6]);
word3_muladd_2(&w1, &w0, &w2, x[ 3], x[ 5]);
word3_muladd (&w1, &w0, &w2, x[ 4], x[ 4]);
z[ 8] = w2; w2 = 0;
word3_muladd_2(&w2, &w1, &w0, x[ 0], x[ 9]);
word3_muladd_2(&w2, &w1, &w0, x[ 1], x[ 8]);
word3_muladd_2(&w2, &w1, &w0, x[ 2], x[ 7]);
word3_muladd_2(&w2, &w1, &w0, x[ 3], x[ 6]);
word3_muladd_2(&w2, &w1, &w0, x[ 4], x[ 5]);
z[ 9] = w0; w0 = 0;
word3_muladd_2(&w0, &w2, &w1, x[ 0], x[10]);
word3_muladd_2(&w0, &w2, &w1, x[ 1], x[ 9]);
word3_muladd_2(&w0, &w2, &w1, x[ 2], x[ 8]);
word3_muladd_2(&w0, &w2, &w1, x[ 3], x[ 7]);
word3_muladd_2(&w0, &w2, &w1, x[ 4], x[ 6]);
word3_muladd (&w0, &w2, &w1, x[ 5], x[ 5]);
z[10] = w1; w1 = 0;
word3_muladd_2(&w1, &w0, &w2, x[ 0], x[11]);
word3_muladd_2(&w1, &w0, &w2, x[ 1], x[10]);
word3_muladd_2(&w1, &w0, &w2, x[ 2], x[ 9]);
word3_muladd_2(&w1, &w0, &w2, x[ 3], x[ 8]);
word3_muladd_2(&w1, &w0, &w2, x[ 4], x[ 7]);
word3_muladd_2(&w1, &w0, &w2, x[ 5], x[ 6]);
z[11] = w2; w2 = 0;
word3_muladd_2(&w2, &w1, &w0, x[ 0], x[12]);
word3_muladd_2(&w2, &w1, &w0, x[ 1], x[11]);
word3_muladd_2(&w2, &w1, &w0, x[ 2], x[10]);
word3_muladd_2(&w2, &w1, &w0, x[ 3], x[ 9]);
word3_muladd_2(&w2, &w1, &w0, x[ 4], x[ 8]);
word3_muladd_2(&w2, &w1, &w0, x[ 5], x[ 7]);
word3_muladd (&w2, &w1, &w0, x[ 6], x[ 6]);
z[12] = w0; w0 = 0;
word3_muladd_2(&w0, &w2, &w1, x[ 0], x[13]);
word3_muladd_2(&w0, &w2, &w1, x[ 1], x[12]);
word3_muladd_2(&w0, &w2, &w1, x[ 2], x[11]);
word3_muladd_2(&w0, &w2, &w1, x[ 3], x[10]);
word3_muladd_2(&w0, &w2, &w1, x[ 4], x[ 9]);
word3_muladd_2(&w0, &w2, &w1, x[ 5], x[ 8]);
word3_muladd_2(&w0, &w2, &w1, x[ 6], x[ 7]);
z[13] = w1; w1 = 0;
word3_muladd_2(&w1, &w0, &w2, x[ 0], x[14]);
word3_muladd_2(&w1, &w0, &w2, x[ 1], x[13]);
word3_muladd_2(&w1, &w0, &w2, x[ 2], x[12]);
word3_muladd_2(&w1, &w0, &w2, x[ 3], x[11]);
word3_muladd_2(&w1, &w0, &w2, x[ 4], x[10]);
word3_muladd_2(&w1, &w0, &w2, x[ 5], x[ 9]);
word3_muladd_2(&w1, &w0, &w2, x[ 6], x[ 8]);
word3_muladd (&w1, &w0, &w2, x[ 7], x[ 7]);
z[14] = w2; w2 = 0;
word3_muladd_2(&w2, &w1, &w0, x[ 0], x[15]);
word3_muladd_2(&w2, &w1, &w0, x[ 1], x[14]);
word3_muladd_2(&w2, &w1, &w0, x[ 2], x[13]);
word3_muladd_2(&w2, &w1, &w0, x[ 3], x[12]);
word3_muladd_2(&w2, &w1, &w0, x[ 4], x[11]);
word3_muladd_2(&w2, &w1, &w0, x[ 5], x[10]);
word3_muladd_2(&w2, &w1, &w0, x[ 6], x[ 9]);
word3_muladd_2(&w2, &w1, &w0, x[ 7], x[ 8]);
z[15] = w0; w0 = 0;
word3_muladd_2(&w0, &w2, &w1, x[ 0], x[16]);
word3_muladd_2(&w0, &w2, &w1, x[ 1], x[15]);
word3_muladd_2(&w0, &w2, &w1, x[ 2], x[14]);
word3_muladd_2(&w0, &w2, &w1, x[ 3], x[13]);
word3_muladd_2(&w0, &w2, &w1, x[ 4], x[12]);
word3_muladd_2(&w0, &w2, &w1, x[ 5], x[11]);
word3_muladd_2(&w0, &w2, &w1, x[ 6], x[10]);
word3_muladd_2(&w0, &w2, &w1, x[ 7], x[ 9]);
word3_muladd (&w0, &w2, &w1, x[ 8], x[ 8]);
z[16] = w1; w1 = 0;
word3_muladd_2(&w1, &w0, &w2, x[ 0], x[17]);
word3_muladd_2(&w1, &w0, &w2, x[ 1], x[16]);
word3_muladd_2(&w1, &w0, &w2, x[ 2], x[15]);
word3_muladd_2(&w1, &w0, &w2, x[ 3], x[14]);
word3_muladd_2(&w1, &w0, &w2, x[ 4], x[13]);
word3_muladd_2(&w1, &w0, &w2, x[ 5], x[12]);
word3_muladd_2(&w1, &w0, &w2, x[ 6], x[11]);
word3_muladd_2(&w1, &w0, &w2, x[ 7], x[10]);
word3_muladd_2(&w1, &w0, &w2, x[ 8], x[ 9]);
z[17] = w2; w2 = 0;
word3_muladd_2(&w2, &w1, &w0, x[ 0], x[18]);
word3_muladd_2(&w2, &w1, &w0, x[ 1], x[17]);
word3_muladd_2(&w2, &w1, &w0, x[ 2], x[16]);
word3_muladd_2(&w2, &w1, &w0, x[ 3], x[15]);
word3_muladd_2(&w2, &w1, &w0, x[ 4], x[14]);
word3_muladd_2(&w2, &w1, &w0, x[ 5], x[13]);
word3_muladd_2(&w2, &w1, &w0, x[ 6], x[12]);
word3_muladd_2(&w2, &w1, &w0, x[ 7], x[11]);
word3_muladd_2(&w2, &w1, &w0, x[ 8], x[10]);
word3_muladd (&w2, &w1, &w0, x[ 9], x[ 9]);
z[18] = w0; w0 = 0;
word3_muladd_2(&w0, &w2, &w1, x[ 0], x[19]);
word3_muladd_2(&w0, &w2, &w1, x[ 1], x[18]);
word3_muladd_2(&w0, &w2, &w1, x[ 2], x[17]);
word3_muladd_2(&w0, &w2, &w1, x[ 3], x[16]);
word3_muladd_2(&w0, &w2, &w1, x[ 4], x[15]);
word3_muladd_2(&w0, &w2, &w1, x[ 5], x[14]);
word3_muladd_2(&w0, &w2, &w1, x[ 6], x[13]);
word3_muladd_2(&w0, &w2, &w1, x[ 7], x[12]);
word3_muladd_2(&w0, &w2, &w1, x[ 8], x[11]);
word3_muladd_2(&w0, &w2, &w1, x[ 9], x[10]);
z[19] = w1; w1 = 0;
word3_muladd_2(&w1, &w0, &w2, x[ 0], x[20]);
word3_muladd_2(&w1, &w0, &w2, x[ 1], x[19]);
word3_muladd_2(&w1, &w0, &w2, x[ 2], x[18]);
word3_muladd_2(&w1, &w0, &w2, x[ 3], x[17]);
word3_muladd_2(&w1, &w0, &w2, x[ 4], x[16]);
word3_muladd_2(&w1, &w0, &w2, x[ 5], x[15]);
word3_muladd_2(&w1, &w0, &w2, x[ 6], x[14]);
word3_muladd_2(&w1, &w0, &w2, x[ 7], x[13]);
word3_muladd_2(&w1, &w0, &w2, x[ 8], x[12]);
word3_muladd_2(&w1, &w0, &w2, x[ 9], x[11]);
word3_muladd (&w1, &w0, &w2, x[10], x[10]);
z[20] = w2; w2 = 0;
word3_muladd_2(&w2, &w1, &w0, x[ 0], x[21]);
word3_muladd_2(&w2, &w1, &w0, x[ 1], x[20]);
word3_muladd_2(&w2, &w1, &w0, x[ 2], x[19]);
word3_muladd_2(&w2, &w1, &w0, x[ 3], x[18]);
word3_muladd_2(&w2, &w1, &w0, x[ 4], x[17]);
word3_muladd_2(&w2, &w1, &w0, x[ 5], x[16]);
word3_muladd_2(&w2, &w1, &w0, x[ 6], x[15]);
word3_muladd_2(&w2, &w1, &w0, x[ 7], x[14]);
word3_muladd_2(&w2, &w1, &w0, x[ 8], x[13]);
word3_muladd_2(&w2, &w1, &w0, x[ 9], x[12]);
word3_muladd_2(&w2, &w1, &w0, x[10], x[11]);
z[21] = w0; w0 = 0;
word3_muladd_2(&w0, &w2, &w1, x[ 0], x[22]);
word3_muladd_2(&w0, &w2, &w1, x[ 1], x[21]);
word3_muladd_2(&w0, &w2, &w1, x[ 2], x[20]);
word3_muladd_2(&w0, &w2, &w1, x[ 3], x[19]);
word3_muladd_2(&w0, &w2, &w1, x[ 4], x[18]);
word3_muladd_2(&w0, &w2, &w1, x[ 5], x[17]);
word3_muladd_2(&w0, &w2, &w1, x[ 6], x[16]);
word3_muladd_2(&w0, &w2, &w1, x[ 7], x[15]);
word3_muladd_2(&w0, &w2, &w1, x[ 8], x[14]);
word3_muladd_2(&w0, &w2, &w1, x[ 9], x[13]);
word3_muladd_2(&w0, &w2, &w1, x[10], x[12]);
word3_muladd (&w0, &w2, &w1, x[11], x[11]);
z[22] = w1; w1 = 0;
word3_muladd_2(&w1, &w0, &w2, x[ 0], x[23]);
word3_muladd_2(&w1, &w0, &w2, x[ 1], x[22]);
word3_muladd_2(&w1, &w0, &w2, x[ 2], x[21]);
word3_muladd_2(&w1, &w0, &w2, x[ 3], x[20]);
word3_muladd_2(&w1, &w0, &w2, x[ 4], x[19]);
word3_muladd_2(&w1, &w0, &w2, x[ 5], x[18]);
word3_muladd_2(&w1, &w0, &w2, x[ 6], x[17]);
word3_muladd_2(&w1, &w0, &w2, x[ 7], x[16]);
word3_muladd_2(&w1, &w0, &w2, x[ 8], x[15]);
word3_muladd_2(&w1, &w0, &w2, x[ 9], x[14]);
word3_muladd_2(&w1, &w0, &w2, x[10], x[13]);
word3_muladd_2(&w1, &w0, &w2, x[11], x[12]);
z[23] = w2; w2 = 0;
word3_muladd_2(&w2, &w1, &w0, x[ 1], x[23]);
word3_muladd_2(&w2, &w1, &w0, x[ 2], x[22]);
word3_muladd_2(&w2, &w1, &w0, x[ 3], x[21]);
word3_muladd_2(&w2, &w1, &w0, x[ 4], x[20]);
word3_muladd_2(&w2, &w1, &w0, x[ 5], x[19]);
word3_muladd_2(&w2, &w1, &w0, x[ 6], x[18]);
word3_muladd_2(&w2, &w1, &w0, x[ 7], x[17]);
word3_muladd_2(&w2, &w1, &w0, x[ 8], x[16]);
word3_muladd_2(&w2, &w1, &w0, x[ 9], x[15]);
word3_muladd_2(&w2, &w1, &w0, x[10], x[14]);
word3_muladd_2(&w2, &w1, &w0, x[11], x[13]);
word3_muladd (&w2, &w1, &w0, x[12], x[12]);
z[24] = w0; w0 = 0;
word3_muladd_2(&w0, &w2, &w1, x[ 2], x[23]);
word3_muladd_2(&w0, &w2, &w1, x[ 3], x[22]);
word3_muladd_2(&w0, &w2, &w1, x[ 4], x[21]);
word3_muladd_2(&w0, &w2, &w1, x[ 5], x[20]);
word3_muladd_2(&w0, &w2, &w1, x[ 6], x[19]);
word3_muladd_2(&w0, &w2, &w1, x[ 7], x[18]);
word3_muladd_2(&w0, &w2, &w1, x[ 8], x[17]);
word3_muladd_2(&w0, &w2, &w1, x[ 9], x[16]);
word3_muladd_2(&w0, &w2, &w1, x[10], x[15]);
word3_muladd_2(&w0, &w2, &w1, x[11], x[14]);
word3_muladd_2(&w0, &w2, &w1, x[12], x[13]);
z[25] = w1; w1 = 0;
word3_muladd_2(&w1, &w0, &w2, x[ 3], x[23]);
word3_muladd_2(&w1, &w0, &w2, x[ 4], x[22]);
word3_muladd_2(&w1, &w0, &w2, x[ 5], x[21]);
word3_muladd_2(&w1, &w0, &w2, x[ 6], x[20]);
word3_muladd_2(&w1, &w0, &w2, x[ 7], x[19]);
word3_muladd_2(&w1, &w0, &w2, x[ 8], x[18]);
word3_muladd_2(&w1, &w0, &w2, x[ 9], x[17]);
word3_muladd_2(&w1, &w0, &w2, x[10], x[16]);
word3_muladd_2(&w1, &w0, &w2, x[11], x[15]);
word3_muladd_2(&w1, &w0, &w2, x[12], x[14]);
word3_muladd (&w1, &w0, &w2, x[13], x[13]);
z[26] = w2; w2 = 0;
word3_muladd_2(&w2, &w1, &w0, x[ 4], x[23]);
word3_muladd_2(&w2, &w1, &w0, x[ 5], x[22]);
word3_muladd_2(&w2, &w1, &w0, x[ 6], x[21]);
word3_muladd_2(&w2, &w1, &w0, x[ 7], x[20]);
word3_muladd_2(&w2, &w1, &w0, x[ 8], x[19]);
word3_muladd_2(&w2, &w1, &w0, x[ 9], x[18]);
word3_muladd_2(&w2, &w1, &w0, x[10], x[17]);
word3_muladd_2(&w2, &w1, &w0, x[11], x[16]);
word3_muladd_2(&w2, &w1, &w0, x[12], x[15]);
word3_muladd_2(&w2, &w1, &w0, x[13], x[14]);
z[27] = w0; w0 = 0;
word3_muladd_2(&w0, &w2, &w1, x[ 5], x[23]);
word3_muladd_2(&w0, &w2, &w1, x[ 6], x[22]);
word3_muladd_2(&w0, &w2, &w1, x[ 7], x[21]);
word3_muladd_2(&w0, &w2, &w1, x[ 8], x[20]);
word3_muladd_2(&w0, &w2, &w1, x[ 9], x[19]);
word3_muladd_2(&w0, &w2, &w1, x[10], x[18]);
word3_muladd_2(&w0, &w2, &w1, x[11], x[17]);
word3_muladd_2(&w0, &w2, &w1, x[12], x[16]);
word3_muladd_2(&w0, &w2, &w1, x[13], x[15]);
word3_muladd (&w0, &w2, &w1, x[14], x[14]);
z[28] = w1; w1 = 0;
word3_muladd_2(&w1, &w0, &w2, x[ 6], x[23]);
word3_muladd_2(&w1, &w0, &w2, x[ 7], x[22]);
word3_muladd_2(&w1, &w0, &w2, x[ 8], x[21]);
word3_muladd_2(&w1, &w0, &w2, x[ 9], x[20]);
word3_muladd_2(&w1, &w0, &w2, x[10], x[19]);
word3_muladd_2(&w1, &w0, &w2, x[11], x[18]);
word3_muladd_2(&w1, &w0, &w2, x[12], x[17]);
word3_muladd_2(&w1, &w0, &w2, x[13], x[16]);
word3_muladd_2(&w1, &w0, &w2, x[14], x[15]);
z[29] = w2; w2 = 0;
word3_muladd_2(&w2, &w1, &w0, x[ 7], x[23]);
word3_muladd_2(&w2, &w1, &w0, x[ 8], x[22]);
word3_muladd_2(&w2, &w1, &w0, x[ 9], x[21]);
word3_muladd_2(&w2, &w1, &w0, x[10], x[20]);
word3_muladd_2(&w2, &w1, &w0, x[11], x[19]);
word3_muladd_2(&w2, &w1, &w0, x[12], x[18]);
word3_muladd_2(&w2, &w1, &w0, x[13], x[17]);
word3_muladd_2(&w2, &w1, &w0, x[14], x[16]);
word3_muladd (&w2, &w1, &w0, x[15], x[15]);
z[30] = w0; w0 = 0;
word3_muladd_2(&w0, &w2, &w1, x[ 8], x[23]);
word3_muladd_2(&w0, &w2, &w1, x[ 9], x[22]);
word3_muladd_2(&w0, &w2, &w1, x[10], x[21]);
word3_muladd_2(&w0, &w2, &w1, x[11], x[20]);
word3_muladd_2(&w0, &w2, &w1, x[12], x[19]);
word3_muladd_2(&w0, &w2, &w1, x[13], x[18]);
word3_muladd_2(&w0, &w2, &w1, x[14], x[17]);
word3_muladd_2(&w0, &w2, &w1, x[15], x[16]);
z[31] = w1; w1 = 0;
word3_muladd_2(&w1, &w0, &w2, x[ 9], x[23]);
word3_muladd_2(&w1, &w0, &w2, x[10], x[22]);
word3_muladd_2(&w1, &w0, &w2, x[11], x[21]);
word3_muladd_2(&w1, &w0, &w2, x[12], x[20]);
word3_muladd_2(&w1, &w0, &w2, x[13], x[19]);
word3_muladd_2(&w1, &w0, &w2, x[14], x[18]);
word3_muladd_2(&w1, &w0, &w2, x[15], x[17]);
word3_muladd (&w1, &w0, &w2, x[16], x[16]);
z[32] = w2; w2 = 0;
word3_muladd_2(&w2, &w1, &w0, x[10], x[23]);
word3_muladd_2(&w2, &w1, &w0, x[11], x[22]);
word3_muladd_2(&w2, &w1, &w0, x[12], x[21]);
word3_muladd_2(&w2, &w1, &w0, x[13], x[20]);
word3_muladd_2(&w2, &w1, &w0, x[14], x[19]);
word3_muladd_2(&w2, &w1, &w0, x[15], x[18]);
word3_muladd_2(&w2, &w1, &w0, x[16], x[17]);
z[33] = w0; w0 = 0;
word3_muladd_2(&w0, &w2, &w1, x[11], x[23]);
word3_muladd_2(&w0, &w2, &w1, x[12], x[22]);
word3_muladd_2(&w0, &w2, &w1, x[13], x[21]);
word3_muladd_2(&w0, &w2, &w1, x[14], x[20]);
word3_muladd_2(&w0, &w2, &w1, x[15], x[19]);
word3_muladd_2(&w0, &w2, &w1, x[16], x[18]);
word3_muladd (&w0, &w2, &w1, x[17], x[17]);
z[34] = w1; w1 = 0;
word3_muladd_2(&w1, &w0, &w2, x[12], x[23]);
word3_muladd_2(&w1, &w0, &w2, x[13], x[22]);
word3_muladd_2(&w1, &w0, &w2, x[14], x[21]);
word3_muladd_2(&w1, &w0, &w2, x[15], x[20]);
word3_muladd_2(&w1, &w0, &w2, x[16], x[19]);
word3_muladd_2(&w1, &w0, &w2, x[17], x[18]);
z[35] = w2; w2 = 0;
word3_muladd_2(&w2, &w1, &w0, x[13], x[23]);
word3_muladd_2(&w2, &w1, &w0, x[14], x[22]);
word3_muladd_2(&w2, &w1, &w0, x[15], x[21]);
word3_muladd_2(&w2, &w1, &w0, x[16], x[20]);
word3_muladd_2(&w2, &w1, &w0, x[17], x[19]);
word3_muladd (&w2, &w1, &w0, x[18], x[18]);
z[36] = w0; w0 = 0;
word3_muladd_2(&w0, &w2, &w1, x[14], x[23]);
word3_muladd_2(&w0, &w2, &w1, x[15], x[22]);
word3_muladd_2(&w0, &w2, &w1, x[16], x[21]);
word3_muladd_2(&w0, &w2, &w1, x[17], x[20]);
word3_muladd_2(&w0, &w2, &w1, x[18], x[19]);
z[37] = w1; w1 = 0;
word3_muladd_2(&w1, &w0, &w2, x[15], x[23]);
word3_muladd_2(&w1, &w0, &w2, x[16], x[22]);
word3_muladd_2(&w1, &w0, &w2, x[17], x[21]);
word3_muladd_2(&w1, &w0, &w2, x[18], x[20]);
word3_muladd (&w1, &w0, &w2, x[19], x[19]);
z[38] = w2; w2 = 0;
word3_muladd_2(&w2, &w1, &w0, x[16], x[23]);
word3_muladd_2(&w2, &w1, &w0, x[17], x[22]);
word3_muladd_2(&w2, &w1, &w0, x[18], x[21]);
word3_muladd_2(&w2, &w1, &w0, x[19], x[20]);
z[39] = w0; w0 = 0;
word3_muladd_2(&w0, &w2, &w1, x[17], x[23]);
word3_muladd_2(&w0, &w2, &w1, x[18], x[22]);
word3_muladd_2(&w0, &w2, &w1, x[19], x[21]);
word3_muladd (&w0, &w2, &w1, x[20], x[20]);
z[40] = w1; w1 = 0;
word3_muladd_2(&w1, &w0, &w2, x[18], x[23]);
word3_muladd_2(&w1, &w0, &w2, x[19], x[22]);
word3_muladd_2(&w1, &w0, &w2, x[20], x[21]);
z[41] = w2; w2 = 0;
word3_muladd_2(&w2, &w1, &w0, x[19], x[23]);
word3_muladd_2(&w2, &w1, &w0, x[20], x[22]);
word3_muladd (&w2, &w1, &w0, x[21], x[21]);
z[42] = w0; w0 = 0;
word3_muladd_2(&w0, &w2, &w1, x[20], x[23]);
word3_muladd_2(&w0, &w2, &w1, x[21], x[22]);
z[43] = w1; w1 = 0;
word3_muladd_2(&w1, &w0, &w2, x[21], x[23]);
word3_muladd (&w1, &w0, &w2, x[22], x[22]);
z[44] = w2; w2 = 0;
word3_muladd_2(&w2, &w1, &w0, x[22], x[23]);
z[45] = w0; w0 = 0;
word3_muladd (&w0, &w2, &w1, x[23], x[23]);
z[46] = w1;
z[47] = w2;
}
/*
* Comba 24x24 Multiplication
*/
void bigint_comba_mul24(word z[48], const word x[24], const word y[24])
{
word w2 = 0, w1 = 0, w0 = 0;
word3_muladd(&w2, &w1, &w0, x[ 0], y[ 0]);
z[ 0] = w0; w0 = 0;
word3_muladd(&w0, &w2, &w1, x[ 0], y[ 1]);
word3_muladd(&w0, &w2, &w1, x[ 1], y[ 0]);
z[ 1] = w1; w1 = 0;
word3_muladd(&w1, &w0, &w2, x[ 0], y[ 2]);
word3_muladd(&w1, &w0, &w2, x[ 1], y[ 1]);
word3_muladd(&w1, &w0, &w2, x[ 2], y[ 0]);
z[ 2] = w2; w2 = 0;
word3_muladd(&w2, &w1, &w0, x[ 0], y[ 3]);
word3_muladd(&w2, &w1, &w0, x[ 1], y[ 2]);
word3_muladd(&w2, &w1, &w0, x[ 2], y[ 1]);
word3_muladd(&w2, &w1, &w0, x[ 3], y[ 0]);
z[ 3] = w0; w0 = 0;
word3_muladd(&w0, &w2, &w1, x[ 0], y[ 4]);
word3_muladd(&w0, &w2, &w1, x[ 1], y[ 3]);
word3_muladd(&w0, &w2, &w1, x[ 2], y[ 2]);
word3_muladd(&w0, &w2, &w1, x[ 3], y[ 1]);
word3_muladd(&w0, &w2, &w1, x[ 4], y[ 0]);
z[ 4] = w1; w1 = 0;
word3_muladd(&w1, &w0, &w2, x[ 0], y[ 5]);
word3_muladd(&w1, &w0, &w2, x[ 1], y[ 4]);
word3_muladd(&w1, &w0, &w2, x[ 2], y[ 3]);
word3_muladd(&w1, &w0, &w2, x[ 3], y[ 2]);
word3_muladd(&w1, &w0, &w2, x[ 4], y[ 1]);
word3_muladd(&w1, &w0, &w2, x[ 5], y[ 0]);
z[ 5] = w2; w2 = 0;
word3_muladd(&w2, &w1, &w0, x[ 0], y[ 6]);
word3_muladd(&w2, &w1, &w0, x[ 1], y[ 5]);
word3_muladd(&w2, &w1, &w0, x[ 2], y[ 4]);
word3_muladd(&w2, &w1, &w0, x[ 3], y[ 3]);
word3_muladd(&w2, &w1, &w0, x[ 4], y[ 2]);
word3_muladd(&w2, &w1, &w0, x[ 5], y[ 1]);
word3_muladd(&w2, &w1, &w0, x[ 6], y[ 0]);
z[ 6] = w0; w0 = 0;
word3_muladd(&w0, &w2, &w1, x[ 0], y[ 7]);
word3_muladd(&w0, &w2, &w1, x[ 1], y[ 6]);
word3_muladd(&w0, &w2, &w1, x[ 2], y[ 5]);
word3_muladd(&w0, &w2, &w1, x[ 3], y[ 4]);
word3_muladd(&w0, &w2, &w1, x[ 4], y[ 3]);
word3_muladd(&w0, &w2, &w1, x[ 5], y[ 2]);
word3_muladd(&w0, &w2, &w1, x[ 6], y[ 1]);
word3_muladd(&w0, &w2, &w1, x[ 7], y[ 0]);
z[ 7] = w1; w1 = 0;
word3_muladd(&w1, &w0, &w2, x[ 0], y[ 8]);
word3_muladd(&w1, &w0, &w2, x[ 1], y[ 7]);
word3_muladd(&w1, &w0, &w2, x[ 2], y[ 6]);
word3_muladd(&w1, &w0, &w2, x[ 3], y[ 5]);
word3_muladd(&w1, &w0, &w2, x[ 4], y[ 4]);
word3_muladd(&w1, &w0, &w2, x[ 5], y[ 3]);
word3_muladd(&w1, &w0, &w2, x[ 6], y[ 2]);
word3_muladd(&w1, &w0, &w2, x[ 7], y[ 1]);
word3_muladd(&w1, &w0, &w2, x[ 8], y[ 0]);
z[ 8] = w2; w2 = 0;
word3_muladd(&w2, &w1, &w0, x[ 0], y[ 9]);
word3_muladd(&w2, &w1, &w0, x[ 1], y[ 8]);
word3_muladd(&w2, &w1, &w0, x[ 2], y[ 7]);
word3_muladd(&w2, &w1, &w0, x[ 3], y[ 6]);
word3_muladd(&w2, &w1, &w0, x[ 4], y[ 5]);
word3_muladd(&w2, &w1, &w0, x[ 5], y[ 4]);
word3_muladd(&w2, &w1, &w0, x[ 6], y[ 3]);
word3_muladd(&w2, &w1, &w0, x[ 7], y[ 2]);
word3_muladd(&w2, &w1, &w0, x[ 8], y[ 1]);
word3_muladd(&w2, &w1, &w0, x[ 9], y[ 0]);
z[ 9] = w0; w0 = 0;
word3_muladd(&w0, &w2, &w1, x[ 0], y[10]);
word3_muladd(&w0, &w2, &w1, x[ 1], y[ 9]);
word3_muladd(&w0, &w2, &w1, x[ 2], y[ 8]);
word3_muladd(&w0, &w2, &w1, x[ 3], y[ 7]);
word3_muladd(&w0, &w2, &w1, x[ 4], y[ 6]);
word3_muladd(&w0, &w2, &w1, x[ 5], y[ 5]);
word3_muladd(&w0, &w2, &w1, x[ 6], y[ 4]);
word3_muladd(&w0, &w2, &w1, x[ 7], y[ 3]);
word3_muladd(&w0, &w2, &w1, x[ 8], y[ 2]);
word3_muladd(&w0, &w2, &w1, x[ 9], y[ 1]);
word3_muladd(&w0, &w2, &w1, x[10], y[ 0]);
z[10] = w1; w1 = 0;
word3_muladd(&w1, &w0, &w2, x[ 0], y[11]);
word3_muladd(&w1, &w0, &w2, x[ 1], y[10]);
word3_muladd(&w1, &w0, &w2, x[ 2], y[ 9]);
word3_muladd(&w1, &w0, &w2, x[ 3], y[ 8]);
word3_muladd(&w1, &w0, &w2, x[ 4], y[ 7]);
word3_muladd(&w1, &w0, &w2, x[ 5], y[ 6]);
word3_muladd(&w1, &w0, &w2, x[ 6], y[ 5]);
word3_muladd(&w1, &w0, &w2, x[ 7], y[ 4]);
word3_muladd(&w1, &w0, &w2, x[ 8], y[ 3]);
word3_muladd(&w1, &w0, &w2, x[ 9], y[ 2]);
word3_muladd(&w1, &w0, &w2, x[10], y[ 1]);
word3_muladd(&w1, &w0, &w2, x[11], y[ 0]);
z[11] = w2; w2 = 0;
word3_muladd(&w2, &w1, &w0, x[ 0], y[12]);
word3_muladd(&w2, &w1, &w0, x[ 1], y[11]);
word3_muladd(&w2, &w1, &w0, x[ 2], y[10]);
word3_muladd(&w2, &w1, &w0, x[ 3], y[ 9]);
word3_muladd(&w2, &w1, &w0, x[ 4], y[ 8]);
word3_muladd(&w2, &w1, &w0, x[ 5], y[ 7]);
word3_muladd(&w2, &w1, &w0, x[ 6], y[ 6]);
word3_muladd(&w2, &w1, &w0, x[ 7], y[ 5]);
word3_muladd(&w2, &w1, &w0, x[ 8], y[ 4]);
word3_muladd(&w2, &w1, &w0, x[ 9], y[ 3]);
word3_muladd(&w2, &w1, &w0, x[10], y[ 2]);
word3_muladd(&w2, &w1, &w0, x[11], y[ 1]);
word3_muladd(&w2, &w1, &w0, x[12], y[ 0]);
z[12] = w0; w0 = 0;
word3_muladd(&w0, &w2, &w1, x[ 0], y[13]);
word3_muladd(&w0, &w2, &w1, x[ 1], y[12]);
word3_muladd(&w0, &w2, &w1, x[ 2], y[11]);
word3_muladd(&w0, &w2, &w1, x[ 3], y[10]);
word3_muladd(&w0, &w2, &w1, x[ 4], y[ 9]);
word3_muladd(&w0, &w2, &w1, x[ 5], y[ 8]);
word3_muladd(&w0, &w2, &w1, x[ 6], y[ 7]);
word3_muladd(&w0, &w2, &w1, x[ 7], y[ 6]);
word3_muladd(&w0, &w2, &w1, x[ 8], y[ 5]);
word3_muladd(&w0, &w2, &w1, x[ 9], y[ 4]);
word3_muladd(&w0, &w2, &w1, x[10], y[ 3]);
word3_muladd(&w0, &w2, &w1, x[11], y[ 2]);
word3_muladd(&w0, &w2, &w1, x[12], y[ 1]);
word3_muladd(&w0, &w2, &w1, x[13], y[ 0]);
z[13] = w1; w1 = 0;
word3_muladd(&w1, &w0, &w2, x[ 0], y[14]);
word3_muladd(&w1, &w0, &w2, x[ 1], y[13]);
word3_muladd(&w1, &w0, &w2, x[ 2], y[12]);
word3_muladd(&w1, &w0, &w2, x[ 3], y[11]);
word3_muladd(&w1, &w0, &w2, x[ 4], y[10]);
word3_muladd(&w1, &w0, &w2, x[ 5], y[ 9]);
word3_muladd(&w1, &w0, &w2, x[ 6], y[ 8]);
word3_muladd(&w1, &w0, &w2, x[ 7], y[ 7]);
word3_muladd(&w1, &w0, &w2, x[ 8], y[ 6]);
word3_muladd(&w1, &w0, &w2, x[ 9], y[ 5]);
word3_muladd(&w1, &w0, &w2, x[10], y[ 4]);
word3_muladd(&w1, &w0, &w2, x[11], y[ 3]);
word3_muladd(&w1, &w0, &w2, x[12], y[ 2]);
word3_muladd(&w1, &w0, &w2, x[13], y[ 1]);
word3_muladd(&w1, &w0, &w2, x[14], y[ 0]);
z[14] = w2; w2 = 0;
word3_muladd(&w2, &w1, &w0, x[ 0], y[15]);
word3_muladd(&w2, &w1, &w0, x[ 1], y[14]);
word3_muladd(&w2, &w1, &w0, x[ 2], y[13]);
word3_muladd(&w2, &w1, &w0, x[ 3], y[12]);
word3_muladd(&w2, &w1, &w0, x[ 4], y[11]);
word3_muladd(&w2, &w1, &w0, x[ 5], y[10]);
word3_muladd(&w2, &w1, &w0, x[ 6], y[ 9]);
word3_muladd(&w2, &w1, &w0, x[ 7], y[ 8]);
word3_muladd(&w2, &w1, &w0, x[ 8], y[ 7]);
word3_muladd(&w2, &w1, &w0, x[ 9], y[ 6]);
word3_muladd(&w2, &w1, &w0, x[10], y[ 5]);
word3_muladd(&w2, &w1, &w0, x[11], y[ 4]);
word3_muladd(&w2, &w1, &w0, x[12], y[ 3]);
word3_muladd(&w2, &w1, &w0, x[13], y[ 2]);
word3_muladd(&w2, &w1, &w0, x[14], y[ 1]);
word3_muladd(&w2, &w1, &w0, x[15], y[ 0]);
z[15] = w0; w0 = 0;
word3_muladd(&w0, &w2, &w1, x[ 0], y[16]);
word3_muladd(&w0, &w2, &w1, x[ 1], y[15]);
word3_muladd(&w0, &w2, &w1, x[ 2], y[14]);
word3_muladd(&w0, &w2, &w1, x[ 3], y[13]);
word3_muladd(&w0, &w2, &w1, x[ 4], y[12]);
word3_muladd(&w0, &w2, &w1, x[ 5], y[11]);
word3_muladd(&w0, &w2, &w1, x[ 6], y[10]);
word3_muladd(&w0, &w2, &w1, x[ 7], y[ 9]);
word3_muladd(&w0, &w2, &w1, x[ 8], y[ 8]);
word3_muladd(&w0, &w2, &w1, x[ 9], y[ 7]);
word3_muladd(&w0, &w2, &w1, x[10], y[ 6]);
word3_muladd(&w0, &w2, &w1, x[11], y[ 5]);
word3_muladd(&w0, &w2, &w1, x[12], y[ 4]);
word3_muladd(&w0, &w2, &w1, x[13], y[ 3]);
word3_muladd(&w0, &w2, &w1, x[14], y[ 2]);
word3_muladd(&w0, &w2, &w1, x[15], y[ 1]);
word3_muladd(&w0, &w2, &w1, x[16], y[ 0]);
z[16] = w1; w1 = 0;
word3_muladd(&w1, &w0, &w2, x[ 0], y[17]);
word3_muladd(&w1, &w0, &w2, x[ 1], y[16]);
word3_muladd(&w1, &w0, &w2, x[ 2], y[15]);
word3_muladd(&w1, &w0, &w2, x[ 3], y[14]);
word3_muladd(&w1, &w0, &w2, x[ 4], y[13]);
word3_muladd(&w1, &w0, &w2, x[ 5], y[12]);
word3_muladd(&w1, &w0, &w2, x[ 6], y[11]);
word3_muladd(&w1, &w0, &w2, x[ 7], y[10]);
word3_muladd(&w1, &w0, &w2, x[ 8], y[ 9]);
word3_muladd(&w1, &w0, &w2, x[ 9], y[ 8]);
word3_muladd(&w1, &w0, &w2, x[10], y[ 7]);
word3_muladd(&w1, &w0, &w2, x[11], y[ 6]);
word3_muladd(&w1, &w0, &w2, x[12], y[ 5]);
word3_muladd(&w1, &w0, &w2, x[13], y[ 4]);
word3_muladd(&w1, &w0, &w2, x[14], y[ 3]);
word3_muladd(&w1, &w0, &w2, x[15], y[ 2]);
word3_muladd(&w1, &w0, &w2, x[16], y[ 1]);
word3_muladd(&w1, &w0, &w2, x[17], y[ 0]);
z[17] = w2; w2 = 0;
word3_muladd(&w2, &w1, &w0, x[ 0], y[18]);
word3_muladd(&w2, &w1, &w0, x[ 1], y[17]);
word3_muladd(&w2, &w1, &w0, x[ 2], y[16]);
word3_muladd(&w2, &w1, &w0, x[ 3], y[15]);
word3_muladd(&w2, &w1, &w0, x[ 4], y[14]);
word3_muladd(&w2, &w1, &w0, x[ 5], y[13]);
word3_muladd(&w2, &w1, &w0, x[ 6], y[12]);
word3_muladd(&w2, &w1, &w0, x[ 7], y[11]);
word3_muladd(&w2, &w1, &w0, x[ 8], y[10]);
word3_muladd(&w2, &w1, &w0, x[ 9], y[ 9]);
word3_muladd(&w2, &w1, &w0, x[10], y[ 8]);
word3_muladd(&w2, &w1, &w0, x[11], y[ 7]);
word3_muladd(&w2, &w1, &w0, x[12], y[ 6]);
word3_muladd(&w2, &w1, &w0, x[13], y[ 5]);
word3_muladd(&w2, &w1, &w0, x[14], y[ 4]);
word3_muladd(&w2, &w1, &w0, x[15], y[ 3]);
word3_muladd(&w2, &w1, &w0, x[16], y[ 2]);
word3_muladd(&w2, &w1, &w0, x[17], y[ 1]);
word3_muladd(&w2, &w1, &w0, x[18], y[ 0]);
z[18] = w0; w0 = 0;
word3_muladd(&w0, &w2, &w1, x[ 0], y[19]);
word3_muladd(&w0, &w2, &w1, x[ 1], y[18]);
word3_muladd(&w0, &w2, &w1, x[ 2], y[17]);
word3_muladd(&w0, &w2, &w1, x[ 3], y[16]);
word3_muladd(&w0, &w2, &w1, x[ 4], y[15]);
word3_muladd(&w0, &w2, &w1, x[ 5], y[14]);
word3_muladd(&w0, &w2, &w1, x[ 6], y[13]);
word3_muladd(&w0, &w2, &w1, x[ 7], y[12]);
word3_muladd(&w0, &w2, &w1, x[ 8], y[11]);
word3_muladd(&w0, &w2, &w1, x[ 9], y[10]);
word3_muladd(&w0, &w2, &w1, x[10], y[ 9]);
word3_muladd(&w0, &w2, &w1, x[11], y[ 8]);
word3_muladd(&w0, &w2, &w1, x[12], y[ 7]);
word3_muladd(&w0, &w2, &w1, x[13], y[ 6]);
word3_muladd(&w0, &w2, &w1, x[14], y[ 5]);
word3_muladd(&w0, &w2, &w1, x[15], y[ 4]);
word3_muladd(&w0, &w2, &w1, x[16], y[ 3]);
word3_muladd(&w0, &w2, &w1, x[17], y[ 2]);
word3_muladd(&w0, &w2, &w1, x[18], y[ 1]);
word3_muladd(&w0, &w2, &w1, x[19], y[ 0]);
z[19] = w1; w1 = 0;
word3_muladd(&w1, &w0, &w2, x[ 0], y[20]);
word3_muladd(&w1, &w0, &w2, x[ 1], y[19]);
word3_muladd(&w1, &w0, &w2, x[ 2], y[18]);
word3_muladd(&w1, &w0, &w2, x[ 3], y[17]);
word3_muladd(&w1, &w0, &w2, x[ 4], y[16]);
word3_muladd(&w1, &w0, &w2, x[ 5], y[15]);
word3_muladd(&w1, &w0, &w2, x[ 6], y[14]);
word3_muladd(&w1, &w0, &w2, x[ 7], y[13]);
word3_muladd(&w1, &w0, &w2, x[ 8], y[12]);
word3_muladd(&w1, &w0, &w2, x[ 9], y[11]);
word3_muladd(&w1, &w0, &w2, x[10], y[10]);
word3_muladd(&w1, &w0, &w2, x[11], y[ 9]);
word3_muladd(&w1, &w0, &w2, x[12], y[ 8]);
word3_muladd(&w1, &w0, &w2, x[13], y[ 7]);
word3_muladd(&w1, &w0, &w2, x[14], y[ 6]);
word3_muladd(&w1, &w0, &w2, x[15], y[ 5]);
word3_muladd(&w1, &w0, &w2, x[16], y[ 4]);
word3_muladd(&w1, &w0, &w2, x[17], y[ 3]);
word3_muladd(&w1, &w0, &w2, x[18], y[ 2]);
word3_muladd(&w1, &w0, &w2, x[19], y[ 1]);
word3_muladd(&w1, &w0, &w2, x[20], y[ 0]);
z[20] = w2; w2 = 0;
word3_muladd(&w2, &w1, &w0, x[ 0], y[21]);
word3_muladd(&w2, &w1, &w0, x[ 1], y[20]);
word3_muladd(&w2, &w1, &w0, x[ 2], y[19]);
word3_muladd(&w2, &w1, &w0, x[ 3], y[18]);
word3_muladd(&w2, &w1, &w0, x[ 4], y[17]);
word3_muladd(&w2, &w1, &w0, x[ 5], y[16]);
word3_muladd(&w2, &w1, &w0, x[ 6], y[15]);
word3_muladd(&w2, &w1, &w0, x[ 7], y[14]);
word3_muladd(&w2, &w1, &w0, x[ 8], y[13]);
word3_muladd(&w2, &w1, &w0, x[ 9], y[12]);
word3_muladd(&w2, &w1, &w0, x[10], y[11]);
word3_muladd(&w2, &w1, &w0, x[11], y[10]);
word3_muladd(&w2, &w1, &w0, x[12], y[ 9]);
word3_muladd(&w2, &w1, &w0, x[13], y[ 8]);
word3_muladd(&w2, &w1, &w0, x[14], y[ 7]);
word3_muladd(&w2, &w1, &w0, x[15], y[ 6]);
word3_muladd(&w2, &w1, &w0, x[16], y[ 5]);
word3_muladd(&w2, &w1, &w0, x[17], y[ 4]);
word3_muladd(&w2, &w1, &w0, x[18], y[ 3]);
word3_muladd(&w2, &w1, &w0, x[19], y[ 2]);
word3_muladd(&w2, &w1, &w0, x[20], y[ 1]);
word3_muladd(&w2, &w1, &w0, x[21], y[ 0]);
z[21] = w0; w0 = 0;
word3_muladd(&w0, &w2, &w1, x[ 0], y[22]);
word3_muladd(&w0, &w2, &w1, x[ 1], y[21]);
word3_muladd(&w0, &w2, &w1, x[ 2], y[20]);
word3_muladd(&w0, &w2, &w1, x[ 3], y[19]);
word3_muladd(&w0, &w2, &w1, x[ 4], y[18]);
word3_muladd(&w0, &w2, &w1, x[ 5], y[17]);
word3_muladd(&w0, &w2, &w1, x[ 6], y[16]);
word3_muladd(&w0, &w2, &w1, x[ 7], y[15]);
word3_muladd(&w0, &w2, &w1, x[ 8], y[14]);
word3_muladd(&w0, &w2, &w1, x[ 9], y[13]);
word3_muladd(&w0, &w2, &w1, x[10], y[12]);
word3_muladd(&w0, &w2, &w1, x[11], y[11]);
word3_muladd(&w0, &w2, &w1, x[12], y[10]);
word3_muladd(&w0, &w2, &w1, x[13], y[ 9]);
word3_muladd(&w0, &w2, &w1, x[14], y[ 8]);
word3_muladd(&w0, &w2, &w1, x[15], y[ 7]);
word3_muladd(&w0, &w2, &w1, x[16], y[ 6]);
word3_muladd(&w0, &w2, &w1, x[17], y[ 5]);
word3_muladd(&w0, &w2, &w1, x[18], y[ 4]);
word3_muladd(&w0, &w2, &w1, x[19], y[ 3]);
word3_muladd(&w0, &w2, &w1, x[20], y[ 2]);
word3_muladd(&w0, &w2, &w1, x[21], y[ 1]);
word3_muladd(&w0, &w2, &w1, x[22], y[ 0]);
z[22] = w1; w1 = 0;
word3_muladd(&w1, &w0, &w2, x[ 0], y[23]);
word3_muladd(&w1, &w0, &w2, x[ 1], y[22]);
word3_muladd(&w1, &w0, &w2, x[ 2], y[21]);
word3_muladd(&w1, &w0, &w2, x[ 3], y[20]);
word3_muladd(&w1, &w0, &w2, x[ 4], y[19]);
word3_muladd(&w1, &w0, &w2, x[ 5], y[18]);
word3_muladd(&w1, &w0, &w2, x[ 6], y[17]);
word3_muladd(&w1, &w0, &w2, x[ 7], y[16]);
word3_muladd(&w1, &w0, &w2, x[ 8], y[15]);
word3_muladd(&w1, &w0, &w2, x[ 9], y[14]);
word3_muladd(&w1, &w0, &w2, x[10], y[13]);
word3_muladd(&w1, &w0, &w2, x[11], y[12]);
word3_muladd(&w1, &w0, &w2, x[12], y[11]);
word3_muladd(&w1, &w0, &w2, x[13], y[10]);
word3_muladd(&w1, &w0, &w2, x[14], y[ 9]);
word3_muladd(&w1, &w0, &w2, x[15], y[ 8]);
word3_muladd(&w1, &w0, &w2, x[16], y[ 7]);
word3_muladd(&w1, &w0, &w2, x[17], y[ 6]);
word3_muladd(&w1, &w0, &w2, x[18], y[ 5]);
word3_muladd(&w1, &w0, &w2, x[19], y[ 4]);
word3_muladd(&w1, &w0, &w2, x[20], y[ 3]);
word3_muladd(&w1, &w0, &w2, x[21], y[ 2]);
word3_muladd(&w1, &w0, &w2, x[22], y[ 1]);
word3_muladd(&w1, &w0, &w2, x[23], y[ 0]);
z[23] = w2; w2 = 0;
word3_muladd(&w2, &w1, &w0, x[ 1], y[23]);
word3_muladd(&w2, &w1, &w0, x[ 2], y[22]);
word3_muladd(&w2, &w1, &w0, x[ 3], y[21]);
word3_muladd(&w2, &w1, &w0, x[ 4], y[20]);
word3_muladd(&w2, &w1, &w0, x[ 5], y[19]);
word3_muladd(&w2, &w1, &w0, x[ 6], y[18]);
word3_muladd(&w2, &w1, &w0, x[ 7], y[17]);
word3_muladd(&w2, &w1, &w0, x[ 8], y[16]);
word3_muladd(&w2, &w1, &w0, x[ 9], y[15]);
word3_muladd(&w2, &w1, &w0, x[10], y[14]);
word3_muladd(&w2, &w1, &w0, x[11], y[13]);
word3_muladd(&w2, &w1, &w0, x[12], y[12]);
word3_muladd(&w2, &w1, &w0, x[13], y[11]);
word3_muladd(&w2, &w1, &w0, x[14], y[10]);
word3_muladd(&w2, &w1, &w0, x[15], y[ 9]);
word3_muladd(&w2, &w1, &w0, x[16], y[ 8]);
word3_muladd(&w2, &w1, &w0, x[17], y[ 7]);
word3_muladd(&w2, &w1, &w0, x[18], y[ 6]);
word3_muladd(&w2, &w1, &w0, x[19], y[ 5]);
word3_muladd(&w2, &w1, &w0, x[20], y[ 4]);
word3_muladd(&w2, &w1, &w0, x[21], y[ 3]);
word3_muladd(&w2, &w1, &w0, x[22], y[ 2]);
word3_muladd(&w2, &w1, &w0, x[23], y[ 1]);
z[24] = w0; w0 = 0;
word3_muladd(&w0, &w2, &w1, x[ 2], y[23]);
word3_muladd(&w0, &w2, &w1, x[ 3], y[22]);
word3_muladd(&w0, &w2, &w1, x[ 4], y[21]);
word3_muladd(&w0, &w2, &w1, x[ 5], y[20]);
word3_muladd(&w0, &w2, &w1, x[ 6], y[19]);
word3_muladd(&w0, &w2, &w1, x[ 7], y[18]);
word3_muladd(&w0, &w2, &w1, x[ 8], y[17]);
word3_muladd(&w0, &w2, &w1, x[ 9], y[16]);
word3_muladd(&w0, &w2, &w1, x[10], y[15]);
word3_muladd(&w0, &w2, &w1, x[11], y[14]);
word3_muladd(&w0, &w2, &w1, x[12], y[13]);
word3_muladd(&w0, &w2, &w1, x[13], y[12]);
word3_muladd(&w0, &w2, &w1, x[14], y[11]);
word3_muladd(&w0, &w2, &w1, x[15], y[10]);
word3_muladd(&w0, &w2, &w1, x[16], y[ 9]);
word3_muladd(&w0, &w2, &w1, x[17], y[ 8]);
word3_muladd(&w0, &w2, &w1, x[18], y[ 7]);
word3_muladd(&w0, &w2, &w1, x[19], y[ 6]);
word3_muladd(&w0, &w2, &w1, x[20], y[ 5]);
word3_muladd(&w0, &w2, &w1, x[21], y[ 4]);
word3_muladd(&w0, &w2, &w1, x[22], y[ 3]);
word3_muladd(&w0, &w2, &w1, x[23], y[ 2]);
z[25] = w1; w1 = 0;
word3_muladd(&w1, &w0, &w2, x[ 3], y[23]);
word3_muladd(&w1, &w0, &w2, x[ 4], y[22]);
word3_muladd(&w1, &w0, &w2, x[ 5], y[21]);
word3_muladd(&w1, &w0, &w2, x[ 6], y[20]);
word3_muladd(&w1, &w0, &w2, x[ 7], y[19]);
word3_muladd(&w1, &w0, &w2, x[ 8], y[18]);
word3_muladd(&w1, &w0, &w2, x[ 9], y[17]);
word3_muladd(&w1, &w0, &w2, x[10], y[16]);
word3_muladd(&w1, &w0, &w2, x[11], y[15]);
word3_muladd(&w1, &w0, &w2, x[12], y[14]);
word3_muladd(&w1, &w0, &w2, x[13], y[13]);
word3_muladd(&w1, &w0, &w2, x[14], y[12]);
word3_muladd(&w1, &w0, &w2, x[15], y[11]);
word3_muladd(&w1, &w0, &w2, x[16], y[10]);
word3_muladd(&w1, &w0, &w2, x[17], y[ 9]);
word3_muladd(&w1, &w0, &w2, x[18], y[ 8]);
word3_muladd(&w1, &w0, &w2, x[19], y[ 7]);
word3_muladd(&w1, &w0, &w2, x[20], y[ 6]);
word3_muladd(&w1, &w0, &w2, x[21], y[ 5]);
word3_muladd(&w1, &w0, &w2, x[22], y[ 4]);
word3_muladd(&w1, &w0, &w2, x[23], y[ 3]);
z[26] = w2; w2 = 0;
word3_muladd(&w2, &w1, &w0, x[ 4], y[23]);
word3_muladd(&w2, &w1, &w0, x[ 5], y[22]);
word3_muladd(&w2, &w1, &w0, x[ 6], y[21]);
word3_muladd(&w2, &w1, &w0, x[ 7], y[20]);
word3_muladd(&w2, &w1, &w0, x[ 8], y[19]);
word3_muladd(&w2, &w1, &w0, x[ 9], y[18]);
word3_muladd(&w2, &w1, &w0, x[10], y[17]);
word3_muladd(&w2, &w1, &w0, x[11], y[16]);
word3_muladd(&w2, &w1, &w0, x[12], y[15]);
word3_muladd(&w2, &w1, &w0, x[13], y[14]);
word3_muladd(&w2, &w1, &w0, x[14], y[13]);
word3_muladd(&w2, &w1, &w0, x[15], y[12]);
word3_muladd(&w2, &w1, &w0, x[16], y[11]);
word3_muladd(&w2, &w1, &w0, x[17], y[10]);
word3_muladd(&w2, &w1, &w0, x[18], y[ 9]);
word3_muladd(&w2, &w1, &w0, x[19], y[ 8]);
word3_muladd(&w2, &w1, &w0, x[20], y[ 7]);
word3_muladd(&w2, &w1, &w0, x[21], y[ 6]);
word3_muladd(&w2, &w1, &w0, x[22], y[ 5]);
word3_muladd(&w2, &w1, &w0, x[23], y[ 4]);
z[27] = w0; w0 = 0;
word3_muladd(&w0, &w2, &w1, x[ 5], y[23]);
word3_muladd(&w0, &w2, &w1, x[ 6], y[22]);
word3_muladd(&w0, &w2, &w1, x[ 7], y[21]);
word3_muladd(&w0, &w2, &w1, x[ 8], y[20]);
word3_muladd(&w0, &w2, &w1, x[ 9], y[19]);
word3_muladd(&w0, &w2, &w1, x[10], y[18]);
word3_muladd(&w0, &w2, &w1, x[11], y[17]);
word3_muladd(&w0, &w2, &w1, x[12], y[16]);
word3_muladd(&w0, &w2, &w1, x[13], y[15]);
word3_muladd(&w0, &w2, &w1, x[14], y[14]);
word3_muladd(&w0, &w2, &w1, x[15], y[13]);
word3_muladd(&w0, &w2, &w1, x[16], y[12]);
word3_muladd(&w0, &w2, &w1, x[17], y[11]);
word3_muladd(&w0, &w2, &w1, x[18], y[10]);
word3_muladd(&w0, &w2, &w1, x[19], y[ 9]);
word3_muladd(&w0, &w2, &w1, x[20], y[ 8]);
word3_muladd(&w0, &w2, &w1, x[21], y[ 7]);
word3_muladd(&w0, &w2, &w1, x[22], y[ 6]);
word3_muladd(&w0, &w2, &w1, x[23], y[ 5]);
z[28] = w1; w1 = 0;
word3_muladd(&w1, &w0, &w2, x[ 6], y[23]);
word3_muladd(&w1, &w0, &w2, x[ 7], y[22]);
word3_muladd(&w1, &w0, &w2, x[ 8], y[21]);
word3_muladd(&w1, &w0, &w2, x[ 9], y[20]);
word3_muladd(&w1, &w0, &w2, x[10], y[19]);
word3_muladd(&w1, &w0, &w2, x[11], y[18]);
word3_muladd(&w1, &w0, &w2, x[12], y[17]);
word3_muladd(&w1, &w0, &w2, x[13], y[16]);
word3_muladd(&w1, &w0, &w2, x[14], y[15]);
word3_muladd(&w1, &w0, &w2, x[15], y[14]);
word3_muladd(&w1, &w0, &w2, x[16], y[13]);
word3_muladd(&w1, &w0, &w2, x[17], y[12]);
word3_muladd(&w1, &w0, &w2, x[18], y[11]);
word3_muladd(&w1, &w0, &w2, x[19], y[10]);
word3_muladd(&w1, &w0, &w2, x[20], y[ 9]);
word3_muladd(&w1, &w0, &w2, x[21], y[ 8]);
word3_muladd(&w1, &w0, &w2, x[22], y[ 7]);
word3_muladd(&w1, &w0, &w2, x[23], y[ 6]);
z[29] = w2; w2 = 0;
word3_muladd(&w2, &w1, &w0, x[ 7], y[23]);
word3_muladd(&w2, &w1, &w0, x[ 8], y[22]);
word3_muladd(&w2, &w1, &w0, x[ 9], y[21]);
word3_muladd(&w2, &w1, &w0, x[10], y[20]);
word3_muladd(&w2, &w1, &w0, x[11], y[19]);
word3_muladd(&w2, &w1, &w0, x[12], y[18]);
word3_muladd(&w2, &w1, &w0, x[13], y[17]);
word3_muladd(&w2, &w1, &w0, x[14], y[16]);
word3_muladd(&w2, &w1, &w0, x[15], y[15]);
word3_muladd(&w2, &w1, &w0, x[16], y[14]);
word3_muladd(&w2, &w1, &w0, x[17], y[13]);
word3_muladd(&w2, &w1, &w0, x[18], y[12]);
word3_muladd(&w2, &w1, &w0, x[19], y[11]);
word3_muladd(&w2, &w1, &w0, x[20], y[10]);
word3_muladd(&w2, &w1, &w0, x[21], y[ 9]);
word3_muladd(&w2, &w1, &w0, x[22], y[ 8]);
word3_muladd(&w2, &w1, &w0, x[23], y[ 7]);
z[30] = w0; w0 = 0;
word3_muladd(&w0, &w2, &w1, x[ 8], y[23]);
word3_muladd(&w0, &w2, &w1, x[ 9], y[22]);
word3_muladd(&w0, &w2, &w1, x[10], y[21]);
word3_muladd(&w0, &w2, &w1, x[11], y[20]);
word3_muladd(&w0, &w2, &w1, x[12], y[19]);
word3_muladd(&w0, &w2, &w1, x[13], y[18]);
word3_muladd(&w0, &w2, &w1, x[14], y[17]);
word3_muladd(&w0, &w2, &w1, x[15], y[16]);
word3_muladd(&w0, &w2, &w1, x[16], y[15]);
word3_muladd(&w0, &w2, &w1, x[17], y[14]);
word3_muladd(&w0, &w2, &w1, x[18], y[13]);
word3_muladd(&w0, &w2, &w1, x[19], y[12]);
word3_muladd(&w0, &w2, &w1, x[20], y[11]);
word3_muladd(&w0, &w2, &w1, x[21], y[10]);
word3_muladd(&w0, &w2, &w1, x[22], y[ 9]);
word3_muladd(&w0, &w2, &w1, x[23], y[ 8]);
z[31] = w1; w1 = 0;
word3_muladd(&w1, &w0, &w2, x[ 9], y[23]);
word3_muladd(&w1, &w0, &w2, x[10], y[22]);
word3_muladd(&w1, &w0, &w2, x[11], y[21]);
word3_muladd(&w1, &w0, &w2, x[12], y[20]);
word3_muladd(&w1, &w0, &w2, x[13], y[19]);
word3_muladd(&w1, &w0, &w2, x[14], y[18]);
word3_muladd(&w1, &w0, &w2, x[15], y[17]);
word3_muladd(&w1, &w0, &w2, x[16], y[16]);
word3_muladd(&w1, &w0, &w2, x[17], y[15]);
word3_muladd(&w1, &w0, &w2, x[18], y[14]);
word3_muladd(&w1, &w0, &w2, x[19], y[13]);
word3_muladd(&w1, &w0, &w2, x[20], y[12]);
word3_muladd(&w1, &w0, &w2, x[21], y[11]);
word3_muladd(&w1, &w0, &w2, x[22], y[10]);
word3_muladd(&w1, &w0, &w2, x[23], y[ 9]);
z[32] = w2; w2 = 0;
word3_muladd(&w2, &w1, &w0, x[10], y[23]);
word3_muladd(&w2, &w1, &w0, x[11], y[22]);
word3_muladd(&w2, &w1, &w0, x[12], y[21]);
word3_muladd(&w2, &w1, &w0, x[13], y[20]);
word3_muladd(&w2, &w1, &w0, x[14], y[19]);
word3_muladd(&w2, &w1, &w0, x[15], y[18]);
word3_muladd(&w2, &w1, &w0, x[16], y[17]);
word3_muladd(&w2, &w1, &w0, x[17], y[16]);
word3_muladd(&w2, &w1, &w0, x[18], y[15]);
word3_muladd(&w2, &w1, &w0, x[19], y[14]);
word3_muladd(&w2, &w1, &w0, x[20], y[13]);
word3_muladd(&w2, &w1, &w0, x[21], y[12]);
word3_muladd(&w2, &w1, &w0, x[22], y[11]);
word3_muladd(&w2, &w1, &w0, x[23], y[10]);
z[33] = w0; w0 = 0;
word3_muladd(&w0, &w2, &w1, x[11], y[23]);
word3_muladd(&w0, &w2, &w1, x[12], y[22]);
word3_muladd(&w0, &w2, &w1, x[13], y[21]);
word3_muladd(&w0, &w2, &w1, x[14], y[20]);
word3_muladd(&w0, &w2, &w1, x[15], y[19]);
word3_muladd(&w0, &w2, &w1, x[16], y[18]);
word3_muladd(&w0, &w2, &w1, x[17], y[17]);
word3_muladd(&w0, &w2, &w1, x[18], y[16]);
word3_muladd(&w0, &w2, &w1, x[19], y[15]);
word3_muladd(&w0, &w2, &w1, x[20], y[14]);
word3_muladd(&w0, &w2, &w1, x[21], y[13]);
word3_muladd(&w0, &w2, &w1, x[22], y[12]);
word3_muladd(&w0, &w2, &w1, x[23], y[11]);
z[34] = w1; w1 = 0;
word3_muladd(&w1, &w0, &w2, x[12], y[23]);
word3_muladd(&w1, &w0, &w2, x[13], y[22]);
word3_muladd(&w1, &w0, &w2, x[14], y[21]);
word3_muladd(&w1, &w0, &w2, x[15], y[20]);
word3_muladd(&w1, &w0, &w2, x[16], y[19]);
word3_muladd(&w1, &w0, &w2, x[17], y[18]);
word3_muladd(&w1, &w0, &w2, x[18], y[17]);
word3_muladd(&w1, &w0, &w2, x[19], y[16]);
word3_muladd(&w1, &w0, &w2, x[20], y[15]);
word3_muladd(&w1, &w0, &w2, x[21], y[14]);
word3_muladd(&w1, &w0, &w2, x[22], y[13]);
word3_muladd(&w1, &w0, &w2, x[23], y[12]);
z[35] = w2; w2 = 0;
word3_muladd(&w2, &w1, &w0, x[13], y[23]);
word3_muladd(&w2, &w1, &w0, x[14], y[22]);
word3_muladd(&w2, &w1, &w0, x[15], y[21]);
word3_muladd(&w2, &w1, &w0, x[16], y[20]);
word3_muladd(&w2, &w1, &w0, x[17], y[19]);
word3_muladd(&w2, &w1, &w0, x[18], y[18]);
word3_muladd(&w2, &w1, &w0, x[19], y[17]);
word3_muladd(&w2, &w1, &w0, x[20], y[16]);
word3_muladd(&w2, &w1, &w0, x[21], y[15]);
word3_muladd(&w2, &w1, &w0, x[22], y[14]);
word3_muladd(&w2, &w1, &w0, x[23], y[13]);
z[36] = w0; w0 = 0;
word3_muladd(&w0, &w2, &w1, x[14], y[23]);
word3_muladd(&w0, &w2, &w1, x[15], y[22]);
word3_muladd(&w0, &w2, &w1, x[16], y[21]);
word3_muladd(&w0, &w2, &w1, x[17], y[20]);
word3_muladd(&w0, &w2, &w1, x[18], y[19]);
word3_muladd(&w0, &w2, &w1, x[19], y[18]);
word3_muladd(&w0, &w2, &w1, x[20], y[17]);
word3_muladd(&w0, &w2, &w1, x[21], y[16]);
word3_muladd(&w0, &w2, &w1, x[22], y[15]);
word3_muladd(&w0, &w2, &w1, x[23], y[14]);
z[37] = w1; w1 = 0;
word3_muladd(&w1, &w0, &w2, x[15], y[23]);
word3_muladd(&w1, &w0, &w2, x[16], y[22]);
word3_muladd(&w1, &w0, &w2, x[17], y[21]);
word3_muladd(&w1, &w0, &w2, x[18], y[20]);
word3_muladd(&w1, &w0, &w2, x[19], y[19]);
word3_muladd(&w1, &w0, &w2, x[20], y[18]);
word3_muladd(&w1, &w0, &w2, x[21], y[17]);
word3_muladd(&w1, &w0, &w2, x[22], y[16]);
word3_muladd(&w1, &w0, &w2, x[23], y[15]);
z[38] = w2; w2 = 0;
word3_muladd(&w2, &w1, &w0, x[16], y[23]);
word3_muladd(&w2, &w1, &w0, x[17], y[22]);
word3_muladd(&w2, &w1, &w0, x[18], y[21]);
word3_muladd(&w2, &w1, &w0, x[19], y[20]);
word3_muladd(&w2, &w1, &w0, x[20], y[19]);
word3_muladd(&w2, &w1, &w0, x[21], y[18]);
word3_muladd(&w2, &w1, &w0, x[22], y[17]);
word3_muladd(&w2, &w1, &w0, x[23], y[16]);
z[39] = w0; w0 = 0;
word3_muladd(&w0, &w2, &w1, x[17], y[23]);
word3_muladd(&w0, &w2, &w1, x[18], y[22]);
word3_muladd(&w0, &w2, &w1, x[19], y[21]);
word3_muladd(&w0, &w2, &w1, x[20], y[20]);
word3_muladd(&w0, &w2, &w1, x[21], y[19]);
word3_muladd(&w0, &w2, &w1, x[22], y[18]);
word3_muladd(&w0, &w2, &w1, x[23], y[17]);
z[40] = w1; w1 = 0;
word3_muladd(&w1, &w0, &w2, x[18], y[23]);
word3_muladd(&w1, &w0, &w2, x[19], y[22]);
word3_muladd(&w1, &w0, &w2, x[20], y[21]);
word3_muladd(&w1, &w0, &w2, x[21], y[20]);
word3_muladd(&w1, &w0, &w2, x[22], y[19]);
word3_muladd(&w1, &w0, &w2, x[23], y[18]);
z[41] = w2; w2 = 0;
word3_muladd(&w2, &w1, &w0, x[19], y[23]);
word3_muladd(&w2, &w1, &w0, x[20], y[22]);
word3_muladd(&w2, &w1, &w0, x[21], y[21]);
word3_muladd(&w2, &w1, &w0, x[22], y[20]);
word3_muladd(&w2, &w1, &w0, x[23], y[19]);
z[42] = w0; w0 = 0;
word3_muladd(&w0, &w2, &w1, x[20], y[23]);
word3_muladd(&w0, &w2, &w1, x[21], y[22]);
word3_muladd(&w0, &w2, &w1, x[22], y[21]);
word3_muladd(&w0, &w2, &w1, x[23], y[20]);
z[43] = w1; w1 = 0;
word3_muladd(&w1, &w0, &w2, x[21], y[23]);
word3_muladd(&w1, &w0, &w2, x[22], y[22]);
word3_muladd(&w1, &w0, &w2, x[23], y[21]);
z[44] = w2; w2 = 0;
word3_muladd(&w2, &w1, &w0, x[22], y[23]);
word3_muladd(&w2, &w1, &w0, x[23], y[22]);
z[45] = w0; w0 = 0;
word3_muladd(&w0, &w2, &w1, x[23], y[23]);
z[46] = w1;
z[47] = w2;
}
}
|
#include <tc/crypto/Sha256Generator.h>
const std::array<byte_t, tc::crypto::Sha256Generator::kAsn1OidDataSize> tc::crypto::Sha256Generator::kAsn1OidData = {0x30, 0x31, 0x30, 0x0D, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05, 0x00, 0x04, 0x20};
void tc::crypto::GenerateSha256Hash(byte_t* hash, const byte_t* data, size_t data_size)
{
tc::crypto::Sha256Generator impl;
impl.initialize();
impl.update(data, data_size);
impl.getHash(hash);
}
|
#include "db-engine/berkeley/MojDbBerkeleyDefs.h"
#include <sys/statvfs.h>
#include <db.h>
// DB
const MojUInt32 defs::MojDbOpenFlags = DB_THREAD /*| DB_MULTIVERSION*/; // NOTE: MULTIVERSION disabled due to leaked transactions
const MojUInt32 defs::MojDbGetFlags = DB_READ_COMMITTED;
// LOG
const MojUInt32 defs::MojLogFlags = 0;
const MojUInt32 defs::MojLogArchiveFlags = DB_ARCH_ABS;
// SEQ
const MojUInt32 defs::MojSeqOpenFlags = DB_CREATE | DB_THREAD;
const MojUInt32 defs::MojSeqGetFlags = DB_TXN_NOSYNC;
const MojUInt32 defs::MojSeqCacheSize = 25;
// GENERAL
const int defs::MojDbFileMode = MOJ_S_IRUSR | MOJ_S_IWUSR;
// ENV
const MojUInt32 defs::MojEnvFlags = DB_AUTO_COMMIT | DB_NOMMAP;
const MojUInt32 defs::MojEnvOpenFlags = DB_CREATE | DB_INIT_LOCK | DB_INIT_LOG | DB_INIT_MPOOL | DB_INIT_TXN | DB_RECOVER | DB_THREAD | DB_PRIVATE | DB_DIRECT_DB;
const bool defs::MojEnvDefaultPrivate = true;
const bool defs::MojEnvDefaultLogAutoRemove = true;
const MojUInt32 defs::MojEnvDefaultLogFileSize = 1024 * 1024 * 2; // 2MB
const MojUInt32 defs::MojEnvDefaultLogRegionSize = 1024 * 512; // 512 KB
const MojUInt32 defs::MojEnvDefaultCacheSize = 1024 * 1024 * 2; // 2MB
const MojUInt32 defs::MojEnvDefaultMaxLocks = 8000; // max db size / page size
const MojUInt32 defs::MojEnvDefaultMaxLockers = 1000 * 2; // twice the default
const MojUInt32 defs::MojEnvDefaultCheckpointMinKb = 512; // 1MB
const MojUInt32 defs::MojEnvDefaultCheckpointMinMinutes = 0;
const MojUInt32 defs::MojEnvDefaultCompactStepSize = 25000;
const MojChar* const defs::MojEnvSeqDbName = _T("sequences.db");
const MojChar* const defs::MojEnvIndexDbName = _T("indexes.db");
// TXN
const MojUInt32 defs::MojTxnBeginFlags = DB_READ_COMMITTED;
const MojUInt32 defs::MojTxnMax = 100; // need up to one per cache page for mvcc
|
/**
* Autogenerated by Thrift for src/module.thrift
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated
*/
#include "thrift/compiler/test/fixtures/mcpp2-compare/gen-cpp2/ParamServiceAsyncClient.h"
#include <thrift/lib/cpp2/gen/client_cpp.h>
namespace some { namespace valid { namespace ns {
typedef apache::thrift::ThriftPresult<false, apache::thrift::FieldData<1, ::apache::thrift::type_class::integral, ::std::int16_t*>> ParamService_void_ret_i16_param_pargs;
typedef apache::thrift::ThriftPresult<true> ParamService_void_ret_i16_param_presult;
typedef apache::thrift::ThriftPresult<false, apache::thrift::FieldData<1, ::apache::thrift::type_class::integral, ::std::int8_t*>, apache::thrift::FieldData<2, ::apache::thrift::type_class::integral, ::std::int16_t*>> ParamService_void_ret_byte_i16_param_pargs;
typedef apache::thrift::ThriftPresult<true> ParamService_void_ret_byte_i16_param_presult;
typedef apache::thrift::ThriftPresult<false, apache::thrift::FieldData<1, ::apache::thrift::type_class::map<::apache::thrift::type_class::string, ::apache::thrift::type_class::integral>, ::std::map<::std::string, ::std::int64_t>*>> ParamService_void_ret_map_param_pargs;
typedef apache::thrift::ThriftPresult<true> ParamService_void_ret_map_param_presult;
typedef apache::thrift::ThriftPresult<false, apache::thrift::FieldData<1, ::apache::thrift::type_class::map<::apache::thrift::type_class::string, ::apache::thrift::type_class::integral>, ::std::map<::std::string, ::std::int64_t>*>, apache::thrift::FieldData<3, ::apache::thrift::type_class::set<::apache::thrift::type_class::list<::apache::thrift::type_class::string>>, ::std::set<::std::vector<::std::string>>*>> ParamService_void_ret_map_setlist_param_pargs;
typedef apache::thrift::ThriftPresult<true> ParamService_void_ret_map_setlist_param_presult;
typedef apache::thrift::ThriftPresult<false, apache::thrift::FieldData<1, ::apache::thrift::type_class::integral, ::some::valid::ns::simpleTypeDef*>> ParamService_void_ret_map_typedef_param_pargs;
typedef apache::thrift::ThriftPresult<true> ParamService_void_ret_map_typedef_param_presult;
typedef apache::thrift::ThriftPresult<false, apache::thrift::FieldData<1, ::apache::thrift::type_class::enumeration, ::some::valid::ns::MyEnumA*>> ParamService_void_ret_enum_param_pargs;
typedef apache::thrift::ThriftPresult<true> ParamService_void_ret_enum_param_presult;
typedef apache::thrift::ThriftPresult<false, apache::thrift::FieldData<1, ::apache::thrift::type_class::structure, ::some::valid::ns::MyStruct*>> ParamService_void_ret_struct_param_pargs;
typedef apache::thrift::ThriftPresult<true> ParamService_void_ret_struct_param_presult;
typedef apache::thrift::ThriftPresult<false, apache::thrift::FieldData<1, ::apache::thrift::type_class::list<::apache::thrift::type_class::variant>, ::std::vector<::some::valid::ns::ComplexUnion>*>> ParamService_void_ret_listunion_param_pargs;
typedef apache::thrift::ThriftPresult<true> ParamService_void_ret_listunion_param_presult;
typedef apache::thrift::ThriftPresult<false, apache::thrift::FieldData<1, ::apache::thrift::type_class::integral, ::std::int32_t*>, apache::thrift::FieldData<3, ::apache::thrift::type_class::integral, ::std::int64_t*>> ParamService_bool_ret_i32_i64_param_pargs;
typedef apache::thrift::ThriftPresult<true, apache::thrift::FieldData<0, ::apache::thrift::type_class::integral, bool*>> ParamService_bool_ret_i32_i64_param_presult;
typedef apache::thrift::ThriftPresult<false, apache::thrift::FieldData<1, ::apache::thrift::type_class::map<::apache::thrift::type_class::string, ::apache::thrift::type_class::integral>, ::std::map<::std::string, ::std::int64_t>*>> ParamService_bool_ret_map_param_pargs;
typedef apache::thrift::ThriftPresult<true, apache::thrift::FieldData<0, ::apache::thrift::type_class::integral, bool*>> ParamService_bool_ret_map_param_presult;
typedef apache::thrift::ThriftPresult<false, apache::thrift::FieldData<1, ::apache::thrift::type_class::variant, ::some::valid::ns::ComplexUnion*>> ParamService_bool_ret_union_param_pargs;
typedef apache::thrift::ThriftPresult<true, apache::thrift::FieldData<0, ::apache::thrift::type_class::integral, bool*>> ParamService_bool_ret_union_param_presult;
typedef apache::thrift::ThriftPresult<false, apache::thrift::FieldData<1, ::apache::thrift::type_class::floating_point, float*>, apache::thrift::FieldData<3, ::apache::thrift::type_class::floating_point, double*>> ParamService_i64_ret_float_double_param_pargs;
typedef apache::thrift::ThriftPresult<true, apache::thrift::FieldData<0, ::apache::thrift::type_class::integral, ::std::int64_t*>> ParamService_i64_ret_float_double_param_presult;
typedef apache::thrift::ThriftPresult<false, apache::thrift::FieldData<1, ::apache::thrift::type_class::string, ::std::string*>, apache::thrift::FieldData<3, ::apache::thrift::type_class::set<::apache::thrift::type_class::list<::apache::thrift::type_class::list<::apache::thrift::type_class::map<::apache::thrift::type_class::structure, ::apache::thrift::type_class::structure>>>>, ::std::set<::some::valid::ns::mostComplexTypeDef>*>> ParamService_i64_ret_string_typedef_param_pargs;
typedef apache::thrift::ThriftPresult<true, apache::thrift::FieldData<0, ::apache::thrift::type_class::integral, ::std::int64_t*>> ParamService_i64_ret_string_typedef_param_presult;
typedef apache::thrift::ThriftPresult<false, apache::thrift::FieldData<1, ::apache::thrift::type_class::integral, ::std::int32_t*>, apache::thrift::FieldData<2, ::apache::thrift::type_class::integral, ::std::int32_t*>, apache::thrift::FieldData<3, ::apache::thrift::type_class::integral, ::std::int32_t*>, apache::thrift::FieldData<4, ::apache::thrift::type_class::integral, ::std::int32_t*>, apache::thrift::FieldData<5, ::apache::thrift::type_class::integral, ::std::int32_t*>> ParamService_i64_ret_i32_i32_i32_i32_i32_param_pargs;
typedef apache::thrift::ThriftPresult<true, apache::thrift::FieldData<0, ::apache::thrift::type_class::integral, ::std::int64_t*>> ParamService_i64_ret_i32_i32_i32_i32_i32_param_presult;
typedef apache::thrift::ThriftPresult<false, apache::thrift::FieldData<4, ::apache::thrift::type_class::set<::apache::thrift::type_class::structure>, ::std::set<::some::valid::ns::MyStruct>*>> ParamService_double_ret_setstruct_param_pargs;
typedef apache::thrift::ThriftPresult<true, apache::thrift::FieldData<0, ::apache::thrift::type_class::floating_point, double*>> ParamService_double_ret_setstruct_param_presult;
typedef apache::thrift::ThriftPresult<false, apache::thrift::FieldData<1, ::apache::thrift::type_class::string, ::std::string*>> ParamService_string_ret_string_param_pargs;
typedef apache::thrift::ThriftPresult<true, apache::thrift::FieldData<0, ::apache::thrift::type_class::string, ::std::string*>> ParamService_string_ret_string_param_presult;
typedef apache::thrift::ThriftPresult<false, apache::thrift::FieldData<1, ::apache::thrift::type_class::binary, ::std::string*>> ParamService_binary_ret_binary_param_pargs;
typedef apache::thrift::ThriftPresult<true, apache::thrift::FieldData<0, ::apache::thrift::type_class::binary, ::std::string*>> ParamService_binary_ret_binary_param_presult;
typedef apache::thrift::ThriftPresult<false, apache::thrift::FieldData<1, ::apache::thrift::type_class::integral, bool*>> ParamService_map_ret_bool_param_pargs;
typedef apache::thrift::ThriftPresult<true, apache::thrift::FieldData<0, ::apache::thrift::type_class::map<::apache::thrift::type_class::string, ::apache::thrift::type_class::integral>, ::std::map<::std::string, ::std::int64_t>*>> ParamService_map_ret_bool_param_presult;
typedef apache::thrift::ThriftPresult<false, apache::thrift::FieldData<1, ::apache::thrift::type_class::map<::apache::thrift::type_class::integral, ::apache::thrift::type_class::list<::apache::thrift::type_class::string>>, ::std::map<::std::int32_t, ::std::vector<::std::string>>*>, apache::thrift::FieldData<2, ::apache::thrift::type_class::list<::apache::thrift::type_class::string>, ::std::vector<::std::string>*>> ParamService_list_ret_map_setlist_param_pargs;
typedef apache::thrift::ThriftPresult<true, apache::thrift::FieldData<0, ::apache::thrift::type_class::list<::apache::thrift::type_class::integral>, ::std::vector<bool>*>> ParamService_list_ret_map_setlist_param_presult;
typedef apache::thrift::ThriftPresult<false, apache::thrift::FieldData<1, ::apache::thrift::type_class::list<::apache::thrift::type_class::list<::apache::thrift::type_class::list<::apache::thrift::type_class::list<::apache::thrift::type_class::integral>>>>, ::std::vector<::std::vector<::std::vector<::std::vector<::std::int32_t>>>>*>> ParamService_mapsetlistmapliststring_ret_listlistlist_param_pargs;
typedef apache::thrift::ThriftPresult<true, apache::thrift::FieldData<0, ::apache::thrift::type_class::map<::apache::thrift::type_class::set<::apache::thrift::type_class::list<::apache::thrift::type_class::integral>>, ::apache::thrift::type_class::map<::apache::thrift::type_class::list<::apache::thrift::type_class::set<::apache::thrift::type_class::string>>, ::apache::thrift::type_class::string>>, ::std::map<::std::set<::std::vector<::std::int32_t>>, ::std::map<::std::vector<::std::set<::std::string>>, ::std::string>>*>> ParamService_mapsetlistmapliststring_ret_listlistlist_param_presult;
typedef apache::thrift::ThriftPresult<false, apache::thrift::FieldData<1, ::apache::thrift::type_class::integral, ::std::int32_t*>> ParamService_typedef_ret_i32_param_pargs;
typedef apache::thrift::ThriftPresult<true, apache::thrift::FieldData<0, ::apache::thrift::type_class::integral, ::some::valid::ns::simpleTypeDef*>> ParamService_typedef_ret_i32_param_presult;
typedef apache::thrift::ThriftPresult<false, apache::thrift::FieldData<1, ::apache::thrift::type_class::list<::apache::thrift::type_class::map<::apache::thrift::type_class::structure, ::apache::thrift::type_class::structure>>, ::some::valid::ns::complexStructTypeDef*>> ParamService_listtypedef_ret_typedef_param_pargs;
typedef apache::thrift::ThriftPresult<true, apache::thrift::FieldData<0, ::apache::thrift::type_class::list<::apache::thrift::type_class::integral>, ::std::vector<::some::valid::ns::simpleTypeDef>*>> ParamService_listtypedef_ret_typedef_param_presult;
typedef apache::thrift::ThriftPresult<false, apache::thrift::FieldData<3, ::apache::thrift::type_class::floating_point, double*>> ParamService_enum_ret_double_param_pargs;
typedef apache::thrift::ThriftPresult<true, apache::thrift::FieldData<0, ::apache::thrift::type_class::enumeration, ::some::valid::ns::MyEnumA*>> ParamService_enum_ret_double_param_presult;
typedef apache::thrift::ThriftPresult<false, apache::thrift::FieldData<3, ::apache::thrift::type_class::floating_point, double*>, apache::thrift::FieldData<5, ::apache::thrift::type_class::enumeration, ::some::valid::ns::MyEnumA*>> ParamService_enum_ret_double_enum_param_pargs;
typedef apache::thrift::ThriftPresult<true, apache::thrift::FieldData<0, ::apache::thrift::type_class::enumeration, ::some::valid::ns::MyEnumA*>> ParamService_enum_ret_double_enum_param_presult;
typedef apache::thrift::ThriftPresult<false, apache::thrift::FieldData<1, ::apache::thrift::type_class::map<::apache::thrift::type_class::string, ::apache::thrift::type_class::integral>, ::std::map<::std::string, ::std::int64_t>*>> ParamService_listenum_ret_map_param_pargs;
typedef apache::thrift::ThriftPresult<true, apache::thrift::FieldData<0, ::apache::thrift::type_class::list<::apache::thrift::type_class::enumeration>, ::std::vector<::some::valid::ns::MyEnumA>*>> ParamService_listenum_ret_map_param_presult;
typedef apache::thrift::ThriftPresult<false, apache::thrift::FieldData<1, ::apache::thrift::type_class::integral, ::std::int16_t*>> ParamService_struct_ret_i16_param_pargs;
typedef apache::thrift::ThriftPresult<true, apache::thrift::FieldData<0, ::apache::thrift::type_class::structure, ::some::valid::ns::MyStruct*>> ParamService_struct_ret_i16_param_presult;
typedef apache::thrift::ThriftPresult<false, apache::thrift::FieldData<8, ::apache::thrift::type_class::set<::apache::thrift::type_class::string>, ::std::set<::std::string>*>> ParamService_setstruct_ret_set_param_pargs;
typedef apache::thrift::ThriftPresult<true, apache::thrift::FieldData<0, ::apache::thrift::type_class::set<::apache::thrift::type_class::structure>, ::std::set<::some::valid::ns::MyStruct>*>> ParamService_setstruct_ret_set_param_presult;
typedef apache::thrift::ThriftPresult<false, apache::thrift::FieldData<4, ::apache::thrift::type_class::integral, ::std::int32_t*>, apache::thrift::FieldData<2, ::apache::thrift::type_class::integral, ::std::int32_t*>> ParamService_union_ret_i32_i32_param_pargs;
typedef apache::thrift::ThriftPresult<true, apache::thrift::FieldData<0, ::apache::thrift::type_class::variant, ::some::valid::ns::ComplexUnion*>> ParamService_union_ret_i32_i32_param_presult;
typedef apache::thrift::ThriftPresult<false, apache::thrift::FieldData<1, ::apache::thrift::type_class::string, ::std::string*>> ParamService_listunion_string_param_pargs;
typedef apache::thrift::ThriftPresult<true, apache::thrift::FieldData<0, ::apache::thrift::type_class::list<::apache::thrift::type_class::variant>, ::std::vector<::some::valid::ns::ComplexUnion>*>> ParamService_listunion_string_param_presult;
template <typename Protocol_>
void ParamServiceAsyncClient::void_ret_i16_paramT(Protocol_* prot, apache::thrift::RpcOptions rpcOptions, std::shared_ptr<apache::thrift::transport::THeader> header, apache::thrift::ContextStack* contextStack, apache::thrift::RequestClientCallback::Ptr callback, ::std::int16_t p_param1) {
ParamService_void_ret_i16_param_pargs args;
args.get<0>().value = &p_param1;
auto sizer = [&](Protocol_* p) { return args.serializedSizeZC(p); };
auto writer = [&](Protocol_* p) { args.write(p); };
static ::apache::thrift::MethodMetadata::Data* methodMetadata =
new ::apache::thrift::MethodMetadata::Data(
"void_ret_i16_param",
::apache::thrift::FunctionQualifier::None);
apache::thrift::clientSendT<apache::thrift::RpcKind::SINGLE_REQUEST_SINGLE_RESPONSE, Protocol_>(prot, std::move(rpcOptions), std::move(callback), contextStack, std::move(header), channel_.get(), ::apache::thrift::MethodMetadata::from_static(methodMetadata), writer, sizer);
}
template <typename Protocol_>
void ParamServiceAsyncClient::void_ret_byte_i16_paramT(Protocol_* prot, apache::thrift::RpcOptions rpcOptions, std::shared_ptr<apache::thrift::transport::THeader> header, apache::thrift::ContextStack* contextStack, apache::thrift::RequestClientCallback::Ptr callback, ::std::int8_t p_param1, ::std::int16_t p_param2) {
ParamService_void_ret_byte_i16_param_pargs args;
args.get<0>().value = &p_param1;
args.get<1>().value = &p_param2;
auto sizer = [&](Protocol_* p) { return args.serializedSizeZC(p); };
auto writer = [&](Protocol_* p) { args.write(p); };
static ::apache::thrift::MethodMetadata::Data* methodMetadata =
new ::apache::thrift::MethodMetadata::Data(
"void_ret_byte_i16_param",
::apache::thrift::FunctionQualifier::None);
apache::thrift::clientSendT<apache::thrift::RpcKind::SINGLE_REQUEST_SINGLE_RESPONSE, Protocol_>(prot, std::move(rpcOptions), std::move(callback), contextStack, std::move(header), channel_.get(), ::apache::thrift::MethodMetadata::from_static(methodMetadata), writer, sizer);
}
template <typename Protocol_>
void ParamServiceAsyncClient::void_ret_map_paramT(Protocol_* prot, apache::thrift::RpcOptions rpcOptions, std::shared_ptr<apache::thrift::transport::THeader> header, apache::thrift::ContextStack* contextStack, apache::thrift::RequestClientCallback::Ptr callback, const ::std::map<::std::string, ::std::int64_t>& p_param1) {
ParamService_void_ret_map_param_pargs args;
args.get<0>().value = const_cast<::std::map<::std::string, ::std::int64_t>*>(&p_param1);
auto sizer = [&](Protocol_* p) { return args.serializedSizeZC(p); };
auto writer = [&](Protocol_* p) { args.write(p); };
static ::apache::thrift::MethodMetadata::Data* methodMetadata =
new ::apache::thrift::MethodMetadata::Data(
"void_ret_map_param",
::apache::thrift::FunctionQualifier::None);
apache::thrift::clientSendT<apache::thrift::RpcKind::SINGLE_REQUEST_SINGLE_RESPONSE, Protocol_>(prot, std::move(rpcOptions), std::move(callback), contextStack, std::move(header), channel_.get(), ::apache::thrift::MethodMetadata::from_static(methodMetadata), writer, sizer);
}
template <typename Protocol_>
void ParamServiceAsyncClient::void_ret_map_setlist_paramT(Protocol_* prot, apache::thrift::RpcOptions rpcOptions, std::shared_ptr<apache::thrift::transport::THeader> header, apache::thrift::ContextStack* contextStack, apache::thrift::RequestClientCallback::Ptr callback, const ::std::map<::std::string, ::std::int64_t>& p_param1, const ::std::set<::std::vector<::std::string>>& p_param2) {
ParamService_void_ret_map_setlist_param_pargs args;
args.get<0>().value = const_cast<::std::map<::std::string, ::std::int64_t>*>(&p_param1);
args.get<1>().value = const_cast<::std::set<::std::vector<::std::string>>*>(&p_param2);
auto sizer = [&](Protocol_* p) { return args.serializedSizeZC(p); };
auto writer = [&](Protocol_* p) { args.write(p); };
static ::apache::thrift::MethodMetadata::Data* methodMetadata =
new ::apache::thrift::MethodMetadata::Data(
"void_ret_map_setlist_param",
::apache::thrift::FunctionQualifier::None);
apache::thrift::clientSendT<apache::thrift::RpcKind::SINGLE_REQUEST_SINGLE_RESPONSE, Protocol_>(prot, std::move(rpcOptions), std::move(callback), contextStack, std::move(header), channel_.get(), ::apache::thrift::MethodMetadata::from_static(methodMetadata), writer, sizer);
}
template <typename Protocol_>
void ParamServiceAsyncClient::void_ret_map_typedef_paramT(Protocol_* prot, apache::thrift::RpcOptions rpcOptions, std::shared_ptr<apache::thrift::transport::THeader> header, apache::thrift::ContextStack* contextStack, apache::thrift::RequestClientCallback::Ptr callback, ::some::valid::ns::simpleTypeDef p_param1) {
ParamService_void_ret_map_typedef_param_pargs args;
args.get<0>().value = &p_param1;
auto sizer = [&](Protocol_* p) { return args.serializedSizeZC(p); };
auto writer = [&](Protocol_* p) { args.write(p); };
static ::apache::thrift::MethodMetadata::Data* methodMetadata =
new ::apache::thrift::MethodMetadata::Data(
"void_ret_map_typedef_param",
::apache::thrift::FunctionQualifier::None);
apache::thrift::clientSendT<apache::thrift::RpcKind::SINGLE_REQUEST_SINGLE_RESPONSE, Protocol_>(prot, std::move(rpcOptions), std::move(callback), contextStack, std::move(header), channel_.get(), ::apache::thrift::MethodMetadata::from_static(methodMetadata), writer, sizer);
}
template <typename Protocol_>
void ParamServiceAsyncClient::void_ret_enum_paramT(Protocol_* prot, apache::thrift::RpcOptions rpcOptions, std::shared_ptr<apache::thrift::transport::THeader> header, apache::thrift::ContextStack* contextStack, apache::thrift::RequestClientCallback::Ptr callback, ::some::valid::ns::MyEnumA p_param1) {
ParamService_void_ret_enum_param_pargs args;
args.get<0>().value = &p_param1;
auto sizer = [&](Protocol_* p) { return args.serializedSizeZC(p); };
auto writer = [&](Protocol_* p) { args.write(p); };
static ::apache::thrift::MethodMetadata::Data* methodMetadata =
new ::apache::thrift::MethodMetadata::Data(
"void_ret_enum_param",
::apache::thrift::FunctionQualifier::None);
apache::thrift::clientSendT<apache::thrift::RpcKind::SINGLE_REQUEST_SINGLE_RESPONSE, Protocol_>(prot, std::move(rpcOptions), std::move(callback), contextStack, std::move(header), channel_.get(), ::apache::thrift::MethodMetadata::from_static(methodMetadata), writer, sizer);
}
template <typename Protocol_>
void ParamServiceAsyncClient::void_ret_struct_paramT(Protocol_* prot, apache::thrift::RpcOptions rpcOptions, std::shared_ptr<apache::thrift::transport::THeader> header, apache::thrift::ContextStack* contextStack, apache::thrift::RequestClientCallback::Ptr callback, const ::some::valid::ns::MyStruct& p_param1) {
ParamService_void_ret_struct_param_pargs args;
args.get<0>().value = const_cast<::some::valid::ns::MyStruct*>(&p_param1);
auto sizer = [&](Protocol_* p) { return args.serializedSizeZC(p); };
auto writer = [&](Protocol_* p) { args.write(p); };
static ::apache::thrift::MethodMetadata::Data* methodMetadata =
new ::apache::thrift::MethodMetadata::Data(
"void_ret_struct_param",
::apache::thrift::FunctionQualifier::None);
apache::thrift::clientSendT<apache::thrift::RpcKind::SINGLE_REQUEST_SINGLE_RESPONSE, Protocol_>(prot, std::move(rpcOptions), std::move(callback), contextStack, std::move(header), channel_.get(), ::apache::thrift::MethodMetadata::from_static(methodMetadata), writer, sizer);
}
template <typename Protocol_>
void ParamServiceAsyncClient::void_ret_listunion_paramT(Protocol_* prot, apache::thrift::RpcOptions rpcOptions, std::shared_ptr<apache::thrift::transport::THeader> header, apache::thrift::ContextStack* contextStack, apache::thrift::RequestClientCallback::Ptr callback, const ::std::vector<::some::valid::ns::ComplexUnion>& p_param1) {
ParamService_void_ret_listunion_param_pargs args;
args.get<0>().value = const_cast<::std::vector<::some::valid::ns::ComplexUnion>*>(&p_param1);
auto sizer = [&](Protocol_* p) { return args.serializedSizeZC(p); };
auto writer = [&](Protocol_* p) { args.write(p); };
static ::apache::thrift::MethodMetadata::Data* methodMetadata =
new ::apache::thrift::MethodMetadata::Data(
"void_ret_listunion_param",
::apache::thrift::FunctionQualifier::None);
apache::thrift::clientSendT<apache::thrift::RpcKind::SINGLE_REQUEST_SINGLE_RESPONSE, Protocol_>(prot, std::move(rpcOptions), std::move(callback), contextStack, std::move(header), channel_.get(), ::apache::thrift::MethodMetadata::from_static(methodMetadata), writer, sizer);
}
template <typename Protocol_>
void ParamServiceAsyncClient::bool_ret_i32_i64_paramT(Protocol_* prot, apache::thrift::RpcOptions rpcOptions, std::shared_ptr<apache::thrift::transport::THeader> header, apache::thrift::ContextStack* contextStack, apache::thrift::RequestClientCallback::Ptr callback, ::std::int32_t p_param1, ::std::int64_t p_param2) {
ParamService_bool_ret_i32_i64_param_pargs args;
args.get<0>().value = &p_param1;
args.get<1>().value = &p_param2;
auto sizer = [&](Protocol_* p) { return args.serializedSizeZC(p); };
auto writer = [&](Protocol_* p) { args.write(p); };
static ::apache::thrift::MethodMetadata::Data* methodMetadata =
new ::apache::thrift::MethodMetadata::Data(
"bool_ret_i32_i64_param",
::apache::thrift::FunctionQualifier::None);
apache::thrift::clientSendT<apache::thrift::RpcKind::SINGLE_REQUEST_SINGLE_RESPONSE, Protocol_>(prot, std::move(rpcOptions), std::move(callback), contextStack, std::move(header), channel_.get(), ::apache::thrift::MethodMetadata::from_static(methodMetadata), writer, sizer);
}
template <typename Protocol_>
void ParamServiceAsyncClient::bool_ret_map_paramT(Protocol_* prot, apache::thrift::RpcOptions rpcOptions, std::shared_ptr<apache::thrift::transport::THeader> header, apache::thrift::ContextStack* contextStack, apache::thrift::RequestClientCallback::Ptr callback, const ::std::map<::std::string, ::std::int64_t>& p_param1) {
ParamService_bool_ret_map_param_pargs args;
args.get<0>().value = const_cast<::std::map<::std::string, ::std::int64_t>*>(&p_param1);
auto sizer = [&](Protocol_* p) { return args.serializedSizeZC(p); };
auto writer = [&](Protocol_* p) { args.write(p); };
static ::apache::thrift::MethodMetadata::Data* methodMetadata =
new ::apache::thrift::MethodMetadata::Data(
"bool_ret_map_param",
::apache::thrift::FunctionQualifier::None);
apache::thrift::clientSendT<apache::thrift::RpcKind::SINGLE_REQUEST_SINGLE_RESPONSE, Protocol_>(prot, std::move(rpcOptions), std::move(callback), contextStack, std::move(header), channel_.get(), ::apache::thrift::MethodMetadata::from_static(methodMetadata), writer, sizer);
}
template <typename Protocol_>
void ParamServiceAsyncClient::bool_ret_union_paramT(Protocol_* prot, apache::thrift::RpcOptions rpcOptions, std::shared_ptr<apache::thrift::transport::THeader> header, apache::thrift::ContextStack* contextStack, apache::thrift::RequestClientCallback::Ptr callback, const ::some::valid::ns::ComplexUnion& p_param1) {
ParamService_bool_ret_union_param_pargs args;
args.get<0>().value = const_cast<::some::valid::ns::ComplexUnion*>(&p_param1);
auto sizer = [&](Protocol_* p) { return args.serializedSizeZC(p); };
auto writer = [&](Protocol_* p) { args.write(p); };
static ::apache::thrift::MethodMetadata::Data* methodMetadata =
new ::apache::thrift::MethodMetadata::Data(
"bool_ret_union_param",
::apache::thrift::FunctionQualifier::None);
apache::thrift::clientSendT<apache::thrift::RpcKind::SINGLE_REQUEST_SINGLE_RESPONSE, Protocol_>(prot, std::move(rpcOptions), std::move(callback), contextStack, std::move(header), channel_.get(), ::apache::thrift::MethodMetadata::from_static(methodMetadata), writer, sizer);
}
template <typename Protocol_>
void ParamServiceAsyncClient::i64_ret_float_double_paramT(Protocol_* prot, apache::thrift::RpcOptions rpcOptions, std::shared_ptr<apache::thrift::transport::THeader> header, apache::thrift::ContextStack* contextStack, apache::thrift::RequestClientCallback::Ptr callback, float p_param1, double p_param2) {
ParamService_i64_ret_float_double_param_pargs args;
args.get<0>().value = &p_param1;
args.get<1>().value = &p_param2;
auto sizer = [&](Protocol_* p) { return args.serializedSizeZC(p); };
auto writer = [&](Protocol_* p) { args.write(p); };
static ::apache::thrift::MethodMetadata::Data* methodMetadata =
new ::apache::thrift::MethodMetadata::Data(
"i64_ret_float_double_param",
::apache::thrift::FunctionQualifier::None);
apache::thrift::clientSendT<apache::thrift::RpcKind::SINGLE_REQUEST_SINGLE_RESPONSE, Protocol_>(prot, std::move(rpcOptions), std::move(callback), contextStack, std::move(header), channel_.get(), ::apache::thrift::MethodMetadata::from_static(methodMetadata), writer, sizer);
}
template <typename Protocol_>
void ParamServiceAsyncClient::i64_ret_string_typedef_paramT(Protocol_* prot, apache::thrift::RpcOptions rpcOptions, std::shared_ptr<apache::thrift::transport::THeader> header, apache::thrift::ContextStack* contextStack, apache::thrift::RequestClientCallback::Ptr callback, const ::std::string& p_param1, const ::std::set<::some::valid::ns::mostComplexTypeDef>& p_param2) {
ParamService_i64_ret_string_typedef_param_pargs args;
args.get<0>().value = const_cast<::std::string*>(&p_param1);
args.get<1>().value = const_cast<::std::set<::some::valid::ns::mostComplexTypeDef>*>(&p_param2);
auto sizer = [&](Protocol_* p) { return args.serializedSizeZC(p); };
auto writer = [&](Protocol_* p) { args.write(p); };
static ::apache::thrift::MethodMetadata::Data* methodMetadata =
new ::apache::thrift::MethodMetadata::Data(
"i64_ret_string_typedef_param",
::apache::thrift::FunctionQualifier::None);
apache::thrift::clientSendT<apache::thrift::RpcKind::SINGLE_REQUEST_SINGLE_RESPONSE, Protocol_>(prot, std::move(rpcOptions), std::move(callback), contextStack, std::move(header), channel_.get(), ::apache::thrift::MethodMetadata::from_static(methodMetadata), writer, sizer);
}
template <typename Protocol_>
void ParamServiceAsyncClient::i64_ret_i32_i32_i32_i32_i32_paramT(Protocol_* prot, apache::thrift::RpcOptions rpcOptions, std::shared_ptr<apache::thrift::transport::THeader> header, apache::thrift::ContextStack* contextStack, apache::thrift::RequestClientCallback::Ptr callback, ::std::int32_t p_param1, ::std::int32_t p_param2, ::std::int32_t p_param3, ::std::int32_t p_param4, ::std::int32_t p_param5) {
ParamService_i64_ret_i32_i32_i32_i32_i32_param_pargs args;
args.get<0>().value = &p_param1;
args.get<1>().value = &p_param2;
args.get<2>().value = &p_param3;
args.get<3>().value = &p_param4;
args.get<4>().value = &p_param5;
auto sizer = [&](Protocol_* p) { return args.serializedSizeZC(p); };
auto writer = [&](Protocol_* p) { args.write(p); };
static ::apache::thrift::MethodMetadata::Data* methodMetadata =
new ::apache::thrift::MethodMetadata::Data(
"i64_ret_i32_i32_i32_i32_i32_param",
::apache::thrift::FunctionQualifier::None);
apache::thrift::clientSendT<apache::thrift::RpcKind::SINGLE_REQUEST_SINGLE_RESPONSE, Protocol_>(prot, std::move(rpcOptions), std::move(callback), contextStack, std::move(header), channel_.get(), ::apache::thrift::MethodMetadata::from_static(methodMetadata), writer, sizer);
}
template <typename Protocol_>
void ParamServiceAsyncClient::double_ret_setstruct_paramT(Protocol_* prot, apache::thrift::RpcOptions rpcOptions, std::shared_ptr<apache::thrift::transport::THeader> header, apache::thrift::ContextStack* contextStack, apache::thrift::RequestClientCallback::Ptr callback, const ::std::set<::some::valid::ns::MyStruct>& p_param1) {
ParamService_double_ret_setstruct_param_pargs args;
args.get<0>().value = const_cast<::std::set<::some::valid::ns::MyStruct>*>(&p_param1);
auto sizer = [&](Protocol_* p) { return args.serializedSizeZC(p); };
auto writer = [&](Protocol_* p) { args.write(p); };
static ::apache::thrift::MethodMetadata::Data* methodMetadata =
new ::apache::thrift::MethodMetadata::Data(
"double_ret_setstruct_param",
::apache::thrift::FunctionQualifier::None);
apache::thrift::clientSendT<apache::thrift::RpcKind::SINGLE_REQUEST_SINGLE_RESPONSE, Protocol_>(prot, std::move(rpcOptions), std::move(callback), contextStack, std::move(header), channel_.get(), ::apache::thrift::MethodMetadata::from_static(methodMetadata), writer, sizer);
}
template <typename Protocol_>
void ParamServiceAsyncClient::string_ret_string_paramT(Protocol_* prot, apache::thrift::RpcOptions rpcOptions, std::shared_ptr<apache::thrift::transport::THeader> header, apache::thrift::ContextStack* contextStack, apache::thrift::RequestClientCallback::Ptr callback, const ::std::string& p_param1) {
ParamService_string_ret_string_param_pargs args;
args.get<0>().value = const_cast<::std::string*>(&p_param1);
auto sizer = [&](Protocol_* p) { return args.serializedSizeZC(p); };
auto writer = [&](Protocol_* p) { args.write(p); };
static ::apache::thrift::MethodMetadata::Data* methodMetadata =
new ::apache::thrift::MethodMetadata::Data(
"string_ret_string_param",
::apache::thrift::FunctionQualifier::None);
apache::thrift::clientSendT<apache::thrift::RpcKind::SINGLE_REQUEST_SINGLE_RESPONSE, Protocol_>(prot, std::move(rpcOptions), std::move(callback), contextStack, std::move(header), channel_.get(), ::apache::thrift::MethodMetadata::from_static(methodMetadata), writer, sizer);
}
template <typename Protocol_>
void ParamServiceAsyncClient::binary_ret_binary_paramT(Protocol_* prot, apache::thrift::RpcOptions rpcOptions, std::shared_ptr<apache::thrift::transport::THeader> header, apache::thrift::ContextStack* contextStack, apache::thrift::RequestClientCallback::Ptr callback, const ::std::string& p_param1) {
ParamService_binary_ret_binary_param_pargs args;
args.get<0>().value = const_cast<::std::string*>(&p_param1);
auto sizer = [&](Protocol_* p) { return args.serializedSizeZC(p); };
auto writer = [&](Protocol_* p) { args.write(p); };
static ::apache::thrift::MethodMetadata::Data* methodMetadata =
new ::apache::thrift::MethodMetadata::Data(
"binary_ret_binary_param",
::apache::thrift::FunctionQualifier::None);
apache::thrift::clientSendT<apache::thrift::RpcKind::SINGLE_REQUEST_SINGLE_RESPONSE, Protocol_>(prot, std::move(rpcOptions), std::move(callback), contextStack, std::move(header), channel_.get(), ::apache::thrift::MethodMetadata::from_static(methodMetadata), writer, sizer);
}
template <typename Protocol_>
void ParamServiceAsyncClient::map_ret_bool_paramT(Protocol_* prot, apache::thrift::RpcOptions rpcOptions, std::shared_ptr<apache::thrift::transport::THeader> header, apache::thrift::ContextStack* contextStack, apache::thrift::RequestClientCallback::Ptr callback, bool p_param1) {
ParamService_map_ret_bool_param_pargs args;
args.get<0>().value = &p_param1;
auto sizer = [&](Protocol_* p) { return args.serializedSizeZC(p); };
auto writer = [&](Protocol_* p) { args.write(p); };
static ::apache::thrift::MethodMetadata::Data* methodMetadata =
new ::apache::thrift::MethodMetadata::Data(
"map_ret_bool_param",
::apache::thrift::FunctionQualifier::None);
apache::thrift::clientSendT<apache::thrift::RpcKind::SINGLE_REQUEST_SINGLE_RESPONSE, Protocol_>(prot, std::move(rpcOptions), std::move(callback), contextStack, std::move(header), channel_.get(), ::apache::thrift::MethodMetadata::from_static(methodMetadata), writer, sizer);
}
template <typename Protocol_>
void ParamServiceAsyncClient::list_ret_map_setlist_paramT(Protocol_* prot, apache::thrift::RpcOptions rpcOptions, std::shared_ptr<apache::thrift::transport::THeader> header, apache::thrift::ContextStack* contextStack, apache::thrift::RequestClientCallback::Ptr callback, const ::std::map<::std::int32_t, ::std::vector<::std::string>>& p_param1, const ::std::vector<::std::string>& p_param2) {
ParamService_list_ret_map_setlist_param_pargs args;
args.get<0>().value = const_cast<::std::map<::std::int32_t, ::std::vector<::std::string>>*>(&p_param1);
args.get<1>().value = const_cast<::std::vector<::std::string>*>(&p_param2);
auto sizer = [&](Protocol_* p) { return args.serializedSizeZC(p); };
auto writer = [&](Protocol_* p) { args.write(p); };
static ::apache::thrift::MethodMetadata::Data* methodMetadata =
new ::apache::thrift::MethodMetadata::Data(
"list_ret_map_setlist_param",
::apache::thrift::FunctionQualifier::None);
apache::thrift::clientSendT<apache::thrift::RpcKind::SINGLE_REQUEST_SINGLE_RESPONSE, Protocol_>(prot, std::move(rpcOptions), std::move(callback), contextStack, std::move(header), channel_.get(), ::apache::thrift::MethodMetadata::from_static(methodMetadata), writer, sizer);
}
template <typename Protocol_>
void ParamServiceAsyncClient::mapsetlistmapliststring_ret_listlistlist_paramT(Protocol_* prot, apache::thrift::RpcOptions rpcOptions, std::shared_ptr<apache::thrift::transport::THeader> header, apache::thrift::ContextStack* contextStack, apache::thrift::RequestClientCallback::Ptr callback, const ::std::vector<::std::vector<::std::vector<::std::vector<::std::int32_t>>>>& p_param1) {
ParamService_mapsetlistmapliststring_ret_listlistlist_param_pargs args;
args.get<0>().value = const_cast<::std::vector<::std::vector<::std::vector<::std::vector<::std::int32_t>>>>*>(&p_param1);
auto sizer = [&](Protocol_* p) { return args.serializedSizeZC(p); };
auto writer = [&](Protocol_* p) { args.write(p); };
static ::apache::thrift::MethodMetadata::Data* methodMetadata =
new ::apache::thrift::MethodMetadata::Data(
"mapsetlistmapliststring_ret_listlistlist_param",
::apache::thrift::FunctionQualifier::None);
apache::thrift::clientSendT<apache::thrift::RpcKind::SINGLE_REQUEST_SINGLE_RESPONSE, Protocol_>(prot, std::move(rpcOptions), std::move(callback), contextStack, std::move(header), channel_.get(), ::apache::thrift::MethodMetadata::from_static(methodMetadata), writer, sizer);
}
template <typename Protocol_>
void ParamServiceAsyncClient::typedef_ret_i32_paramT(Protocol_* prot, apache::thrift::RpcOptions rpcOptions, std::shared_ptr<apache::thrift::transport::THeader> header, apache::thrift::ContextStack* contextStack, apache::thrift::RequestClientCallback::Ptr callback, ::std::int32_t p_param1) {
ParamService_typedef_ret_i32_param_pargs args;
args.get<0>().value = &p_param1;
auto sizer = [&](Protocol_* p) { return args.serializedSizeZC(p); };
auto writer = [&](Protocol_* p) { args.write(p); };
static ::apache::thrift::MethodMetadata::Data* methodMetadata =
new ::apache::thrift::MethodMetadata::Data(
"typedef_ret_i32_param",
::apache::thrift::FunctionQualifier::None);
apache::thrift::clientSendT<apache::thrift::RpcKind::SINGLE_REQUEST_SINGLE_RESPONSE, Protocol_>(prot, std::move(rpcOptions), std::move(callback), contextStack, std::move(header), channel_.get(), ::apache::thrift::MethodMetadata::from_static(methodMetadata), writer, sizer);
}
template <typename Protocol_>
void ParamServiceAsyncClient::listtypedef_ret_typedef_paramT(Protocol_* prot, apache::thrift::RpcOptions rpcOptions, std::shared_ptr<apache::thrift::transport::THeader> header, apache::thrift::ContextStack* contextStack, apache::thrift::RequestClientCallback::Ptr callback, const ::some::valid::ns::complexStructTypeDef& p_param1) {
ParamService_listtypedef_ret_typedef_param_pargs args;
args.get<0>().value = const_cast<::some::valid::ns::complexStructTypeDef*>(&p_param1);
auto sizer = [&](Protocol_* p) { return args.serializedSizeZC(p); };
auto writer = [&](Protocol_* p) { args.write(p); };
static ::apache::thrift::MethodMetadata::Data* methodMetadata =
new ::apache::thrift::MethodMetadata::Data(
"listtypedef_ret_typedef_param",
::apache::thrift::FunctionQualifier::None);
apache::thrift::clientSendT<apache::thrift::RpcKind::SINGLE_REQUEST_SINGLE_RESPONSE, Protocol_>(prot, std::move(rpcOptions), std::move(callback), contextStack, std::move(header), channel_.get(), ::apache::thrift::MethodMetadata::from_static(methodMetadata), writer, sizer);
}
template <typename Protocol_>
void ParamServiceAsyncClient::enum_ret_double_paramT(Protocol_* prot, apache::thrift::RpcOptions rpcOptions, std::shared_ptr<apache::thrift::transport::THeader> header, apache::thrift::ContextStack* contextStack, apache::thrift::RequestClientCallback::Ptr callback, double p_param1) {
ParamService_enum_ret_double_param_pargs args;
args.get<0>().value = &p_param1;
auto sizer = [&](Protocol_* p) { return args.serializedSizeZC(p); };
auto writer = [&](Protocol_* p) { args.write(p); };
static ::apache::thrift::MethodMetadata::Data* methodMetadata =
new ::apache::thrift::MethodMetadata::Data(
"enum_ret_double_param",
::apache::thrift::FunctionQualifier::None);
apache::thrift::clientSendT<apache::thrift::RpcKind::SINGLE_REQUEST_SINGLE_RESPONSE, Protocol_>(prot, std::move(rpcOptions), std::move(callback), contextStack, std::move(header), channel_.get(), ::apache::thrift::MethodMetadata::from_static(methodMetadata), writer, sizer);
}
template <typename Protocol_>
void ParamServiceAsyncClient::enum_ret_double_enum_paramT(Protocol_* prot, apache::thrift::RpcOptions rpcOptions, std::shared_ptr<apache::thrift::transport::THeader> header, apache::thrift::ContextStack* contextStack, apache::thrift::RequestClientCallback::Ptr callback, double p_param1, ::some::valid::ns::MyEnumA p_param2) {
ParamService_enum_ret_double_enum_param_pargs args;
args.get<0>().value = &p_param1;
args.get<1>().value = &p_param2;
auto sizer = [&](Protocol_* p) { return args.serializedSizeZC(p); };
auto writer = [&](Protocol_* p) { args.write(p); };
static ::apache::thrift::MethodMetadata::Data* methodMetadata =
new ::apache::thrift::MethodMetadata::Data(
"enum_ret_double_enum_param",
::apache::thrift::FunctionQualifier::None);
apache::thrift::clientSendT<apache::thrift::RpcKind::SINGLE_REQUEST_SINGLE_RESPONSE, Protocol_>(prot, std::move(rpcOptions), std::move(callback), contextStack, std::move(header), channel_.get(), ::apache::thrift::MethodMetadata::from_static(methodMetadata), writer, sizer);
}
template <typename Protocol_>
void ParamServiceAsyncClient::listenum_ret_map_paramT(Protocol_* prot, apache::thrift::RpcOptions rpcOptions, std::shared_ptr<apache::thrift::transport::THeader> header, apache::thrift::ContextStack* contextStack, apache::thrift::RequestClientCallback::Ptr callback, const ::std::map<::std::string, ::std::int64_t>& p_param1) {
ParamService_listenum_ret_map_param_pargs args;
args.get<0>().value = const_cast<::std::map<::std::string, ::std::int64_t>*>(&p_param1);
auto sizer = [&](Protocol_* p) { return args.serializedSizeZC(p); };
auto writer = [&](Protocol_* p) { args.write(p); };
static ::apache::thrift::MethodMetadata::Data* methodMetadata =
new ::apache::thrift::MethodMetadata::Data(
"listenum_ret_map_param",
::apache::thrift::FunctionQualifier::None);
apache::thrift::clientSendT<apache::thrift::RpcKind::SINGLE_REQUEST_SINGLE_RESPONSE, Protocol_>(prot, std::move(rpcOptions), std::move(callback), contextStack, std::move(header), channel_.get(), ::apache::thrift::MethodMetadata::from_static(methodMetadata), writer, sizer);
}
template <typename Protocol_>
void ParamServiceAsyncClient::struct_ret_i16_paramT(Protocol_* prot, apache::thrift::RpcOptions rpcOptions, std::shared_ptr<apache::thrift::transport::THeader> header, apache::thrift::ContextStack* contextStack, apache::thrift::RequestClientCallback::Ptr callback, ::std::int16_t p_param1) {
ParamService_struct_ret_i16_param_pargs args;
args.get<0>().value = &p_param1;
auto sizer = [&](Protocol_* p) { return args.serializedSizeZC(p); };
auto writer = [&](Protocol_* p) { args.write(p); };
static ::apache::thrift::MethodMetadata::Data* methodMetadata =
new ::apache::thrift::MethodMetadata::Data(
"struct_ret_i16_param",
::apache::thrift::FunctionQualifier::None);
apache::thrift::clientSendT<apache::thrift::RpcKind::SINGLE_REQUEST_SINGLE_RESPONSE, Protocol_>(prot, std::move(rpcOptions), std::move(callback), contextStack, std::move(header), channel_.get(), ::apache::thrift::MethodMetadata::from_static(methodMetadata), writer, sizer);
}
template <typename Protocol_>
void ParamServiceAsyncClient::setstruct_ret_set_paramT(Protocol_* prot, apache::thrift::RpcOptions rpcOptions, std::shared_ptr<apache::thrift::transport::THeader> header, apache::thrift::ContextStack* contextStack, apache::thrift::RequestClientCallback::Ptr callback, const ::std::set<::std::string>& p_param1) {
ParamService_setstruct_ret_set_param_pargs args;
args.get<0>().value = const_cast<::std::set<::std::string>*>(&p_param1);
auto sizer = [&](Protocol_* p) { return args.serializedSizeZC(p); };
auto writer = [&](Protocol_* p) { args.write(p); };
static ::apache::thrift::MethodMetadata::Data* methodMetadata =
new ::apache::thrift::MethodMetadata::Data(
"setstruct_ret_set_param",
::apache::thrift::FunctionQualifier::None);
apache::thrift::clientSendT<apache::thrift::RpcKind::SINGLE_REQUEST_SINGLE_RESPONSE, Protocol_>(prot, std::move(rpcOptions), std::move(callback), contextStack, std::move(header), channel_.get(), ::apache::thrift::MethodMetadata::from_static(methodMetadata), writer, sizer);
}
template <typename Protocol_>
void ParamServiceAsyncClient::union_ret_i32_i32_paramT(Protocol_* prot, apache::thrift::RpcOptions rpcOptions, std::shared_ptr<apache::thrift::transport::THeader> header, apache::thrift::ContextStack* contextStack, apache::thrift::RequestClientCallback::Ptr callback, ::std::int32_t p_param1, ::std::int32_t p_param2) {
ParamService_union_ret_i32_i32_param_pargs args;
args.get<0>().value = &p_param1;
args.get<1>().value = &p_param2;
auto sizer = [&](Protocol_* p) { return args.serializedSizeZC(p); };
auto writer = [&](Protocol_* p) { args.write(p); };
static ::apache::thrift::MethodMetadata::Data* methodMetadata =
new ::apache::thrift::MethodMetadata::Data(
"union_ret_i32_i32_param",
::apache::thrift::FunctionQualifier::None);
apache::thrift::clientSendT<apache::thrift::RpcKind::SINGLE_REQUEST_SINGLE_RESPONSE, Protocol_>(prot, std::move(rpcOptions), std::move(callback), contextStack, std::move(header), channel_.get(), ::apache::thrift::MethodMetadata::from_static(methodMetadata), writer, sizer);
}
template <typename Protocol_>
void ParamServiceAsyncClient::listunion_string_paramT(Protocol_* prot, apache::thrift::RpcOptions rpcOptions, std::shared_ptr<apache::thrift::transport::THeader> header, apache::thrift::ContextStack* contextStack, apache::thrift::RequestClientCallback::Ptr callback, const ::std::string& p_param1) {
ParamService_listunion_string_param_pargs args;
args.get<0>().value = const_cast<::std::string*>(&p_param1);
auto sizer = [&](Protocol_* p) { return args.serializedSizeZC(p); };
auto writer = [&](Protocol_* p) { args.write(p); };
static ::apache::thrift::MethodMetadata::Data* methodMetadata =
new ::apache::thrift::MethodMetadata::Data(
"listunion_string_param",
::apache::thrift::FunctionQualifier::None);
apache::thrift::clientSendT<apache::thrift::RpcKind::SINGLE_REQUEST_SINGLE_RESPONSE, Protocol_>(prot, std::move(rpcOptions), std::move(callback), contextStack, std::move(header), channel_.get(), ::apache::thrift::MethodMetadata::from_static(methodMetadata), writer, sizer);
}
void ParamServiceAsyncClient::void_ret_i16_param(std::unique_ptr<apache::thrift::RequestCallback> callback, ::std::int16_t p_param1) {
::apache::thrift::RpcOptions rpcOptions;
void_ret_i16_param(rpcOptions, std::move(callback), p_param1);
}
void ParamServiceAsyncClient::void_ret_i16_param(apache::thrift::RpcOptions& rpcOptions, std::unique_ptr<apache::thrift::RequestCallback> callback, ::std::int16_t p_param1) {
auto [ctx, header] = void_ret_i16_paramCtx(&rpcOptions);
apache::thrift::RequestCallback::Context callbackContext;
callbackContext.protocolId =
apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId();
auto* contextStack = ctx.get();
if (callback) {
callbackContext.ctx = std::move(ctx);
}
auto wrappedCallback = apache::thrift::toRequestClientCallbackPtr(std::move(callback), std::move(callbackContext));
void_ret_i16_paramImpl(rpcOptions, std::move(header), contextStack, std::move(wrappedCallback), p_param1);
}
void ParamServiceAsyncClient::void_ret_i16_paramImpl(const apache::thrift::RpcOptions& rpcOptions, std::shared_ptr<apache::thrift::transport::THeader> header, apache::thrift::ContextStack* contextStack, apache::thrift::RequestClientCallback::Ptr callback, ::std::int16_t p_param1) {
switch (apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId()) {
case apache::thrift::protocol::T_BINARY_PROTOCOL:
{
apache::thrift::BinaryProtocolWriter writer;
void_ret_i16_paramT(&writer, rpcOptions, std::move(header), contextStack, std::move(callback), p_param1);
break;
}
case apache::thrift::protocol::T_COMPACT_PROTOCOL:
{
apache::thrift::CompactProtocolWriter writer;
void_ret_i16_paramT(&writer, rpcOptions, std::move(header), contextStack, std::move(callback), p_param1);
break;
}
default:
{
apache::thrift::detail::ac::throw_app_exn("Could not find Protocol");
}
}
}
std::pair<std::unique_ptr<::apache::thrift::ContextStack>, std::shared_ptr<::apache::thrift::transport::THeader>> ParamServiceAsyncClient::void_ret_i16_paramCtx(apache::thrift::RpcOptions* rpcOptions) {
auto header = std::make_shared<apache::thrift::transport::THeader>(
apache::thrift::transport::THeader::ALLOW_BIG_FRAMES);
header->setProtocolId(channel_->getProtocolId());
if (rpcOptions) {
header->setHeaders(rpcOptions->releaseWriteHeaders());
}
auto ctx = apache::thrift::ContextStack::createWithClientContext(
handlers_,
getServiceName(),
"ParamService.void_ret_i16_param",
*header);
return {std::move(ctx), std::move(header)};
}
void ParamServiceAsyncClient::sync_void_ret_i16_param(::std::int16_t p_param1) {
::apache::thrift::RpcOptions rpcOptions;
sync_void_ret_i16_param(rpcOptions, p_param1);
}
void ParamServiceAsyncClient::sync_void_ret_i16_param(apache::thrift::RpcOptions& rpcOptions, ::std::int16_t p_param1) {
apache::thrift::ClientReceiveState returnState;
apache::thrift::ClientSyncCallback<false> callback(&returnState);
auto protocolId = apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId();
auto evb = apache::thrift::GeneratedAsyncClient::getChannel()->getEventBase();
auto [ctx, header] = void_ret_i16_paramCtx(&rpcOptions);
auto wrappedCallback = apache::thrift::RequestClientCallback::Ptr(&callback);
void_ret_i16_paramImpl(rpcOptions, std::move(header), ctx.get(), std::move(wrappedCallback), p_param1);
callback.waitUntilDone(evb);
if (returnState.isException()) {
returnState.exception().throw_exception();
}
returnState.resetProtocolId(protocolId);
returnState.resetCtx(std::move(ctx));
SCOPE_EXIT {
if (returnState.header() && !returnState.header()->getHeaders().empty()) {
rpcOptions.setReadHeaders(returnState.header()->releaseHeaders());
}
};
return folly::fibers::runInMainContext([&] {
recv_void_ret_i16_param(returnState);
});
}
folly::Future<folly::Unit> ParamServiceAsyncClient::future_void_ret_i16_param(::std::int16_t p_param1) {
::apache::thrift::RpcOptions rpcOptions;
return future_void_ret_i16_param(rpcOptions, p_param1);
}
folly::SemiFuture<folly::Unit> ParamServiceAsyncClient::semifuture_void_ret_i16_param(::std::int16_t p_param1) {
::apache::thrift::RpcOptions rpcOptions;
return semifuture_void_ret_i16_param(rpcOptions, p_param1);
}
folly::Future<folly::Unit> ParamServiceAsyncClient::future_void_ret_i16_param(apache::thrift::RpcOptions& rpcOptions, ::std::int16_t p_param1) {
folly::Promise<folly::Unit> promise;
auto future = promise.getFuture();
auto callback = std::make_unique<apache::thrift::FutureCallback<folly::Unit>>(std::move(promise), recv_wrapped_void_ret_i16_param, channel_);
void_ret_i16_param(rpcOptions, std::move(callback), p_param1);
return future;
}
folly::SemiFuture<folly::Unit> ParamServiceAsyncClient::semifuture_void_ret_i16_param(apache::thrift::RpcOptions& rpcOptions, ::std::int16_t p_param1) {
auto callbackAndFuture = makeSemiFutureCallback(recv_wrapped_void_ret_i16_param, channel_);
auto callback = std::move(callbackAndFuture.first);
void_ret_i16_param(rpcOptions, std::move(callback), p_param1);
return std::move(callbackAndFuture.second);
}
folly::Future<std::pair<folly::Unit, std::unique_ptr<apache::thrift::transport::THeader>>> ParamServiceAsyncClient::header_future_void_ret_i16_param(apache::thrift::RpcOptions& rpcOptions, ::std::int16_t p_param1) {
folly::Promise<std::pair<folly::Unit, std::unique_ptr<apache::thrift::transport::THeader>>> promise;
auto future = promise.getFuture();
auto callback = std::make_unique<apache::thrift::HeaderFutureCallback<folly::Unit>>(std::move(promise), recv_wrapped_void_ret_i16_param, channel_);
void_ret_i16_param(rpcOptions, std::move(callback), p_param1);
return future;
}
folly::SemiFuture<std::pair<folly::Unit, std::unique_ptr<apache::thrift::transport::THeader>>> ParamServiceAsyncClient::header_semifuture_void_ret_i16_param(apache::thrift::RpcOptions& rpcOptions, ::std::int16_t p_param1) {
auto callbackAndFuture = makeHeaderSemiFutureCallback(recv_wrapped_void_ret_i16_param, channel_);
auto callback = std::move(callbackAndFuture.first);
void_ret_i16_param(rpcOptions, std::move(callback), p_param1);
return std::move(callbackAndFuture.second);
}
void ParamServiceAsyncClient::void_ret_i16_param(folly::Function<void (::apache::thrift::ClientReceiveState&&)> callback, ::std::int16_t p_param1) {
void_ret_i16_param(std::make_unique<apache::thrift::FunctionReplyCallback>(std::move(callback)), p_param1);
}
#if FOLLY_HAS_COROUTINES
#endif // FOLLY_HAS_COROUTINES
folly::exception_wrapper ParamServiceAsyncClient::recv_wrapped_void_ret_i16_param(::apache::thrift::ClientReceiveState& state) {
if (state.isException()) {
return std::move(state.exception());
}
if (!state.hasResponseBuffer()) {
return folly::make_exception_wrapper<apache::thrift::TApplicationException>("recv_ called without result");
}
using result = ParamService_void_ret_i16_param_presult;
switch (state.protocolId()) {
case apache::thrift::protocol::T_BINARY_PROTOCOL:
{
apache::thrift::BinaryProtocolReader reader;
return apache::thrift::detail::ac::recv_wrapped<result>(
&reader, state);
}
case apache::thrift::protocol::T_COMPACT_PROTOCOL:
{
apache::thrift::CompactProtocolReader reader;
return apache::thrift::detail::ac::recv_wrapped<result>(
&reader, state);
}
default:
{
}
}
return folly::make_exception_wrapper<apache::thrift::TApplicationException>("Could not find Protocol");
}
void ParamServiceAsyncClient::recv_void_ret_i16_param(::apache::thrift::ClientReceiveState& state) {
auto ew = recv_wrapped_void_ret_i16_param(state);
if (ew) {
ew.throw_exception();
}
}
void ParamServiceAsyncClient::recv_instance_void_ret_i16_param(::apache::thrift::ClientReceiveState& state) {
recv_void_ret_i16_param(state);
}
folly::exception_wrapper ParamServiceAsyncClient::recv_instance_wrapped_void_ret_i16_param(::apache::thrift::ClientReceiveState& state) {
return recv_wrapped_void_ret_i16_param(state);
}
void ParamServiceAsyncClient::void_ret_byte_i16_param(std::unique_ptr<apache::thrift::RequestCallback> callback, ::std::int8_t p_param1, ::std::int16_t p_param2) {
::apache::thrift::RpcOptions rpcOptions;
void_ret_byte_i16_param(rpcOptions, std::move(callback), p_param1, p_param2);
}
void ParamServiceAsyncClient::void_ret_byte_i16_param(apache::thrift::RpcOptions& rpcOptions, std::unique_ptr<apache::thrift::RequestCallback> callback, ::std::int8_t p_param1, ::std::int16_t p_param2) {
auto [ctx, header] = void_ret_byte_i16_paramCtx(&rpcOptions);
apache::thrift::RequestCallback::Context callbackContext;
callbackContext.protocolId =
apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId();
auto* contextStack = ctx.get();
if (callback) {
callbackContext.ctx = std::move(ctx);
}
auto wrappedCallback = apache::thrift::toRequestClientCallbackPtr(std::move(callback), std::move(callbackContext));
void_ret_byte_i16_paramImpl(rpcOptions, std::move(header), contextStack, std::move(wrappedCallback), p_param1, p_param2);
}
void ParamServiceAsyncClient::void_ret_byte_i16_paramImpl(const apache::thrift::RpcOptions& rpcOptions, std::shared_ptr<apache::thrift::transport::THeader> header, apache::thrift::ContextStack* contextStack, apache::thrift::RequestClientCallback::Ptr callback, ::std::int8_t p_param1, ::std::int16_t p_param2) {
switch (apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId()) {
case apache::thrift::protocol::T_BINARY_PROTOCOL:
{
apache::thrift::BinaryProtocolWriter writer;
void_ret_byte_i16_paramT(&writer, rpcOptions, std::move(header), contextStack, std::move(callback), p_param1, p_param2);
break;
}
case apache::thrift::protocol::T_COMPACT_PROTOCOL:
{
apache::thrift::CompactProtocolWriter writer;
void_ret_byte_i16_paramT(&writer, rpcOptions, std::move(header), contextStack, std::move(callback), p_param1, p_param2);
break;
}
default:
{
apache::thrift::detail::ac::throw_app_exn("Could not find Protocol");
}
}
}
std::pair<std::unique_ptr<::apache::thrift::ContextStack>, std::shared_ptr<::apache::thrift::transport::THeader>> ParamServiceAsyncClient::void_ret_byte_i16_paramCtx(apache::thrift::RpcOptions* rpcOptions) {
auto header = std::make_shared<apache::thrift::transport::THeader>(
apache::thrift::transport::THeader::ALLOW_BIG_FRAMES);
header->setProtocolId(channel_->getProtocolId());
if (rpcOptions) {
header->setHeaders(rpcOptions->releaseWriteHeaders());
}
auto ctx = apache::thrift::ContextStack::createWithClientContext(
handlers_,
getServiceName(),
"ParamService.void_ret_byte_i16_param",
*header);
return {std::move(ctx), std::move(header)};
}
void ParamServiceAsyncClient::sync_void_ret_byte_i16_param(::std::int8_t p_param1, ::std::int16_t p_param2) {
::apache::thrift::RpcOptions rpcOptions;
sync_void_ret_byte_i16_param(rpcOptions, p_param1, p_param2);
}
void ParamServiceAsyncClient::sync_void_ret_byte_i16_param(apache::thrift::RpcOptions& rpcOptions, ::std::int8_t p_param1, ::std::int16_t p_param2) {
apache::thrift::ClientReceiveState returnState;
apache::thrift::ClientSyncCallback<false> callback(&returnState);
auto protocolId = apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId();
auto evb = apache::thrift::GeneratedAsyncClient::getChannel()->getEventBase();
auto [ctx, header] = void_ret_byte_i16_paramCtx(&rpcOptions);
auto wrappedCallback = apache::thrift::RequestClientCallback::Ptr(&callback);
void_ret_byte_i16_paramImpl(rpcOptions, std::move(header), ctx.get(), std::move(wrappedCallback), p_param1, p_param2);
callback.waitUntilDone(evb);
if (returnState.isException()) {
returnState.exception().throw_exception();
}
returnState.resetProtocolId(protocolId);
returnState.resetCtx(std::move(ctx));
SCOPE_EXIT {
if (returnState.header() && !returnState.header()->getHeaders().empty()) {
rpcOptions.setReadHeaders(returnState.header()->releaseHeaders());
}
};
return folly::fibers::runInMainContext([&] {
recv_void_ret_byte_i16_param(returnState);
});
}
folly::Future<folly::Unit> ParamServiceAsyncClient::future_void_ret_byte_i16_param(::std::int8_t p_param1, ::std::int16_t p_param2) {
::apache::thrift::RpcOptions rpcOptions;
return future_void_ret_byte_i16_param(rpcOptions, p_param1, p_param2);
}
folly::SemiFuture<folly::Unit> ParamServiceAsyncClient::semifuture_void_ret_byte_i16_param(::std::int8_t p_param1, ::std::int16_t p_param2) {
::apache::thrift::RpcOptions rpcOptions;
return semifuture_void_ret_byte_i16_param(rpcOptions, p_param1, p_param2);
}
folly::Future<folly::Unit> ParamServiceAsyncClient::future_void_ret_byte_i16_param(apache::thrift::RpcOptions& rpcOptions, ::std::int8_t p_param1, ::std::int16_t p_param2) {
folly::Promise<folly::Unit> promise;
auto future = promise.getFuture();
auto callback = std::make_unique<apache::thrift::FutureCallback<folly::Unit>>(std::move(promise), recv_wrapped_void_ret_byte_i16_param, channel_);
void_ret_byte_i16_param(rpcOptions, std::move(callback), p_param1, p_param2);
return future;
}
folly::SemiFuture<folly::Unit> ParamServiceAsyncClient::semifuture_void_ret_byte_i16_param(apache::thrift::RpcOptions& rpcOptions, ::std::int8_t p_param1, ::std::int16_t p_param2) {
auto callbackAndFuture = makeSemiFutureCallback(recv_wrapped_void_ret_byte_i16_param, channel_);
auto callback = std::move(callbackAndFuture.first);
void_ret_byte_i16_param(rpcOptions, std::move(callback), p_param1, p_param2);
return std::move(callbackAndFuture.second);
}
folly::Future<std::pair<folly::Unit, std::unique_ptr<apache::thrift::transport::THeader>>> ParamServiceAsyncClient::header_future_void_ret_byte_i16_param(apache::thrift::RpcOptions& rpcOptions, ::std::int8_t p_param1, ::std::int16_t p_param2) {
folly::Promise<std::pair<folly::Unit, std::unique_ptr<apache::thrift::transport::THeader>>> promise;
auto future = promise.getFuture();
auto callback = std::make_unique<apache::thrift::HeaderFutureCallback<folly::Unit>>(std::move(promise), recv_wrapped_void_ret_byte_i16_param, channel_);
void_ret_byte_i16_param(rpcOptions, std::move(callback), p_param1, p_param2);
return future;
}
folly::SemiFuture<std::pair<folly::Unit, std::unique_ptr<apache::thrift::transport::THeader>>> ParamServiceAsyncClient::header_semifuture_void_ret_byte_i16_param(apache::thrift::RpcOptions& rpcOptions, ::std::int8_t p_param1, ::std::int16_t p_param2) {
auto callbackAndFuture = makeHeaderSemiFutureCallback(recv_wrapped_void_ret_byte_i16_param, channel_);
auto callback = std::move(callbackAndFuture.first);
void_ret_byte_i16_param(rpcOptions, std::move(callback), p_param1, p_param2);
return std::move(callbackAndFuture.second);
}
void ParamServiceAsyncClient::void_ret_byte_i16_param(folly::Function<void (::apache::thrift::ClientReceiveState&&)> callback, ::std::int8_t p_param1, ::std::int16_t p_param2) {
void_ret_byte_i16_param(std::make_unique<apache::thrift::FunctionReplyCallback>(std::move(callback)), p_param1, p_param2);
}
#if FOLLY_HAS_COROUTINES
#endif // FOLLY_HAS_COROUTINES
folly::exception_wrapper ParamServiceAsyncClient::recv_wrapped_void_ret_byte_i16_param(::apache::thrift::ClientReceiveState& state) {
if (state.isException()) {
return std::move(state.exception());
}
if (!state.hasResponseBuffer()) {
return folly::make_exception_wrapper<apache::thrift::TApplicationException>("recv_ called without result");
}
using result = ParamService_void_ret_byte_i16_param_presult;
switch (state.protocolId()) {
case apache::thrift::protocol::T_BINARY_PROTOCOL:
{
apache::thrift::BinaryProtocolReader reader;
return apache::thrift::detail::ac::recv_wrapped<result>(
&reader, state);
}
case apache::thrift::protocol::T_COMPACT_PROTOCOL:
{
apache::thrift::CompactProtocolReader reader;
return apache::thrift::detail::ac::recv_wrapped<result>(
&reader, state);
}
default:
{
}
}
return folly::make_exception_wrapper<apache::thrift::TApplicationException>("Could not find Protocol");
}
void ParamServiceAsyncClient::recv_void_ret_byte_i16_param(::apache::thrift::ClientReceiveState& state) {
auto ew = recv_wrapped_void_ret_byte_i16_param(state);
if (ew) {
ew.throw_exception();
}
}
void ParamServiceAsyncClient::recv_instance_void_ret_byte_i16_param(::apache::thrift::ClientReceiveState& state) {
recv_void_ret_byte_i16_param(state);
}
folly::exception_wrapper ParamServiceAsyncClient::recv_instance_wrapped_void_ret_byte_i16_param(::apache::thrift::ClientReceiveState& state) {
return recv_wrapped_void_ret_byte_i16_param(state);
}
void ParamServiceAsyncClient::void_ret_map_param(std::unique_ptr<apache::thrift::RequestCallback> callback, const ::std::map<::std::string, ::std::int64_t>& p_param1) {
::apache::thrift::RpcOptions rpcOptions;
void_ret_map_param(rpcOptions, std::move(callback), p_param1);
}
void ParamServiceAsyncClient::void_ret_map_param(apache::thrift::RpcOptions& rpcOptions, std::unique_ptr<apache::thrift::RequestCallback> callback, const ::std::map<::std::string, ::std::int64_t>& p_param1) {
auto [ctx, header] = void_ret_map_paramCtx(&rpcOptions);
apache::thrift::RequestCallback::Context callbackContext;
callbackContext.protocolId =
apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId();
auto* contextStack = ctx.get();
if (callback) {
callbackContext.ctx = std::move(ctx);
}
auto wrappedCallback = apache::thrift::toRequestClientCallbackPtr(std::move(callback), std::move(callbackContext));
void_ret_map_paramImpl(rpcOptions, std::move(header), contextStack, std::move(wrappedCallback), p_param1);
}
void ParamServiceAsyncClient::void_ret_map_paramImpl(const apache::thrift::RpcOptions& rpcOptions, std::shared_ptr<apache::thrift::transport::THeader> header, apache::thrift::ContextStack* contextStack, apache::thrift::RequestClientCallback::Ptr callback, const ::std::map<::std::string, ::std::int64_t>& p_param1) {
switch (apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId()) {
case apache::thrift::protocol::T_BINARY_PROTOCOL:
{
apache::thrift::BinaryProtocolWriter writer;
void_ret_map_paramT(&writer, rpcOptions, std::move(header), contextStack, std::move(callback), p_param1);
break;
}
case apache::thrift::protocol::T_COMPACT_PROTOCOL:
{
apache::thrift::CompactProtocolWriter writer;
void_ret_map_paramT(&writer, rpcOptions, std::move(header), contextStack, std::move(callback), p_param1);
break;
}
default:
{
apache::thrift::detail::ac::throw_app_exn("Could not find Protocol");
}
}
}
std::pair<std::unique_ptr<::apache::thrift::ContextStack>, std::shared_ptr<::apache::thrift::transport::THeader>> ParamServiceAsyncClient::void_ret_map_paramCtx(apache::thrift::RpcOptions* rpcOptions) {
auto header = std::make_shared<apache::thrift::transport::THeader>(
apache::thrift::transport::THeader::ALLOW_BIG_FRAMES);
header->setProtocolId(channel_->getProtocolId());
if (rpcOptions) {
header->setHeaders(rpcOptions->releaseWriteHeaders());
}
auto ctx = apache::thrift::ContextStack::createWithClientContext(
handlers_,
getServiceName(),
"ParamService.void_ret_map_param",
*header);
return {std::move(ctx), std::move(header)};
}
void ParamServiceAsyncClient::sync_void_ret_map_param(const ::std::map<::std::string, ::std::int64_t>& p_param1) {
::apache::thrift::RpcOptions rpcOptions;
sync_void_ret_map_param(rpcOptions, p_param1);
}
void ParamServiceAsyncClient::sync_void_ret_map_param(apache::thrift::RpcOptions& rpcOptions, const ::std::map<::std::string, ::std::int64_t>& p_param1) {
apache::thrift::ClientReceiveState returnState;
apache::thrift::ClientSyncCallback<false> callback(&returnState);
auto protocolId = apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId();
auto evb = apache::thrift::GeneratedAsyncClient::getChannel()->getEventBase();
auto [ctx, header] = void_ret_map_paramCtx(&rpcOptions);
auto wrappedCallback = apache::thrift::RequestClientCallback::Ptr(&callback);
void_ret_map_paramImpl(rpcOptions, std::move(header), ctx.get(), std::move(wrappedCallback), p_param1);
callback.waitUntilDone(evb);
if (returnState.isException()) {
returnState.exception().throw_exception();
}
returnState.resetProtocolId(protocolId);
returnState.resetCtx(std::move(ctx));
SCOPE_EXIT {
if (returnState.header() && !returnState.header()->getHeaders().empty()) {
rpcOptions.setReadHeaders(returnState.header()->releaseHeaders());
}
};
return folly::fibers::runInMainContext([&] {
recv_void_ret_map_param(returnState);
});
}
folly::Future<folly::Unit> ParamServiceAsyncClient::future_void_ret_map_param(const ::std::map<::std::string, ::std::int64_t>& p_param1) {
::apache::thrift::RpcOptions rpcOptions;
return future_void_ret_map_param(rpcOptions, p_param1);
}
folly::SemiFuture<folly::Unit> ParamServiceAsyncClient::semifuture_void_ret_map_param(const ::std::map<::std::string, ::std::int64_t>& p_param1) {
::apache::thrift::RpcOptions rpcOptions;
return semifuture_void_ret_map_param(rpcOptions, p_param1);
}
folly::Future<folly::Unit> ParamServiceAsyncClient::future_void_ret_map_param(apache::thrift::RpcOptions& rpcOptions, const ::std::map<::std::string, ::std::int64_t>& p_param1) {
folly::Promise<folly::Unit> promise;
auto future = promise.getFuture();
auto callback = std::make_unique<apache::thrift::FutureCallback<folly::Unit>>(std::move(promise), recv_wrapped_void_ret_map_param, channel_);
void_ret_map_param(rpcOptions, std::move(callback), p_param1);
return future;
}
folly::SemiFuture<folly::Unit> ParamServiceAsyncClient::semifuture_void_ret_map_param(apache::thrift::RpcOptions& rpcOptions, const ::std::map<::std::string, ::std::int64_t>& p_param1) {
auto callbackAndFuture = makeSemiFutureCallback(recv_wrapped_void_ret_map_param, channel_);
auto callback = std::move(callbackAndFuture.first);
void_ret_map_param(rpcOptions, std::move(callback), p_param1);
return std::move(callbackAndFuture.second);
}
folly::Future<std::pair<folly::Unit, std::unique_ptr<apache::thrift::transport::THeader>>> ParamServiceAsyncClient::header_future_void_ret_map_param(apache::thrift::RpcOptions& rpcOptions, const ::std::map<::std::string, ::std::int64_t>& p_param1) {
folly::Promise<std::pair<folly::Unit, std::unique_ptr<apache::thrift::transport::THeader>>> promise;
auto future = promise.getFuture();
auto callback = std::make_unique<apache::thrift::HeaderFutureCallback<folly::Unit>>(std::move(promise), recv_wrapped_void_ret_map_param, channel_);
void_ret_map_param(rpcOptions, std::move(callback), p_param1);
return future;
}
folly::SemiFuture<std::pair<folly::Unit, std::unique_ptr<apache::thrift::transport::THeader>>> ParamServiceAsyncClient::header_semifuture_void_ret_map_param(apache::thrift::RpcOptions& rpcOptions, const ::std::map<::std::string, ::std::int64_t>& p_param1) {
auto callbackAndFuture = makeHeaderSemiFutureCallback(recv_wrapped_void_ret_map_param, channel_);
auto callback = std::move(callbackAndFuture.first);
void_ret_map_param(rpcOptions, std::move(callback), p_param1);
return std::move(callbackAndFuture.second);
}
void ParamServiceAsyncClient::void_ret_map_param(folly::Function<void (::apache::thrift::ClientReceiveState&&)> callback, const ::std::map<::std::string, ::std::int64_t>& p_param1) {
void_ret_map_param(std::make_unique<apache::thrift::FunctionReplyCallback>(std::move(callback)), p_param1);
}
#if FOLLY_HAS_COROUTINES
#endif // FOLLY_HAS_COROUTINES
folly::exception_wrapper ParamServiceAsyncClient::recv_wrapped_void_ret_map_param(::apache::thrift::ClientReceiveState& state) {
if (state.isException()) {
return std::move(state.exception());
}
if (!state.hasResponseBuffer()) {
return folly::make_exception_wrapper<apache::thrift::TApplicationException>("recv_ called without result");
}
using result = ParamService_void_ret_map_param_presult;
switch (state.protocolId()) {
case apache::thrift::protocol::T_BINARY_PROTOCOL:
{
apache::thrift::BinaryProtocolReader reader;
return apache::thrift::detail::ac::recv_wrapped<result>(
&reader, state);
}
case apache::thrift::protocol::T_COMPACT_PROTOCOL:
{
apache::thrift::CompactProtocolReader reader;
return apache::thrift::detail::ac::recv_wrapped<result>(
&reader, state);
}
default:
{
}
}
return folly::make_exception_wrapper<apache::thrift::TApplicationException>("Could not find Protocol");
}
void ParamServiceAsyncClient::recv_void_ret_map_param(::apache::thrift::ClientReceiveState& state) {
auto ew = recv_wrapped_void_ret_map_param(state);
if (ew) {
ew.throw_exception();
}
}
void ParamServiceAsyncClient::recv_instance_void_ret_map_param(::apache::thrift::ClientReceiveState& state) {
recv_void_ret_map_param(state);
}
folly::exception_wrapper ParamServiceAsyncClient::recv_instance_wrapped_void_ret_map_param(::apache::thrift::ClientReceiveState& state) {
return recv_wrapped_void_ret_map_param(state);
}
void ParamServiceAsyncClient::void_ret_map_setlist_param(std::unique_ptr<apache::thrift::RequestCallback> callback, const ::std::map<::std::string, ::std::int64_t>& p_param1, const ::std::set<::std::vector<::std::string>>& p_param2) {
::apache::thrift::RpcOptions rpcOptions;
void_ret_map_setlist_param(rpcOptions, std::move(callback), p_param1, p_param2);
}
void ParamServiceAsyncClient::void_ret_map_setlist_param(apache::thrift::RpcOptions& rpcOptions, std::unique_ptr<apache::thrift::RequestCallback> callback, const ::std::map<::std::string, ::std::int64_t>& p_param1, const ::std::set<::std::vector<::std::string>>& p_param2) {
auto [ctx, header] = void_ret_map_setlist_paramCtx(&rpcOptions);
apache::thrift::RequestCallback::Context callbackContext;
callbackContext.protocolId =
apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId();
auto* contextStack = ctx.get();
if (callback) {
callbackContext.ctx = std::move(ctx);
}
auto wrappedCallback = apache::thrift::toRequestClientCallbackPtr(std::move(callback), std::move(callbackContext));
void_ret_map_setlist_paramImpl(rpcOptions, std::move(header), contextStack, std::move(wrappedCallback), p_param1, p_param2);
}
void ParamServiceAsyncClient::void_ret_map_setlist_paramImpl(const apache::thrift::RpcOptions& rpcOptions, std::shared_ptr<apache::thrift::transport::THeader> header, apache::thrift::ContextStack* contextStack, apache::thrift::RequestClientCallback::Ptr callback, const ::std::map<::std::string, ::std::int64_t>& p_param1, const ::std::set<::std::vector<::std::string>>& p_param2) {
switch (apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId()) {
case apache::thrift::protocol::T_BINARY_PROTOCOL:
{
apache::thrift::BinaryProtocolWriter writer;
void_ret_map_setlist_paramT(&writer, rpcOptions, std::move(header), contextStack, std::move(callback), p_param1, p_param2);
break;
}
case apache::thrift::protocol::T_COMPACT_PROTOCOL:
{
apache::thrift::CompactProtocolWriter writer;
void_ret_map_setlist_paramT(&writer, rpcOptions, std::move(header), contextStack, std::move(callback), p_param1, p_param2);
break;
}
default:
{
apache::thrift::detail::ac::throw_app_exn("Could not find Protocol");
}
}
}
std::pair<std::unique_ptr<::apache::thrift::ContextStack>, std::shared_ptr<::apache::thrift::transport::THeader>> ParamServiceAsyncClient::void_ret_map_setlist_paramCtx(apache::thrift::RpcOptions* rpcOptions) {
auto header = std::make_shared<apache::thrift::transport::THeader>(
apache::thrift::transport::THeader::ALLOW_BIG_FRAMES);
header->setProtocolId(channel_->getProtocolId());
if (rpcOptions) {
header->setHeaders(rpcOptions->releaseWriteHeaders());
}
auto ctx = apache::thrift::ContextStack::createWithClientContext(
handlers_,
getServiceName(),
"ParamService.void_ret_map_setlist_param",
*header);
return {std::move(ctx), std::move(header)};
}
void ParamServiceAsyncClient::sync_void_ret_map_setlist_param(const ::std::map<::std::string, ::std::int64_t>& p_param1, const ::std::set<::std::vector<::std::string>>& p_param2) {
::apache::thrift::RpcOptions rpcOptions;
sync_void_ret_map_setlist_param(rpcOptions, p_param1, p_param2);
}
void ParamServiceAsyncClient::sync_void_ret_map_setlist_param(apache::thrift::RpcOptions& rpcOptions, const ::std::map<::std::string, ::std::int64_t>& p_param1, const ::std::set<::std::vector<::std::string>>& p_param2) {
apache::thrift::ClientReceiveState returnState;
apache::thrift::ClientSyncCallback<false> callback(&returnState);
auto protocolId = apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId();
auto evb = apache::thrift::GeneratedAsyncClient::getChannel()->getEventBase();
auto [ctx, header] = void_ret_map_setlist_paramCtx(&rpcOptions);
auto wrappedCallback = apache::thrift::RequestClientCallback::Ptr(&callback);
void_ret_map_setlist_paramImpl(rpcOptions, std::move(header), ctx.get(), std::move(wrappedCallback), p_param1, p_param2);
callback.waitUntilDone(evb);
if (returnState.isException()) {
returnState.exception().throw_exception();
}
returnState.resetProtocolId(protocolId);
returnState.resetCtx(std::move(ctx));
SCOPE_EXIT {
if (returnState.header() && !returnState.header()->getHeaders().empty()) {
rpcOptions.setReadHeaders(returnState.header()->releaseHeaders());
}
};
return folly::fibers::runInMainContext([&] {
recv_void_ret_map_setlist_param(returnState);
});
}
folly::Future<folly::Unit> ParamServiceAsyncClient::future_void_ret_map_setlist_param(const ::std::map<::std::string, ::std::int64_t>& p_param1, const ::std::set<::std::vector<::std::string>>& p_param2) {
::apache::thrift::RpcOptions rpcOptions;
return future_void_ret_map_setlist_param(rpcOptions, p_param1, p_param2);
}
folly::SemiFuture<folly::Unit> ParamServiceAsyncClient::semifuture_void_ret_map_setlist_param(const ::std::map<::std::string, ::std::int64_t>& p_param1, const ::std::set<::std::vector<::std::string>>& p_param2) {
::apache::thrift::RpcOptions rpcOptions;
return semifuture_void_ret_map_setlist_param(rpcOptions, p_param1, p_param2);
}
folly::Future<folly::Unit> ParamServiceAsyncClient::future_void_ret_map_setlist_param(apache::thrift::RpcOptions& rpcOptions, const ::std::map<::std::string, ::std::int64_t>& p_param1, const ::std::set<::std::vector<::std::string>>& p_param2) {
folly::Promise<folly::Unit> promise;
auto future = promise.getFuture();
auto callback = std::make_unique<apache::thrift::FutureCallback<folly::Unit>>(std::move(promise), recv_wrapped_void_ret_map_setlist_param, channel_);
void_ret_map_setlist_param(rpcOptions, std::move(callback), p_param1, p_param2);
return future;
}
folly::SemiFuture<folly::Unit> ParamServiceAsyncClient::semifuture_void_ret_map_setlist_param(apache::thrift::RpcOptions& rpcOptions, const ::std::map<::std::string, ::std::int64_t>& p_param1, const ::std::set<::std::vector<::std::string>>& p_param2) {
auto callbackAndFuture = makeSemiFutureCallback(recv_wrapped_void_ret_map_setlist_param, channel_);
auto callback = std::move(callbackAndFuture.first);
void_ret_map_setlist_param(rpcOptions, std::move(callback), p_param1, p_param2);
return std::move(callbackAndFuture.second);
}
folly::Future<std::pair<folly::Unit, std::unique_ptr<apache::thrift::transport::THeader>>> ParamServiceAsyncClient::header_future_void_ret_map_setlist_param(apache::thrift::RpcOptions& rpcOptions, const ::std::map<::std::string, ::std::int64_t>& p_param1, const ::std::set<::std::vector<::std::string>>& p_param2) {
folly::Promise<std::pair<folly::Unit, std::unique_ptr<apache::thrift::transport::THeader>>> promise;
auto future = promise.getFuture();
auto callback = std::make_unique<apache::thrift::HeaderFutureCallback<folly::Unit>>(std::move(promise), recv_wrapped_void_ret_map_setlist_param, channel_);
void_ret_map_setlist_param(rpcOptions, std::move(callback), p_param1, p_param2);
return future;
}
folly::SemiFuture<std::pair<folly::Unit, std::unique_ptr<apache::thrift::transport::THeader>>> ParamServiceAsyncClient::header_semifuture_void_ret_map_setlist_param(apache::thrift::RpcOptions& rpcOptions, const ::std::map<::std::string, ::std::int64_t>& p_param1, const ::std::set<::std::vector<::std::string>>& p_param2) {
auto callbackAndFuture = makeHeaderSemiFutureCallback(recv_wrapped_void_ret_map_setlist_param, channel_);
auto callback = std::move(callbackAndFuture.first);
void_ret_map_setlist_param(rpcOptions, std::move(callback), p_param1, p_param2);
return std::move(callbackAndFuture.second);
}
void ParamServiceAsyncClient::void_ret_map_setlist_param(folly::Function<void (::apache::thrift::ClientReceiveState&&)> callback, const ::std::map<::std::string, ::std::int64_t>& p_param1, const ::std::set<::std::vector<::std::string>>& p_param2) {
void_ret_map_setlist_param(std::make_unique<apache::thrift::FunctionReplyCallback>(std::move(callback)), p_param1, p_param2);
}
#if FOLLY_HAS_COROUTINES
#endif // FOLLY_HAS_COROUTINES
folly::exception_wrapper ParamServiceAsyncClient::recv_wrapped_void_ret_map_setlist_param(::apache::thrift::ClientReceiveState& state) {
if (state.isException()) {
return std::move(state.exception());
}
if (!state.hasResponseBuffer()) {
return folly::make_exception_wrapper<apache::thrift::TApplicationException>("recv_ called without result");
}
using result = ParamService_void_ret_map_setlist_param_presult;
switch (state.protocolId()) {
case apache::thrift::protocol::T_BINARY_PROTOCOL:
{
apache::thrift::BinaryProtocolReader reader;
return apache::thrift::detail::ac::recv_wrapped<result>(
&reader, state);
}
case apache::thrift::protocol::T_COMPACT_PROTOCOL:
{
apache::thrift::CompactProtocolReader reader;
return apache::thrift::detail::ac::recv_wrapped<result>(
&reader, state);
}
default:
{
}
}
return folly::make_exception_wrapper<apache::thrift::TApplicationException>("Could not find Protocol");
}
void ParamServiceAsyncClient::recv_void_ret_map_setlist_param(::apache::thrift::ClientReceiveState& state) {
auto ew = recv_wrapped_void_ret_map_setlist_param(state);
if (ew) {
ew.throw_exception();
}
}
void ParamServiceAsyncClient::recv_instance_void_ret_map_setlist_param(::apache::thrift::ClientReceiveState& state) {
recv_void_ret_map_setlist_param(state);
}
folly::exception_wrapper ParamServiceAsyncClient::recv_instance_wrapped_void_ret_map_setlist_param(::apache::thrift::ClientReceiveState& state) {
return recv_wrapped_void_ret_map_setlist_param(state);
}
void ParamServiceAsyncClient::void_ret_map_typedef_param(std::unique_ptr<apache::thrift::RequestCallback> callback, ::some::valid::ns::simpleTypeDef p_param1) {
::apache::thrift::RpcOptions rpcOptions;
void_ret_map_typedef_param(rpcOptions, std::move(callback), p_param1);
}
void ParamServiceAsyncClient::void_ret_map_typedef_param(apache::thrift::RpcOptions& rpcOptions, std::unique_ptr<apache::thrift::RequestCallback> callback, ::some::valid::ns::simpleTypeDef p_param1) {
auto [ctx, header] = void_ret_map_typedef_paramCtx(&rpcOptions);
apache::thrift::RequestCallback::Context callbackContext;
callbackContext.protocolId =
apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId();
auto* contextStack = ctx.get();
if (callback) {
callbackContext.ctx = std::move(ctx);
}
auto wrappedCallback = apache::thrift::toRequestClientCallbackPtr(std::move(callback), std::move(callbackContext));
void_ret_map_typedef_paramImpl(rpcOptions, std::move(header), contextStack, std::move(wrappedCallback), p_param1);
}
void ParamServiceAsyncClient::void_ret_map_typedef_paramImpl(const apache::thrift::RpcOptions& rpcOptions, std::shared_ptr<apache::thrift::transport::THeader> header, apache::thrift::ContextStack* contextStack, apache::thrift::RequestClientCallback::Ptr callback, ::some::valid::ns::simpleTypeDef p_param1) {
switch (apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId()) {
case apache::thrift::protocol::T_BINARY_PROTOCOL:
{
apache::thrift::BinaryProtocolWriter writer;
void_ret_map_typedef_paramT(&writer, rpcOptions, std::move(header), contextStack, std::move(callback), p_param1);
break;
}
case apache::thrift::protocol::T_COMPACT_PROTOCOL:
{
apache::thrift::CompactProtocolWriter writer;
void_ret_map_typedef_paramT(&writer, rpcOptions, std::move(header), contextStack, std::move(callback), p_param1);
break;
}
default:
{
apache::thrift::detail::ac::throw_app_exn("Could not find Protocol");
}
}
}
std::pair<std::unique_ptr<::apache::thrift::ContextStack>, std::shared_ptr<::apache::thrift::transport::THeader>> ParamServiceAsyncClient::void_ret_map_typedef_paramCtx(apache::thrift::RpcOptions* rpcOptions) {
auto header = std::make_shared<apache::thrift::transport::THeader>(
apache::thrift::transport::THeader::ALLOW_BIG_FRAMES);
header->setProtocolId(channel_->getProtocolId());
if (rpcOptions) {
header->setHeaders(rpcOptions->releaseWriteHeaders());
}
auto ctx = apache::thrift::ContextStack::createWithClientContext(
handlers_,
getServiceName(),
"ParamService.void_ret_map_typedef_param",
*header);
return {std::move(ctx), std::move(header)};
}
void ParamServiceAsyncClient::sync_void_ret_map_typedef_param(::some::valid::ns::simpleTypeDef p_param1) {
::apache::thrift::RpcOptions rpcOptions;
sync_void_ret_map_typedef_param(rpcOptions, p_param1);
}
void ParamServiceAsyncClient::sync_void_ret_map_typedef_param(apache::thrift::RpcOptions& rpcOptions, ::some::valid::ns::simpleTypeDef p_param1) {
apache::thrift::ClientReceiveState returnState;
apache::thrift::ClientSyncCallback<false> callback(&returnState);
auto protocolId = apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId();
auto evb = apache::thrift::GeneratedAsyncClient::getChannel()->getEventBase();
auto [ctx, header] = void_ret_map_typedef_paramCtx(&rpcOptions);
auto wrappedCallback = apache::thrift::RequestClientCallback::Ptr(&callback);
void_ret_map_typedef_paramImpl(rpcOptions, std::move(header), ctx.get(), std::move(wrappedCallback), p_param1);
callback.waitUntilDone(evb);
if (returnState.isException()) {
returnState.exception().throw_exception();
}
returnState.resetProtocolId(protocolId);
returnState.resetCtx(std::move(ctx));
SCOPE_EXIT {
if (returnState.header() && !returnState.header()->getHeaders().empty()) {
rpcOptions.setReadHeaders(returnState.header()->releaseHeaders());
}
};
return folly::fibers::runInMainContext([&] {
recv_void_ret_map_typedef_param(returnState);
});
}
folly::Future<folly::Unit> ParamServiceAsyncClient::future_void_ret_map_typedef_param(::some::valid::ns::simpleTypeDef p_param1) {
::apache::thrift::RpcOptions rpcOptions;
return future_void_ret_map_typedef_param(rpcOptions, p_param1);
}
folly::SemiFuture<folly::Unit> ParamServiceAsyncClient::semifuture_void_ret_map_typedef_param(::some::valid::ns::simpleTypeDef p_param1) {
::apache::thrift::RpcOptions rpcOptions;
return semifuture_void_ret_map_typedef_param(rpcOptions, p_param1);
}
folly::Future<folly::Unit> ParamServiceAsyncClient::future_void_ret_map_typedef_param(apache::thrift::RpcOptions& rpcOptions, ::some::valid::ns::simpleTypeDef p_param1) {
folly::Promise<folly::Unit> promise;
auto future = promise.getFuture();
auto callback = std::make_unique<apache::thrift::FutureCallback<folly::Unit>>(std::move(promise), recv_wrapped_void_ret_map_typedef_param, channel_);
void_ret_map_typedef_param(rpcOptions, std::move(callback), p_param1);
return future;
}
folly::SemiFuture<folly::Unit> ParamServiceAsyncClient::semifuture_void_ret_map_typedef_param(apache::thrift::RpcOptions& rpcOptions, ::some::valid::ns::simpleTypeDef p_param1) {
auto callbackAndFuture = makeSemiFutureCallback(recv_wrapped_void_ret_map_typedef_param, channel_);
auto callback = std::move(callbackAndFuture.first);
void_ret_map_typedef_param(rpcOptions, std::move(callback), p_param1);
return std::move(callbackAndFuture.second);
}
folly::Future<std::pair<folly::Unit, std::unique_ptr<apache::thrift::transport::THeader>>> ParamServiceAsyncClient::header_future_void_ret_map_typedef_param(apache::thrift::RpcOptions& rpcOptions, ::some::valid::ns::simpleTypeDef p_param1) {
folly::Promise<std::pair<folly::Unit, std::unique_ptr<apache::thrift::transport::THeader>>> promise;
auto future = promise.getFuture();
auto callback = std::make_unique<apache::thrift::HeaderFutureCallback<folly::Unit>>(std::move(promise), recv_wrapped_void_ret_map_typedef_param, channel_);
void_ret_map_typedef_param(rpcOptions, std::move(callback), p_param1);
return future;
}
folly::SemiFuture<std::pair<folly::Unit, std::unique_ptr<apache::thrift::transport::THeader>>> ParamServiceAsyncClient::header_semifuture_void_ret_map_typedef_param(apache::thrift::RpcOptions& rpcOptions, ::some::valid::ns::simpleTypeDef p_param1) {
auto callbackAndFuture = makeHeaderSemiFutureCallback(recv_wrapped_void_ret_map_typedef_param, channel_);
auto callback = std::move(callbackAndFuture.first);
void_ret_map_typedef_param(rpcOptions, std::move(callback), p_param1);
return std::move(callbackAndFuture.second);
}
void ParamServiceAsyncClient::void_ret_map_typedef_param(folly::Function<void (::apache::thrift::ClientReceiveState&&)> callback, ::some::valid::ns::simpleTypeDef p_param1) {
void_ret_map_typedef_param(std::make_unique<apache::thrift::FunctionReplyCallback>(std::move(callback)), p_param1);
}
#if FOLLY_HAS_COROUTINES
#endif // FOLLY_HAS_COROUTINES
folly::exception_wrapper ParamServiceAsyncClient::recv_wrapped_void_ret_map_typedef_param(::apache::thrift::ClientReceiveState& state) {
if (state.isException()) {
return std::move(state.exception());
}
if (!state.hasResponseBuffer()) {
return folly::make_exception_wrapper<apache::thrift::TApplicationException>("recv_ called without result");
}
using result = ParamService_void_ret_map_typedef_param_presult;
switch (state.protocolId()) {
case apache::thrift::protocol::T_BINARY_PROTOCOL:
{
apache::thrift::BinaryProtocolReader reader;
return apache::thrift::detail::ac::recv_wrapped<result>(
&reader, state);
}
case apache::thrift::protocol::T_COMPACT_PROTOCOL:
{
apache::thrift::CompactProtocolReader reader;
return apache::thrift::detail::ac::recv_wrapped<result>(
&reader, state);
}
default:
{
}
}
return folly::make_exception_wrapper<apache::thrift::TApplicationException>("Could not find Protocol");
}
void ParamServiceAsyncClient::recv_void_ret_map_typedef_param(::apache::thrift::ClientReceiveState& state) {
auto ew = recv_wrapped_void_ret_map_typedef_param(state);
if (ew) {
ew.throw_exception();
}
}
void ParamServiceAsyncClient::recv_instance_void_ret_map_typedef_param(::apache::thrift::ClientReceiveState& state) {
recv_void_ret_map_typedef_param(state);
}
folly::exception_wrapper ParamServiceAsyncClient::recv_instance_wrapped_void_ret_map_typedef_param(::apache::thrift::ClientReceiveState& state) {
return recv_wrapped_void_ret_map_typedef_param(state);
}
void ParamServiceAsyncClient::void_ret_enum_param(std::unique_ptr<apache::thrift::RequestCallback> callback, ::some::valid::ns::MyEnumA p_param1) {
::apache::thrift::RpcOptions rpcOptions;
void_ret_enum_param(rpcOptions, std::move(callback), p_param1);
}
void ParamServiceAsyncClient::void_ret_enum_param(apache::thrift::RpcOptions& rpcOptions, std::unique_ptr<apache::thrift::RequestCallback> callback, ::some::valid::ns::MyEnumA p_param1) {
auto [ctx, header] = void_ret_enum_paramCtx(&rpcOptions);
apache::thrift::RequestCallback::Context callbackContext;
callbackContext.protocolId =
apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId();
auto* contextStack = ctx.get();
if (callback) {
callbackContext.ctx = std::move(ctx);
}
auto wrappedCallback = apache::thrift::toRequestClientCallbackPtr(std::move(callback), std::move(callbackContext));
void_ret_enum_paramImpl(rpcOptions, std::move(header), contextStack, std::move(wrappedCallback), p_param1);
}
void ParamServiceAsyncClient::void_ret_enum_paramImpl(const apache::thrift::RpcOptions& rpcOptions, std::shared_ptr<apache::thrift::transport::THeader> header, apache::thrift::ContextStack* contextStack, apache::thrift::RequestClientCallback::Ptr callback, ::some::valid::ns::MyEnumA p_param1) {
switch (apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId()) {
case apache::thrift::protocol::T_BINARY_PROTOCOL:
{
apache::thrift::BinaryProtocolWriter writer;
void_ret_enum_paramT(&writer, rpcOptions, std::move(header), contextStack, std::move(callback), p_param1);
break;
}
case apache::thrift::protocol::T_COMPACT_PROTOCOL:
{
apache::thrift::CompactProtocolWriter writer;
void_ret_enum_paramT(&writer, rpcOptions, std::move(header), contextStack, std::move(callback), p_param1);
break;
}
default:
{
apache::thrift::detail::ac::throw_app_exn("Could not find Protocol");
}
}
}
std::pair<std::unique_ptr<::apache::thrift::ContextStack>, std::shared_ptr<::apache::thrift::transport::THeader>> ParamServiceAsyncClient::void_ret_enum_paramCtx(apache::thrift::RpcOptions* rpcOptions) {
auto header = std::make_shared<apache::thrift::transport::THeader>(
apache::thrift::transport::THeader::ALLOW_BIG_FRAMES);
header->setProtocolId(channel_->getProtocolId());
if (rpcOptions) {
header->setHeaders(rpcOptions->releaseWriteHeaders());
}
auto ctx = apache::thrift::ContextStack::createWithClientContext(
handlers_,
getServiceName(),
"ParamService.void_ret_enum_param",
*header);
return {std::move(ctx), std::move(header)};
}
void ParamServiceAsyncClient::sync_void_ret_enum_param(::some::valid::ns::MyEnumA p_param1) {
::apache::thrift::RpcOptions rpcOptions;
sync_void_ret_enum_param(rpcOptions, p_param1);
}
void ParamServiceAsyncClient::sync_void_ret_enum_param(apache::thrift::RpcOptions& rpcOptions, ::some::valid::ns::MyEnumA p_param1) {
apache::thrift::ClientReceiveState returnState;
apache::thrift::ClientSyncCallback<false> callback(&returnState);
auto protocolId = apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId();
auto evb = apache::thrift::GeneratedAsyncClient::getChannel()->getEventBase();
auto [ctx, header] = void_ret_enum_paramCtx(&rpcOptions);
auto wrappedCallback = apache::thrift::RequestClientCallback::Ptr(&callback);
void_ret_enum_paramImpl(rpcOptions, std::move(header), ctx.get(), std::move(wrappedCallback), p_param1);
callback.waitUntilDone(evb);
if (returnState.isException()) {
returnState.exception().throw_exception();
}
returnState.resetProtocolId(protocolId);
returnState.resetCtx(std::move(ctx));
SCOPE_EXIT {
if (returnState.header() && !returnState.header()->getHeaders().empty()) {
rpcOptions.setReadHeaders(returnState.header()->releaseHeaders());
}
};
return folly::fibers::runInMainContext([&] {
recv_void_ret_enum_param(returnState);
});
}
folly::Future<folly::Unit> ParamServiceAsyncClient::future_void_ret_enum_param(::some::valid::ns::MyEnumA p_param1) {
::apache::thrift::RpcOptions rpcOptions;
return future_void_ret_enum_param(rpcOptions, p_param1);
}
folly::SemiFuture<folly::Unit> ParamServiceAsyncClient::semifuture_void_ret_enum_param(::some::valid::ns::MyEnumA p_param1) {
::apache::thrift::RpcOptions rpcOptions;
return semifuture_void_ret_enum_param(rpcOptions, p_param1);
}
folly::Future<folly::Unit> ParamServiceAsyncClient::future_void_ret_enum_param(apache::thrift::RpcOptions& rpcOptions, ::some::valid::ns::MyEnumA p_param1) {
folly::Promise<folly::Unit> promise;
auto future = promise.getFuture();
auto callback = std::make_unique<apache::thrift::FutureCallback<folly::Unit>>(std::move(promise), recv_wrapped_void_ret_enum_param, channel_);
void_ret_enum_param(rpcOptions, std::move(callback), p_param1);
return future;
}
folly::SemiFuture<folly::Unit> ParamServiceAsyncClient::semifuture_void_ret_enum_param(apache::thrift::RpcOptions& rpcOptions, ::some::valid::ns::MyEnumA p_param1) {
auto callbackAndFuture = makeSemiFutureCallback(recv_wrapped_void_ret_enum_param, channel_);
auto callback = std::move(callbackAndFuture.first);
void_ret_enum_param(rpcOptions, std::move(callback), p_param1);
return std::move(callbackAndFuture.second);
}
folly::Future<std::pair<folly::Unit, std::unique_ptr<apache::thrift::transport::THeader>>> ParamServiceAsyncClient::header_future_void_ret_enum_param(apache::thrift::RpcOptions& rpcOptions, ::some::valid::ns::MyEnumA p_param1) {
folly::Promise<std::pair<folly::Unit, std::unique_ptr<apache::thrift::transport::THeader>>> promise;
auto future = promise.getFuture();
auto callback = std::make_unique<apache::thrift::HeaderFutureCallback<folly::Unit>>(std::move(promise), recv_wrapped_void_ret_enum_param, channel_);
void_ret_enum_param(rpcOptions, std::move(callback), p_param1);
return future;
}
folly::SemiFuture<std::pair<folly::Unit, std::unique_ptr<apache::thrift::transport::THeader>>> ParamServiceAsyncClient::header_semifuture_void_ret_enum_param(apache::thrift::RpcOptions& rpcOptions, ::some::valid::ns::MyEnumA p_param1) {
auto callbackAndFuture = makeHeaderSemiFutureCallback(recv_wrapped_void_ret_enum_param, channel_);
auto callback = std::move(callbackAndFuture.first);
void_ret_enum_param(rpcOptions, std::move(callback), p_param1);
return std::move(callbackAndFuture.second);
}
void ParamServiceAsyncClient::void_ret_enum_param(folly::Function<void (::apache::thrift::ClientReceiveState&&)> callback, ::some::valid::ns::MyEnumA p_param1) {
void_ret_enum_param(std::make_unique<apache::thrift::FunctionReplyCallback>(std::move(callback)), p_param1);
}
#if FOLLY_HAS_COROUTINES
#endif // FOLLY_HAS_COROUTINES
folly::exception_wrapper ParamServiceAsyncClient::recv_wrapped_void_ret_enum_param(::apache::thrift::ClientReceiveState& state) {
if (state.isException()) {
return std::move(state.exception());
}
if (!state.hasResponseBuffer()) {
return folly::make_exception_wrapper<apache::thrift::TApplicationException>("recv_ called without result");
}
using result = ParamService_void_ret_enum_param_presult;
switch (state.protocolId()) {
case apache::thrift::protocol::T_BINARY_PROTOCOL:
{
apache::thrift::BinaryProtocolReader reader;
return apache::thrift::detail::ac::recv_wrapped<result>(
&reader, state);
}
case apache::thrift::protocol::T_COMPACT_PROTOCOL:
{
apache::thrift::CompactProtocolReader reader;
return apache::thrift::detail::ac::recv_wrapped<result>(
&reader, state);
}
default:
{
}
}
return folly::make_exception_wrapper<apache::thrift::TApplicationException>("Could not find Protocol");
}
void ParamServiceAsyncClient::recv_void_ret_enum_param(::apache::thrift::ClientReceiveState& state) {
auto ew = recv_wrapped_void_ret_enum_param(state);
if (ew) {
ew.throw_exception();
}
}
void ParamServiceAsyncClient::recv_instance_void_ret_enum_param(::apache::thrift::ClientReceiveState& state) {
recv_void_ret_enum_param(state);
}
folly::exception_wrapper ParamServiceAsyncClient::recv_instance_wrapped_void_ret_enum_param(::apache::thrift::ClientReceiveState& state) {
return recv_wrapped_void_ret_enum_param(state);
}
void ParamServiceAsyncClient::void_ret_struct_param(std::unique_ptr<apache::thrift::RequestCallback> callback, const ::some::valid::ns::MyStruct& p_param1) {
::apache::thrift::RpcOptions rpcOptions;
void_ret_struct_param(rpcOptions, std::move(callback), p_param1);
}
void ParamServiceAsyncClient::void_ret_struct_param(apache::thrift::RpcOptions& rpcOptions, std::unique_ptr<apache::thrift::RequestCallback> callback, const ::some::valid::ns::MyStruct& p_param1) {
auto [ctx, header] = void_ret_struct_paramCtx(&rpcOptions);
apache::thrift::RequestCallback::Context callbackContext;
callbackContext.protocolId =
apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId();
auto* contextStack = ctx.get();
if (callback) {
callbackContext.ctx = std::move(ctx);
}
auto wrappedCallback = apache::thrift::toRequestClientCallbackPtr(std::move(callback), std::move(callbackContext));
void_ret_struct_paramImpl(rpcOptions, std::move(header), contextStack, std::move(wrappedCallback), p_param1);
}
void ParamServiceAsyncClient::void_ret_struct_paramImpl(const apache::thrift::RpcOptions& rpcOptions, std::shared_ptr<apache::thrift::transport::THeader> header, apache::thrift::ContextStack* contextStack, apache::thrift::RequestClientCallback::Ptr callback, const ::some::valid::ns::MyStruct& p_param1) {
switch (apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId()) {
case apache::thrift::protocol::T_BINARY_PROTOCOL:
{
apache::thrift::BinaryProtocolWriter writer;
void_ret_struct_paramT(&writer, rpcOptions, std::move(header), contextStack, std::move(callback), p_param1);
break;
}
case apache::thrift::protocol::T_COMPACT_PROTOCOL:
{
apache::thrift::CompactProtocolWriter writer;
void_ret_struct_paramT(&writer, rpcOptions, std::move(header), contextStack, std::move(callback), p_param1);
break;
}
default:
{
apache::thrift::detail::ac::throw_app_exn("Could not find Protocol");
}
}
}
std::pair<std::unique_ptr<::apache::thrift::ContextStack>, std::shared_ptr<::apache::thrift::transport::THeader>> ParamServiceAsyncClient::void_ret_struct_paramCtx(apache::thrift::RpcOptions* rpcOptions) {
auto header = std::make_shared<apache::thrift::transport::THeader>(
apache::thrift::transport::THeader::ALLOW_BIG_FRAMES);
header->setProtocolId(channel_->getProtocolId());
if (rpcOptions) {
header->setHeaders(rpcOptions->releaseWriteHeaders());
}
auto ctx = apache::thrift::ContextStack::createWithClientContext(
handlers_,
getServiceName(),
"ParamService.void_ret_struct_param",
*header);
return {std::move(ctx), std::move(header)};
}
void ParamServiceAsyncClient::sync_void_ret_struct_param(const ::some::valid::ns::MyStruct& p_param1) {
::apache::thrift::RpcOptions rpcOptions;
sync_void_ret_struct_param(rpcOptions, p_param1);
}
void ParamServiceAsyncClient::sync_void_ret_struct_param(apache::thrift::RpcOptions& rpcOptions, const ::some::valid::ns::MyStruct& p_param1) {
apache::thrift::ClientReceiveState returnState;
apache::thrift::ClientSyncCallback<false> callback(&returnState);
auto protocolId = apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId();
auto evb = apache::thrift::GeneratedAsyncClient::getChannel()->getEventBase();
auto [ctx, header] = void_ret_struct_paramCtx(&rpcOptions);
auto wrappedCallback = apache::thrift::RequestClientCallback::Ptr(&callback);
void_ret_struct_paramImpl(rpcOptions, std::move(header), ctx.get(), std::move(wrappedCallback), p_param1);
callback.waitUntilDone(evb);
if (returnState.isException()) {
returnState.exception().throw_exception();
}
returnState.resetProtocolId(protocolId);
returnState.resetCtx(std::move(ctx));
SCOPE_EXIT {
if (returnState.header() && !returnState.header()->getHeaders().empty()) {
rpcOptions.setReadHeaders(returnState.header()->releaseHeaders());
}
};
return folly::fibers::runInMainContext([&] {
recv_void_ret_struct_param(returnState);
});
}
folly::Future<folly::Unit> ParamServiceAsyncClient::future_void_ret_struct_param(const ::some::valid::ns::MyStruct& p_param1) {
::apache::thrift::RpcOptions rpcOptions;
return future_void_ret_struct_param(rpcOptions, p_param1);
}
folly::SemiFuture<folly::Unit> ParamServiceAsyncClient::semifuture_void_ret_struct_param(const ::some::valid::ns::MyStruct& p_param1) {
::apache::thrift::RpcOptions rpcOptions;
return semifuture_void_ret_struct_param(rpcOptions, p_param1);
}
folly::Future<folly::Unit> ParamServiceAsyncClient::future_void_ret_struct_param(apache::thrift::RpcOptions& rpcOptions, const ::some::valid::ns::MyStruct& p_param1) {
folly::Promise<folly::Unit> promise;
auto future = promise.getFuture();
auto callback = std::make_unique<apache::thrift::FutureCallback<folly::Unit>>(std::move(promise), recv_wrapped_void_ret_struct_param, channel_);
void_ret_struct_param(rpcOptions, std::move(callback), p_param1);
return future;
}
folly::SemiFuture<folly::Unit> ParamServiceAsyncClient::semifuture_void_ret_struct_param(apache::thrift::RpcOptions& rpcOptions, const ::some::valid::ns::MyStruct& p_param1) {
auto callbackAndFuture = makeSemiFutureCallback(recv_wrapped_void_ret_struct_param, channel_);
auto callback = std::move(callbackAndFuture.first);
void_ret_struct_param(rpcOptions, std::move(callback), p_param1);
return std::move(callbackAndFuture.second);
}
folly::Future<std::pair<folly::Unit, std::unique_ptr<apache::thrift::transport::THeader>>> ParamServiceAsyncClient::header_future_void_ret_struct_param(apache::thrift::RpcOptions& rpcOptions, const ::some::valid::ns::MyStruct& p_param1) {
folly::Promise<std::pair<folly::Unit, std::unique_ptr<apache::thrift::transport::THeader>>> promise;
auto future = promise.getFuture();
auto callback = std::make_unique<apache::thrift::HeaderFutureCallback<folly::Unit>>(std::move(promise), recv_wrapped_void_ret_struct_param, channel_);
void_ret_struct_param(rpcOptions, std::move(callback), p_param1);
return future;
}
folly::SemiFuture<std::pair<folly::Unit, std::unique_ptr<apache::thrift::transport::THeader>>> ParamServiceAsyncClient::header_semifuture_void_ret_struct_param(apache::thrift::RpcOptions& rpcOptions, const ::some::valid::ns::MyStruct& p_param1) {
auto callbackAndFuture = makeHeaderSemiFutureCallback(recv_wrapped_void_ret_struct_param, channel_);
auto callback = std::move(callbackAndFuture.first);
void_ret_struct_param(rpcOptions, std::move(callback), p_param1);
return std::move(callbackAndFuture.second);
}
void ParamServiceAsyncClient::void_ret_struct_param(folly::Function<void (::apache::thrift::ClientReceiveState&&)> callback, const ::some::valid::ns::MyStruct& p_param1) {
void_ret_struct_param(std::make_unique<apache::thrift::FunctionReplyCallback>(std::move(callback)), p_param1);
}
#if FOLLY_HAS_COROUTINES
#endif // FOLLY_HAS_COROUTINES
folly::exception_wrapper ParamServiceAsyncClient::recv_wrapped_void_ret_struct_param(::apache::thrift::ClientReceiveState& state) {
if (state.isException()) {
return std::move(state.exception());
}
if (!state.hasResponseBuffer()) {
return folly::make_exception_wrapper<apache::thrift::TApplicationException>("recv_ called without result");
}
using result = ParamService_void_ret_struct_param_presult;
switch (state.protocolId()) {
case apache::thrift::protocol::T_BINARY_PROTOCOL:
{
apache::thrift::BinaryProtocolReader reader;
return apache::thrift::detail::ac::recv_wrapped<result>(
&reader, state);
}
case apache::thrift::protocol::T_COMPACT_PROTOCOL:
{
apache::thrift::CompactProtocolReader reader;
return apache::thrift::detail::ac::recv_wrapped<result>(
&reader, state);
}
default:
{
}
}
return folly::make_exception_wrapper<apache::thrift::TApplicationException>("Could not find Protocol");
}
void ParamServiceAsyncClient::recv_void_ret_struct_param(::apache::thrift::ClientReceiveState& state) {
auto ew = recv_wrapped_void_ret_struct_param(state);
if (ew) {
ew.throw_exception();
}
}
void ParamServiceAsyncClient::recv_instance_void_ret_struct_param(::apache::thrift::ClientReceiveState& state) {
recv_void_ret_struct_param(state);
}
folly::exception_wrapper ParamServiceAsyncClient::recv_instance_wrapped_void_ret_struct_param(::apache::thrift::ClientReceiveState& state) {
return recv_wrapped_void_ret_struct_param(state);
}
void ParamServiceAsyncClient::void_ret_listunion_param(std::unique_ptr<apache::thrift::RequestCallback> callback, const ::std::vector<::some::valid::ns::ComplexUnion>& p_param1) {
::apache::thrift::RpcOptions rpcOptions;
void_ret_listunion_param(rpcOptions, std::move(callback), p_param1);
}
void ParamServiceAsyncClient::void_ret_listunion_param(apache::thrift::RpcOptions& rpcOptions, std::unique_ptr<apache::thrift::RequestCallback> callback, const ::std::vector<::some::valid::ns::ComplexUnion>& p_param1) {
auto [ctx, header] = void_ret_listunion_paramCtx(&rpcOptions);
apache::thrift::RequestCallback::Context callbackContext;
callbackContext.protocolId =
apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId();
auto* contextStack = ctx.get();
if (callback) {
callbackContext.ctx = std::move(ctx);
}
auto wrappedCallback = apache::thrift::toRequestClientCallbackPtr(std::move(callback), std::move(callbackContext));
void_ret_listunion_paramImpl(rpcOptions, std::move(header), contextStack, std::move(wrappedCallback), p_param1);
}
void ParamServiceAsyncClient::void_ret_listunion_paramImpl(const apache::thrift::RpcOptions& rpcOptions, std::shared_ptr<apache::thrift::transport::THeader> header, apache::thrift::ContextStack* contextStack, apache::thrift::RequestClientCallback::Ptr callback, const ::std::vector<::some::valid::ns::ComplexUnion>& p_param1) {
switch (apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId()) {
case apache::thrift::protocol::T_BINARY_PROTOCOL:
{
apache::thrift::BinaryProtocolWriter writer;
void_ret_listunion_paramT(&writer, rpcOptions, std::move(header), contextStack, std::move(callback), p_param1);
break;
}
case apache::thrift::protocol::T_COMPACT_PROTOCOL:
{
apache::thrift::CompactProtocolWriter writer;
void_ret_listunion_paramT(&writer, rpcOptions, std::move(header), contextStack, std::move(callback), p_param1);
break;
}
default:
{
apache::thrift::detail::ac::throw_app_exn("Could not find Protocol");
}
}
}
std::pair<std::unique_ptr<::apache::thrift::ContextStack>, std::shared_ptr<::apache::thrift::transport::THeader>> ParamServiceAsyncClient::void_ret_listunion_paramCtx(apache::thrift::RpcOptions* rpcOptions) {
auto header = std::make_shared<apache::thrift::transport::THeader>(
apache::thrift::transport::THeader::ALLOW_BIG_FRAMES);
header->setProtocolId(channel_->getProtocolId());
if (rpcOptions) {
header->setHeaders(rpcOptions->releaseWriteHeaders());
}
auto ctx = apache::thrift::ContextStack::createWithClientContext(
handlers_,
getServiceName(),
"ParamService.void_ret_listunion_param",
*header);
return {std::move(ctx), std::move(header)};
}
void ParamServiceAsyncClient::sync_void_ret_listunion_param(const ::std::vector<::some::valid::ns::ComplexUnion>& p_param1) {
::apache::thrift::RpcOptions rpcOptions;
sync_void_ret_listunion_param(rpcOptions, p_param1);
}
void ParamServiceAsyncClient::sync_void_ret_listunion_param(apache::thrift::RpcOptions& rpcOptions, const ::std::vector<::some::valid::ns::ComplexUnion>& p_param1) {
apache::thrift::ClientReceiveState returnState;
apache::thrift::ClientSyncCallback<false> callback(&returnState);
auto protocolId = apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId();
auto evb = apache::thrift::GeneratedAsyncClient::getChannel()->getEventBase();
auto [ctx, header] = void_ret_listunion_paramCtx(&rpcOptions);
auto wrappedCallback = apache::thrift::RequestClientCallback::Ptr(&callback);
void_ret_listunion_paramImpl(rpcOptions, std::move(header), ctx.get(), std::move(wrappedCallback), p_param1);
callback.waitUntilDone(evb);
if (returnState.isException()) {
returnState.exception().throw_exception();
}
returnState.resetProtocolId(protocolId);
returnState.resetCtx(std::move(ctx));
SCOPE_EXIT {
if (returnState.header() && !returnState.header()->getHeaders().empty()) {
rpcOptions.setReadHeaders(returnState.header()->releaseHeaders());
}
};
return folly::fibers::runInMainContext([&] {
recv_void_ret_listunion_param(returnState);
});
}
folly::Future<folly::Unit> ParamServiceAsyncClient::future_void_ret_listunion_param(const ::std::vector<::some::valid::ns::ComplexUnion>& p_param1) {
::apache::thrift::RpcOptions rpcOptions;
return future_void_ret_listunion_param(rpcOptions, p_param1);
}
folly::SemiFuture<folly::Unit> ParamServiceAsyncClient::semifuture_void_ret_listunion_param(const ::std::vector<::some::valid::ns::ComplexUnion>& p_param1) {
::apache::thrift::RpcOptions rpcOptions;
return semifuture_void_ret_listunion_param(rpcOptions, p_param1);
}
folly::Future<folly::Unit> ParamServiceAsyncClient::future_void_ret_listunion_param(apache::thrift::RpcOptions& rpcOptions, const ::std::vector<::some::valid::ns::ComplexUnion>& p_param1) {
folly::Promise<folly::Unit> promise;
auto future = promise.getFuture();
auto callback = std::make_unique<apache::thrift::FutureCallback<folly::Unit>>(std::move(promise), recv_wrapped_void_ret_listunion_param, channel_);
void_ret_listunion_param(rpcOptions, std::move(callback), p_param1);
return future;
}
folly::SemiFuture<folly::Unit> ParamServiceAsyncClient::semifuture_void_ret_listunion_param(apache::thrift::RpcOptions& rpcOptions, const ::std::vector<::some::valid::ns::ComplexUnion>& p_param1) {
auto callbackAndFuture = makeSemiFutureCallback(recv_wrapped_void_ret_listunion_param, channel_);
auto callback = std::move(callbackAndFuture.first);
void_ret_listunion_param(rpcOptions, std::move(callback), p_param1);
return std::move(callbackAndFuture.second);
}
folly::Future<std::pair<folly::Unit, std::unique_ptr<apache::thrift::transport::THeader>>> ParamServiceAsyncClient::header_future_void_ret_listunion_param(apache::thrift::RpcOptions& rpcOptions, const ::std::vector<::some::valid::ns::ComplexUnion>& p_param1) {
folly::Promise<std::pair<folly::Unit, std::unique_ptr<apache::thrift::transport::THeader>>> promise;
auto future = promise.getFuture();
auto callback = std::make_unique<apache::thrift::HeaderFutureCallback<folly::Unit>>(std::move(promise), recv_wrapped_void_ret_listunion_param, channel_);
void_ret_listunion_param(rpcOptions, std::move(callback), p_param1);
return future;
}
folly::SemiFuture<std::pair<folly::Unit, std::unique_ptr<apache::thrift::transport::THeader>>> ParamServiceAsyncClient::header_semifuture_void_ret_listunion_param(apache::thrift::RpcOptions& rpcOptions, const ::std::vector<::some::valid::ns::ComplexUnion>& p_param1) {
auto callbackAndFuture = makeHeaderSemiFutureCallback(recv_wrapped_void_ret_listunion_param, channel_);
auto callback = std::move(callbackAndFuture.first);
void_ret_listunion_param(rpcOptions, std::move(callback), p_param1);
return std::move(callbackAndFuture.second);
}
void ParamServiceAsyncClient::void_ret_listunion_param(folly::Function<void (::apache::thrift::ClientReceiveState&&)> callback, const ::std::vector<::some::valid::ns::ComplexUnion>& p_param1) {
void_ret_listunion_param(std::make_unique<apache::thrift::FunctionReplyCallback>(std::move(callback)), p_param1);
}
#if FOLLY_HAS_COROUTINES
#endif // FOLLY_HAS_COROUTINES
folly::exception_wrapper ParamServiceAsyncClient::recv_wrapped_void_ret_listunion_param(::apache::thrift::ClientReceiveState& state) {
if (state.isException()) {
return std::move(state.exception());
}
if (!state.hasResponseBuffer()) {
return folly::make_exception_wrapper<apache::thrift::TApplicationException>("recv_ called without result");
}
using result = ParamService_void_ret_listunion_param_presult;
switch (state.protocolId()) {
case apache::thrift::protocol::T_BINARY_PROTOCOL:
{
apache::thrift::BinaryProtocolReader reader;
return apache::thrift::detail::ac::recv_wrapped<result>(
&reader, state);
}
case apache::thrift::protocol::T_COMPACT_PROTOCOL:
{
apache::thrift::CompactProtocolReader reader;
return apache::thrift::detail::ac::recv_wrapped<result>(
&reader, state);
}
default:
{
}
}
return folly::make_exception_wrapper<apache::thrift::TApplicationException>("Could not find Protocol");
}
void ParamServiceAsyncClient::recv_void_ret_listunion_param(::apache::thrift::ClientReceiveState& state) {
auto ew = recv_wrapped_void_ret_listunion_param(state);
if (ew) {
ew.throw_exception();
}
}
void ParamServiceAsyncClient::recv_instance_void_ret_listunion_param(::apache::thrift::ClientReceiveState& state) {
recv_void_ret_listunion_param(state);
}
folly::exception_wrapper ParamServiceAsyncClient::recv_instance_wrapped_void_ret_listunion_param(::apache::thrift::ClientReceiveState& state) {
return recv_wrapped_void_ret_listunion_param(state);
}
void ParamServiceAsyncClient::bool_ret_i32_i64_param(std::unique_ptr<apache::thrift::RequestCallback> callback, ::std::int32_t p_param1, ::std::int64_t p_param2) {
::apache::thrift::RpcOptions rpcOptions;
bool_ret_i32_i64_param(rpcOptions, std::move(callback), p_param1, p_param2);
}
void ParamServiceAsyncClient::bool_ret_i32_i64_param(apache::thrift::RpcOptions& rpcOptions, std::unique_ptr<apache::thrift::RequestCallback> callback, ::std::int32_t p_param1, ::std::int64_t p_param2) {
auto [ctx, header] = bool_ret_i32_i64_paramCtx(&rpcOptions);
apache::thrift::RequestCallback::Context callbackContext;
callbackContext.protocolId =
apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId();
auto* contextStack = ctx.get();
if (callback) {
callbackContext.ctx = std::move(ctx);
}
auto wrappedCallback = apache::thrift::toRequestClientCallbackPtr(std::move(callback), std::move(callbackContext));
bool_ret_i32_i64_paramImpl(rpcOptions, std::move(header), contextStack, std::move(wrappedCallback), p_param1, p_param2);
}
void ParamServiceAsyncClient::bool_ret_i32_i64_paramImpl(const apache::thrift::RpcOptions& rpcOptions, std::shared_ptr<apache::thrift::transport::THeader> header, apache::thrift::ContextStack* contextStack, apache::thrift::RequestClientCallback::Ptr callback, ::std::int32_t p_param1, ::std::int64_t p_param2) {
switch (apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId()) {
case apache::thrift::protocol::T_BINARY_PROTOCOL:
{
apache::thrift::BinaryProtocolWriter writer;
bool_ret_i32_i64_paramT(&writer, rpcOptions, std::move(header), contextStack, std::move(callback), p_param1, p_param2);
break;
}
case apache::thrift::protocol::T_COMPACT_PROTOCOL:
{
apache::thrift::CompactProtocolWriter writer;
bool_ret_i32_i64_paramT(&writer, rpcOptions, std::move(header), contextStack, std::move(callback), p_param1, p_param2);
break;
}
default:
{
apache::thrift::detail::ac::throw_app_exn("Could not find Protocol");
}
}
}
std::pair<std::unique_ptr<::apache::thrift::ContextStack>, std::shared_ptr<::apache::thrift::transport::THeader>> ParamServiceAsyncClient::bool_ret_i32_i64_paramCtx(apache::thrift::RpcOptions* rpcOptions) {
auto header = std::make_shared<apache::thrift::transport::THeader>(
apache::thrift::transport::THeader::ALLOW_BIG_FRAMES);
header->setProtocolId(channel_->getProtocolId());
if (rpcOptions) {
header->setHeaders(rpcOptions->releaseWriteHeaders());
}
auto ctx = apache::thrift::ContextStack::createWithClientContext(
handlers_,
getServiceName(),
"ParamService.bool_ret_i32_i64_param",
*header);
return {std::move(ctx), std::move(header)};
}
bool ParamServiceAsyncClient::sync_bool_ret_i32_i64_param(::std::int32_t p_param1, ::std::int64_t p_param2) {
::apache::thrift::RpcOptions rpcOptions;
return sync_bool_ret_i32_i64_param(rpcOptions, p_param1, p_param2);
}
bool ParamServiceAsyncClient::sync_bool_ret_i32_i64_param(apache::thrift::RpcOptions& rpcOptions, ::std::int32_t p_param1, ::std::int64_t p_param2) {
apache::thrift::ClientReceiveState returnState;
apache::thrift::ClientSyncCallback<false> callback(&returnState);
auto protocolId = apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId();
auto evb = apache::thrift::GeneratedAsyncClient::getChannel()->getEventBase();
auto [ctx, header] = bool_ret_i32_i64_paramCtx(&rpcOptions);
auto wrappedCallback = apache::thrift::RequestClientCallback::Ptr(&callback);
bool_ret_i32_i64_paramImpl(rpcOptions, std::move(header), ctx.get(), std::move(wrappedCallback), p_param1, p_param2);
callback.waitUntilDone(evb);
if (returnState.isException()) {
returnState.exception().throw_exception();
}
returnState.resetProtocolId(protocolId);
returnState.resetCtx(std::move(ctx));
SCOPE_EXIT {
if (returnState.header() && !returnState.header()->getHeaders().empty()) {
rpcOptions.setReadHeaders(returnState.header()->releaseHeaders());
}
};
return folly::fibers::runInMainContext([&] {
return recv_bool_ret_i32_i64_param(returnState);
});
}
folly::Future<bool> ParamServiceAsyncClient::future_bool_ret_i32_i64_param(::std::int32_t p_param1, ::std::int64_t p_param2) {
::apache::thrift::RpcOptions rpcOptions;
return future_bool_ret_i32_i64_param(rpcOptions, p_param1, p_param2);
}
folly::SemiFuture<bool> ParamServiceAsyncClient::semifuture_bool_ret_i32_i64_param(::std::int32_t p_param1, ::std::int64_t p_param2) {
::apache::thrift::RpcOptions rpcOptions;
return semifuture_bool_ret_i32_i64_param(rpcOptions, p_param1, p_param2);
}
folly::Future<bool> ParamServiceAsyncClient::future_bool_ret_i32_i64_param(apache::thrift::RpcOptions& rpcOptions, ::std::int32_t p_param1, ::std::int64_t p_param2) {
folly::Promise<bool> promise;
auto future = promise.getFuture();
auto callback = std::make_unique<apache::thrift::FutureCallback<bool>>(std::move(promise), recv_wrapped_bool_ret_i32_i64_param, channel_);
bool_ret_i32_i64_param(rpcOptions, std::move(callback), p_param1, p_param2);
return future;
}
folly::SemiFuture<bool> ParamServiceAsyncClient::semifuture_bool_ret_i32_i64_param(apache::thrift::RpcOptions& rpcOptions, ::std::int32_t p_param1, ::std::int64_t p_param2) {
auto callbackAndFuture = makeSemiFutureCallback(recv_wrapped_bool_ret_i32_i64_param, channel_);
auto callback = std::move(callbackAndFuture.first);
bool_ret_i32_i64_param(rpcOptions, std::move(callback), p_param1, p_param2);
return std::move(callbackAndFuture.second);
}
folly::Future<std::pair<bool, std::unique_ptr<apache::thrift::transport::THeader>>> ParamServiceAsyncClient::header_future_bool_ret_i32_i64_param(apache::thrift::RpcOptions& rpcOptions, ::std::int32_t p_param1, ::std::int64_t p_param2) {
folly::Promise<std::pair<bool, std::unique_ptr<apache::thrift::transport::THeader>>> promise;
auto future = promise.getFuture();
auto callback = std::make_unique<apache::thrift::HeaderFutureCallback<bool>>(std::move(promise), recv_wrapped_bool_ret_i32_i64_param, channel_);
bool_ret_i32_i64_param(rpcOptions, std::move(callback), p_param1, p_param2);
return future;
}
folly::SemiFuture<std::pair<bool, std::unique_ptr<apache::thrift::transport::THeader>>> ParamServiceAsyncClient::header_semifuture_bool_ret_i32_i64_param(apache::thrift::RpcOptions& rpcOptions, ::std::int32_t p_param1, ::std::int64_t p_param2) {
auto callbackAndFuture = makeHeaderSemiFutureCallback(recv_wrapped_bool_ret_i32_i64_param, channel_);
auto callback = std::move(callbackAndFuture.first);
bool_ret_i32_i64_param(rpcOptions, std::move(callback), p_param1, p_param2);
return std::move(callbackAndFuture.second);
}
void ParamServiceAsyncClient::bool_ret_i32_i64_param(folly::Function<void (::apache::thrift::ClientReceiveState&&)> callback, ::std::int32_t p_param1, ::std::int64_t p_param2) {
bool_ret_i32_i64_param(std::make_unique<apache::thrift::FunctionReplyCallback>(std::move(callback)), p_param1, p_param2);
}
#if FOLLY_HAS_COROUTINES
#endif // FOLLY_HAS_COROUTINES
folly::exception_wrapper ParamServiceAsyncClient::recv_wrapped_bool_ret_i32_i64_param(bool& _return, ::apache::thrift::ClientReceiveState& state) {
if (state.isException()) {
return std::move(state.exception());
}
if (!state.hasResponseBuffer()) {
return folly::make_exception_wrapper<apache::thrift::TApplicationException>("recv_ called without result");
}
using result = ParamService_bool_ret_i32_i64_param_presult;
switch (state.protocolId()) {
case apache::thrift::protocol::T_BINARY_PROTOCOL:
{
apache::thrift::BinaryProtocolReader reader;
return apache::thrift::detail::ac::recv_wrapped<result>(
&reader, state, _return);
}
case apache::thrift::protocol::T_COMPACT_PROTOCOL:
{
apache::thrift::CompactProtocolReader reader;
return apache::thrift::detail::ac::recv_wrapped<result>(
&reader, state, _return);
}
default:
{
}
}
return folly::make_exception_wrapper<apache::thrift::TApplicationException>("Could not find Protocol");
}
bool ParamServiceAsyncClient::recv_bool_ret_i32_i64_param(::apache::thrift::ClientReceiveState& state) {
bool _return;
auto ew = recv_wrapped_bool_ret_i32_i64_param(_return, state);
if (ew) {
ew.throw_exception();
}
return _return;
}
bool ParamServiceAsyncClient::recv_instance_bool_ret_i32_i64_param(::apache::thrift::ClientReceiveState& state) {
return recv_bool_ret_i32_i64_param(state);
}
folly::exception_wrapper ParamServiceAsyncClient::recv_instance_wrapped_bool_ret_i32_i64_param(bool& _return, ::apache::thrift::ClientReceiveState& state) {
return recv_wrapped_bool_ret_i32_i64_param(_return, state);
}
void ParamServiceAsyncClient::bool_ret_map_param(std::unique_ptr<apache::thrift::RequestCallback> callback, const ::std::map<::std::string, ::std::int64_t>& p_param1) {
::apache::thrift::RpcOptions rpcOptions;
bool_ret_map_param(rpcOptions, std::move(callback), p_param1);
}
void ParamServiceAsyncClient::bool_ret_map_param(apache::thrift::RpcOptions& rpcOptions, std::unique_ptr<apache::thrift::RequestCallback> callback, const ::std::map<::std::string, ::std::int64_t>& p_param1) {
auto [ctx, header] = bool_ret_map_paramCtx(&rpcOptions);
apache::thrift::RequestCallback::Context callbackContext;
callbackContext.protocolId =
apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId();
auto* contextStack = ctx.get();
if (callback) {
callbackContext.ctx = std::move(ctx);
}
auto wrappedCallback = apache::thrift::toRequestClientCallbackPtr(std::move(callback), std::move(callbackContext));
bool_ret_map_paramImpl(rpcOptions, std::move(header), contextStack, std::move(wrappedCallback), p_param1);
}
void ParamServiceAsyncClient::bool_ret_map_paramImpl(const apache::thrift::RpcOptions& rpcOptions, std::shared_ptr<apache::thrift::transport::THeader> header, apache::thrift::ContextStack* contextStack, apache::thrift::RequestClientCallback::Ptr callback, const ::std::map<::std::string, ::std::int64_t>& p_param1) {
switch (apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId()) {
case apache::thrift::protocol::T_BINARY_PROTOCOL:
{
apache::thrift::BinaryProtocolWriter writer;
bool_ret_map_paramT(&writer, rpcOptions, std::move(header), contextStack, std::move(callback), p_param1);
break;
}
case apache::thrift::protocol::T_COMPACT_PROTOCOL:
{
apache::thrift::CompactProtocolWriter writer;
bool_ret_map_paramT(&writer, rpcOptions, std::move(header), contextStack, std::move(callback), p_param1);
break;
}
default:
{
apache::thrift::detail::ac::throw_app_exn("Could not find Protocol");
}
}
}
std::pair<std::unique_ptr<::apache::thrift::ContextStack>, std::shared_ptr<::apache::thrift::transport::THeader>> ParamServiceAsyncClient::bool_ret_map_paramCtx(apache::thrift::RpcOptions* rpcOptions) {
auto header = std::make_shared<apache::thrift::transport::THeader>(
apache::thrift::transport::THeader::ALLOW_BIG_FRAMES);
header->setProtocolId(channel_->getProtocolId());
if (rpcOptions) {
header->setHeaders(rpcOptions->releaseWriteHeaders());
}
auto ctx = apache::thrift::ContextStack::createWithClientContext(
handlers_,
getServiceName(),
"ParamService.bool_ret_map_param",
*header);
return {std::move(ctx), std::move(header)};
}
bool ParamServiceAsyncClient::sync_bool_ret_map_param(const ::std::map<::std::string, ::std::int64_t>& p_param1) {
::apache::thrift::RpcOptions rpcOptions;
return sync_bool_ret_map_param(rpcOptions, p_param1);
}
bool ParamServiceAsyncClient::sync_bool_ret_map_param(apache::thrift::RpcOptions& rpcOptions, const ::std::map<::std::string, ::std::int64_t>& p_param1) {
apache::thrift::ClientReceiveState returnState;
apache::thrift::ClientSyncCallback<false> callback(&returnState);
auto protocolId = apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId();
auto evb = apache::thrift::GeneratedAsyncClient::getChannel()->getEventBase();
auto [ctx, header] = bool_ret_map_paramCtx(&rpcOptions);
auto wrappedCallback = apache::thrift::RequestClientCallback::Ptr(&callback);
bool_ret_map_paramImpl(rpcOptions, std::move(header), ctx.get(), std::move(wrappedCallback), p_param1);
callback.waitUntilDone(evb);
if (returnState.isException()) {
returnState.exception().throw_exception();
}
returnState.resetProtocolId(protocolId);
returnState.resetCtx(std::move(ctx));
SCOPE_EXIT {
if (returnState.header() && !returnState.header()->getHeaders().empty()) {
rpcOptions.setReadHeaders(returnState.header()->releaseHeaders());
}
};
return folly::fibers::runInMainContext([&] {
return recv_bool_ret_map_param(returnState);
});
}
folly::Future<bool> ParamServiceAsyncClient::future_bool_ret_map_param(const ::std::map<::std::string, ::std::int64_t>& p_param1) {
::apache::thrift::RpcOptions rpcOptions;
return future_bool_ret_map_param(rpcOptions, p_param1);
}
folly::SemiFuture<bool> ParamServiceAsyncClient::semifuture_bool_ret_map_param(const ::std::map<::std::string, ::std::int64_t>& p_param1) {
::apache::thrift::RpcOptions rpcOptions;
return semifuture_bool_ret_map_param(rpcOptions, p_param1);
}
folly::Future<bool> ParamServiceAsyncClient::future_bool_ret_map_param(apache::thrift::RpcOptions& rpcOptions, const ::std::map<::std::string, ::std::int64_t>& p_param1) {
folly::Promise<bool> promise;
auto future = promise.getFuture();
auto callback = std::make_unique<apache::thrift::FutureCallback<bool>>(std::move(promise), recv_wrapped_bool_ret_map_param, channel_);
bool_ret_map_param(rpcOptions, std::move(callback), p_param1);
return future;
}
folly::SemiFuture<bool> ParamServiceAsyncClient::semifuture_bool_ret_map_param(apache::thrift::RpcOptions& rpcOptions, const ::std::map<::std::string, ::std::int64_t>& p_param1) {
auto callbackAndFuture = makeSemiFutureCallback(recv_wrapped_bool_ret_map_param, channel_);
auto callback = std::move(callbackAndFuture.first);
bool_ret_map_param(rpcOptions, std::move(callback), p_param1);
return std::move(callbackAndFuture.second);
}
folly::Future<std::pair<bool, std::unique_ptr<apache::thrift::transport::THeader>>> ParamServiceAsyncClient::header_future_bool_ret_map_param(apache::thrift::RpcOptions& rpcOptions, const ::std::map<::std::string, ::std::int64_t>& p_param1) {
folly::Promise<std::pair<bool, std::unique_ptr<apache::thrift::transport::THeader>>> promise;
auto future = promise.getFuture();
auto callback = std::make_unique<apache::thrift::HeaderFutureCallback<bool>>(std::move(promise), recv_wrapped_bool_ret_map_param, channel_);
bool_ret_map_param(rpcOptions, std::move(callback), p_param1);
return future;
}
folly::SemiFuture<std::pair<bool, std::unique_ptr<apache::thrift::transport::THeader>>> ParamServiceAsyncClient::header_semifuture_bool_ret_map_param(apache::thrift::RpcOptions& rpcOptions, const ::std::map<::std::string, ::std::int64_t>& p_param1) {
auto callbackAndFuture = makeHeaderSemiFutureCallback(recv_wrapped_bool_ret_map_param, channel_);
auto callback = std::move(callbackAndFuture.first);
bool_ret_map_param(rpcOptions, std::move(callback), p_param1);
return std::move(callbackAndFuture.second);
}
void ParamServiceAsyncClient::bool_ret_map_param(folly::Function<void (::apache::thrift::ClientReceiveState&&)> callback, const ::std::map<::std::string, ::std::int64_t>& p_param1) {
bool_ret_map_param(std::make_unique<apache::thrift::FunctionReplyCallback>(std::move(callback)), p_param1);
}
#if FOLLY_HAS_COROUTINES
#endif // FOLLY_HAS_COROUTINES
folly::exception_wrapper ParamServiceAsyncClient::recv_wrapped_bool_ret_map_param(bool& _return, ::apache::thrift::ClientReceiveState& state) {
if (state.isException()) {
return std::move(state.exception());
}
if (!state.hasResponseBuffer()) {
return folly::make_exception_wrapper<apache::thrift::TApplicationException>("recv_ called without result");
}
using result = ParamService_bool_ret_map_param_presult;
switch (state.protocolId()) {
case apache::thrift::protocol::T_BINARY_PROTOCOL:
{
apache::thrift::BinaryProtocolReader reader;
return apache::thrift::detail::ac::recv_wrapped<result>(
&reader, state, _return);
}
case apache::thrift::protocol::T_COMPACT_PROTOCOL:
{
apache::thrift::CompactProtocolReader reader;
return apache::thrift::detail::ac::recv_wrapped<result>(
&reader, state, _return);
}
default:
{
}
}
return folly::make_exception_wrapper<apache::thrift::TApplicationException>("Could not find Protocol");
}
bool ParamServiceAsyncClient::recv_bool_ret_map_param(::apache::thrift::ClientReceiveState& state) {
bool _return;
auto ew = recv_wrapped_bool_ret_map_param(_return, state);
if (ew) {
ew.throw_exception();
}
return _return;
}
bool ParamServiceAsyncClient::recv_instance_bool_ret_map_param(::apache::thrift::ClientReceiveState& state) {
return recv_bool_ret_map_param(state);
}
folly::exception_wrapper ParamServiceAsyncClient::recv_instance_wrapped_bool_ret_map_param(bool& _return, ::apache::thrift::ClientReceiveState& state) {
return recv_wrapped_bool_ret_map_param(_return, state);
}
void ParamServiceAsyncClient::bool_ret_union_param(std::unique_ptr<apache::thrift::RequestCallback> callback, const ::some::valid::ns::ComplexUnion& p_param1) {
::apache::thrift::RpcOptions rpcOptions;
bool_ret_union_param(rpcOptions, std::move(callback), p_param1);
}
void ParamServiceAsyncClient::bool_ret_union_param(apache::thrift::RpcOptions& rpcOptions, std::unique_ptr<apache::thrift::RequestCallback> callback, const ::some::valid::ns::ComplexUnion& p_param1) {
auto [ctx, header] = bool_ret_union_paramCtx(&rpcOptions);
apache::thrift::RequestCallback::Context callbackContext;
callbackContext.protocolId =
apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId();
auto* contextStack = ctx.get();
if (callback) {
callbackContext.ctx = std::move(ctx);
}
auto wrappedCallback = apache::thrift::toRequestClientCallbackPtr(std::move(callback), std::move(callbackContext));
bool_ret_union_paramImpl(rpcOptions, std::move(header), contextStack, std::move(wrappedCallback), p_param1);
}
void ParamServiceAsyncClient::bool_ret_union_paramImpl(const apache::thrift::RpcOptions& rpcOptions, std::shared_ptr<apache::thrift::transport::THeader> header, apache::thrift::ContextStack* contextStack, apache::thrift::RequestClientCallback::Ptr callback, const ::some::valid::ns::ComplexUnion& p_param1) {
switch (apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId()) {
case apache::thrift::protocol::T_BINARY_PROTOCOL:
{
apache::thrift::BinaryProtocolWriter writer;
bool_ret_union_paramT(&writer, rpcOptions, std::move(header), contextStack, std::move(callback), p_param1);
break;
}
case apache::thrift::protocol::T_COMPACT_PROTOCOL:
{
apache::thrift::CompactProtocolWriter writer;
bool_ret_union_paramT(&writer, rpcOptions, std::move(header), contextStack, std::move(callback), p_param1);
break;
}
default:
{
apache::thrift::detail::ac::throw_app_exn("Could not find Protocol");
}
}
}
std::pair<std::unique_ptr<::apache::thrift::ContextStack>, std::shared_ptr<::apache::thrift::transport::THeader>> ParamServiceAsyncClient::bool_ret_union_paramCtx(apache::thrift::RpcOptions* rpcOptions) {
auto header = std::make_shared<apache::thrift::transport::THeader>(
apache::thrift::transport::THeader::ALLOW_BIG_FRAMES);
header->setProtocolId(channel_->getProtocolId());
if (rpcOptions) {
header->setHeaders(rpcOptions->releaseWriteHeaders());
}
auto ctx = apache::thrift::ContextStack::createWithClientContext(
handlers_,
getServiceName(),
"ParamService.bool_ret_union_param",
*header);
return {std::move(ctx), std::move(header)};
}
bool ParamServiceAsyncClient::sync_bool_ret_union_param(const ::some::valid::ns::ComplexUnion& p_param1) {
::apache::thrift::RpcOptions rpcOptions;
return sync_bool_ret_union_param(rpcOptions, p_param1);
}
bool ParamServiceAsyncClient::sync_bool_ret_union_param(apache::thrift::RpcOptions& rpcOptions, const ::some::valid::ns::ComplexUnion& p_param1) {
apache::thrift::ClientReceiveState returnState;
apache::thrift::ClientSyncCallback<false> callback(&returnState);
auto protocolId = apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId();
auto evb = apache::thrift::GeneratedAsyncClient::getChannel()->getEventBase();
auto [ctx, header] = bool_ret_union_paramCtx(&rpcOptions);
auto wrappedCallback = apache::thrift::RequestClientCallback::Ptr(&callback);
bool_ret_union_paramImpl(rpcOptions, std::move(header), ctx.get(), std::move(wrappedCallback), p_param1);
callback.waitUntilDone(evb);
if (returnState.isException()) {
returnState.exception().throw_exception();
}
returnState.resetProtocolId(protocolId);
returnState.resetCtx(std::move(ctx));
SCOPE_EXIT {
if (returnState.header() && !returnState.header()->getHeaders().empty()) {
rpcOptions.setReadHeaders(returnState.header()->releaseHeaders());
}
};
return folly::fibers::runInMainContext([&] {
return recv_bool_ret_union_param(returnState);
});
}
folly::Future<bool> ParamServiceAsyncClient::future_bool_ret_union_param(const ::some::valid::ns::ComplexUnion& p_param1) {
::apache::thrift::RpcOptions rpcOptions;
return future_bool_ret_union_param(rpcOptions, p_param1);
}
folly::SemiFuture<bool> ParamServiceAsyncClient::semifuture_bool_ret_union_param(const ::some::valid::ns::ComplexUnion& p_param1) {
::apache::thrift::RpcOptions rpcOptions;
return semifuture_bool_ret_union_param(rpcOptions, p_param1);
}
folly::Future<bool> ParamServiceAsyncClient::future_bool_ret_union_param(apache::thrift::RpcOptions& rpcOptions, const ::some::valid::ns::ComplexUnion& p_param1) {
folly::Promise<bool> promise;
auto future = promise.getFuture();
auto callback = std::make_unique<apache::thrift::FutureCallback<bool>>(std::move(promise), recv_wrapped_bool_ret_union_param, channel_);
bool_ret_union_param(rpcOptions, std::move(callback), p_param1);
return future;
}
folly::SemiFuture<bool> ParamServiceAsyncClient::semifuture_bool_ret_union_param(apache::thrift::RpcOptions& rpcOptions, const ::some::valid::ns::ComplexUnion& p_param1) {
auto callbackAndFuture = makeSemiFutureCallback(recv_wrapped_bool_ret_union_param, channel_);
auto callback = std::move(callbackAndFuture.first);
bool_ret_union_param(rpcOptions, std::move(callback), p_param1);
return std::move(callbackAndFuture.second);
}
folly::Future<std::pair<bool, std::unique_ptr<apache::thrift::transport::THeader>>> ParamServiceAsyncClient::header_future_bool_ret_union_param(apache::thrift::RpcOptions& rpcOptions, const ::some::valid::ns::ComplexUnion& p_param1) {
folly::Promise<std::pair<bool, std::unique_ptr<apache::thrift::transport::THeader>>> promise;
auto future = promise.getFuture();
auto callback = std::make_unique<apache::thrift::HeaderFutureCallback<bool>>(std::move(promise), recv_wrapped_bool_ret_union_param, channel_);
bool_ret_union_param(rpcOptions, std::move(callback), p_param1);
return future;
}
folly::SemiFuture<std::pair<bool, std::unique_ptr<apache::thrift::transport::THeader>>> ParamServiceAsyncClient::header_semifuture_bool_ret_union_param(apache::thrift::RpcOptions& rpcOptions, const ::some::valid::ns::ComplexUnion& p_param1) {
auto callbackAndFuture = makeHeaderSemiFutureCallback(recv_wrapped_bool_ret_union_param, channel_);
auto callback = std::move(callbackAndFuture.first);
bool_ret_union_param(rpcOptions, std::move(callback), p_param1);
return std::move(callbackAndFuture.second);
}
void ParamServiceAsyncClient::bool_ret_union_param(folly::Function<void (::apache::thrift::ClientReceiveState&&)> callback, const ::some::valid::ns::ComplexUnion& p_param1) {
bool_ret_union_param(std::make_unique<apache::thrift::FunctionReplyCallback>(std::move(callback)), p_param1);
}
#if FOLLY_HAS_COROUTINES
#endif // FOLLY_HAS_COROUTINES
folly::exception_wrapper ParamServiceAsyncClient::recv_wrapped_bool_ret_union_param(bool& _return, ::apache::thrift::ClientReceiveState& state) {
if (state.isException()) {
return std::move(state.exception());
}
if (!state.hasResponseBuffer()) {
return folly::make_exception_wrapper<apache::thrift::TApplicationException>("recv_ called without result");
}
using result = ParamService_bool_ret_union_param_presult;
switch (state.protocolId()) {
case apache::thrift::protocol::T_BINARY_PROTOCOL:
{
apache::thrift::BinaryProtocolReader reader;
return apache::thrift::detail::ac::recv_wrapped<result>(
&reader, state, _return);
}
case apache::thrift::protocol::T_COMPACT_PROTOCOL:
{
apache::thrift::CompactProtocolReader reader;
return apache::thrift::detail::ac::recv_wrapped<result>(
&reader, state, _return);
}
default:
{
}
}
return folly::make_exception_wrapper<apache::thrift::TApplicationException>("Could not find Protocol");
}
bool ParamServiceAsyncClient::recv_bool_ret_union_param(::apache::thrift::ClientReceiveState& state) {
bool _return;
auto ew = recv_wrapped_bool_ret_union_param(_return, state);
if (ew) {
ew.throw_exception();
}
return _return;
}
bool ParamServiceAsyncClient::recv_instance_bool_ret_union_param(::apache::thrift::ClientReceiveState& state) {
return recv_bool_ret_union_param(state);
}
folly::exception_wrapper ParamServiceAsyncClient::recv_instance_wrapped_bool_ret_union_param(bool& _return, ::apache::thrift::ClientReceiveState& state) {
return recv_wrapped_bool_ret_union_param(_return, state);
}
void ParamServiceAsyncClient::i64_ret_float_double_param(std::unique_ptr<apache::thrift::RequestCallback> callback, float p_param1, double p_param2) {
::apache::thrift::RpcOptions rpcOptions;
i64_ret_float_double_param(rpcOptions, std::move(callback), p_param1, p_param2);
}
void ParamServiceAsyncClient::i64_ret_float_double_param(apache::thrift::RpcOptions& rpcOptions, std::unique_ptr<apache::thrift::RequestCallback> callback, float p_param1, double p_param2) {
auto [ctx, header] = i64_ret_float_double_paramCtx(&rpcOptions);
apache::thrift::RequestCallback::Context callbackContext;
callbackContext.protocolId =
apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId();
auto* contextStack = ctx.get();
if (callback) {
callbackContext.ctx = std::move(ctx);
}
auto wrappedCallback = apache::thrift::toRequestClientCallbackPtr(std::move(callback), std::move(callbackContext));
i64_ret_float_double_paramImpl(rpcOptions, std::move(header), contextStack, std::move(wrappedCallback), p_param1, p_param2);
}
void ParamServiceAsyncClient::i64_ret_float_double_paramImpl(const apache::thrift::RpcOptions& rpcOptions, std::shared_ptr<apache::thrift::transport::THeader> header, apache::thrift::ContextStack* contextStack, apache::thrift::RequestClientCallback::Ptr callback, float p_param1, double p_param2) {
switch (apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId()) {
case apache::thrift::protocol::T_BINARY_PROTOCOL:
{
apache::thrift::BinaryProtocolWriter writer;
i64_ret_float_double_paramT(&writer, rpcOptions, std::move(header), contextStack, std::move(callback), p_param1, p_param2);
break;
}
case apache::thrift::protocol::T_COMPACT_PROTOCOL:
{
apache::thrift::CompactProtocolWriter writer;
i64_ret_float_double_paramT(&writer, rpcOptions, std::move(header), contextStack, std::move(callback), p_param1, p_param2);
break;
}
default:
{
apache::thrift::detail::ac::throw_app_exn("Could not find Protocol");
}
}
}
std::pair<std::unique_ptr<::apache::thrift::ContextStack>, std::shared_ptr<::apache::thrift::transport::THeader>> ParamServiceAsyncClient::i64_ret_float_double_paramCtx(apache::thrift::RpcOptions* rpcOptions) {
auto header = std::make_shared<apache::thrift::transport::THeader>(
apache::thrift::transport::THeader::ALLOW_BIG_FRAMES);
header->setProtocolId(channel_->getProtocolId());
if (rpcOptions) {
header->setHeaders(rpcOptions->releaseWriteHeaders());
}
auto ctx = apache::thrift::ContextStack::createWithClientContext(
handlers_,
getServiceName(),
"ParamService.i64_ret_float_double_param",
*header);
return {std::move(ctx), std::move(header)};
}
::std::int64_t ParamServiceAsyncClient::sync_i64_ret_float_double_param(float p_param1, double p_param2) {
::apache::thrift::RpcOptions rpcOptions;
return sync_i64_ret_float_double_param(rpcOptions, p_param1, p_param2);
}
::std::int64_t ParamServiceAsyncClient::sync_i64_ret_float_double_param(apache::thrift::RpcOptions& rpcOptions, float p_param1, double p_param2) {
apache::thrift::ClientReceiveState returnState;
apache::thrift::ClientSyncCallback<false> callback(&returnState);
auto protocolId = apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId();
auto evb = apache::thrift::GeneratedAsyncClient::getChannel()->getEventBase();
auto [ctx, header] = i64_ret_float_double_paramCtx(&rpcOptions);
auto wrappedCallback = apache::thrift::RequestClientCallback::Ptr(&callback);
i64_ret_float_double_paramImpl(rpcOptions, std::move(header), ctx.get(), std::move(wrappedCallback), p_param1, p_param2);
callback.waitUntilDone(evb);
if (returnState.isException()) {
returnState.exception().throw_exception();
}
returnState.resetProtocolId(protocolId);
returnState.resetCtx(std::move(ctx));
SCOPE_EXIT {
if (returnState.header() && !returnState.header()->getHeaders().empty()) {
rpcOptions.setReadHeaders(returnState.header()->releaseHeaders());
}
};
return folly::fibers::runInMainContext([&] {
return recv_i64_ret_float_double_param(returnState);
});
}
folly::Future<::std::int64_t> ParamServiceAsyncClient::future_i64_ret_float_double_param(float p_param1, double p_param2) {
::apache::thrift::RpcOptions rpcOptions;
return future_i64_ret_float_double_param(rpcOptions, p_param1, p_param2);
}
folly::SemiFuture<::std::int64_t> ParamServiceAsyncClient::semifuture_i64_ret_float_double_param(float p_param1, double p_param2) {
::apache::thrift::RpcOptions rpcOptions;
return semifuture_i64_ret_float_double_param(rpcOptions, p_param1, p_param2);
}
folly::Future<::std::int64_t> ParamServiceAsyncClient::future_i64_ret_float_double_param(apache::thrift::RpcOptions& rpcOptions, float p_param1, double p_param2) {
folly::Promise<::std::int64_t> promise;
auto future = promise.getFuture();
auto callback = std::make_unique<apache::thrift::FutureCallback<::std::int64_t>>(std::move(promise), recv_wrapped_i64_ret_float_double_param, channel_);
i64_ret_float_double_param(rpcOptions, std::move(callback), p_param1, p_param2);
return future;
}
folly::SemiFuture<::std::int64_t> ParamServiceAsyncClient::semifuture_i64_ret_float_double_param(apache::thrift::RpcOptions& rpcOptions, float p_param1, double p_param2) {
auto callbackAndFuture = makeSemiFutureCallback(recv_wrapped_i64_ret_float_double_param, channel_);
auto callback = std::move(callbackAndFuture.first);
i64_ret_float_double_param(rpcOptions, std::move(callback), p_param1, p_param2);
return std::move(callbackAndFuture.second);
}
folly::Future<std::pair<::std::int64_t, std::unique_ptr<apache::thrift::transport::THeader>>> ParamServiceAsyncClient::header_future_i64_ret_float_double_param(apache::thrift::RpcOptions& rpcOptions, float p_param1, double p_param2) {
folly::Promise<std::pair<::std::int64_t, std::unique_ptr<apache::thrift::transport::THeader>>> promise;
auto future = promise.getFuture();
auto callback = std::make_unique<apache::thrift::HeaderFutureCallback<::std::int64_t>>(std::move(promise), recv_wrapped_i64_ret_float_double_param, channel_);
i64_ret_float_double_param(rpcOptions, std::move(callback), p_param1, p_param2);
return future;
}
folly::SemiFuture<std::pair<::std::int64_t, std::unique_ptr<apache::thrift::transport::THeader>>> ParamServiceAsyncClient::header_semifuture_i64_ret_float_double_param(apache::thrift::RpcOptions& rpcOptions, float p_param1, double p_param2) {
auto callbackAndFuture = makeHeaderSemiFutureCallback(recv_wrapped_i64_ret_float_double_param, channel_);
auto callback = std::move(callbackAndFuture.first);
i64_ret_float_double_param(rpcOptions, std::move(callback), p_param1, p_param2);
return std::move(callbackAndFuture.second);
}
void ParamServiceAsyncClient::i64_ret_float_double_param(folly::Function<void (::apache::thrift::ClientReceiveState&&)> callback, float p_param1, double p_param2) {
i64_ret_float_double_param(std::make_unique<apache::thrift::FunctionReplyCallback>(std::move(callback)), p_param1, p_param2);
}
#if FOLLY_HAS_COROUTINES
#endif // FOLLY_HAS_COROUTINES
folly::exception_wrapper ParamServiceAsyncClient::recv_wrapped_i64_ret_float_double_param(::std::int64_t& _return, ::apache::thrift::ClientReceiveState& state) {
if (state.isException()) {
return std::move(state.exception());
}
if (!state.hasResponseBuffer()) {
return folly::make_exception_wrapper<apache::thrift::TApplicationException>("recv_ called without result");
}
using result = ParamService_i64_ret_float_double_param_presult;
switch (state.protocolId()) {
case apache::thrift::protocol::T_BINARY_PROTOCOL:
{
apache::thrift::BinaryProtocolReader reader;
return apache::thrift::detail::ac::recv_wrapped<result>(
&reader, state, _return);
}
case apache::thrift::protocol::T_COMPACT_PROTOCOL:
{
apache::thrift::CompactProtocolReader reader;
return apache::thrift::detail::ac::recv_wrapped<result>(
&reader, state, _return);
}
default:
{
}
}
return folly::make_exception_wrapper<apache::thrift::TApplicationException>("Could not find Protocol");
}
::std::int64_t ParamServiceAsyncClient::recv_i64_ret_float_double_param(::apache::thrift::ClientReceiveState& state) {
::std::int64_t _return;
auto ew = recv_wrapped_i64_ret_float_double_param(_return, state);
if (ew) {
ew.throw_exception();
}
return _return;
}
::std::int64_t ParamServiceAsyncClient::recv_instance_i64_ret_float_double_param(::apache::thrift::ClientReceiveState& state) {
return recv_i64_ret_float_double_param(state);
}
folly::exception_wrapper ParamServiceAsyncClient::recv_instance_wrapped_i64_ret_float_double_param(::std::int64_t& _return, ::apache::thrift::ClientReceiveState& state) {
return recv_wrapped_i64_ret_float_double_param(_return, state);
}
void ParamServiceAsyncClient::i64_ret_string_typedef_param(std::unique_ptr<apache::thrift::RequestCallback> callback, const ::std::string& p_param1, const ::std::set<::some::valid::ns::mostComplexTypeDef>& p_param2) {
::apache::thrift::RpcOptions rpcOptions;
i64_ret_string_typedef_param(rpcOptions, std::move(callback), p_param1, p_param2);
}
void ParamServiceAsyncClient::i64_ret_string_typedef_param(apache::thrift::RpcOptions& rpcOptions, std::unique_ptr<apache::thrift::RequestCallback> callback, const ::std::string& p_param1, const ::std::set<::some::valid::ns::mostComplexTypeDef>& p_param2) {
auto [ctx, header] = i64_ret_string_typedef_paramCtx(&rpcOptions);
apache::thrift::RequestCallback::Context callbackContext;
callbackContext.protocolId =
apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId();
auto* contextStack = ctx.get();
if (callback) {
callbackContext.ctx = std::move(ctx);
}
auto wrappedCallback = apache::thrift::toRequestClientCallbackPtr(std::move(callback), std::move(callbackContext));
i64_ret_string_typedef_paramImpl(rpcOptions, std::move(header), contextStack, std::move(wrappedCallback), p_param1, p_param2);
}
void ParamServiceAsyncClient::i64_ret_string_typedef_paramImpl(const apache::thrift::RpcOptions& rpcOptions, std::shared_ptr<apache::thrift::transport::THeader> header, apache::thrift::ContextStack* contextStack, apache::thrift::RequestClientCallback::Ptr callback, const ::std::string& p_param1, const ::std::set<::some::valid::ns::mostComplexTypeDef>& p_param2) {
switch (apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId()) {
case apache::thrift::protocol::T_BINARY_PROTOCOL:
{
apache::thrift::BinaryProtocolWriter writer;
i64_ret_string_typedef_paramT(&writer, rpcOptions, std::move(header), contextStack, std::move(callback), p_param1, p_param2);
break;
}
case apache::thrift::protocol::T_COMPACT_PROTOCOL:
{
apache::thrift::CompactProtocolWriter writer;
i64_ret_string_typedef_paramT(&writer, rpcOptions, std::move(header), contextStack, std::move(callback), p_param1, p_param2);
break;
}
default:
{
apache::thrift::detail::ac::throw_app_exn("Could not find Protocol");
}
}
}
std::pair<std::unique_ptr<::apache::thrift::ContextStack>, std::shared_ptr<::apache::thrift::transport::THeader>> ParamServiceAsyncClient::i64_ret_string_typedef_paramCtx(apache::thrift::RpcOptions* rpcOptions) {
auto header = std::make_shared<apache::thrift::transport::THeader>(
apache::thrift::transport::THeader::ALLOW_BIG_FRAMES);
header->setProtocolId(channel_->getProtocolId());
if (rpcOptions) {
header->setHeaders(rpcOptions->releaseWriteHeaders());
}
auto ctx = apache::thrift::ContextStack::createWithClientContext(
handlers_,
getServiceName(),
"ParamService.i64_ret_string_typedef_param",
*header);
return {std::move(ctx), std::move(header)};
}
::std::int64_t ParamServiceAsyncClient::sync_i64_ret_string_typedef_param(const ::std::string& p_param1, const ::std::set<::some::valid::ns::mostComplexTypeDef>& p_param2) {
::apache::thrift::RpcOptions rpcOptions;
return sync_i64_ret_string_typedef_param(rpcOptions, p_param1, p_param2);
}
::std::int64_t ParamServiceAsyncClient::sync_i64_ret_string_typedef_param(apache::thrift::RpcOptions& rpcOptions, const ::std::string& p_param1, const ::std::set<::some::valid::ns::mostComplexTypeDef>& p_param2) {
apache::thrift::ClientReceiveState returnState;
apache::thrift::ClientSyncCallback<false> callback(&returnState);
auto protocolId = apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId();
auto evb = apache::thrift::GeneratedAsyncClient::getChannel()->getEventBase();
auto [ctx, header] = i64_ret_string_typedef_paramCtx(&rpcOptions);
auto wrappedCallback = apache::thrift::RequestClientCallback::Ptr(&callback);
i64_ret_string_typedef_paramImpl(rpcOptions, std::move(header), ctx.get(), std::move(wrappedCallback), p_param1, p_param2);
callback.waitUntilDone(evb);
if (returnState.isException()) {
returnState.exception().throw_exception();
}
returnState.resetProtocolId(protocolId);
returnState.resetCtx(std::move(ctx));
SCOPE_EXIT {
if (returnState.header() && !returnState.header()->getHeaders().empty()) {
rpcOptions.setReadHeaders(returnState.header()->releaseHeaders());
}
};
return folly::fibers::runInMainContext([&] {
return recv_i64_ret_string_typedef_param(returnState);
});
}
folly::Future<::std::int64_t> ParamServiceAsyncClient::future_i64_ret_string_typedef_param(const ::std::string& p_param1, const ::std::set<::some::valid::ns::mostComplexTypeDef>& p_param2) {
::apache::thrift::RpcOptions rpcOptions;
return future_i64_ret_string_typedef_param(rpcOptions, p_param1, p_param2);
}
folly::SemiFuture<::std::int64_t> ParamServiceAsyncClient::semifuture_i64_ret_string_typedef_param(const ::std::string& p_param1, const ::std::set<::some::valid::ns::mostComplexTypeDef>& p_param2) {
::apache::thrift::RpcOptions rpcOptions;
return semifuture_i64_ret_string_typedef_param(rpcOptions, p_param1, p_param2);
}
folly::Future<::std::int64_t> ParamServiceAsyncClient::future_i64_ret_string_typedef_param(apache::thrift::RpcOptions& rpcOptions, const ::std::string& p_param1, const ::std::set<::some::valid::ns::mostComplexTypeDef>& p_param2) {
folly::Promise<::std::int64_t> promise;
auto future = promise.getFuture();
auto callback = std::make_unique<apache::thrift::FutureCallback<::std::int64_t>>(std::move(promise), recv_wrapped_i64_ret_string_typedef_param, channel_);
i64_ret_string_typedef_param(rpcOptions, std::move(callback), p_param1, p_param2);
return future;
}
folly::SemiFuture<::std::int64_t> ParamServiceAsyncClient::semifuture_i64_ret_string_typedef_param(apache::thrift::RpcOptions& rpcOptions, const ::std::string& p_param1, const ::std::set<::some::valid::ns::mostComplexTypeDef>& p_param2) {
auto callbackAndFuture = makeSemiFutureCallback(recv_wrapped_i64_ret_string_typedef_param, channel_);
auto callback = std::move(callbackAndFuture.first);
i64_ret_string_typedef_param(rpcOptions, std::move(callback), p_param1, p_param2);
return std::move(callbackAndFuture.second);
}
folly::Future<std::pair<::std::int64_t, std::unique_ptr<apache::thrift::transport::THeader>>> ParamServiceAsyncClient::header_future_i64_ret_string_typedef_param(apache::thrift::RpcOptions& rpcOptions, const ::std::string& p_param1, const ::std::set<::some::valid::ns::mostComplexTypeDef>& p_param2) {
folly::Promise<std::pair<::std::int64_t, std::unique_ptr<apache::thrift::transport::THeader>>> promise;
auto future = promise.getFuture();
auto callback = std::make_unique<apache::thrift::HeaderFutureCallback<::std::int64_t>>(std::move(promise), recv_wrapped_i64_ret_string_typedef_param, channel_);
i64_ret_string_typedef_param(rpcOptions, std::move(callback), p_param1, p_param2);
return future;
}
folly::SemiFuture<std::pair<::std::int64_t, std::unique_ptr<apache::thrift::transport::THeader>>> ParamServiceAsyncClient::header_semifuture_i64_ret_string_typedef_param(apache::thrift::RpcOptions& rpcOptions, const ::std::string& p_param1, const ::std::set<::some::valid::ns::mostComplexTypeDef>& p_param2) {
auto callbackAndFuture = makeHeaderSemiFutureCallback(recv_wrapped_i64_ret_string_typedef_param, channel_);
auto callback = std::move(callbackAndFuture.first);
i64_ret_string_typedef_param(rpcOptions, std::move(callback), p_param1, p_param2);
return std::move(callbackAndFuture.second);
}
void ParamServiceAsyncClient::i64_ret_string_typedef_param(folly::Function<void (::apache::thrift::ClientReceiveState&&)> callback, const ::std::string& p_param1, const ::std::set<::some::valid::ns::mostComplexTypeDef>& p_param2) {
i64_ret_string_typedef_param(std::make_unique<apache::thrift::FunctionReplyCallback>(std::move(callback)), p_param1, p_param2);
}
#if FOLLY_HAS_COROUTINES
#endif // FOLLY_HAS_COROUTINES
folly::exception_wrapper ParamServiceAsyncClient::recv_wrapped_i64_ret_string_typedef_param(::std::int64_t& _return, ::apache::thrift::ClientReceiveState& state) {
if (state.isException()) {
return std::move(state.exception());
}
if (!state.hasResponseBuffer()) {
return folly::make_exception_wrapper<apache::thrift::TApplicationException>("recv_ called without result");
}
using result = ParamService_i64_ret_string_typedef_param_presult;
switch (state.protocolId()) {
case apache::thrift::protocol::T_BINARY_PROTOCOL:
{
apache::thrift::BinaryProtocolReader reader;
return apache::thrift::detail::ac::recv_wrapped<result>(
&reader, state, _return);
}
case apache::thrift::protocol::T_COMPACT_PROTOCOL:
{
apache::thrift::CompactProtocolReader reader;
return apache::thrift::detail::ac::recv_wrapped<result>(
&reader, state, _return);
}
default:
{
}
}
return folly::make_exception_wrapper<apache::thrift::TApplicationException>("Could not find Protocol");
}
::std::int64_t ParamServiceAsyncClient::recv_i64_ret_string_typedef_param(::apache::thrift::ClientReceiveState& state) {
::std::int64_t _return;
auto ew = recv_wrapped_i64_ret_string_typedef_param(_return, state);
if (ew) {
ew.throw_exception();
}
return _return;
}
::std::int64_t ParamServiceAsyncClient::recv_instance_i64_ret_string_typedef_param(::apache::thrift::ClientReceiveState& state) {
return recv_i64_ret_string_typedef_param(state);
}
folly::exception_wrapper ParamServiceAsyncClient::recv_instance_wrapped_i64_ret_string_typedef_param(::std::int64_t& _return, ::apache::thrift::ClientReceiveState& state) {
return recv_wrapped_i64_ret_string_typedef_param(_return, state);
}
void ParamServiceAsyncClient::i64_ret_i32_i32_i32_i32_i32_param(std::unique_ptr<apache::thrift::RequestCallback> callback, ::std::int32_t p_param1, ::std::int32_t p_param2, ::std::int32_t p_param3, ::std::int32_t p_param4, ::std::int32_t p_param5) {
::apache::thrift::RpcOptions rpcOptions;
i64_ret_i32_i32_i32_i32_i32_param(rpcOptions, std::move(callback), p_param1, p_param2, p_param3, p_param4, p_param5);
}
void ParamServiceAsyncClient::i64_ret_i32_i32_i32_i32_i32_param(apache::thrift::RpcOptions& rpcOptions, std::unique_ptr<apache::thrift::RequestCallback> callback, ::std::int32_t p_param1, ::std::int32_t p_param2, ::std::int32_t p_param3, ::std::int32_t p_param4, ::std::int32_t p_param5) {
auto [ctx, header] = i64_ret_i32_i32_i32_i32_i32_paramCtx(&rpcOptions);
apache::thrift::RequestCallback::Context callbackContext;
callbackContext.protocolId =
apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId();
auto* contextStack = ctx.get();
if (callback) {
callbackContext.ctx = std::move(ctx);
}
auto wrappedCallback = apache::thrift::toRequestClientCallbackPtr(std::move(callback), std::move(callbackContext));
i64_ret_i32_i32_i32_i32_i32_paramImpl(rpcOptions, std::move(header), contextStack, std::move(wrappedCallback), p_param1, p_param2, p_param3, p_param4, p_param5);
}
void ParamServiceAsyncClient::i64_ret_i32_i32_i32_i32_i32_paramImpl(const apache::thrift::RpcOptions& rpcOptions, std::shared_ptr<apache::thrift::transport::THeader> header, apache::thrift::ContextStack* contextStack, apache::thrift::RequestClientCallback::Ptr callback, ::std::int32_t p_param1, ::std::int32_t p_param2, ::std::int32_t p_param3, ::std::int32_t p_param4, ::std::int32_t p_param5) {
switch (apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId()) {
case apache::thrift::protocol::T_BINARY_PROTOCOL:
{
apache::thrift::BinaryProtocolWriter writer;
i64_ret_i32_i32_i32_i32_i32_paramT(&writer, rpcOptions, std::move(header), contextStack, std::move(callback), p_param1, p_param2, p_param3, p_param4, p_param5);
break;
}
case apache::thrift::protocol::T_COMPACT_PROTOCOL:
{
apache::thrift::CompactProtocolWriter writer;
i64_ret_i32_i32_i32_i32_i32_paramT(&writer, rpcOptions, std::move(header), contextStack, std::move(callback), p_param1, p_param2, p_param3, p_param4, p_param5);
break;
}
default:
{
apache::thrift::detail::ac::throw_app_exn("Could not find Protocol");
}
}
}
std::pair<std::unique_ptr<::apache::thrift::ContextStack>, std::shared_ptr<::apache::thrift::transport::THeader>> ParamServiceAsyncClient::i64_ret_i32_i32_i32_i32_i32_paramCtx(apache::thrift::RpcOptions* rpcOptions) {
auto header = std::make_shared<apache::thrift::transport::THeader>(
apache::thrift::transport::THeader::ALLOW_BIG_FRAMES);
header->setProtocolId(channel_->getProtocolId());
if (rpcOptions) {
header->setHeaders(rpcOptions->releaseWriteHeaders());
}
auto ctx = apache::thrift::ContextStack::createWithClientContext(
handlers_,
getServiceName(),
"ParamService.i64_ret_i32_i32_i32_i32_i32_param",
*header);
return {std::move(ctx), std::move(header)};
}
::std::int64_t ParamServiceAsyncClient::sync_i64_ret_i32_i32_i32_i32_i32_param(::std::int32_t p_param1, ::std::int32_t p_param2, ::std::int32_t p_param3, ::std::int32_t p_param4, ::std::int32_t p_param5) {
::apache::thrift::RpcOptions rpcOptions;
return sync_i64_ret_i32_i32_i32_i32_i32_param(rpcOptions, p_param1, p_param2, p_param3, p_param4, p_param5);
}
::std::int64_t ParamServiceAsyncClient::sync_i64_ret_i32_i32_i32_i32_i32_param(apache::thrift::RpcOptions& rpcOptions, ::std::int32_t p_param1, ::std::int32_t p_param2, ::std::int32_t p_param3, ::std::int32_t p_param4, ::std::int32_t p_param5) {
apache::thrift::ClientReceiveState returnState;
apache::thrift::ClientSyncCallback<false> callback(&returnState);
auto protocolId = apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId();
auto evb = apache::thrift::GeneratedAsyncClient::getChannel()->getEventBase();
auto [ctx, header] = i64_ret_i32_i32_i32_i32_i32_paramCtx(&rpcOptions);
auto wrappedCallback = apache::thrift::RequestClientCallback::Ptr(&callback);
i64_ret_i32_i32_i32_i32_i32_paramImpl(rpcOptions, std::move(header), ctx.get(), std::move(wrappedCallback), p_param1, p_param2, p_param3, p_param4, p_param5);
callback.waitUntilDone(evb);
if (returnState.isException()) {
returnState.exception().throw_exception();
}
returnState.resetProtocolId(protocolId);
returnState.resetCtx(std::move(ctx));
SCOPE_EXIT {
if (returnState.header() && !returnState.header()->getHeaders().empty()) {
rpcOptions.setReadHeaders(returnState.header()->releaseHeaders());
}
};
return folly::fibers::runInMainContext([&] {
return recv_i64_ret_i32_i32_i32_i32_i32_param(returnState);
});
}
folly::Future<::std::int64_t> ParamServiceAsyncClient::future_i64_ret_i32_i32_i32_i32_i32_param(::std::int32_t p_param1, ::std::int32_t p_param2, ::std::int32_t p_param3, ::std::int32_t p_param4, ::std::int32_t p_param5) {
::apache::thrift::RpcOptions rpcOptions;
return future_i64_ret_i32_i32_i32_i32_i32_param(rpcOptions, p_param1, p_param2, p_param3, p_param4, p_param5);
}
folly::SemiFuture<::std::int64_t> ParamServiceAsyncClient::semifuture_i64_ret_i32_i32_i32_i32_i32_param(::std::int32_t p_param1, ::std::int32_t p_param2, ::std::int32_t p_param3, ::std::int32_t p_param4, ::std::int32_t p_param5) {
::apache::thrift::RpcOptions rpcOptions;
return semifuture_i64_ret_i32_i32_i32_i32_i32_param(rpcOptions, p_param1, p_param2, p_param3, p_param4, p_param5);
}
folly::Future<::std::int64_t> ParamServiceAsyncClient::future_i64_ret_i32_i32_i32_i32_i32_param(apache::thrift::RpcOptions& rpcOptions, ::std::int32_t p_param1, ::std::int32_t p_param2, ::std::int32_t p_param3, ::std::int32_t p_param4, ::std::int32_t p_param5) {
folly::Promise<::std::int64_t> promise;
auto future = promise.getFuture();
auto callback = std::make_unique<apache::thrift::FutureCallback<::std::int64_t>>(std::move(promise), recv_wrapped_i64_ret_i32_i32_i32_i32_i32_param, channel_);
i64_ret_i32_i32_i32_i32_i32_param(rpcOptions, std::move(callback), p_param1, p_param2, p_param3, p_param4, p_param5);
return future;
}
folly::SemiFuture<::std::int64_t> ParamServiceAsyncClient::semifuture_i64_ret_i32_i32_i32_i32_i32_param(apache::thrift::RpcOptions& rpcOptions, ::std::int32_t p_param1, ::std::int32_t p_param2, ::std::int32_t p_param3, ::std::int32_t p_param4, ::std::int32_t p_param5) {
auto callbackAndFuture = makeSemiFutureCallback(recv_wrapped_i64_ret_i32_i32_i32_i32_i32_param, channel_);
auto callback = std::move(callbackAndFuture.first);
i64_ret_i32_i32_i32_i32_i32_param(rpcOptions, std::move(callback), p_param1, p_param2, p_param3, p_param4, p_param5);
return std::move(callbackAndFuture.second);
}
folly::Future<std::pair<::std::int64_t, std::unique_ptr<apache::thrift::transport::THeader>>> ParamServiceAsyncClient::header_future_i64_ret_i32_i32_i32_i32_i32_param(apache::thrift::RpcOptions& rpcOptions, ::std::int32_t p_param1, ::std::int32_t p_param2, ::std::int32_t p_param3, ::std::int32_t p_param4, ::std::int32_t p_param5) {
folly::Promise<std::pair<::std::int64_t, std::unique_ptr<apache::thrift::transport::THeader>>> promise;
auto future = promise.getFuture();
auto callback = std::make_unique<apache::thrift::HeaderFutureCallback<::std::int64_t>>(std::move(promise), recv_wrapped_i64_ret_i32_i32_i32_i32_i32_param, channel_);
i64_ret_i32_i32_i32_i32_i32_param(rpcOptions, std::move(callback), p_param1, p_param2, p_param3, p_param4, p_param5);
return future;
}
folly::SemiFuture<std::pair<::std::int64_t, std::unique_ptr<apache::thrift::transport::THeader>>> ParamServiceAsyncClient::header_semifuture_i64_ret_i32_i32_i32_i32_i32_param(apache::thrift::RpcOptions& rpcOptions, ::std::int32_t p_param1, ::std::int32_t p_param2, ::std::int32_t p_param3, ::std::int32_t p_param4, ::std::int32_t p_param5) {
auto callbackAndFuture = makeHeaderSemiFutureCallback(recv_wrapped_i64_ret_i32_i32_i32_i32_i32_param, channel_);
auto callback = std::move(callbackAndFuture.first);
i64_ret_i32_i32_i32_i32_i32_param(rpcOptions, std::move(callback), p_param1, p_param2, p_param3, p_param4, p_param5);
return std::move(callbackAndFuture.second);
}
void ParamServiceAsyncClient::i64_ret_i32_i32_i32_i32_i32_param(folly::Function<void (::apache::thrift::ClientReceiveState&&)> callback, ::std::int32_t p_param1, ::std::int32_t p_param2, ::std::int32_t p_param3, ::std::int32_t p_param4, ::std::int32_t p_param5) {
i64_ret_i32_i32_i32_i32_i32_param(std::make_unique<apache::thrift::FunctionReplyCallback>(std::move(callback)), p_param1, p_param2, p_param3, p_param4, p_param5);
}
#if FOLLY_HAS_COROUTINES
#endif // FOLLY_HAS_COROUTINES
folly::exception_wrapper ParamServiceAsyncClient::recv_wrapped_i64_ret_i32_i32_i32_i32_i32_param(::std::int64_t& _return, ::apache::thrift::ClientReceiveState& state) {
if (state.isException()) {
return std::move(state.exception());
}
if (!state.hasResponseBuffer()) {
return folly::make_exception_wrapper<apache::thrift::TApplicationException>("recv_ called without result");
}
using result = ParamService_i64_ret_i32_i32_i32_i32_i32_param_presult;
switch (state.protocolId()) {
case apache::thrift::protocol::T_BINARY_PROTOCOL:
{
apache::thrift::BinaryProtocolReader reader;
return apache::thrift::detail::ac::recv_wrapped<result>(
&reader, state, _return);
}
case apache::thrift::protocol::T_COMPACT_PROTOCOL:
{
apache::thrift::CompactProtocolReader reader;
return apache::thrift::detail::ac::recv_wrapped<result>(
&reader, state, _return);
}
default:
{
}
}
return folly::make_exception_wrapper<apache::thrift::TApplicationException>("Could not find Protocol");
}
::std::int64_t ParamServiceAsyncClient::recv_i64_ret_i32_i32_i32_i32_i32_param(::apache::thrift::ClientReceiveState& state) {
::std::int64_t _return;
auto ew = recv_wrapped_i64_ret_i32_i32_i32_i32_i32_param(_return, state);
if (ew) {
ew.throw_exception();
}
return _return;
}
::std::int64_t ParamServiceAsyncClient::recv_instance_i64_ret_i32_i32_i32_i32_i32_param(::apache::thrift::ClientReceiveState& state) {
return recv_i64_ret_i32_i32_i32_i32_i32_param(state);
}
folly::exception_wrapper ParamServiceAsyncClient::recv_instance_wrapped_i64_ret_i32_i32_i32_i32_i32_param(::std::int64_t& _return, ::apache::thrift::ClientReceiveState& state) {
return recv_wrapped_i64_ret_i32_i32_i32_i32_i32_param(_return, state);
}
void ParamServiceAsyncClient::double_ret_setstruct_param(std::unique_ptr<apache::thrift::RequestCallback> callback, const ::std::set<::some::valid::ns::MyStruct>& p_param1) {
::apache::thrift::RpcOptions rpcOptions;
double_ret_setstruct_param(rpcOptions, std::move(callback), p_param1);
}
void ParamServiceAsyncClient::double_ret_setstruct_param(apache::thrift::RpcOptions& rpcOptions, std::unique_ptr<apache::thrift::RequestCallback> callback, const ::std::set<::some::valid::ns::MyStruct>& p_param1) {
auto [ctx, header] = double_ret_setstruct_paramCtx(&rpcOptions);
apache::thrift::RequestCallback::Context callbackContext;
callbackContext.protocolId =
apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId();
auto* contextStack = ctx.get();
if (callback) {
callbackContext.ctx = std::move(ctx);
}
auto wrappedCallback = apache::thrift::toRequestClientCallbackPtr(std::move(callback), std::move(callbackContext));
double_ret_setstruct_paramImpl(rpcOptions, std::move(header), contextStack, std::move(wrappedCallback), p_param1);
}
void ParamServiceAsyncClient::double_ret_setstruct_paramImpl(const apache::thrift::RpcOptions& rpcOptions, std::shared_ptr<apache::thrift::transport::THeader> header, apache::thrift::ContextStack* contextStack, apache::thrift::RequestClientCallback::Ptr callback, const ::std::set<::some::valid::ns::MyStruct>& p_param1) {
switch (apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId()) {
case apache::thrift::protocol::T_BINARY_PROTOCOL:
{
apache::thrift::BinaryProtocolWriter writer;
double_ret_setstruct_paramT(&writer, rpcOptions, std::move(header), contextStack, std::move(callback), p_param1);
break;
}
case apache::thrift::protocol::T_COMPACT_PROTOCOL:
{
apache::thrift::CompactProtocolWriter writer;
double_ret_setstruct_paramT(&writer, rpcOptions, std::move(header), contextStack, std::move(callback), p_param1);
break;
}
default:
{
apache::thrift::detail::ac::throw_app_exn("Could not find Protocol");
}
}
}
std::pair<std::unique_ptr<::apache::thrift::ContextStack>, std::shared_ptr<::apache::thrift::transport::THeader>> ParamServiceAsyncClient::double_ret_setstruct_paramCtx(apache::thrift::RpcOptions* rpcOptions) {
auto header = std::make_shared<apache::thrift::transport::THeader>(
apache::thrift::transport::THeader::ALLOW_BIG_FRAMES);
header->setProtocolId(channel_->getProtocolId());
if (rpcOptions) {
header->setHeaders(rpcOptions->releaseWriteHeaders());
}
auto ctx = apache::thrift::ContextStack::createWithClientContext(
handlers_,
getServiceName(),
"ParamService.double_ret_setstruct_param",
*header);
return {std::move(ctx), std::move(header)};
}
double ParamServiceAsyncClient::sync_double_ret_setstruct_param(const ::std::set<::some::valid::ns::MyStruct>& p_param1) {
::apache::thrift::RpcOptions rpcOptions;
return sync_double_ret_setstruct_param(rpcOptions, p_param1);
}
double ParamServiceAsyncClient::sync_double_ret_setstruct_param(apache::thrift::RpcOptions& rpcOptions, const ::std::set<::some::valid::ns::MyStruct>& p_param1) {
apache::thrift::ClientReceiveState returnState;
apache::thrift::ClientSyncCallback<false> callback(&returnState);
auto protocolId = apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId();
auto evb = apache::thrift::GeneratedAsyncClient::getChannel()->getEventBase();
auto [ctx, header] = double_ret_setstruct_paramCtx(&rpcOptions);
auto wrappedCallback = apache::thrift::RequestClientCallback::Ptr(&callback);
double_ret_setstruct_paramImpl(rpcOptions, std::move(header), ctx.get(), std::move(wrappedCallback), p_param1);
callback.waitUntilDone(evb);
if (returnState.isException()) {
returnState.exception().throw_exception();
}
returnState.resetProtocolId(protocolId);
returnState.resetCtx(std::move(ctx));
SCOPE_EXIT {
if (returnState.header() && !returnState.header()->getHeaders().empty()) {
rpcOptions.setReadHeaders(returnState.header()->releaseHeaders());
}
};
return folly::fibers::runInMainContext([&] {
return recv_double_ret_setstruct_param(returnState);
});
}
folly::Future<double> ParamServiceAsyncClient::future_double_ret_setstruct_param(const ::std::set<::some::valid::ns::MyStruct>& p_param1) {
::apache::thrift::RpcOptions rpcOptions;
return future_double_ret_setstruct_param(rpcOptions, p_param1);
}
folly::SemiFuture<double> ParamServiceAsyncClient::semifuture_double_ret_setstruct_param(const ::std::set<::some::valid::ns::MyStruct>& p_param1) {
::apache::thrift::RpcOptions rpcOptions;
return semifuture_double_ret_setstruct_param(rpcOptions, p_param1);
}
folly::Future<double> ParamServiceAsyncClient::future_double_ret_setstruct_param(apache::thrift::RpcOptions& rpcOptions, const ::std::set<::some::valid::ns::MyStruct>& p_param1) {
folly::Promise<double> promise;
auto future = promise.getFuture();
auto callback = std::make_unique<apache::thrift::FutureCallback<double>>(std::move(promise), recv_wrapped_double_ret_setstruct_param, channel_);
double_ret_setstruct_param(rpcOptions, std::move(callback), p_param1);
return future;
}
folly::SemiFuture<double> ParamServiceAsyncClient::semifuture_double_ret_setstruct_param(apache::thrift::RpcOptions& rpcOptions, const ::std::set<::some::valid::ns::MyStruct>& p_param1) {
auto callbackAndFuture = makeSemiFutureCallback(recv_wrapped_double_ret_setstruct_param, channel_);
auto callback = std::move(callbackAndFuture.first);
double_ret_setstruct_param(rpcOptions, std::move(callback), p_param1);
return std::move(callbackAndFuture.second);
}
folly::Future<std::pair<double, std::unique_ptr<apache::thrift::transport::THeader>>> ParamServiceAsyncClient::header_future_double_ret_setstruct_param(apache::thrift::RpcOptions& rpcOptions, const ::std::set<::some::valid::ns::MyStruct>& p_param1) {
folly::Promise<std::pair<double, std::unique_ptr<apache::thrift::transport::THeader>>> promise;
auto future = promise.getFuture();
auto callback = std::make_unique<apache::thrift::HeaderFutureCallback<double>>(std::move(promise), recv_wrapped_double_ret_setstruct_param, channel_);
double_ret_setstruct_param(rpcOptions, std::move(callback), p_param1);
return future;
}
folly::SemiFuture<std::pair<double, std::unique_ptr<apache::thrift::transport::THeader>>> ParamServiceAsyncClient::header_semifuture_double_ret_setstruct_param(apache::thrift::RpcOptions& rpcOptions, const ::std::set<::some::valid::ns::MyStruct>& p_param1) {
auto callbackAndFuture = makeHeaderSemiFutureCallback(recv_wrapped_double_ret_setstruct_param, channel_);
auto callback = std::move(callbackAndFuture.first);
double_ret_setstruct_param(rpcOptions, std::move(callback), p_param1);
return std::move(callbackAndFuture.second);
}
void ParamServiceAsyncClient::double_ret_setstruct_param(folly::Function<void (::apache::thrift::ClientReceiveState&&)> callback, const ::std::set<::some::valid::ns::MyStruct>& p_param1) {
double_ret_setstruct_param(std::make_unique<apache::thrift::FunctionReplyCallback>(std::move(callback)), p_param1);
}
#if FOLLY_HAS_COROUTINES
#endif // FOLLY_HAS_COROUTINES
folly::exception_wrapper ParamServiceAsyncClient::recv_wrapped_double_ret_setstruct_param(double& _return, ::apache::thrift::ClientReceiveState& state) {
if (state.isException()) {
return std::move(state.exception());
}
if (!state.hasResponseBuffer()) {
return folly::make_exception_wrapper<apache::thrift::TApplicationException>("recv_ called without result");
}
using result = ParamService_double_ret_setstruct_param_presult;
switch (state.protocolId()) {
case apache::thrift::protocol::T_BINARY_PROTOCOL:
{
apache::thrift::BinaryProtocolReader reader;
return apache::thrift::detail::ac::recv_wrapped<result>(
&reader, state, _return);
}
case apache::thrift::protocol::T_COMPACT_PROTOCOL:
{
apache::thrift::CompactProtocolReader reader;
return apache::thrift::detail::ac::recv_wrapped<result>(
&reader, state, _return);
}
default:
{
}
}
return folly::make_exception_wrapper<apache::thrift::TApplicationException>("Could not find Protocol");
}
double ParamServiceAsyncClient::recv_double_ret_setstruct_param(::apache::thrift::ClientReceiveState& state) {
double _return;
auto ew = recv_wrapped_double_ret_setstruct_param(_return, state);
if (ew) {
ew.throw_exception();
}
return _return;
}
double ParamServiceAsyncClient::recv_instance_double_ret_setstruct_param(::apache::thrift::ClientReceiveState& state) {
return recv_double_ret_setstruct_param(state);
}
folly::exception_wrapper ParamServiceAsyncClient::recv_instance_wrapped_double_ret_setstruct_param(double& _return, ::apache::thrift::ClientReceiveState& state) {
return recv_wrapped_double_ret_setstruct_param(_return, state);
}
void ParamServiceAsyncClient::string_ret_string_param(std::unique_ptr<apache::thrift::RequestCallback> callback, const ::std::string& p_param1) {
::apache::thrift::RpcOptions rpcOptions;
string_ret_string_param(rpcOptions, std::move(callback), p_param1);
}
void ParamServiceAsyncClient::string_ret_string_param(apache::thrift::RpcOptions& rpcOptions, std::unique_ptr<apache::thrift::RequestCallback> callback, const ::std::string& p_param1) {
auto [ctx, header] = string_ret_string_paramCtx(&rpcOptions);
apache::thrift::RequestCallback::Context callbackContext;
callbackContext.protocolId =
apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId();
auto* contextStack = ctx.get();
if (callback) {
callbackContext.ctx = std::move(ctx);
}
auto wrappedCallback = apache::thrift::toRequestClientCallbackPtr(std::move(callback), std::move(callbackContext));
string_ret_string_paramImpl(rpcOptions, std::move(header), contextStack, std::move(wrappedCallback), p_param1);
}
void ParamServiceAsyncClient::string_ret_string_paramImpl(const apache::thrift::RpcOptions& rpcOptions, std::shared_ptr<apache::thrift::transport::THeader> header, apache::thrift::ContextStack* contextStack, apache::thrift::RequestClientCallback::Ptr callback, const ::std::string& p_param1) {
switch (apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId()) {
case apache::thrift::protocol::T_BINARY_PROTOCOL:
{
apache::thrift::BinaryProtocolWriter writer;
string_ret_string_paramT(&writer, rpcOptions, std::move(header), contextStack, std::move(callback), p_param1);
break;
}
case apache::thrift::protocol::T_COMPACT_PROTOCOL:
{
apache::thrift::CompactProtocolWriter writer;
string_ret_string_paramT(&writer, rpcOptions, std::move(header), contextStack, std::move(callback), p_param1);
break;
}
default:
{
apache::thrift::detail::ac::throw_app_exn("Could not find Protocol");
}
}
}
std::pair<std::unique_ptr<::apache::thrift::ContextStack>, std::shared_ptr<::apache::thrift::transport::THeader>> ParamServiceAsyncClient::string_ret_string_paramCtx(apache::thrift::RpcOptions* rpcOptions) {
auto header = std::make_shared<apache::thrift::transport::THeader>(
apache::thrift::transport::THeader::ALLOW_BIG_FRAMES);
header->setProtocolId(channel_->getProtocolId());
if (rpcOptions) {
header->setHeaders(rpcOptions->releaseWriteHeaders());
}
auto ctx = apache::thrift::ContextStack::createWithClientContext(
handlers_,
getServiceName(),
"ParamService.string_ret_string_param",
*header);
return {std::move(ctx), std::move(header)};
}
void ParamServiceAsyncClient::sync_string_ret_string_param(::std::string& _return, const ::std::string& p_param1) {
::apache::thrift::RpcOptions rpcOptions;
sync_string_ret_string_param(rpcOptions, _return, p_param1);
}
void ParamServiceAsyncClient::sync_string_ret_string_param(apache::thrift::RpcOptions& rpcOptions, ::std::string& _return, const ::std::string& p_param1) {
apache::thrift::ClientReceiveState returnState;
apache::thrift::ClientSyncCallback<false> callback(&returnState);
auto protocolId = apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId();
auto evb = apache::thrift::GeneratedAsyncClient::getChannel()->getEventBase();
auto [ctx, header] = string_ret_string_paramCtx(&rpcOptions);
auto wrappedCallback = apache::thrift::RequestClientCallback::Ptr(&callback);
string_ret_string_paramImpl(rpcOptions, std::move(header), ctx.get(), std::move(wrappedCallback), p_param1);
callback.waitUntilDone(evb);
if (returnState.isException()) {
returnState.exception().throw_exception();
}
returnState.resetProtocolId(protocolId);
returnState.resetCtx(std::move(ctx));
SCOPE_EXIT {
if (returnState.header() && !returnState.header()->getHeaders().empty()) {
rpcOptions.setReadHeaders(returnState.header()->releaseHeaders());
}
};
return folly::fibers::runInMainContext([&] {
recv_string_ret_string_param(_return, returnState);
});
}
folly::Future<::std::string> ParamServiceAsyncClient::future_string_ret_string_param(const ::std::string& p_param1) {
::apache::thrift::RpcOptions rpcOptions;
return future_string_ret_string_param(rpcOptions, p_param1);
}
folly::SemiFuture<::std::string> ParamServiceAsyncClient::semifuture_string_ret_string_param(const ::std::string& p_param1) {
::apache::thrift::RpcOptions rpcOptions;
return semifuture_string_ret_string_param(rpcOptions, p_param1);
}
folly::Future<::std::string> ParamServiceAsyncClient::future_string_ret_string_param(apache::thrift::RpcOptions& rpcOptions, const ::std::string& p_param1) {
folly::Promise<::std::string> promise;
auto future = promise.getFuture();
auto callback = std::make_unique<apache::thrift::FutureCallback<::std::string>>(std::move(promise), recv_wrapped_string_ret_string_param, channel_);
string_ret_string_param(rpcOptions, std::move(callback), p_param1);
return future;
}
folly::SemiFuture<::std::string> ParamServiceAsyncClient::semifuture_string_ret_string_param(apache::thrift::RpcOptions& rpcOptions, const ::std::string& p_param1) {
auto callbackAndFuture = makeSemiFutureCallback(recv_wrapped_string_ret_string_param, channel_);
auto callback = std::move(callbackAndFuture.first);
string_ret_string_param(rpcOptions, std::move(callback), p_param1);
return std::move(callbackAndFuture.second);
}
folly::Future<std::pair<::std::string, std::unique_ptr<apache::thrift::transport::THeader>>> ParamServiceAsyncClient::header_future_string_ret_string_param(apache::thrift::RpcOptions& rpcOptions, const ::std::string& p_param1) {
folly::Promise<std::pair<::std::string, std::unique_ptr<apache::thrift::transport::THeader>>> promise;
auto future = promise.getFuture();
auto callback = std::make_unique<apache::thrift::HeaderFutureCallback<::std::string>>(std::move(promise), recv_wrapped_string_ret_string_param, channel_);
string_ret_string_param(rpcOptions, std::move(callback), p_param1);
return future;
}
folly::SemiFuture<std::pair<::std::string, std::unique_ptr<apache::thrift::transport::THeader>>> ParamServiceAsyncClient::header_semifuture_string_ret_string_param(apache::thrift::RpcOptions& rpcOptions, const ::std::string& p_param1) {
auto callbackAndFuture = makeHeaderSemiFutureCallback(recv_wrapped_string_ret_string_param, channel_);
auto callback = std::move(callbackAndFuture.first);
string_ret_string_param(rpcOptions, std::move(callback), p_param1);
return std::move(callbackAndFuture.second);
}
void ParamServiceAsyncClient::string_ret_string_param(folly::Function<void (::apache::thrift::ClientReceiveState&&)> callback, const ::std::string& p_param1) {
string_ret_string_param(std::make_unique<apache::thrift::FunctionReplyCallback>(std::move(callback)), p_param1);
}
#if FOLLY_HAS_COROUTINES
#endif // FOLLY_HAS_COROUTINES
folly::exception_wrapper ParamServiceAsyncClient::recv_wrapped_string_ret_string_param(::std::string& _return, ::apache::thrift::ClientReceiveState& state) {
if (state.isException()) {
return std::move(state.exception());
}
if (!state.hasResponseBuffer()) {
return folly::make_exception_wrapper<apache::thrift::TApplicationException>("recv_ called without result");
}
using result = ParamService_string_ret_string_param_presult;
switch (state.protocolId()) {
case apache::thrift::protocol::T_BINARY_PROTOCOL:
{
apache::thrift::BinaryProtocolReader reader;
return apache::thrift::detail::ac::recv_wrapped<result>(
&reader, state, _return);
}
case apache::thrift::protocol::T_COMPACT_PROTOCOL:
{
apache::thrift::CompactProtocolReader reader;
return apache::thrift::detail::ac::recv_wrapped<result>(
&reader, state, _return);
}
default:
{
}
}
return folly::make_exception_wrapper<apache::thrift::TApplicationException>("Could not find Protocol");
}
void ParamServiceAsyncClient::recv_string_ret_string_param(::std::string& _return, ::apache::thrift::ClientReceiveState& state) {
auto ew = recv_wrapped_string_ret_string_param(_return, state);
if (ew) {
ew.throw_exception();
}
}
void ParamServiceAsyncClient::recv_instance_string_ret_string_param(::std::string& _return, ::apache::thrift::ClientReceiveState& state) {
return recv_string_ret_string_param(_return, state);
}
folly::exception_wrapper ParamServiceAsyncClient::recv_instance_wrapped_string_ret_string_param(::std::string& _return, ::apache::thrift::ClientReceiveState& state) {
return recv_wrapped_string_ret_string_param(_return, state);
}
void ParamServiceAsyncClient::binary_ret_binary_param(std::unique_ptr<apache::thrift::RequestCallback> callback, const ::std::string& p_param1) {
::apache::thrift::RpcOptions rpcOptions;
binary_ret_binary_param(rpcOptions, std::move(callback), p_param1);
}
void ParamServiceAsyncClient::binary_ret_binary_param(apache::thrift::RpcOptions& rpcOptions, std::unique_ptr<apache::thrift::RequestCallback> callback, const ::std::string& p_param1) {
auto [ctx, header] = binary_ret_binary_paramCtx(&rpcOptions);
apache::thrift::RequestCallback::Context callbackContext;
callbackContext.protocolId =
apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId();
auto* contextStack = ctx.get();
if (callback) {
callbackContext.ctx = std::move(ctx);
}
auto wrappedCallback = apache::thrift::toRequestClientCallbackPtr(std::move(callback), std::move(callbackContext));
binary_ret_binary_paramImpl(rpcOptions, std::move(header), contextStack, std::move(wrappedCallback), p_param1);
}
void ParamServiceAsyncClient::binary_ret_binary_paramImpl(const apache::thrift::RpcOptions& rpcOptions, std::shared_ptr<apache::thrift::transport::THeader> header, apache::thrift::ContextStack* contextStack, apache::thrift::RequestClientCallback::Ptr callback, const ::std::string& p_param1) {
switch (apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId()) {
case apache::thrift::protocol::T_BINARY_PROTOCOL:
{
apache::thrift::BinaryProtocolWriter writer;
binary_ret_binary_paramT(&writer, rpcOptions, std::move(header), contextStack, std::move(callback), p_param1);
break;
}
case apache::thrift::protocol::T_COMPACT_PROTOCOL:
{
apache::thrift::CompactProtocolWriter writer;
binary_ret_binary_paramT(&writer, rpcOptions, std::move(header), contextStack, std::move(callback), p_param1);
break;
}
default:
{
apache::thrift::detail::ac::throw_app_exn("Could not find Protocol");
}
}
}
std::pair<std::unique_ptr<::apache::thrift::ContextStack>, std::shared_ptr<::apache::thrift::transport::THeader>> ParamServiceAsyncClient::binary_ret_binary_paramCtx(apache::thrift::RpcOptions* rpcOptions) {
auto header = std::make_shared<apache::thrift::transport::THeader>(
apache::thrift::transport::THeader::ALLOW_BIG_FRAMES);
header->setProtocolId(channel_->getProtocolId());
if (rpcOptions) {
header->setHeaders(rpcOptions->releaseWriteHeaders());
}
auto ctx = apache::thrift::ContextStack::createWithClientContext(
handlers_,
getServiceName(),
"ParamService.binary_ret_binary_param",
*header);
return {std::move(ctx), std::move(header)};
}
void ParamServiceAsyncClient::sync_binary_ret_binary_param(::std::string& _return, const ::std::string& p_param1) {
::apache::thrift::RpcOptions rpcOptions;
sync_binary_ret_binary_param(rpcOptions, _return, p_param1);
}
void ParamServiceAsyncClient::sync_binary_ret_binary_param(apache::thrift::RpcOptions& rpcOptions, ::std::string& _return, const ::std::string& p_param1) {
apache::thrift::ClientReceiveState returnState;
apache::thrift::ClientSyncCallback<false> callback(&returnState);
auto protocolId = apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId();
auto evb = apache::thrift::GeneratedAsyncClient::getChannel()->getEventBase();
auto [ctx, header] = binary_ret_binary_paramCtx(&rpcOptions);
auto wrappedCallback = apache::thrift::RequestClientCallback::Ptr(&callback);
binary_ret_binary_paramImpl(rpcOptions, std::move(header), ctx.get(), std::move(wrappedCallback), p_param1);
callback.waitUntilDone(evb);
if (returnState.isException()) {
returnState.exception().throw_exception();
}
returnState.resetProtocolId(protocolId);
returnState.resetCtx(std::move(ctx));
SCOPE_EXIT {
if (returnState.header() && !returnState.header()->getHeaders().empty()) {
rpcOptions.setReadHeaders(returnState.header()->releaseHeaders());
}
};
return folly::fibers::runInMainContext([&] {
recv_binary_ret_binary_param(_return, returnState);
});
}
folly::Future<::std::string> ParamServiceAsyncClient::future_binary_ret_binary_param(const ::std::string& p_param1) {
::apache::thrift::RpcOptions rpcOptions;
return future_binary_ret_binary_param(rpcOptions, p_param1);
}
folly::SemiFuture<::std::string> ParamServiceAsyncClient::semifuture_binary_ret_binary_param(const ::std::string& p_param1) {
::apache::thrift::RpcOptions rpcOptions;
return semifuture_binary_ret_binary_param(rpcOptions, p_param1);
}
folly::Future<::std::string> ParamServiceAsyncClient::future_binary_ret_binary_param(apache::thrift::RpcOptions& rpcOptions, const ::std::string& p_param1) {
folly::Promise<::std::string> promise;
auto future = promise.getFuture();
auto callback = std::make_unique<apache::thrift::FutureCallback<::std::string>>(std::move(promise), recv_wrapped_binary_ret_binary_param, channel_);
binary_ret_binary_param(rpcOptions, std::move(callback), p_param1);
return future;
}
folly::SemiFuture<::std::string> ParamServiceAsyncClient::semifuture_binary_ret_binary_param(apache::thrift::RpcOptions& rpcOptions, const ::std::string& p_param1) {
auto callbackAndFuture = makeSemiFutureCallback(recv_wrapped_binary_ret_binary_param, channel_);
auto callback = std::move(callbackAndFuture.first);
binary_ret_binary_param(rpcOptions, std::move(callback), p_param1);
return std::move(callbackAndFuture.second);
}
folly::Future<std::pair<::std::string, std::unique_ptr<apache::thrift::transport::THeader>>> ParamServiceAsyncClient::header_future_binary_ret_binary_param(apache::thrift::RpcOptions& rpcOptions, const ::std::string& p_param1) {
folly::Promise<std::pair<::std::string, std::unique_ptr<apache::thrift::transport::THeader>>> promise;
auto future = promise.getFuture();
auto callback = std::make_unique<apache::thrift::HeaderFutureCallback<::std::string>>(std::move(promise), recv_wrapped_binary_ret_binary_param, channel_);
binary_ret_binary_param(rpcOptions, std::move(callback), p_param1);
return future;
}
folly::SemiFuture<std::pair<::std::string, std::unique_ptr<apache::thrift::transport::THeader>>> ParamServiceAsyncClient::header_semifuture_binary_ret_binary_param(apache::thrift::RpcOptions& rpcOptions, const ::std::string& p_param1) {
auto callbackAndFuture = makeHeaderSemiFutureCallback(recv_wrapped_binary_ret_binary_param, channel_);
auto callback = std::move(callbackAndFuture.first);
binary_ret_binary_param(rpcOptions, std::move(callback), p_param1);
return std::move(callbackAndFuture.second);
}
void ParamServiceAsyncClient::binary_ret_binary_param(folly::Function<void (::apache::thrift::ClientReceiveState&&)> callback, const ::std::string& p_param1) {
binary_ret_binary_param(std::make_unique<apache::thrift::FunctionReplyCallback>(std::move(callback)), p_param1);
}
#if FOLLY_HAS_COROUTINES
#endif // FOLLY_HAS_COROUTINES
folly::exception_wrapper ParamServiceAsyncClient::recv_wrapped_binary_ret_binary_param(::std::string& _return, ::apache::thrift::ClientReceiveState& state) {
if (state.isException()) {
return std::move(state.exception());
}
if (!state.hasResponseBuffer()) {
return folly::make_exception_wrapper<apache::thrift::TApplicationException>("recv_ called without result");
}
using result = ParamService_binary_ret_binary_param_presult;
switch (state.protocolId()) {
case apache::thrift::protocol::T_BINARY_PROTOCOL:
{
apache::thrift::BinaryProtocolReader reader;
return apache::thrift::detail::ac::recv_wrapped<result>(
&reader, state, _return);
}
case apache::thrift::protocol::T_COMPACT_PROTOCOL:
{
apache::thrift::CompactProtocolReader reader;
return apache::thrift::detail::ac::recv_wrapped<result>(
&reader, state, _return);
}
default:
{
}
}
return folly::make_exception_wrapper<apache::thrift::TApplicationException>("Could not find Protocol");
}
void ParamServiceAsyncClient::recv_binary_ret_binary_param(::std::string& _return, ::apache::thrift::ClientReceiveState& state) {
auto ew = recv_wrapped_binary_ret_binary_param(_return, state);
if (ew) {
ew.throw_exception();
}
}
void ParamServiceAsyncClient::recv_instance_binary_ret_binary_param(::std::string& _return, ::apache::thrift::ClientReceiveState& state) {
return recv_binary_ret_binary_param(_return, state);
}
folly::exception_wrapper ParamServiceAsyncClient::recv_instance_wrapped_binary_ret_binary_param(::std::string& _return, ::apache::thrift::ClientReceiveState& state) {
return recv_wrapped_binary_ret_binary_param(_return, state);
}
void ParamServiceAsyncClient::map_ret_bool_param(std::unique_ptr<apache::thrift::RequestCallback> callback, bool p_param1) {
::apache::thrift::RpcOptions rpcOptions;
map_ret_bool_param(rpcOptions, std::move(callback), p_param1);
}
void ParamServiceAsyncClient::map_ret_bool_param(apache::thrift::RpcOptions& rpcOptions, std::unique_ptr<apache::thrift::RequestCallback> callback, bool p_param1) {
auto [ctx, header] = map_ret_bool_paramCtx(&rpcOptions);
apache::thrift::RequestCallback::Context callbackContext;
callbackContext.protocolId =
apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId();
auto* contextStack = ctx.get();
if (callback) {
callbackContext.ctx = std::move(ctx);
}
auto wrappedCallback = apache::thrift::toRequestClientCallbackPtr(std::move(callback), std::move(callbackContext));
map_ret_bool_paramImpl(rpcOptions, std::move(header), contextStack, std::move(wrappedCallback), p_param1);
}
void ParamServiceAsyncClient::map_ret_bool_paramImpl(const apache::thrift::RpcOptions& rpcOptions, std::shared_ptr<apache::thrift::transport::THeader> header, apache::thrift::ContextStack* contextStack, apache::thrift::RequestClientCallback::Ptr callback, bool p_param1) {
switch (apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId()) {
case apache::thrift::protocol::T_BINARY_PROTOCOL:
{
apache::thrift::BinaryProtocolWriter writer;
map_ret_bool_paramT(&writer, rpcOptions, std::move(header), contextStack, std::move(callback), p_param1);
break;
}
case apache::thrift::protocol::T_COMPACT_PROTOCOL:
{
apache::thrift::CompactProtocolWriter writer;
map_ret_bool_paramT(&writer, rpcOptions, std::move(header), contextStack, std::move(callback), p_param1);
break;
}
default:
{
apache::thrift::detail::ac::throw_app_exn("Could not find Protocol");
}
}
}
std::pair<std::unique_ptr<::apache::thrift::ContextStack>, std::shared_ptr<::apache::thrift::transport::THeader>> ParamServiceAsyncClient::map_ret_bool_paramCtx(apache::thrift::RpcOptions* rpcOptions) {
auto header = std::make_shared<apache::thrift::transport::THeader>(
apache::thrift::transport::THeader::ALLOW_BIG_FRAMES);
header->setProtocolId(channel_->getProtocolId());
if (rpcOptions) {
header->setHeaders(rpcOptions->releaseWriteHeaders());
}
auto ctx = apache::thrift::ContextStack::createWithClientContext(
handlers_,
getServiceName(),
"ParamService.map_ret_bool_param",
*header);
return {std::move(ctx), std::move(header)};
}
void ParamServiceAsyncClient::sync_map_ret_bool_param(::std::map<::std::string, ::std::int64_t>& _return, bool p_param1) {
::apache::thrift::RpcOptions rpcOptions;
sync_map_ret_bool_param(rpcOptions, _return, p_param1);
}
void ParamServiceAsyncClient::sync_map_ret_bool_param(apache::thrift::RpcOptions& rpcOptions, ::std::map<::std::string, ::std::int64_t>& _return, bool p_param1) {
apache::thrift::ClientReceiveState returnState;
apache::thrift::ClientSyncCallback<false> callback(&returnState);
auto protocolId = apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId();
auto evb = apache::thrift::GeneratedAsyncClient::getChannel()->getEventBase();
auto [ctx, header] = map_ret_bool_paramCtx(&rpcOptions);
auto wrappedCallback = apache::thrift::RequestClientCallback::Ptr(&callback);
map_ret_bool_paramImpl(rpcOptions, std::move(header), ctx.get(), std::move(wrappedCallback), p_param1);
callback.waitUntilDone(evb);
if (returnState.isException()) {
returnState.exception().throw_exception();
}
returnState.resetProtocolId(protocolId);
returnState.resetCtx(std::move(ctx));
SCOPE_EXIT {
if (returnState.header() && !returnState.header()->getHeaders().empty()) {
rpcOptions.setReadHeaders(returnState.header()->releaseHeaders());
}
};
return folly::fibers::runInMainContext([&] {
recv_map_ret_bool_param(_return, returnState);
});
}
folly::Future<::std::map<::std::string, ::std::int64_t>> ParamServiceAsyncClient::future_map_ret_bool_param(bool p_param1) {
::apache::thrift::RpcOptions rpcOptions;
return future_map_ret_bool_param(rpcOptions, p_param1);
}
folly::SemiFuture<::std::map<::std::string, ::std::int64_t>> ParamServiceAsyncClient::semifuture_map_ret_bool_param(bool p_param1) {
::apache::thrift::RpcOptions rpcOptions;
return semifuture_map_ret_bool_param(rpcOptions, p_param1);
}
folly::Future<::std::map<::std::string, ::std::int64_t>> ParamServiceAsyncClient::future_map_ret_bool_param(apache::thrift::RpcOptions& rpcOptions, bool p_param1) {
folly::Promise<::std::map<::std::string, ::std::int64_t>> promise;
auto future = promise.getFuture();
auto callback = std::make_unique<apache::thrift::FutureCallback<::std::map<::std::string, ::std::int64_t>>>(std::move(promise), recv_wrapped_map_ret_bool_param, channel_);
map_ret_bool_param(rpcOptions, std::move(callback), p_param1);
return future;
}
folly::SemiFuture<::std::map<::std::string, ::std::int64_t>> ParamServiceAsyncClient::semifuture_map_ret_bool_param(apache::thrift::RpcOptions& rpcOptions, bool p_param1) {
auto callbackAndFuture = makeSemiFutureCallback(recv_wrapped_map_ret_bool_param, channel_);
auto callback = std::move(callbackAndFuture.first);
map_ret_bool_param(rpcOptions, std::move(callback), p_param1);
return std::move(callbackAndFuture.second);
}
folly::Future<std::pair<::std::map<::std::string, ::std::int64_t>, std::unique_ptr<apache::thrift::transport::THeader>>> ParamServiceAsyncClient::header_future_map_ret_bool_param(apache::thrift::RpcOptions& rpcOptions, bool p_param1) {
folly::Promise<std::pair<::std::map<::std::string, ::std::int64_t>, std::unique_ptr<apache::thrift::transport::THeader>>> promise;
auto future = promise.getFuture();
auto callback = std::make_unique<apache::thrift::HeaderFutureCallback<::std::map<::std::string, ::std::int64_t>>>(std::move(promise), recv_wrapped_map_ret_bool_param, channel_);
map_ret_bool_param(rpcOptions, std::move(callback), p_param1);
return future;
}
folly::SemiFuture<std::pair<::std::map<::std::string, ::std::int64_t>, std::unique_ptr<apache::thrift::transport::THeader>>> ParamServiceAsyncClient::header_semifuture_map_ret_bool_param(apache::thrift::RpcOptions& rpcOptions, bool p_param1) {
auto callbackAndFuture = makeHeaderSemiFutureCallback(recv_wrapped_map_ret_bool_param, channel_);
auto callback = std::move(callbackAndFuture.first);
map_ret_bool_param(rpcOptions, std::move(callback), p_param1);
return std::move(callbackAndFuture.second);
}
void ParamServiceAsyncClient::map_ret_bool_param(folly::Function<void (::apache::thrift::ClientReceiveState&&)> callback, bool p_param1) {
map_ret_bool_param(std::make_unique<apache::thrift::FunctionReplyCallback>(std::move(callback)), p_param1);
}
#if FOLLY_HAS_COROUTINES
#endif // FOLLY_HAS_COROUTINES
folly::exception_wrapper ParamServiceAsyncClient::recv_wrapped_map_ret_bool_param(::std::map<::std::string, ::std::int64_t>& _return, ::apache::thrift::ClientReceiveState& state) {
if (state.isException()) {
return std::move(state.exception());
}
if (!state.hasResponseBuffer()) {
return folly::make_exception_wrapper<apache::thrift::TApplicationException>("recv_ called without result");
}
using result = ParamService_map_ret_bool_param_presult;
switch (state.protocolId()) {
case apache::thrift::protocol::T_BINARY_PROTOCOL:
{
apache::thrift::BinaryProtocolReader reader;
return apache::thrift::detail::ac::recv_wrapped<result>(
&reader, state, _return);
}
case apache::thrift::protocol::T_COMPACT_PROTOCOL:
{
apache::thrift::CompactProtocolReader reader;
return apache::thrift::detail::ac::recv_wrapped<result>(
&reader, state, _return);
}
default:
{
}
}
return folly::make_exception_wrapper<apache::thrift::TApplicationException>("Could not find Protocol");
}
void ParamServiceAsyncClient::recv_map_ret_bool_param(::std::map<::std::string, ::std::int64_t>& _return, ::apache::thrift::ClientReceiveState& state) {
auto ew = recv_wrapped_map_ret_bool_param(_return, state);
if (ew) {
ew.throw_exception();
}
}
void ParamServiceAsyncClient::recv_instance_map_ret_bool_param(::std::map<::std::string, ::std::int64_t>& _return, ::apache::thrift::ClientReceiveState& state) {
return recv_map_ret_bool_param(_return, state);
}
folly::exception_wrapper ParamServiceAsyncClient::recv_instance_wrapped_map_ret_bool_param(::std::map<::std::string, ::std::int64_t>& _return, ::apache::thrift::ClientReceiveState& state) {
return recv_wrapped_map_ret_bool_param(_return, state);
}
void ParamServiceAsyncClient::list_ret_map_setlist_param(std::unique_ptr<apache::thrift::RequestCallback> callback, const ::std::map<::std::int32_t, ::std::vector<::std::string>>& p_param1, const ::std::vector<::std::string>& p_param2) {
::apache::thrift::RpcOptions rpcOptions;
list_ret_map_setlist_param(rpcOptions, std::move(callback), p_param1, p_param2);
}
void ParamServiceAsyncClient::list_ret_map_setlist_param(apache::thrift::RpcOptions& rpcOptions, std::unique_ptr<apache::thrift::RequestCallback> callback, const ::std::map<::std::int32_t, ::std::vector<::std::string>>& p_param1, const ::std::vector<::std::string>& p_param2) {
auto [ctx, header] = list_ret_map_setlist_paramCtx(&rpcOptions);
apache::thrift::RequestCallback::Context callbackContext;
callbackContext.protocolId =
apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId();
auto* contextStack = ctx.get();
if (callback) {
callbackContext.ctx = std::move(ctx);
}
auto wrappedCallback = apache::thrift::toRequestClientCallbackPtr(std::move(callback), std::move(callbackContext));
list_ret_map_setlist_paramImpl(rpcOptions, std::move(header), contextStack, std::move(wrappedCallback), p_param1, p_param2);
}
void ParamServiceAsyncClient::list_ret_map_setlist_paramImpl(const apache::thrift::RpcOptions& rpcOptions, std::shared_ptr<apache::thrift::transport::THeader> header, apache::thrift::ContextStack* contextStack, apache::thrift::RequestClientCallback::Ptr callback, const ::std::map<::std::int32_t, ::std::vector<::std::string>>& p_param1, const ::std::vector<::std::string>& p_param2) {
switch (apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId()) {
case apache::thrift::protocol::T_BINARY_PROTOCOL:
{
apache::thrift::BinaryProtocolWriter writer;
list_ret_map_setlist_paramT(&writer, rpcOptions, std::move(header), contextStack, std::move(callback), p_param1, p_param2);
break;
}
case apache::thrift::protocol::T_COMPACT_PROTOCOL:
{
apache::thrift::CompactProtocolWriter writer;
list_ret_map_setlist_paramT(&writer, rpcOptions, std::move(header), contextStack, std::move(callback), p_param1, p_param2);
break;
}
default:
{
apache::thrift::detail::ac::throw_app_exn("Could not find Protocol");
}
}
}
std::pair<std::unique_ptr<::apache::thrift::ContextStack>, std::shared_ptr<::apache::thrift::transport::THeader>> ParamServiceAsyncClient::list_ret_map_setlist_paramCtx(apache::thrift::RpcOptions* rpcOptions) {
auto header = std::make_shared<apache::thrift::transport::THeader>(
apache::thrift::transport::THeader::ALLOW_BIG_FRAMES);
header->setProtocolId(channel_->getProtocolId());
if (rpcOptions) {
header->setHeaders(rpcOptions->releaseWriteHeaders());
}
auto ctx = apache::thrift::ContextStack::createWithClientContext(
handlers_,
getServiceName(),
"ParamService.list_ret_map_setlist_param",
*header);
return {std::move(ctx), std::move(header)};
}
void ParamServiceAsyncClient::sync_list_ret_map_setlist_param(::std::vector<bool>& _return, const ::std::map<::std::int32_t, ::std::vector<::std::string>>& p_param1, const ::std::vector<::std::string>& p_param2) {
::apache::thrift::RpcOptions rpcOptions;
sync_list_ret_map_setlist_param(rpcOptions, _return, p_param1, p_param2);
}
void ParamServiceAsyncClient::sync_list_ret_map_setlist_param(apache::thrift::RpcOptions& rpcOptions, ::std::vector<bool>& _return, const ::std::map<::std::int32_t, ::std::vector<::std::string>>& p_param1, const ::std::vector<::std::string>& p_param2) {
apache::thrift::ClientReceiveState returnState;
apache::thrift::ClientSyncCallback<false> callback(&returnState);
auto protocolId = apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId();
auto evb = apache::thrift::GeneratedAsyncClient::getChannel()->getEventBase();
auto [ctx, header] = list_ret_map_setlist_paramCtx(&rpcOptions);
auto wrappedCallback = apache::thrift::RequestClientCallback::Ptr(&callback);
list_ret_map_setlist_paramImpl(rpcOptions, std::move(header), ctx.get(), std::move(wrappedCallback), p_param1, p_param2);
callback.waitUntilDone(evb);
if (returnState.isException()) {
returnState.exception().throw_exception();
}
returnState.resetProtocolId(protocolId);
returnState.resetCtx(std::move(ctx));
SCOPE_EXIT {
if (returnState.header() && !returnState.header()->getHeaders().empty()) {
rpcOptions.setReadHeaders(returnState.header()->releaseHeaders());
}
};
return folly::fibers::runInMainContext([&] {
recv_list_ret_map_setlist_param(_return, returnState);
});
}
folly::Future<::std::vector<bool>> ParamServiceAsyncClient::future_list_ret_map_setlist_param(const ::std::map<::std::int32_t, ::std::vector<::std::string>>& p_param1, const ::std::vector<::std::string>& p_param2) {
::apache::thrift::RpcOptions rpcOptions;
return future_list_ret_map_setlist_param(rpcOptions, p_param1, p_param2);
}
folly::SemiFuture<::std::vector<bool>> ParamServiceAsyncClient::semifuture_list_ret_map_setlist_param(const ::std::map<::std::int32_t, ::std::vector<::std::string>>& p_param1, const ::std::vector<::std::string>& p_param2) {
::apache::thrift::RpcOptions rpcOptions;
return semifuture_list_ret_map_setlist_param(rpcOptions, p_param1, p_param2);
}
folly::Future<::std::vector<bool>> ParamServiceAsyncClient::future_list_ret_map_setlist_param(apache::thrift::RpcOptions& rpcOptions, const ::std::map<::std::int32_t, ::std::vector<::std::string>>& p_param1, const ::std::vector<::std::string>& p_param2) {
folly::Promise<::std::vector<bool>> promise;
auto future = promise.getFuture();
auto callback = std::make_unique<apache::thrift::FutureCallback<::std::vector<bool>>>(std::move(promise), recv_wrapped_list_ret_map_setlist_param, channel_);
list_ret_map_setlist_param(rpcOptions, std::move(callback), p_param1, p_param2);
return future;
}
folly::SemiFuture<::std::vector<bool>> ParamServiceAsyncClient::semifuture_list_ret_map_setlist_param(apache::thrift::RpcOptions& rpcOptions, const ::std::map<::std::int32_t, ::std::vector<::std::string>>& p_param1, const ::std::vector<::std::string>& p_param2) {
auto callbackAndFuture = makeSemiFutureCallback(recv_wrapped_list_ret_map_setlist_param, channel_);
auto callback = std::move(callbackAndFuture.first);
list_ret_map_setlist_param(rpcOptions, std::move(callback), p_param1, p_param2);
return std::move(callbackAndFuture.second);
}
folly::Future<std::pair<::std::vector<bool>, std::unique_ptr<apache::thrift::transport::THeader>>> ParamServiceAsyncClient::header_future_list_ret_map_setlist_param(apache::thrift::RpcOptions& rpcOptions, const ::std::map<::std::int32_t, ::std::vector<::std::string>>& p_param1, const ::std::vector<::std::string>& p_param2) {
folly::Promise<std::pair<::std::vector<bool>, std::unique_ptr<apache::thrift::transport::THeader>>> promise;
auto future = promise.getFuture();
auto callback = std::make_unique<apache::thrift::HeaderFutureCallback<::std::vector<bool>>>(std::move(promise), recv_wrapped_list_ret_map_setlist_param, channel_);
list_ret_map_setlist_param(rpcOptions, std::move(callback), p_param1, p_param2);
return future;
}
folly::SemiFuture<std::pair<::std::vector<bool>, std::unique_ptr<apache::thrift::transport::THeader>>> ParamServiceAsyncClient::header_semifuture_list_ret_map_setlist_param(apache::thrift::RpcOptions& rpcOptions, const ::std::map<::std::int32_t, ::std::vector<::std::string>>& p_param1, const ::std::vector<::std::string>& p_param2) {
auto callbackAndFuture = makeHeaderSemiFutureCallback(recv_wrapped_list_ret_map_setlist_param, channel_);
auto callback = std::move(callbackAndFuture.first);
list_ret_map_setlist_param(rpcOptions, std::move(callback), p_param1, p_param2);
return std::move(callbackAndFuture.second);
}
void ParamServiceAsyncClient::list_ret_map_setlist_param(folly::Function<void (::apache::thrift::ClientReceiveState&&)> callback, const ::std::map<::std::int32_t, ::std::vector<::std::string>>& p_param1, const ::std::vector<::std::string>& p_param2) {
list_ret_map_setlist_param(std::make_unique<apache::thrift::FunctionReplyCallback>(std::move(callback)), p_param1, p_param2);
}
#if FOLLY_HAS_COROUTINES
#endif // FOLLY_HAS_COROUTINES
folly::exception_wrapper ParamServiceAsyncClient::recv_wrapped_list_ret_map_setlist_param(::std::vector<bool>& _return, ::apache::thrift::ClientReceiveState& state) {
if (state.isException()) {
return std::move(state.exception());
}
if (!state.hasResponseBuffer()) {
return folly::make_exception_wrapper<apache::thrift::TApplicationException>("recv_ called without result");
}
using result = ParamService_list_ret_map_setlist_param_presult;
switch (state.protocolId()) {
case apache::thrift::protocol::T_BINARY_PROTOCOL:
{
apache::thrift::BinaryProtocolReader reader;
return apache::thrift::detail::ac::recv_wrapped<result>(
&reader, state, _return);
}
case apache::thrift::protocol::T_COMPACT_PROTOCOL:
{
apache::thrift::CompactProtocolReader reader;
return apache::thrift::detail::ac::recv_wrapped<result>(
&reader, state, _return);
}
default:
{
}
}
return folly::make_exception_wrapper<apache::thrift::TApplicationException>("Could not find Protocol");
}
void ParamServiceAsyncClient::recv_list_ret_map_setlist_param(::std::vector<bool>& _return, ::apache::thrift::ClientReceiveState& state) {
auto ew = recv_wrapped_list_ret_map_setlist_param(_return, state);
if (ew) {
ew.throw_exception();
}
}
void ParamServiceAsyncClient::recv_instance_list_ret_map_setlist_param(::std::vector<bool>& _return, ::apache::thrift::ClientReceiveState& state) {
return recv_list_ret_map_setlist_param(_return, state);
}
folly::exception_wrapper ParamServiceAsyncClient::recv_instance_wrapped_list_ret_map_setlist_param(::std::vector<bool>& _return, ::apache::thrift::ClientReceiveState& state) {
return recv_wrapped_list_ret_map_setlist_param(_return, state);
}
void ParamServiceAsyncClient::mapsetlistmapliststring_ret_listlistlist_param(std::unique_ptr<apache::thrift::RequestCallback> callback, const ::std::vector<::std::vector<::std::vector<::std::vector<::std::int32_t>>>>& p_param1) {
::apache::thrift::RpcOptions rpcOptions;
mapsetlistmapliststring_ret_listlistlist_param(rpcOptions, std::move(callback), p_param1);
}
void ParamServiceAsyncClient::mapsetlistmapliststring_ret_listlistlist_param(apache::thrift::RpcOptions& rpcOptions, std::unique_ptr<apache::thrift::RequestCallback> callback, const ::std::vector<::std::vector<::std::vector<::std::vector<::std::int32_t>>>>& p_param1) {
auto [ctx, header] = mapsetlistmapliststring_ret_listlistlist_paramCtx(&rpcOptions);
apache::thrift::RequestCallback::Context callbackContext;
callbackContext.protocolId =
apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId();
auto* contextStack = ctx.get();
if (callback) {
callbackContext.ctx = std::move(ctx);
}
auto wrappedCallback = apache::thrift::toRequestClientCallbackPtr(std::move(callback), std::move(callbackContext));
mapsetlistmapliststring_ret_listlistlist_paramImpl(rpcOptions, std::move(header), contextStack, std::move(wrappedCallback), p_param1);
}
void ParamServiceAsyncClient::mapsetlistmapliststring_ret_listlistlist_paramImpl(const apache::thrift::RpcOptions& rpcOptions, std::shared_ptr<apache::thrift::transport::THeader> header, apache::thrift::ContextStack* contextStack, apache::thrift::RequestClientCallback::Ptr callback, const ::std::vector<::std::vector<::std::vector<::std::vector<::std::int32_t>>>>& p_param1) {
switch (apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId()) {
case apache::thrift::protocol::T_BINARY_PROTOCOL:
{
apache::thrift::BinaryProtocolWriter writer;
mapsetlistmapliststring_ret_listlistlist_paramT(&writer, rpcOptions, std::move(header), contextStack, std::move(callback), p_param1);
break;
}
case apache::thrift::protocol::T_COMPACT_PROTOCOL:
{
apache::thrift::CompactProtocolWriter writer;
mapsetlistmapliststring_ret_listlistlist_paramT(&writer, rpcOptions, std::move(header), contextStack, std::move(callback), p_param1);
break;
}
default:
{
apache::thrift::detail::ac::throw_app_exn("Could not find Protocol");
}
}
}
std::pair<std::unique_ptr<::apache::thrift::ContextStack>, std::shared_ptr<::apache::thrift::transport::THeader>> ParamServiceAsyncClient::mapsetlistmapliststring_ret_listlistlist_paramCtx(apache::thrift::RpcOptions* rpcOptions) {
auto header = std::make_shared<apache::thrift::transport::THeader>(
apache::thrift::transport::THeader::ALLOW_BIG_FRAMES);
header->setProtocolId(channel_->getProtocolId());
if (rpcOptions) {
header->setHeaders(rpcOptions->releaseWriteHeaders());
}
auto ctx = apache::thrift::ContextStack::createWithClientContext(
handlers_,
getServiceName(),
"ParamService.mapsetlistmapliststring_ret_listlistlist_param",
*header);
return {std::move(ctx), std::move(header)};
}
void ParamServiceAsyncClient::sync_mapsetlistmapliststring_ret_listlistlist_param(::std::map<::std::set<::std::vector<::std::int32_t>>, ::std::map<::std::vector<::std::set<::std::string>>, ::std::string>>& _return, const ::std::vector<::std::vector<::std::vector<::std::vector<::std::int32_t>>>>& p_param1) {
::apache::thrift::RpcOptions rpcOptions;
sync_mapsetlistmapliststring_ret_listlistlist_param(rpcOptions, _return, p_param1);
}
void ParamServiceAsyncClient::sync_mapsetlistmapliststring_ret_listlistlist_param(apache::thrift::RpcOptions& rpcOptions, ::std::map<::std::set<::std::vector<::std::int32_t>>, ::std::map<::std::vector<::std::set<::std::string>>, ::std::string>>& _return, const ::std::vector<::std::vector<::std::vector<::std::vector<::std::int32_t>>>>& p_param1) {
apache::thrift::ClientReceiveState returnState;
apache::thrift::ClientSyncCallback<false> callback(&returnState);
auto protocolId = apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId();
auto evb = apache::thrift::GeneratedAsyncClient::getChannel()->getEventBase();
auto [ctx, header] = mapsetlistmapliststring_ret_listlistlist_paramCtx(&rpcOptions);
auto wrappedCallback = apache::thrift::RequestClientCallback::Ptr(&callback);
mapsetlistmapliststring_ret_listlistlist_paramImpl(rpcOptions, std::move(header), ctx.get(), std::move(wrappedCallback), p_param1);
callback.waitUntilDone(evb);
if (returnState.isException()) {
returnState.exception().throw_exception();
}
returnState.resetProtocolId(protocolId);
returnState.resetCtx(std::move(ctx));
SCOPE_EXIT {
if (returnState.header() && !returnState.header()->getHeaders().empty()) {
rpcOptions.setReadHeaders(returnState.header()->releaseHeaders());
}
};
return folly::fibers::runInMainContext([&] {
recv_mapsetlistmapliststring_ret_listlistlist_param(_return, returnState);
});
}
folly::Future<::std::map<::std::set<::std::vector<::std::int32_t>>, ::std::map<::std::vector<::std::set<::std::string>>, ::std::string>>> ParamServiceAsyncClient::future_mapsetlistmapliststring_ret_listlistlist_param(const ::std::vector<::std::vector<::std::vector<::std::vector<::std::int32_t>>>>& p_param1) {
::apache::thrift::RpcOptions rpcOptions;
return future_mapsetlistmapliststring_ret_listlistlist_param(rpcOptions, p_param1);
}
folly::SemiFuture<::std::map<::std::set<::std::vector<::std::int32_t>>, ::std::map<::std::vector<::std::set<::std::string>>, ::std::string>>> ParamServiceAsyncClient::semifuture_mapsetlistmapliststring_ret_listlistlist_param(const ::std::vector<::std::vector<::std::vector<::std::vector<::std::int32_t>>>>& p_param1) {
::apache::thrift::RpcOptions rpcOptions;
return semifuture_mapsetlistmapliststring_ret_listlistlist_param(rpcOptions, p_param1);
}
folly::Future<::std::map<::std::set<::std::vector<::std::int32_t>>, ::std::map<::std::vector<::std::set<::std::string>>, ::std::string>>> ParamServiceAsyncClient::future_mapsetlistmapliststring_ret_listlistlist_param(apache::thrift::RpcOptions& rpcOptions, const ::std::vector<::std::vector<::std::vector<::std::vector<::std::int32_t>>>>& p_param1) {
folly::Promise<::std::map<::std::set<::std::vector<::std::int32_t>>, ::std::map<::std::vector<::std::set<::std::string>>, ::std::string>>> promise;
auto future = promise.getFuture();
auto callback = std::make_unique<apache::thrift::FutureCallback<::std::map<::std::set<::std::vector<::std::int32_t>>, ::std::map<::std::vector<::std::set<::std::string>>, ::std::string>>>>(std::move(promise), recv_wrapped_mapsetlistmapliststring_ret_listlistlist_param, channel_);
mapsetlistmapliststring_ret_listlistlist_param(rpcOptions, std::move(callback), p_param1);
return future;
}
folly::SemiFuture<::std::map<::std::set<::std::vector<::std::int32_t>>, ::std::map<::std::vector<::std::set<::std::string>>, ::std::string>>> ParamServiceAsyncClient::semifuture_mapsetlistmapliststring_ret_listlistlist_param(apache::thrift::RpcOptions& rpcOptions, const ::std::vector<::std::vector<::std::vector<::std::vector<::std::int32_t>>>>& p_param1) {
auto callbackAndFuture = makeSemiFutureCallback(recv_wrapped_mapsetlistmapliststring_ret_listlistlist_param, channel_);
auto callback = std::move(callbackAndFuture.first);
mapsetlistmapliststring_ret_listlistlist_param(rpcOptions, std::move(callback), p_param1);
return std::move(callbackAndFuture.second);
}
folly::Future<std::pair<::std::map<::std::set<::std::vector<::std::int32_t>>, ::std::map<::std::vector<::std::set<::std::string>>, ::std::string>>, std::unique_ptr<apache::thrift::transport::THeader>>> ParamServiceAsyncClient::header_future_mapsetlistmapliststring_ret_listlistlist_param(apache::thrift::RpcOptions& rpcOptions, const ::std::vector<::std::vector<::std::vector<::std::vector<::std::int32_t>>>>& p_param1) {
folly::Promise<std::pair<::std::map<::std::set<::std::vector<::std::int32_t>>, ::std::map<::std::vector<::std::set<::std::string>>, ::std::string>>, std::unique_ptr<apache::thrift::transport::THeader>>> promise;
auto future = promise.getFuture();
auto callback = std::make_unique<apache::thrift::HeaderFutureCallback<::std::map<::std::set<::std::vector<::std::int32_t>>, ::std::map<::std::vector<::std::set<::std::string>>, ::std::string>>>>(std::move(promise), recv_wrapped_mapsetlistmapliststring_ret_listlistlist_param, channel_);
mapsetlistmapliststring_ret_listlistlist_param(rpcOptions, std::move(callback), p_param1);
return future;
}
folly::SemiFuture<std::pair<::std::map<::std::set<::std::vector<::std::int32_t>>, ::std::map<::std::vector<::std::set<::std::string>>, ::std::string>>, std::unique_ptr<apache::thrift::transport::THeader>>> ParamServiceAsyncClient::header_semifuture_mapsetlistmapliststring_ret_listlistlist_param(apache::thrift::RpcOptions& rpcOptions, const ::std::vector<::std::vector<::std::vector<::std::vector<::std::int32_t>>>>& p_param1) {
auto callbackAndFuture = makeHeaderSemiFutureCallback(recv_wrapped_mapsetlistmapliststring_ret_listlistlist_param, channel_);
auto callback = std::move(callbackAndFuture.first);
mapsetlistmapliststring_ret_listlistlist_param(rpcOptions, std::move(callback), p_param1);
return std::move(callbackAndFuture.second);
}
void ParamServiceAsyncClient::mapsetlistmapliststring_ret_listlistlist_param(folly::Function<void (::apache::thrift::ClientReceiveState&&)> callback, const ::std::vector<::std::vector<::std::vector<::std::vector<::std::int32_t>>>>& p_param1) {
mapsetlistmapliststring_ret_listlistlist_param(std::make_unique<apache::thrift::FunctionReplyCallback>(std::move(callback)), p_param1);
}
#if FOLLY_HAS_COROUTINES
#endif // FOLLY_HAS_COROUTINES
folly::exception_wrapper ParamServiceAsyncClient::recv_wrapped_mapsetlistmapliststring_ret_listlistlist_param(::std::map<::std::set<::std::vector<::std::int32_t>>, ::std::map<::std::vector<::std::set<::std::string>>, ::std::string>>& _return, ::apache::thrift::ClientReceiveState& state) {
if (state.isException()) {
return std::move(state.exception());
}
if (!state.hasResponseBuffer()) {
return folly::make_exception_wrapper<apache::thrift::TApplicationException>("recv_ called without result");
}
using result = ParamService_mapsetlistmapliststring_ret_listlistlist_param_presult;
switch (state.protocolId()) {
case apache::thrift::protocol::T_BINARY_PROTOCOL:
{
apache::thrift::BinaryProtocolReader reader;
return apache::thrift::detail::ac::recv_wrapped<result>(
&reader, state, _return);
}
case apache::thrift::protocol::T_COMPACT_PROTOCOL:
{
apache::thrift::CompactProtocolReader reader;
return apache::thrift::detail::ac::recv_wrapped<result>(
&reader, state, _return);
}
default:
{
}
}
return folly::make_exception_wrapper<apache::thrift::TApplicationException>("Could not find Protocol");
}
void ParamServiceAsyncClient::recv_mapsetlistmapliststring_ret_listlistlist_param(::std::map<::std::set<::std::vector<::std::int32_t>>, ::std::map<::std::vector<::std::set<::std::string>>, ::std::string>>& _return, ::apache::thrift::ClientReceiveState& state) {
auto ew = recv_wrapped_mapsetlistmapliststring_ret_listlistlist_param(_return, state);
if (ew) {
ew.throw_exception();
}
}
void ParamServiceAsyncClient::recv_instance_mapsetlistmapliststring_ret_listlistlist_param(::std::map<::std::set<::std::vector<::std::int32_t>>, ::std::map<::std::vector<::std::set<::std::string>>, ::std::string>>& _return, ::apache::thrift::ClientReceiveState& state) {
return recv_mapsetlistmapliststring_ret_listlistlist_param(_return, state);
}
folly::exception_wrapper ParamServiceAsyncClient::recv_instance_wrapped_mapsetlistmapliststring_ret_listlistlist_param(::std::map<::std::set<::std::vector<::std::int32_t>>, ::std::map<::std::vector<::std::set<::std::string>>, ::std::string>>& _return, ::apache::thrift::ClientReceiveState& state) {
return recv_wrapped_mapsetlistmapliststring_ret_listlistlist_param(_return, state);
}
void ParamServiceAsyncClient::typedef_ret_i32_param(std::unique_ptr<apache::thrift::RequestCallback> callback, ::std::int32_t p_param1) {
::apache::thrift::RpcOptions rpcOptions;
typedef_ret_i32_param(rpcOptions, std::move(callback), p_param1);
}
void ParamServiceAsyncClient::typedef_ret_i32_param(apache::thrift::RpcOptions& rpcOptions, std::unique_ptr<apache::thrift::RequestCallback> callback, ::std::int32_t p_param1) {
auto [ctx, header] = typedef_ret_i32_paramCtx(&rpcOptions);
apache::thrift::RequestCallback::Context callbackContext;
callbackContext.protocolId =
apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId();
auto* contextStack = ctx.get();
if (callback) {
callbackContext.ctx = std::move(ctx);
}
auto wrappedCallback = apache::thrift::toRequestClientCallbackPtr(std::move(callback), std::move(callbackContext));
typedef_ret_i32_paramImpl(rpcOptions, std::move(header), contextStack, std::move(wrappedCallback), p_param1);
}
void ParamServiceAsyncClient::typedef_ret_i32_paramImpl(const apache::thrift::RpcOptions& rpcOptions, std::shared_ptr<apache::thrift::transport::THeader> header, apache::thrift::ContextStack* contextStack, apache::thrift::RequestClientCallback::Ptr callback, ::std::int32_t p_param1) {
switch (apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId()) {
case apache::thrift::protocol::T_BINARY_PROTOCOL:
{
apache::thrift::BinaryProtocolWriter writer;
typedef_ret_i32_paramT(&writer, rpcOptions, std::move(header), contextStack, std::move(callback), p_param1);
break;
}
case apache::thrift::protocol::T_COMPACT_PROTOCOL:
{
apache::thrift::CompactProtocolWriter writer;
typedef_ret_i32_paramT(&writer, rpcOptions, std::move(header), contextStack, std::move(callback), p_param1);
break;
}
default:
{
apache::thrift::detail::ac::throw_app_exn("Could not find Protocol");
}
}
}
std::pair<std::unique_ptr<::apache::thrift::ContextStack>, std::shared_ptr<::apache::thrift::transport::THeader>> ParamServiceAsyncClient::typedef_ret_i32_paramCtx(apache::thrift::RpcOptions* rpcOptions) {
auto header = std::make_shared<apache::thrift::transport::THeader>(
apache::thrift::transport::THeader::ALLOW_BIG_FRAMES);
header->setProtocolId(channel_->getProtocolId());
if (rpcOptions) {
header->setHeaders(rpcOptions->releaseWriteHeaders());
}
auto ctx = apache::thrift::ContextStack::createWithClientContext(
handlers_,
getServiceName(),
"ParamService.typedef_ret_i32_param",
*header);
return {std::move(ctx), std::move(header)};
}
::some::valid::ns::simpleTypeDef ParamServiceAsyncClient::sync_typedef_ret_i32_param(::std::int32_t p_param1) {
::apache::thrift::RpcOptions rpcOptions;
return sync_typedef_ret_i32_param(rpcOptions, p_param1);
}
::some::valid::ns::simpleTypeDef ParamServiceAsyncClient::sync_typedef_ret_i32_param(apache::thrift::RpcOptions& rpcOptions, ::std::int32_t p_param1) {
apache::thrift::ClientReceiveState returnState;
apache::thrift::ClientSyncCallback<false> callback(&returnState);
auto protocolId = apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId();
auto evb = apache::thrift::GeneratedAsyncClient::getChannel()->getEventBase();
auto [ctx, header] = typedef_ret_i32_paramCtx(&rpcOptions);
auto wrappedCallback = apache::thrift::RequestClientCallback::Ptr(&callback);
typedef_ret_i32_paramImpl(rpcOptions, std::move(header), ctx.get(), std::move(wrappedCallback), p_param1);
callback.waitUntilDone(evb);
if (returnState.isException()) {
returnState.exception().throw_exception();
}
returnState.resetProtocolId(protocolId);
returnState.resetCtx(std::move(ctx));
SCOPE_EXIT {
if (returnState.header() && !returnState.header()->getHeaders().empty()) {
rpcOptions.setReadHeaders(returnState.header()->releaseHeaders());
}
};
return folly::fibers::runInMainContext([&] {
return recv_typedef_ret_i32_param(returnState);
});
}
folly::Future<::some::valid::ns::simpleTypeDef> ParamServiceAsyncClient::future_typedef_ret_i32_param(::std::int32_t p_param1) {
::apache::thrift::RpcOptions rpcOptions;
return future_typedef_ret_i32_param(rpcOptions, p_param1);
}
folly::SemiFuture<::some::valid::ns::simpleTypeDef> ParamServiceAsyncClient::semifuture_typedef_ret_i32_param(::std::int32_t p_param1) {
::apache::thrift::RpcOptions rpcOptions;
return semifuture_typedef_ret_i32_param(rpcOptions, p_param1);
}
folly::Future<::some::valid::ns::simpleTypeDef> ParamServiceAsyncClient::future_typedef_ret_i32_param(apache::thrift::RpcOptions& rpcOptions, ::std::int32_t p_param1) {
folly::Promise<::some::valid::ns::simpleTypeDef> promise;
auto future = promise.getFuture();
auto callback = std::make_unique<apache::thrift::FutureCallback<::some::valid::ns::simpleTypeDef>>(std::move(promise), recv_wrapped_typedef_ret_i32_param, channel_);
typedef_ret_i32_param(rpcOptions, std::move(callback), p_param1);
return future;
}
folly::SemiFuture<::some::valid::ns::simpleTypeDef> ParamServiceAsyncClient::semifuture_typedef_ret_i32_param(apache::thrift::RpcOptions& rpcOptions, ::std::int32_t p_param1) {
auto callbackAndFuture = makeSemiFutureCallback(recv_wrapped_typedef_ret_i32_param, channel_);
auto callback = std::move(callbackAndFuture.first);
typedef_ret_i32_param(rpcOptions, std::move(callback), p_param1);
return std::move(callbackAndFuture.second);
}
folly::Future<std::pair<::some::valid::ns::simpleTypeDef, std::unique_ptr<apache::thrift::transport::THeader>>> ParamServiceAsyncClient::header_future_typedef_ret_i32_param(apache::thrift::RpcOptions& rpcOptions, ::std::int32_t p_param1) {
folly::Promise<std::pair<::some::valid::ns::simpleTypeDef, std::unique_ptr<apache::thrift::transport::THeader>>> promise;
auto future = promise.getFuture();
auto callback = std::make_unique<apache::thrift::HeaderFutureCallback<::some::valid::ns::simpleTypeDef>>(std::move(promise), recv_wrapped_typedef_ret_i32_param, channel_);
typedef_ret_i32_param(rpcOptions, std::move(callback), p_param1);
return future;
}
folly::SemiFuture<std::pair<::some::valid::ns::simpleTypeDef, std::unique_ptr<apache::thrift::transport::THeader>>> ParamServiceAsyncClient::header_semifuture_typedef_ret_i32_param(apache::thrift::RpcOptions& rpcOptions, ::std::int32_t p_param1) {
auto callbackAndFuture = makeHeaderSemiFutureCallback(recv_wrapped_typedef_ret_i32_param, channel_);
auto callback = std::move(callbackAndFuture.first);
typedef_ret_i32_param(rpcOptions, std::move(callback), p_param1);
return std::move(callbackAndFuture.second);
}
void ParamServiceAsyncClient::typedef_ret_i32_param(folly::Function<void (::apache::thrift::ClientReceiveState&&)> callback, ::std::int32_t p_param1) {
typedef_ret_i32_param(std::make_unique<apache::thrift::FunctionReplyCallback>(std::move(callback)), p_param1);
}
#if FOLLY_HAS_COROUTINES
#endif // FOLLY_HAS_COROUTINES
folly::exception_wrapper ParamServiceAsyncClient::recv_wrapped_typedef_ret_i32_param(::some::valid::ns::simpleTypeDef& _return, ::apache::thrift::ClientReceiveState& state) {
if (state.isException()) {
return std::move(state.exception());
}
if (!state.hasResponseBuffer()) {
return folly::make_exception_wrapper<apache::thrift::TApplicationException>("recv_ called without result");
}
using result = ParamService_typedef_ret_i32_param_presult;
switch (state.protocolId()) {
case apache::thrift::protocol::T_BINARY_PROTOCOL:
{
apache::thrift::BinaryProtocolReader reader;
return apache::thrift::detail::ac::recv_wrapped<result>(
&reader, state, _return);
}
case apache::thrift::protocol::T_COMPACT_PROTOCOL:
{
apache::thrift::CompactProtocolReader reader;
return apache::thrift::detail::ac::recv_wrapped<result>(
&reader, state, _return);
}
default:
{
}
}
return folly::make_exception_wrapper<apache::thrift::TApplicationException>("Could not find Protocol");
}
::some::valid::ns::simpleTypeDef ParamServiceAsyncClient::recv_typedef_ret_i32_param(::apache::thrift::ClientReceiveState& state) {
::some::valid::ns::simpleTypeDef _return;
auto ew = recv_wrapped_typedef_ret_i32_param(_return, state);
if (ew) {
ew.throw_exception();
}
return _return;
}
::some::valid::ns::simpleTypeDef ParamServiceAsyncClient::recv_instance_typedef_ret_i32_param(::apache::thrift::ClientReceiveState& state) {
return recv_typedef_ret_i32_param(state);
}
folly::exception_wrapper ParamServiceAsyncClient::recv_instance_wrapped_typedef_ret_i32_param(::some::valid::ns::simpleTypeDef& _return, ::apache::thrift::ClientReceiveState& state) {
return recv_wrapped_typedef_ret_i32_param(_return, state);
}
void ParamServiceAsyncClient::listtypedef_ret_typedef_param(std::unique_ptr<apache::thrift::RequestCallback> callback, const ::some::valid::ns::complexStructTypeDef& p_param1) {
::apache::thrift::RpcOptions rpcOptions;
listtypedef_ret_typedef_param(rpcOptions, std::move(callback), p_param1);
}
void ParamServiceAsyncClient::listtypedef_ret_typedef_param(apache::thrift::RpcOptions& rpcOptions, std::unique_ptr<apache::thrift::RequestCallback> callback, const ::some::valid::ns::complexStructTypeDef& p_param1) {
auto [ctx, header] = listtypedef_ret_typedef_paramCtx(&rpcOptions);
apache::thrift::RequestCallback::Context callbackContext;
callbackContext.protocolId =
apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId();
auto* contextStack = ctx.get();
if (callback) {
callbackContext.ctx = std::move(ctx);
}
auto wrappedCallback = apache::thrift::toRequestClientCallbackPtr(std::move(callback), std::move(callbackContext));
listtypedef_ret_typedef_paramImpl(rpcOptions, std::move(header), contextStack, std::move(wrappedCallback), p_param1);
}
void ParamServiceAsyncClient::listtypedef_ret_typedef_paramImpl(const apache::thrift::RpcOptions& rpcOptions, std::shared_ptr<apache::thrift::transport::THeader> header, apache::thrift::ContextStack* contextStack, apache::thrift::RequestClientCallback::Ptr callback, const ::some::valid::ns::complexStructTypeDef& p_param1) {
switch (apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId()) {
case apache::thrift::protocol::T_BINARY_PROTOCOL:
{
apache::thrift::BinaryProtocolWriter writer;
listtypedef_ret_typedef_paramT(&writer, rpcOptions, std::move(header), contextStack, std::move(callback), p_param1);
break;
}
case apache::thrift::protocol::T_COMPACT_PROTOCOL:
{
apache::thrift::CompactProtocolWriter writer;
listtypedef_ret_typedef_paramT(&writer, rpcOptions, std::move(header), contextStack, std::move(callback), p_param1);
break;
}
default:
{
apache::thrift::detail::ac::throw_app_exn("Could not find Protocol");
}
}
}
std::pair<std::unique_ptr<::apache::thrift::ContextStack>, std::shared_ptr<::apache::thrift::transport::THeader>> ParamServiceAsyncClient::listtypedef_ret_typedef_paramCtx(apache::thrift::RpcOptions* rpcOptions) {
auto header = std::make_shared<apache::thrift::transport::THeader>(
apache::thrift::transport::THeader::ALLOW_BIG_FRAMES);
header->setProtocolId(channel_->getProtocolId());
if (rpcOptions) {
header->setHeaders(rpcOptions->releaseWriteHeaders());
}
auto ctx = apache::thrift::ContextStack::createWithClientContext(
handlers_,
getServiceName(),
"ParamService.listtypedef_ret_typedef_param",
*header);
return {std::move(ctx), std::move(header)};
}
void ParamServiceAsyncClient::sync_listtypedef_ret_typedef_param(::std::vector<::some::valid::ns::simpleTypeDef>& _return, const ::some::valid::ns::complexStructTypeDef& p_param1) {
::apache::thrift::RpcOptions rpcOptions;
sync_listtypedef_ret_typedef_param(rpcOptions, _return, p_param1);
}
void ParamServiceAsyncClient::sync_listtypedef_ret_typedef_param(apache::thrift::RpcOptions& rpcOptions, ::std::vector<::some::valid::ns::simpleTypeDef>& _return, const ::some::valid::ns::complexStructTypeDef& p_param1) {
apache::thrift::ClientReceiveState returnState;
apache::thrift::ClientSyncCallback<false> callback(&returnState);
auto protocolId = apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId();
auto evb = apache::thrift::GeneratedAsyncClient::getChannel()->getEventBase();
auto [ctx, header] = listtypedef_ret_typedef_paramCtx(&rpcOptions);
auto wrappedCallback = apache::thrift::RequestClientCallback::Ptr(&callback);
listtypedef_ret_typedef_paramImpl(rpcOptions, std::move(header), ctx.get(), std::move(wrappedCallback), p_param1);
callback.waitUntilDone(evb);
if (returnState.isException()) {
returnState.exception().throw_exception();
}
returnState.resetProtocolId(protocolId);
returnState.resetCtx(std::move(ctx));
SCOPE_EXIT {
if (returnState.header() && !returnState.header()->getHeaders().empty()) {
rpcOptions.setReadHeaders(returnState.header()->releaseHeaders());
}
};
return folly::fibers::runInMainContext([&] {
recv_listtypedef_ret_typedef_param(_return, returnState);
});
}
folly::Future<::std::vector<::some::valid::ns::simpleTypeDef>> ParamServiceAsyncClient::future_listtypedef_ret_typedef_param(const ::some::valid::ns::complexStructTypeDef& p_param1) {
::apache::thrift::RpcOptions rpcOptions;
return future_listtypedef_ret_typedef_param(rpcOptions, p_param1);
}
folly::SemiFuture<::std::vector<::some::valid::ns::simpleTypeDef>> ParamServiceAsyncClient::semifuture_listtypedef_ret_typedef_param(const ::some::valid::ns::complexStructTypeDef& p_param1) {
::apache::thrift::RpcOptions rpcOptions;
return semifuture_listtypedef_ret_typedef_param(rpcOptions, p_param1);
}
folly::Future<::std::vector<::some::valid::ns::simpleTypeDef>> ParamServiceAsyncClient::future_listtypedef_ret_typedef_param(apache::thrift::RpcOptions& rpcOptions, const ::some::valid::ns::complexStructTypeDef& p_param1) {
folly::Promise<::std::vector<::some::valid::ns::simpleTypeDef>> promise;
auto future = promise.getFuture();
auto callback = std::make_unique<apache::thrift::FutureCallback<::std::vector<::some::valid::ns::simpleTypeDef>>>(std::move(promise), recv_wrapped_listtypedef_ret_typedef_param, channel_);
listtypedef_ret_typedef_param(rpcOptions, std::move(callback), p_param1);
return future;
}
folly::SemiFuture<::std::vector<::some::valid::ns::simpleTypeDef>> ParamServiceAsyncClient::semifuture_listtypedef_ret_typedef_param(apache::thrift::RpcOptions& rpcOptions, const ::some::valid::ns::complexStructTypeDef& p_param1) {
auto callbackAndFuture = makeSemiFutureCallback(recv_wrapped_listtypedef_ret_typedef_param, channel_);
auto callback = std::move(callbackAndFuture.first);
listtypedef_ret_typedef_param(rpcOptions, std::move(callback), p_param1);
return std::move(callbackAndFuture.second);
}
folly::Future<std::pair<::std::vector<::some::valid::ns::simpleTypeDef>, std::unique_ptr<apache::thrift::transport::THeader>>> ParamServiceAsyncClient::header_future_listtypedef_ret_typedef_param(apache::thrift::RpcOptions& rpcOptions, const ::some::valid::ns::complexStructTypeDef& p_param1) {
folly::Promise<std::pair<::std::vector<::some::valid::ns::simpleTypeDef>, std::unique_ptr<apache::thrift::transport::THeader>>> promise;
auto future = promise.getFuture();
auto callback = std::make_unique<apache::thrift::HeaderFutureCallback<::std::vector<::some::valid::ns::simpleTypeDef>>>(std::move(promise), recv_wrapped_listtypedef_ret_typedef_param, channel_);
listtypedef_ret_typedef_param(rpcOptions, std::move(callback), p_param1);
return future;
}
folly::SemiFuture<std::pair<::std::vector<::some::valid::ns::simpleTypeDef>, std::unique_ptr<apache::thrift::transport::THeader>>> ParamServiceAsyncClient::header_semifuture_listtypedef_ret_typedef_param(apache::thrift::RpcOptions& rpcOptions, const ::some::valid::ns::complexStructTypeDef& p_param1) {
auto callbackAndFuture = makeHeaderSemiFutureCallback(recv_wrapped_listtypedef_ret_typedef_param, channel_);
auto callback = std::move(callbackAndFuture.first);
listtypedef_ret_typedef_param(rpcOptions, std::move(callback), p_param1);
return std::move(callbackAndFuture.second);
}
void ParamServiceAsyncClient::listtypedef_ret_typedef_param(folly::Function<void (::apache::thrift::ClientReceiveState&&)> callback, const ::some::valid::ns::complexStructTypeDef& p_param1) {
listtypedef_ret_typedef_param(std::make_unique<apache::thrift::FunctionReplyCallback>(std::move(callback)), p_param1);
}
#if FOLLY_HAS_COROUTINES
#endif // FOLLY_HAS_COROUTINES
folly::exception_wrapper ParamServiceAsyncClient::recv_wrapped_listtypedef_ret_typedef_param(::std::vector<::some::valid::ns::simpleTypeDef>& _return, ::apache::thrift::ClientReceiveState& state) {
if (state.isException()) {
return std::move(state.exception());
}
if (!state.hasResponseBuffer()) {
return folly::make_exception_wrapper<apache::thrift::TApplicationException>("recv_ called without result");
}
using result = ParamService_listtypedef_ret_typedef_param_presult;
switch (state.protocolId()) {
case apache::thrift::protocol::T_BINARY_PROTOCOL:
{
apache::thrift::BinaryProtocolReader reader;
return apache::thrift::detail::ac::recv_wrapped<result>(
&reader, state, _return);
}
case apache::thrift::protocol::T_COMPACT_PROTOCOL:
{
apache::thrift::CompactProtocolReader reader;
return apache::thrift::detail::ac::recv_wrapped<result>(
&reader, state, _return);
}
default:
{
}
}
return folly::make_exception_wrapper<apache::thrift::TApplicationException>("Could not find Protocol");
}
void ParamServiceAsyncClient::recv_listtypedef_ret_typedef_param(::std::vector<::some::valid::ns::simpleTypeDef>& _return, ::apache::thrift::ClientReceiveState& state) {
auto ew = recv_wrapped_listtypedef_ret_typedef_param(_return, state);
if (ew) {
ew.throw_exception();
}
}
void ParamServiceAsyncClient::recv_instance_listtypedef_ret_typedef_param(::std::vector<::some::valid::ns::simpleTypeDef>& _return, ::apache::thrift::ClientReceiveState& state) {
return recv_listtypedef_ret_typedef_param(_return, state);
}
folly::exception_wrapper ParamServiceAsyncClient::recv_instance_wrapped_listtypedef_ret_typedef_param(::std::vector<::some::valid::ns::simpleTypeDef>& _return, ::apache::thrift::ClientReceiveState& state) {
return recv_wrapped_listtypedef_ret_typedef_param(_return, state);
}
void ParamServiceAsyncClient::enum_ret_double_param(std::unique_ptr<apache::thrift::RequestCallback> callback, double p_param1) {
::apache::thrift::RpcOptions rpcOptions;
enum_ret_double_param(rpcOptions, std::move(callback), p_param1);
}
void ParamServiceAsyncClient::enum_ret_double_param(apache::thrift::RpcOptions& rpcOptions, std::unique_ptr<apache::thrift::RequestCallback> callback, double p_param1) {
auto [ctx, header] = enum_ret_double_paramCtx(&rpcOptions);
apache::thrift::RequestCallback::Context callbackContext;
callbackContext.protocolId =
apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId();
auto* contextStack = ctx.get();
if (callback) {
callbackContext.ctx = std::move(ctx);
}
auto wrappedCallback = apache::thrift::toRequestClientCallbackPtr(std::move(callback), std::move(callbackContext));
enum_ret_double_paramImpl(rpcOptions, std::move(header), contextStack, std::move(wrappedCallback), p_param1);
}
void ParamServiceAsyncClient::enum_ret_double_paramImpl(const apache::thrift::RpcOptions& rpcOptions, std::shared_ptr<apache::thrift::transport::THeader> header, apache::thrift::ContextStack* contextStack, apache::thrift::RequestClientCallback::Ptr callback, double p_param1) {
switch (apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId()) {
case apache::thrift::protocol::T_BINARY_PROTOCOL:
{
apache::thrift::BinaryProtocolWriter writer;
enum_ret_double_paramT(&writer, rpcOptions, std::move(header), contextStack, std::move(callback), p_param1);
break;
}
case apache::thrift::protocol::T_COMPACT_PROTOCOL:
{
apache::thrift::CompactProtocolWriter writer;
enum_ret_double_paramT(&writer, rpcOptions, std::move(header), contextStack, std::move(callback), p_param1);
break;
}
default:
{
apache::thrift::detail::ac::throw_app_exn("Could not find Protocol");
}
}
}
std::pair<std::unique_ptr<::apache::thrift::ContextStack>, std::shared_ptr<::apache::thrift::transport::THeader>> ParamServiceAsyncClient::enum_ret_double_paramCtx(apache::thrift::RpcOptions* rpcOptions) {
auto header = std::make_shared<apache::thrift::transport::THeader>(
apache::thrift::transport::THeader::ALLOW_BIG_FRAMES);
header->setProtocolId(channel_->getProtocolId());
if (rpcOptions) {
header->setHeaders(rpcOptions->releaseWriteHeaders());
}
auto ctx = apache::thrift::ContextStack::createWithClientContext(
handlers_,
getServiceName(),
"ParamService.enum_ret_double_param",
*header);
return {std::move(ctx), std::move(header)};
}
::some::valid::ns::MyEnumA ParamServiceAsyncClient::sync_enum_ret_double_param(double p_param1) {
::apache::thrift::RpcOptions rpcOptions;
return sync_enum_ret_double_param(rpcOptions, p_param1);
}
::some::valid::ns::MyEnumA ParamServiceAsyncClient::sync_enum_ret_double_param(apache::thrift::RpcOptions& rpcOptions, double p_param1) {
apache::thrift::ClientReceiveState returnState;
apache::thrift::ClientSyncCallback<false> callback(&returnState);
auto protocolId = apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId();
auto evb = apache::thrift::GeneratedAsyncClient::getChannel()->getEventBase();
auto [ctx, header] = enum_ret_double_paramCtx(&rpcOptions);
auto wrappedCallback = apache::thrift::RequestClientCallback::Ptr(&callback);
enum_ret_double_paramImpl(rpcOptions, std::move(header), ctx.get(), std::move(wrappedCallback), p_param1);
callback.waitUntilDone(evb);
if (returnState.isException()) {
returnState.exception().throw_exception();
}
returnState.resetProtocolId(protocolId);
returnState.resetCtx(std::move(ctx));
SCOPE_EXIT {
if (returnState.header() && !returnState.header()->getHeaders().empty()) {
rpcOptions.setReadHeaders(returnState.header()->releaseHeaders());
}
};
return folly::fibers::runInMainContext([&] {
return recv_enum_ret_double_param(returnState);
});
}
folly::Future<::some::valid::ns::MyEnumA> ParamServiceAsyncClient::future_enum_ret_double_param(double p_param1) {
::apache::thrift::RpcOptions rpcOptions;
return future_enum_ret_double_param(rpcOptions, p_param1);
}
folly::SemiFuture<::some::valid::ns::MyEnumA> ParamServiceAsyncClient::semifuture_enum_ret_double_param(double p_param1) {
::apache::thrift::RpcOptions rpcOptions;
return semifuture_enum_ret_double_param(rpcOptions, p_param1);
}
folly::Future<::some::valid::ns::MyEnumA> ParamServiceAsyncClient::future_enum_ret_double_param(apache::thrift::RpcOptions& rpcOptions, double p_param1) {
folly::Promise<::some::valid::ns::MyEnumA> promise;
auto future = promise.getFuture();
auto callback = std::make_unique<apache::thrift::FutureCallback<::some::valid::ns::MyEnumA>>(std::move(promise), recv_wrapped_enum_ret_double_param, channel_);
enum_ret_double_param(rpcOptions, std::move(callback), p_param1);
return future;
}
folly::SemiFuture<::some::valid::ns::MyEnumA> ParamServiceAsyncClient::semifuture_enum_ret_double_param(apache::thrift::RpcOptions& rpcOptions, double p_param1) {
auto callbackAndFuture = makeSemiFutureCallback(recv_wrapped_enum_ret_double_param, channel_);
auto callback = std::move(callbackAndFuture.first);
enum_ret_double_param(rpcOptions, std::move(callback), p_param1);
return std::move(callbackAndFuture.second);
}
folly::Future<std::pair<::some::valid::ns::MyEnumA, std::unique_ptr<apache::thrift::transport::THeader>>> ParamServiceAsyncClient::header_future_enum_ret_double_param(apache::thrift::RpcOptions& rpcOptions, double p_param1) {
folly::Promise<std::pair<::some::valid::ns::MyEnumA, std::unique_ptr<apache::thrift::transport::THeader>>> promise;
auto future = promise.getFuture();
auto callback = std::make_unique<apache::thrift::HeaderFutureCallback<::some::valid::ns::MyEnumA>>(std::move(promise), recv_wrapped_enum_ret_double_param, channel_);
enum_ret_double_param(rpcOptions, std::move(callback), p_param1);
return future;
}
folly::SemiFuture<std::pair<::some::valid::ns::MyEnumA, std::unique_ptr<apache::thrift::transport::THeader>>> ParamServiceAsyncClient::header_semifuture_enum_ret_double_param(apache::thrift::RpcOptions& rpcOptions, double p_param1) {
auto callbackAndFuture = makeHeaderSemiFutureCallback(recv_wrapped_enum_ret_double_param, channel_);
auto callback = std::move(callbackAndFuture.first);
enum_ret_double_param(rpcOptions, std::move(callback), p_param1);
return std::move(callbackAndFuture.second);
}
void ParamServiceAsyncClient::enum_ret_double_param(folly::Function<void (::apache::thrift::ClientReceiveState&&)> callback, double p_param1) {
enum_ret_double_param(std::make_unique<apache::thrift::FunctionReplyCallback>(std::move(callback)), p_param1);
}
#if FOLLY_HAS_COROUTINES
#endif // FOLLY_HAS_COROUTINES
folly::exception_wrapper ParamServiceAsyncClient::recv_wrapped_enum_ret_double_param(::some::valid::ns::MyEnumA& _return, ::apache::thrift::ClientReceiveState& state) {
if (state.isException()) {
return std::move(state.exception());
}
if (!state.hasResponseBuffer()) {
return folly::make_exception_wrapper<apache::thrift::TApplicationException>("recv_ called without result");
}
using result = ParamService_enum_ret_double_param_presult;
switch (state.protocolId()) {
case apache::thrift::protocol::T_BINARY_PROTOCOL:
{
apache::thrift::BinaryProtocolReader reader;
return apache::thrift::detail::ac::recv_wrapped<result>(
&reader, state, _return);
}
case apache::thrift::protocol::T_COMPACT_PROTOCOL:
{
apache::thrift::CompactProtocolReader reader;
return apache::thrift::detail::ac::recv_wrapped<result>(
&reader, state, _return);
}
default:
{
}
}
return folly::make_exception_wrapper<apache::thrift::TApplicationException>("Could not find Protocol");
}
::some::valid::ns::MyEnumA ParamServiceAsyncClient::recv_enum_ret_double_param(::apache::thrift::ClientReceiveState& state) {
::some::valid::ns::MyEnumA _return;
auto ew = recv_wrapped_enum_ret_double_param(_return, state);
if (ew) {
ew.throw_exception();
}
return _return;
}
::some::valid::ns::MyEnumA ParamServiceAsyncClient::recv_instance_enum_ret_double_param(::apache::thrift::ClientReceiveState& state) {
return recv_enum_ret_double_param(state);
}
folly::exception_wrapper ParamServiceAsyncClient::recv_instance_wrapped_enum_ret_double_param(::some::valid::ns::MyEnumA& _return, ::apache::thrift::ClientReceiveState& state) {
return recv_wrapped_enum_ret_double_param(_return, state);
}
void ParamServiceAsyncClient::enum_ret_double_enum_param(std::unique_ptr<apache::thrift::RequestCallback> callback, double p_param1, ::some::valid::ns::MyEnumA p_param2) {
::apache::thrift::RpcOptions rpcOptions;
enum_ret_double_enum_param(rpcOptions, std::move(callback), p_param1, p_param2);
}
void ParamServiceAsyncClient::enum_ret_double_enum_param(apache::thrift::RpcOptions& rpcOptions, std::unique_ptr<apache::thrift::RequestCallback> callback, double p_param1, ::some::valid::ns::MyEnumA p_param2) {
auto [ctx, header] = enum_ret_double_enum_paramCtx(&rpcOptions);
apache::thrift::RequestCallback::Context callbackContext;
callbackContext.protocolId =
apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId();
auto* contextStack = ctx.get();
if (callback) {
callbackContext.ctx = std::move(ctx);
}
auto wrappedCallback = apache::thrift::toRequestClientCallbackPtr(std::move(callback), std::move(callbackContext));
enum_ret_double_enum_paramImpl(rpcOptions, std::move(header), contextStack, std::move(wrappedCallback), p_param1, p_param2);
}
void ParamServiceAsyncClient::enum_ret_double_enum_paramImpl(const apache::thrift::RpcOptions& rpcOptions, std::shared_ptr<apache::thrift::transport::THeader> header, apache::thrift::ContextStack* contextStack, apache::thrift::RequestClientCallback::Ptr callback, double p_param1, ::some::valid::ns::MyEnumA p_param2) {
switch (apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId()) {
case apache::thrift::protocol::T_BINARY_PROTOCOL:
{
apache::thrift::BinaryProtocolWriter writer;
enum_ret_double_enum_paramT(&writer, rpcOptions, std::move(header), contextStack, std::move(callback), p_param1, p_param2);
break;
}
case apache::thrift::protocol::T_COMPACT_PROTOCOL:
{
apache::thrift::CompactProtocolWriter writer;
enum_ret_double_enum_paramT(&writer, rpcOptions, std::move(header), contextStack, std::move(callback), p_param1, p_param2);
break;
}
default:
{
apache::thrift::detail::ac::throw_app_exn("Could not find Protocol");
}
}
}
std::pair<std::unique_ptr<::apache::thrift::ContextStack>, std::shared_ptr<::apache::thrift::transport::THeader>> ParamServiceAsyncClient::enum_ret_double_enum_paramCtx(apache::thrift::RpcOptions* rpcOptions) {
auto header = std::make_shared<apache::thrift::transport::THeader>(
apache::thrift::transport::THeader::ALLOW_BIG_FRAMES);
header->setProtocolId(channel_->getProtocolId());
if (rpcOptions) {
header->setHeaders(rpcOptions->releaseWriteHeaders());
}
auto ctx = apache::thrift::ContextStack::createWithClientContext(
handlers_,
getServiceName(),
"ParamService.enum_ret_double_enum_param",
*header);
return {std::move(ctx), std::move(header)};
}
::some::valid::ns::MyEnumA ParamServiceAsyncClient::sync_enum_ret_double_enum_param(double p_param1, ::some::valid::ns::MyEnumA p_param2) {
::apache::thrift::RpcOptions rpcOptions;
return sync_enum_ret_double_enum_param(rpcOptions, p_param1, p_param2);
}
::some::valid::ns::MyEnumA ParamServiceAsyncClient::sync_enum_ret_double_enum_param(apache::thrift::RpcOptions& rpcOptions, double p_param1, ::some::valid::ns::MyEnumA p_param2) {
apache::thrift::ClientReceiveState returnState;
apache::thrift::ClientSyncCallback<false> callback(&returnState);
auto protocolId = apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId();
auto evb = apache::thrift::GeneratedAsyncClient::getChannel()->getEventBase();
auto [ctx, header] = enum_ret_double_enum_paramCtx(&rpcOptions);
auto wrappedCallback = apache::thrift::RequestClientCallback::Ptr(&callback);
enum_ret_double_enum_paramImpl(rpcOptions, std::move(header), ctx.get(), std::move(wrappedCallback), p_param1, p_param2);
callback.waitUntilDone(evb);
if (returnState.isException()) {
returnState.exception().throw_exception();
}
returnState.resetProtocolId(protocolId);
returnState.resetCtx(std::move(ctx));
SCOPE_EXIT {
if (returnState.header() && !returnState.header()->getHeaders().empty()) {
rpcOptions.setReadHeaders(returnState.header()->releaseHeaders());
}
};
return folly::fibers::runInMainContext([&] {
return recv_enum_ret_double_enum_param(returnState);
});
}
folly::Future<::some::valid::ns::MyEnumA> ParamServiceAsyncClient::future_enum_ret_double_enum_param(double p_param1, ::some::valid::ns::MyEnumA p_param2) {
::apache::thrift::RpcOptions rpcOptions;
return future_enum_ret_double_enum_param(rpcOptions, p_param1, p_param2);
}
folly::SemiFuture<::some::valid::ns::MyEnumA> ParamServiceAsyncClient::semifuture_enum_ret_double_enum_param(double p_param1, ::some::valid::ns::MyEnumA p_param2) {
::apache::thrift::RpcOptions rpcOptions;
return semifuture_enum_ret_double_enum_param(rpcOptions, p_param1, p_param2);
}
folly::Future<::some::valid::ns::MyEnumA> ParamServiceAsyncClient::future_enum_ret_double_enum_param(apache::thrift::RpcOptions& rpcOptions, double p_param1, ::some::valid::ns::MyEnumA p_param2) {
folly::Promise<::some::valid::ns::MyEnumA> promise;
auto future = promise.getFuture();
auto callback = std::make_unique<apache::thrift::FutureCallback<::some::valid::ns::MyEnumA>>(std::move(promise), recv_wrapped_enum_ret_double_enum_param, channel_);
enum_ret_double_enum_param(rpcOptions, std::move(callback), p_param1, p_param2);
return future;
}
folly::SemiFuture<::some::valid::ns::MyEnumA> ParamServiceAsyncClient::semifuture_enum_ret_double_enum_param(apache::thrift::RpcOptions& rpcOptions, double p_param1, ::some::valid::ns::MyEnumA p_param2) {
auto callbackAndFuture = makeSemiFutureCallback(recv_wrapped_enum_ret_double_enum_param, channel_);
auto callback = std::move(callbackAndFuture.first);
enum_ret_double_enum_param(rpcOptions, std::move(callback), p_param1, p_param2);
return std::move(callbackAndFuture.second);
}
folly::Future<std::pair<::some::valid::ns::MyEnumA, std::unique_ptr<apache::thrift::transport::THeader>>> ParamServiceAsyncClient::header_future_enum_ret_double_enum_param(apache::thrift::RpcOptions& rpcOptions, double p_param1, ::some::valid::ns::MyEnumA p_param2) {
folly::Promise<std::pair<::some::valid::ns::MyEnumA, std::unique_ptr<apache::thrift::transport::THeader>>> promise;
auto future = promise.getFuture();
auto callback = std::make_unique<apache::thrift::HeaderFutureCallback<::some::valid::ns::MyEnumA>>(std::move(promise), recv_wrapped_enum_ret_double_enum_param, channel_);
enum_ret_double_enum_param(rpcOptions, std::move(callback), p_param1, p_param2);
return future;
}
folly::SemiFuture<std::pair<::some::valid::ns::MyEnumA, std::unique_ptr<apache::thrift::transport::THeader>>> ParamServiceAsyncClient::header_semifuture_enum_ret_double_enum_param(apache::thrift::RpcOptions& rpcOptions, double p_param1, ::some::valid::ns::MyEnumA p_param2) {
auto callbackAndFuture = makeHeaderSemiFutureCallback(recv_wrapped_enum_ret_double_enum_param, channel_);
auto callback = std::move(callbackAndFuture.first);
enum_ret_double_enum_param(rpcOptions, std::move(callback), p_param1, p_param2);
return std::move(callbackAndFuture.second);
}
void ParamServiceAsyncClient::enum_ret_double_enum_param(folly::Function<void (::apache::thrift::ClientReceiveState&&)> callback, double p_param1, ::some::valid::ns::MyEnumA p_param2) {
enum_ret_double_enum_param(std::make_unique<apache::thrift::FunctionReplyCallback>(std::move(callback)), p_param1, p_param2);
}
#if FOLLY_HAS_COROUTINES
#endif // FOLLY_HAS_COROUTINES
folly::exception_wrapper ParamServiceAsyncClient::recv_wrapped_enum_ret_double_enum_param(::some::valid::ns::MyEnumA& _return, ::apache::thrift::ClientReceiveState& state) {
if (state.isException()) {
return std::move(state.exception());
}
if (!state.hasResponseBuffer()) {
return folly::make_exception_wrapper<apache::thrift::TApplicationException>("recv_ called without result");
}
using result = ParamService_enum_ret_double_enum_param_presult;
switch (state.protocolId()) {
case apache::thrift::protocol::T_BINARY_PROTOCOL:
{
apache::thrift::BinaryProtocolReader reader;
return apache::thrift::detail::ac::recv_wrapped<result>(
&reader, state, _return);
}
case apache::thrift::protocol::T_COMPACT_PROTOCOL:
{
apache::thrift::CompactProtocolReader reader;
return apache::thrift::detail::ac::recv_wrapped<result>(
&reader, state, _return);
}
default:
{
}
}
return folly::make_exception_wrapper<apache::thrift::TApplicationException>("Could not find Protocol");
}
::some::valid::ns::MyEnumA ParamServiceAsyncClient::recv_enum_ret_double_enum_param(::apache::thrift::ClientReceiveState& state) {
::some::valid::ns::MyEnumA _return;
auto ew = recv_wrapped_enum_ret_double_enum_param(_return, state);
if (ew) {
ew.throw_exception();
}
return _return;
}
::some::valid::ns::MyEnumA ParamServiceAsyncClient::recv_instance_enum_ret_double_enum_param(::apache::thrift::ClientReceiveState& state) {
return recv_enum_ret_double_enum_param(state);
}
folly::exception_wrapper ParamServiceAsyncClient::recv_instance_wrapped_enum_ret_double_enum_param(::some::valid::ns::MyEnumA& _return, ::apache::thrift::ClientReceiveState& state) {
return recv_wrapped_enum_ret_double_enum_param(_return, state);
}
void ParamServiceAsyncClient::listenum_ret_map_param(std::unique_ptr<apache::thrift::RequestCallback> callback, const ::std::map<::std::string, ::std::int64_t>& p_param1) {
::apache::thrift::RpcOptions rpcOptions;
listenum_ret_map_param(rpcOptions, std::move(callback), p_param1);
}
void ParamServiceAsyncClient::listenum_ret_map_param(apache::thrift::RpcOptions& rpcOptions, std::unique_ptr<apache::thrift::RequestCallback> callback, const ::std::map<::std::string, ::std::int64_t>& p_param1) {
auto [ctx, header] = listenum_ret_map_paramCtx(&rpcOptions);
apache::thrift::RequestCallback::Context callbackContext;
callbackContext.protocolId =
apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId();
auto* contextStack = ctx.get();
if (callback) {
callbackContext.ctx = std::move(ctx);
}
auto wrappedCallback = apache::thrift::toRequestClientCallbackPtr(std::move(callback), std::move(callbackContext));
listenum_ret_map_paramImpl(rpcOptions, std::move(header), contextStack, std::move(wrappedCallback), p_param1);
}
void ParamServiceAsyncClient::listenum_ret_map_paramImpl(const apache::thrift::RpcOptions& rpcOptions, std::shared_ptr<apache::thrift::transport::THeader> header, apache::thrift::ContextStack* contextStack, apache::thrift::RequestClientCallback::Ptr callback, const ::std::map<::std::string, ::std::int64_t>& p_param1) {
switch (apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId()) {
case apache::thrift::protocol::T_BINARY_PROTOCOL:
{
apache::thrift::BinaryProtocolWriter writer;
listenum_ret_map_paramT(&writer, rpcOptions, std::move(header), contextStack, std::move(callback), p_param1);
break;
}
case apache::thrift::protocol::T_COMPACT_PROTOCOL:
{
apache::thrift::CompactProtocolWriter writer;
listenum_ret_map_paramT(&writer, rpcOptions, std::move(header), contextStack, std::move(callback), p_param1);
break;
}
default:
{
apache::thrift::detail::ac::throw_app_exn("Could not find Protocol");
}
}
}
std::pair<std::unique_ptr<::apache::thrift::ContextStack>, std::shared_ptr<::apache::thrift::transport::THeader>> ParamServiceAsyncClient::listenum_ret_map_paramCtx(apache::thrift::RpcOptions* rpcOptions) {
auto header = std::make_shared<apache::thrift::transport::THeader>(
apache::thrift::transport::THeader::ALLOW_BIG_FRAMES);
header->setProtocolId(channel_->getProtocolId());
if (rpcOptions) {
header->setHeaders(rpcOptions->releaseWriteHeaders());
}
auto ctx = apache::thrift::ContextStack::createWithClientContext(
handlers_,
getServiceName(),
"ParamService.listenum_ret_map_param",
*header);
return {std::move(ctx), std::move(header)};
}
void ParamServiceAsyncClient::sync_listenum_ret_map_param(::std::vector<::some::valid::ns::MyEnumA>& _return, const ::std::map<::std::string, ::std::int64_t>& p_param1) {
::apache::thrift::RpcOptions rpcOptions;
sync_listenum_ret_map_param(rpcOptions, _return, p_param1);
}
void ParamServiceAsyncClient::sync_listenum_ret_map_param(apache::thrift::RpcOptions& rpcOptions, ::std::vector<::some::valid::ns::MyEnumA>& _return, const ::std::map<::std::string, ::std::int64_t>& p_param1) {
apache::thrift::ClientReceiveState returnState;
apache::thrift::ClientSyncCallback<false> callback(&returnState);
auto protocolId = apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId();
auto evb = apache::thrift::GeneratedAsyncClient::getChannel()->getEventBase();
auto [ctx, header] = listenum_ret_map_paramCtx(&rpcOptions);
auto wrappedCallback = apache::thrift::RequestClientCallback::Ptr(&callback);
listenum_ret_map_paramImpl(rpcOptions, std::move(header), ctx.get(), std::move(wrappedCallback), p_param1);
callback.waitUntilDone(evb);
if (returnState.isException()) {
returnState.exception().throw_exception();
}
returnState.resetProtocolId(protocolId);
returnState.resetCtx(std::move(ctx));
SCOPE_EXIT {
if (returnState.header() && !returnState.header()->getHeaders().empty()) {
rpcOptions.setReadHeaders(returnState.header()->releaseHeaders());
}
};
return folly::fibers::runInMainContext([&] {
recv_listenum_ret_map_param(_return, returnState);
});
}
folly::Future<::std::vector<::some::valid::ns::MyEnumA>> ParamServiceAsyncClient::future_listenum_ret_map_param(const ::std::map<::std::string, ::std::int64_t>& p_param1) {
::apache::thrift::RpcOptions rpcOptions;
return future_listenum_ret_map_param(rpcOptions, p_param1);
}
folly::SemiFuture<::std::vector<::some::valid::ns::MyEnumA>> ParamServiceAsyncClient::semifuture_listenum_ret_map_param(const ::std::map<::std::string, ::std::int64_t>& p_param1) {
::apache::thrift::RpcOptions rpcOptions;
return semifuture_listenum_ret_map_param(rpcOptions, p_param1);
}
folly::Future<::std::vector<::some::valid::ns::MyEnumA>> ParamServiceAsyncClient::future_listenum_ret_map_param(apache::thrift::RpcOptions& rpcOptions, const ::std::map<::std::string, ::std::int64_t>& p_param1) {
folly::Promise<::std::vector<::some::valid::ns::MyEnumA>> promise;
auto future = promise.getFuture();
auto callback = std::make_unique<apache::thrift::FutureCallback<::std::vector<::some::valid::ns::MyEnumA>>>(std::move(promise), recv_wrapped_listenum_ret_map_param, channel_);
listenum_ret_map_param(rpcOptions, std::move(callback), p_param1);
return future;
}
folly::SemiFuture<::std::vector<::some::valid::ns::MyEnumA>> ParamServiceAsyncClient::semifuture_listenum_ret_map_param(apache::thrift::RpcOptions& rpcOptions, const ::std::map<::std::string, ::std::int64_t>& p_param1) {
auto callbackAndFuture = makeSemiFutureCallback(recv_wrapped_listenum_ret_map_param, channel_);
auto callback = std::move(callbackAndFuture.first);
listenum_ret_map_param(rpcOptions, std::move(callback), p_param1);
return std::move(callbackAndFuture.second);
}
folly::Future<std::pair<::std::vector<::some::valid::ns::MyEnumA>, std::unique_ptr<apache::thrift::transport::THeader>>> ParamServiceAsyncClient::header_future_listenum_ret_map_param(apache::thrift::RpcOptions& rpcOptions, const ::std::map<::std::string, ::std::int64_t>& p_param1) {
folly::Promise<std::pair<::std::vector<::some::valid::ns::MyEnumA>, std::unique_ptr<apache::thrift::transport::THeader>>> promise;
auto future = promise.getFuture();
auto callback = std::make_unique<apache::thrift::HeaderFutureCallback<::std::vector<::some::valid::ns::MyEnumA>>>(std::move(promise), recv_wrapped_listenum_ret_map_param, channel_);
listenum_ret_map_param(rpcOptions, std::move(callback), p_param1);
return future;
}
folly::SemiFuture<std::pair<::std::vector<::some::valid::ns::MyEnumA>, std::unique_ptr<apache::thrift::transport::THeader>>> ParamServiceAsyncClient::header_semifuture_listenum_ret_map_param(apache::thrift::RpcOptions& rpcOptions, const ::std::map<::std::string, ::std::int64_t>& p_param1) {
auto callbackAndFuture = makeHeaderSemiFutureCallback(recv_wrapped_listenum_ret_map_param, channel_);
auto callback = std::move(callbackAndFuture.first);
listenum_ret_map_param(rpcOptions, std::move(callback), p_param1);
return std::move(callbackAndFuture.second);
}
void ParamServiceAsyncClient::listenum_ret_map_param(folly::Function<void (::apache::thrift::ClientReceiveState&&)> callback, const ::std::map<::std::string, ::std::int64_t>& p_param1) {
listenum_ret_map_param(std::make_unique<apache::thrift::FunctionReplyCallback>(std::move(callback)), p_param1);
}
#if FOLLY_HAS_COROUTINES
#endif // FOLLY_HAS_COROUTINES
folly::exception_wrapper ParamServiceAsyncClient::recv_wrapped_listenum_ret_map_param(::std::vector<::some::valid::ns::MyEnumA>& _return, ::apache::thrift::ClientReceiveState& state) {
if (state.isException()) {
return std::move(state.exception());
}
if (!state.hasResponseBuffer()) {
return folly::make_exception_wrapper<apache::thrift::TApplicationException>("recv_ called without result");
}
using result = ParamService_listenum_ret_map_param_presult;
switch (state.protocolId()) {
case apache::thrift::protocol::T_BINARY_PROTOCOL:
{
apache::thrift::BinaryProtocolReader reader;
return apache::thrift::detail::ac::recv_wrapped<result>(
&reader, state, _return);
}
case apache::thrift::protocol::T_COMPACT_PROTOCOL:
{
apache::thrift::CompactProtocolReader reader;
return apache::thrift::detail::ac::recv_wrapped<result>(
&reader, state, _return);
}
default:
{
}
}
return folly::make_exception_wrapper<apache::thrift::TApplicationException>("Could not find Protocol");
}
void ParamServiceAsyncClient::recv_listenum_ret_map_param(::std::vector<::some::valid::ns::MyEnumA>& _return, ::apache::thrift::ClientReceiveState& state) {
auto ew = recv_wrapped_listenum_ret_map_param(_return, state);
if (ew) {
ew.throw_exception();
}
}
void ParamServiceAsyncClient::recv_instance_listenum_ret_map_param(::std::vector<::some::valid::ns::MyEnumA>& _return, ::apache::thrift::ClientReceiveState& state) {
return recv_listenum_ret_map_param(_return, state);
}
folly::exception_wrapper ParamServiceAsyncClient::recv_instance_wrapped_listenum_ret_map_param(::std::vector<::some::valid::ns::MyEnumA>& _return, ::apache::thrift::ClientReceiveState& state) {
return recv_wrapped_listenum_ret_map_param(_return, state);
}
void ParamServiceAsyncClient::struct_ret_i16_param(std::unique_ptr<apache::thrift::RequestCallback> callback, ::std::int16_t p_param1) {
::apache::thrift::RpcOptions rpcOptions;
struct_ret_i16_param(rpcOptions, std::move(callback), p_param1);
}
void ParamServiceAsyncClient::struct_ret_i16_param(apache::thrift::RpcOptions& rpcOptions, std::unique_ptr<apache::thrift::RequestCallback> callback, ::std::int16_t p_param1) {
auto [ctx, header] = struct_ret_i16_paramCtx(&rpcOptions);
apache::thrift::RequestCallback::Context callbackContext;
callbackContext.protocolId =
apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId();
auto* contextStack = ctx.get();
if (callback) {
callbackContext.ctx = std::move(ctx);
}
auto wrappedCallback = apache::thrift::toRequestClientCallbackPtr(std::move(callback), std::move(callbackContext));
struct_ret_i16_paramImpl(rpcOptions, std::move(header), contextStack, std::move(wrappedCallback), p_param1);
}
void ParamServiceAsyncClient::struct_ret_i16_paramImpl(const apache::thrift::RpcOptions& rpcOptions, std::shared_ptr<apache::thrift::transport::THeader> header, apache::thrift::ContextStack* contextStack, apache::thrift::RequestClientCallback::Ptr callback, ::std::int16_t p_param1) {
switch (apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId()) {
case apache::thrift::protocol::T_BINARY_PROTOCOL:
{
apache::thrift::BinaryProtocolWriter writer;
struct_ret_i16_paramT(&writer, rpcOptions, std::move(header), contextStack, std::move(callback), p_param1);
break;
}
case apache::thrift::protocol::T_COMPACT_PROTOCOL:
{
apache::thrift::CompactProtocolWriter writer;
struct_ret_i16_paramT(&writer, rpcOptions, std::move(header), contextStack, std::move(callback), p_param1);
break;
}
default:
{
apache::thrift::detail::ac::throw_app_exn("Could not find Protocol");
}
}
}
std::pair<std::unique_ptr<::apache::thrift::ContextStack>, std::shared_ptr<::apache::thrift::transport::THeader>> ParamServiceAsyncClient::struct_ret_i16_paramCtx(apache::thrift::RpcOptions* rpcOptions) {
auto header = std::make_shared<apache::thrift::transport::THeader>(
apache::thrift::transport::THeader::ALLOW_BIG_FRAMES);
header->setProtocolId(channel_->getProtocolId());
if (rpcOptions) {
header->setHeaders(rpcOptions->releaseWriteHeaders());
}
auto ctx = apache::thrift::ContextStack::createWithClientContext(
handlers_,
getServiceName(),
"ParamService.struct_ret_i16_param",
*header);
return {std::move(ctx), std::move(header)};
}
void ParamServiceAsyncClient::sync_struct_ret_i16_param(::some::valid::ns::MyStruct& _return, ::std::int16_t p_param1) {
::apache::thrift::RpcOptions rpcOptions;
sync_struct_ret_i16_param(rpcOptions, _return, p_param1);
}
void ParamServiceAsyncClient::sync_struct_ret_i16_param(apache::thrift::RpcOptions& rpcOptions, ::some::valid::ns::MyStruct& _return, ::std::int16_t p_param1) {
apache::thrift::ClientReceiveState returnState;
apache::thrift::ClientSyncCallback<false> callback(&returnState);
auto protocolId = apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId();
auto evb = apache::thrift::GeneratedAsyncClient::getChannel()->getEventBase();
auto [ctx, header] = struct_ret_i16_paramCtx(&rpcOptions);
auto wrappedCallback = apache::thrift::RequestClientCallback::Ptr(&callback);
struct_ret_i16_paramImpl(rpcOptions, std::move(header), ctx.get(), std::move(wrappedCallback), p_param1);
callback.waitUntilDone(evb);
if (returnState.isException()) {
returnState.exception().throw_exception();
}
returnState.resetProtocolId(protocolId);
returnState.resetCtx(std::move(ctx));
SCOPE_EXIT {
if (returnState.header() && !returnState.header()->getHeaders().empty()) {
rpcOptions.setReadHeaders(returnState.header()->releaseHeaders());
}
};
return folly::fibers::runInMainContext([&] {
recv_struct_ret_i16_param(_return, returnState);
});
}
folly::Future<::some::valid::ns::MyStruct> ParamServiceAsyncClient::future_struct_ret_i16_param(::std::int16_t p_param1) {
::apache::thrift::RpcOptions rpcOptions;
return future_struct_ret_i16_param(rpcOptions, p_param1);
}
folly::SemiFuture<::some::valid::ns::MyStruct> ParamServiceAsyncClient::semifuture_struct_ret_i16_param(::std::int16_t p_param1) {
::apache::thrift::RpcOptions rpcOptions;
return semifuture_struct_ret_i16_param(rpcOptions, p_param1);
}
folly::Future<::some::valid::ns::MyStruct> ParamServiceAsyncClient::future_struct_ret_i16_param(apache::thrift::RpcOptions& rpcOptions, ::std::int16_t p_param1) {
folly::Promise<::some::valid::ns::MyStruct> promise;
auto future = promise.getFuture();
auto callback = std::make_unique<apache::thrift::FutureCallback<::some::valid::ns::MyStruct>>(std::move(promise), recv_wrapped_struct_ret_i16_param, channel_);
struct_ret_i16_param(rpcOptions, std::move(callback), p_param1);
return future;
}
folly::SemiFuture<::some::valid::ns::MyStruct> ParamServiceAsyncClient::semifuture_struct_ret_i16_param(apache::thrift::RpcOptions& rpcOptions, ::std::int16_t p_param1) {
auto callbackAndFuture = makeSemiFutureCallback(recv_wrapped_struct_ret_i16_param, channel_);
auto callback = std::move(callbackAndFuture.first);
struct_ret_i16_param(rpcOptions, std::move(callback), p_param1);
return std::move(callbackAndFuture.second);
}
folly::Future<std::pair<::some::valid::ns::MyStruct, std::unique_ptr<apache::thrift::transport::THeader>>> ParamServiceAsyncClient::header_future_struct_ret_i16_param(apache::thrift::RpcOptions& rpcOptions, ::std::int16_t p_param1) {
folly::Promise<std::pair<::some::valid::ns::MyStruct, std::unique_ptr<apache::thrift::transport::THeader>>> promise;
auto future = promise.getFuture();
auto callback = std::make_unique<apache::thrift::HeaderFutureCallback<::some::valid::ns::MyStruct>>(std::move(promise), recv_wrapped_struct_ret_i16_param, channel_);
struct_ret_i16_param(rpcOptions, std::move(callback), p_param1);
return future;
}
folly::SemiFuture<std::pair<::some::valid::ns::MyStruct, std::unique_ptr<apache::thrift::transport::THeader>>> ParamServiceAsyncClient::header_semifuture_struct_ret_i16_param(apache::thrift::RpcOptions& rpcOptions, ::std::int16_t p_param1) {
auto callbackAndFuture = makeHeaderSemiFutureCallback(recv_wrapped_struct_ret_i16_param, channel_);
auto callback = std::move(callbackAndFuture.first);
struct_ret_i16_param(rpcOptions, std::move(callback), p_param1);
return std::move(callbackAndFuture.second);
}
void ParamServiceAsyncClient::struct_ret_i16_param(folly::Function<void (::apache::thrift::ClientReceiveState&&)> callback, ::std::int16_t p_param1) {
struct_ret_i16_param(std::make_unique<apache::thrift::FunctionReplyCallback>(std::move(callback)), p_param1);
}
#if FOLLY_HAS_COROUTINES
#endif // FOLLY_HAS_COROUTINES
folly::exception_wrapper ParamServiceAsyncClient::recv_wrapped_struct_ret_i16_param(::some::valid::ns::MyStruct& _return, ::apache::thrift::ClientReceiveState& state) {
if (state.isException()) {
return std::move(state.exception());
}
if (!state.hasResponseBuffer()) {
return folly::make_exception_wrapper<apache::thrift::TApplicationException>("recv_ called without result");
}
using result = ParamService_struct_ret_i16_param_presult;
switch (state.protocolId()) {
case apache::thrift::protocol::T_BINARY_PROTOCOL:
{
apache::thrift::BinaryProtocolReader reader;
return apache::thrift::detail::ac::recv_wrapped<result>(
&reader, state, _return);
}
case apache::thrift::protocol::T_COMPACT_PROTOCOL:
{
apache::thrift::CompactProtocolReader reader;
return apache::thrift::detail::ac::recv_wrapped<result>(
&reader, state, _return);
}
default:
{
}
}
return folly::make_exception_wrapper<apache::thrift::TApplicationException>("Could not find Protocol");
}
void ParamServiceAsyncClient::recv_struct_ret_i16_param(::some::valid::ns::MyStruct& _return, ::apache::thrift::ClientReceiveState& state) {
auto ew = recv_wrapped_struct_ret_i16_param(_return, state);
if (ew) {
ew.throw_exception();
}
}
void ParamServiceAsyncClient::recv_instance_struct_ret_i16_param(::some::valid::ns::MyStruct& _return, ::apache::thrift::ClientReceiveState& state) {
return recv_struct_ret_i16_param(_return, state);
}
folly::exception_wrapper ParamServiceAsyncClient::recv_instance_wrapped_struct_ret_i16_param(::some::valid::ns::MyStruct& _return, ::apache::thrift::ClientReceiveState& state) {
return recv_wrapped_struct_ret_i16_param(_return, state);
}
void ParamServiceAsyncClient::setstruct_ret_set_param(std::unique_ptr<apache::thrift::RequestCallback> callback, const ::std::set<::std::string>& p_param1) {
::apache::thrift::RpcOptions rpcOptions;
setstruct_ret_set_param(rpcOptions, std::move(callback), p_param1);
}
void ParamServiceAsyncClient::setstruct_ret_set_param(apache::thrift::RpcOptions& rpcOptions, std::unique_ptr<apache::thrift::RequestCallback> callback, const ::std::set<::std::string>& p_param1) {
auto [ctx, header] = setstruct_ret_set_paramCtx(&rpcOptions);
apache::thrift::RequestCallback::Context callbackContext;
callbackContext.protocolId =
apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId();
auto* contextStack = ctx.get();
if (callback) {
callbackContext.ctx = std::move(ctx);
}
auto wrappedCallback = apache::thrift::toRequestClientCallbackPtr(std::move(callback), std::move(callbackContext));
setstruct_ret_set_paramImpl(rpcOptions, std::move(header), contextStack, std::move(wrappedCallback), p_param1);
}
void ParamServiceAsyncClient::setstruct_ret_set_paramImpl(const apache::thrift::RpcOptions& rpcOptions, std::shared_ptr<apache::thrift::transport::THeader> header, apache::thrift::ContextStack* contextStack, apache::thrift::RequestClientCallback::Ptr callback, const ::std::set<::std::string>& p_param1) {
switch (apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId()) {
case apache::thrift::protocol::T_BINARY_PROTOCOL:
{
apache::thrift::BinaryProtocolWriter writer;
setstruct_ret_set_paramT(&writer, rpcOptions, std::move(header), contextStack, std::move(callback), p_param1);
break;
}
case apache::thrift::protocol::T_COMPACT_PROTOCOL:
{
apache::thrift::CompactProtocolWriter writer;
setstruct_ret_set_paramT(&writer, rpcOptions, std::move(header), contextStack, std::move(callback), p_param1);
break;
}
default:
{
apache::thrift::detail::ac::throw_app_exn("Could not find Protocol");
}
}
}
std::pair<std::unique_ptr<::apache::thrift::ContextStack>, std::shared_ptr<::apache::thrift::transport::THeader>> ParamServiceAsyncClient::setstruct_ret_set_paramCtx(apache::thrift::RpcOptions* rpcOptions) {
auto header = std::make_shared<apache::thrift::transport::THeader>(
apache::thrift::transport::THeader::ALLOW_BIG_FRAMES);
header->setProtocolId(channel_->getProtocolId());
if (rpcOptions) {
header->setHeaders(rpcOptions->releaseWriteHeaders());
}
auto ctx = apache::thrift::ContextStack::createWithClientContext(
handlers_,
getServiceName(),
"ParamService.setstruct_ret_set_param",
*header);
return {std::move(ctx), std::move(header)};
}
void ParamServiceAsyncClient::sync_setstruct_ret_set_param(::std::set<::some::valid::ns::MyStruct>& _return, const ::std::set<::std::string>& p_param1) {
::apache::thrift::RpcOptions rpcOptions;
sync_setstruct_ret_set_param(rpcOptions, _return, p_param1);
}
void ParamServiceAsyncClient::sync_setstruct_ret_set_param(apache::thrift::RpcOptions& rpcOptions, ::std::set<::some::valid::ns::MyStruct>& _return, const ::std::set<::std::string>& p_param1) {
apache::thrift::ClientReceiveState returnState;
apache::thrift::ClientSyncCallback<false> callback(&returnState);
auto protocolId = apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId();
auto evb = apache::thrift::GeneratedAsyncClient::getChannel()->getEventBase();
auto [ctx, header] = setstruct_ret_set_paramCtx(&rpcOptions);
auto wrappedCallback = apache::thrift::RequestClientCallback::Ptr(&callback);
setstruct_ret_set_paramImpl(rpcOptions, std::move(header), ctx.get(), std::move(wrappedCallback), p_param1);
callback.waitUntilDone(evb);
if (returnState.isException()) {
returnState.exception().throw_exception();
}
returnState.resetProtocolId(protocolId);
returnState.resetCtx(std::move(ctx));
SCOPE_EXIT {
if (returnState.header() && !returnState.header()->getHeaders().empty()) {
rpcOptions.setReadHeaders(returnState.header()->releaseHeaders());
}
};
return folly::fibers::runInMainContext([&] {
recv_setstruct_ret_set_param(_return, returnState);
});
}
folly::Future<::std::set<::some::valid::ns::MyStruct>> ParamServiceAsyncClient::future_setstruct_ret_set_param(const ::std::set<::std::string>& p_param1) {
::apache::thrift::RpcOptions rpcOptions;
return future_setstruct_ret_set_param(rpcOptions, p_param1);
}
folly::SemiFuture<::std::set<::some::valid::ns::MyStruct>> ParamServiceAsyncClient::semifuture_setstruct_ret_set_param(const ::std::set<::std::string>& p_param1) {
::apache::thrift::RpcOptions rpcOptions;
return semifuture_setstruct_ret_set_param(rpcOptions, p_param1);
}
folly::Future<::std::set<::some::valid::ns::MyStruct>> ParamServiceAsyncClient::future_setstruct_ret_set_param(apache::thrift::RpcOptions& rpcOptions, const ::std::set<::std::string>& p_param1) {
folly::Promise<::std::set<::some::valid::ns::MyStruct>> promise;
auto future = promise.getFuture();
auto callback = std::make_unique<apache::thrift::FutureCallback<::std::set<::some::valid::ns::MyStruct>>>(std::move(promise), recv_wrapped_setstruct_ret_set_param, channel_);
setstruct_ret_set_param(rpcOptions, std::move(callback), p_param1);
return future;
}
folly::SemiFuture<::std::set<::some::valid::ns::MyStruct>> ParamServiceAsyncClient::semifuture_setstruct_ret_set_param(apache::thrift::RpcOptions& rpcOptions, const ::std::set<::std::string>& p_param1) {
auto callbackAndFuture = makeSemiFutureCallback(recv_wrapped_setstruct_ret_set_param, channel_);
auto callback = std::move(callbackAndFuture.first);
setstruct_ret_set_param(rpcOptions, std::move(callback), p_param1);
return std::move(callbackAndFuture.second);
}
folly::Future<std::pair<::std::set<::some::valid::ns::MyStruct>, std::unique_ptr<apache::thrift::transport::THeader>>> ParamServiceAsyncClient::header_future_setstruct_ret_set_param(apache::thrift::RpcOptions& rpcOptions, const ::std::set<::std::string>& p_param1) {
folly::Promise<std::pair<::std::set<::some::valid::ns::MyStruct>, std::unique_ptr<apache::thrift::transport::THeader>>> promise;
auto future = promise.getFuture();
auto callback = std::make_unique<apache::thrift::HeaderFutureCallback<::std::set<::some::valid::ns::MyStruct>>>(std::move(promise), recv_wrapped_setstruct_ret_set_param, channel_);
setstruct_ret_set_param(rpcOptions, std::move(callback), p_param1);
return future;
}
folly::SemiFuture<std::pair<::std::set<::some::valid::ns::MyStruct>, std::unique_ptr<apache::thrift::transport::THeader>>> ParamServiceAsyncClient::header_semifuture_setstruct_ret_set_param(apache::thrift::RpcOptions& rpcOptions, const ::std::set<::std::string>& p_param1) {
auto callbackAndFuture = makeHeaderSemiFutureCallback(recv_wrapped_setstruct_ret_set_param, channel_);
auto callback = std::move(callbackAndFuture.first);
setstruct_ret_set_param(rpcOptions, std::move(callback), p_param1);
return std::move(callbackAndFuture.second);
}
void ParamServiceAsyncClient::setstruct_ret_set_param(folly::Function<void (::apache::thrift::ClientReceiveState&&)> callback, const ::std::set<::std::string>& p_param1) {
setstruct_ret_set_param(std::make_unique<apache::thrift::FunctionReplyCallback>(std::move(callback)), p_param1);
}
#if FOLLY_HAS_COROUTINES
#endif // FOLLY_HAS_COROUTINES
folly::exception_wrapper ParamServiceAsyncClient::recv_wrapped_setstruct_ret_set_param(::std::set<::some::valid::ns::MyStruct>& _return, ::apache::thrift::ClientReceiveState& state) {
if (state.isException()) {
return std::move(state.exception());
}
if (!state.hasResponseBuffer()) {
return folly::make_exception_wrapper<apache::thrift::TApplicationException>("recv_ called without result");
}
using result = ParamService_setstruct_ret_set_param_presult;
switch (state.protocolId()) {
case apache::thrift::protocol::T_BINARY_PROTOCOL:
{
apache::thrift::BinaryProtocolReader reader;
return apache::thrift::detail::ac::recv_wrapped<result>(
&reader, state, _return);
}
case apache::thrift::protocol::T_COMPACT_PROTOCOL:
{
apache::thrift::CompactProtocolReader reader;
return apache::thrift::detail::ac::recv_wrapped<result>(
&reader, state, _return);
}
default:
{
}
}
return folly::make_exception_wrapper<apache::thrift::TApplicationException>("Could not find Protocol");
}
void ParamServiceAsyncClient::recv_setstruct_ret_set_param(::std::set<::some::valid::ns::MyStruct>& _return, ::apache::thrift::ClientReceiveState& state) {
auto ew = recv_wrapped_setstruct_ret_set_param(_return, state);
if (ew) {
ew.throw_exception();
}
}
void ParamServiceAsyncClient::recv_instance_setstruct_ret_set_param(::std::set<::some::valid::ns::MyStruct>& _return, ::apache::thrift::ClientReceiveState& state) {
return recv_setstruct_ret_set_param(_return, state);
}
folly::exception_wrapper ParamServiceAsyncClient::recv_instance_wrapped_setstruct_ret_set_param(::std::set<::some::valid::ns::MyStruct>& _return, ::apache::thrift::ClientReceiveState& state) {
return recv_wrapped_setstruct_ret_set_param(_return, state);
}
void ParamServiceAsyncClient::union_ret_i32_i32_param(std::unique_ptr<apache::thrift::RequestCallback> callback, ::std::int32_t p_param1, ::std::int32_t p_param2) {
::apache::thrift::RpcOptions rpcOptions;
union_ret_i32_i32_param(rpcOptions, std::move(callback), p_param1, p_param2);
}
void ParamServiceAsyncClient::union_ret_i32_i32_param(apache::thrift::RpcOptions& rpcOptions, std::unique_ptr<apache::thrift::RequestCallback> callback, ::std::int32_t p_param1, ::std::int32_t p_param2) {
auto [ctx, header] = union_ret_i32_i32_paramCtx(&rpcOptions);
apache::thrift::RequestCallback::Context callbackContext;
callbackContext.protocolId =
apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId();
auto* contextStack = ctx.get();
if (callback) {
callbackContext.ctx = std::move(ctx);
}
auto wrappedCallback = apache::thrift::toRequestClientCallbackPtr(std::move(callback), std::move(callbackContext));
union_ret_i32_i32_paramImpl(rpcOptions, std::move(header), contextStack, std::move(wrappedCallback), p_param1, p_param2);
}
void ParamServiceAsyncClient::union_ret_i32_i32_paramImpl(const apache::thrift::RpcOptions& rpcOptions, std::shared_ptr<apache::thrift::transport::THeader> header, apache::thrift::ContextStack* contextStack, apache::thrift::RequestClientCallback::Ptr callback, ::std::int32_t p_param1, ::std::int32_t p_param2) {
switch (apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId()) {
case apache::thrift::protocol::T_BINARY_PROTOCOL:
{
apache::thrift::BinaryProtocolWriter writer;
union_ret_i32_i32_paramT(&writer, rpcOptions, std::move(header), contextStack, std::move(callback), p_param1, p_param2);
break;
}
case apache::thrift::protocol::T_COMPACT_PROTOCOL:
{
apache::thrift::CompactProtocolWriter writer;
union_ret_i32_i32_paramT(&writer, rpcOptions, std::move(header), contextStack, std::move(callback), p_param1, p_param2);
break;
}
default:
{
apache::thrift::detail::ac::throw_app_exn("Could not find Protocol");
}
}
}
std::pair<std::unique_ptr<::apache::thrift::ContextStack>, std::shared_ptr<::apache::thrift::transport::THeader>> ParamServiceAsyncClient::union_ret_i32_i32_paramCtx(apache::thrift::RpcOptions* rpcOptions) {
auto header = std::make_shared<apache::thrift::transport::THeader>(
apache::thrift::transport::THeader::ALLOW_BIG_FRAMES);
header->setProtocolId(channel_->getProtocolId());
if (rpcOptions) {
header->setHeaders(rpcOptions->releaseWriteHeaders());
}
auto ctx = apache::thrift::ContextStack::createWithClientContext(
handlers_,
getServiceName(),
"ParamService.union_ret_i32_i32_param",
*header);
return {std::move(ctx), std::move(header)};
}
void ParamServiceAsyncClient::sync_union_ret_i32_i32_param(::some::valid::ns::ComplexUnion& _return, ::std::int32_t p_param1, ::std::int32_t p_param2) {
::apache::thrift::RpcOptions rpcOptions;
sync_union_ret_i32_i32_param(rpcOptions, _return, p_param1, p_param2);
}
void ParamServiceAsyncClient::sync_union_ret_i32_i32_param(apache::thrift::RpcOptions& rpcOptions, ::some::valid::ns::ComplexUnion& _return, ::std::int32_t p_param1, ::std::int32_t p_param2) {
apache::thrift::ClientReceiveState returnState;
apache::thrift::ClientSyncCallback<false> callback(&returnState);
auto protocolId = apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId();
auto evb = apache::thrift::GeneratedAsyncClient::getChannel()->getEventBase();
auto [ctx, header] = union_ret_i32_i32_paramCtx(&rpcOptions);
auto wrappedCallback = apache::thrift::RequestClientCallback::Ptr(&callback);
union_ret_i32_i32_paramImpl(rpcOptions, std::move(header), ctx.get(), std::move(wrappedCallback), p_param1, p_param2);
callback.waitUntilDone(evb);
if (returnState.isException()) {
returnState.exception().throw_exception();
}
returnState.resetProtocolId(protocolId);
returnState.resetCtx(std::move(ctx));
SCOPE_EXIT {
if (returnState.header() && !returnState.header()->getHeaders().empty()) {
rpcOptions.setReadHeaders(returnState.header()->releaseHeaders());
}
};
return folly::fibers::runInMainContext([&] {
recv_union_ret_i32_i32_param(_return, returnState);
});
}
folly::Future<::some::valid::ns::ComplexUnion> ParamServiceAsyncClient::future_union_ret_i32_i32_param(::std::int32_t p_param1, ::std::int32_t p_param2) {
::apache::thrift::RpcOptions rpcOptions;
return future_union_ret_i32_i32_param(rpcOptions, p_param1, p_param2);
}
folly::SemiFuture<::some::valid::ns::ComplexUnion> ParamServiceAsyncClient::semifuture_union_ret_i32_i32_param(::std::int32_t p_param1, ::std::int32_t p_param2) {
::apache::thrift::RpcOptions rpcOptions;
return semifuture_union_ret_i32_i32_param(rpcOptions, p_param1, p_param2);
}
folly::Future<::some::valid::ns::ComplexUnion> ParamServiceAsyncClient::future_union_ret_i32_i32_param(apache::thrift::RpcOptions& rpcOptions, ::std::int32_t p_param1, ::std::int32_t p_param2) {
folly::Promise<::some::valid::ns::ComplexUnion> promise;
auto future = promise.getFuture();
auto callback = std::make_unique<apache::thrift::FutureCallback<::some::valid::ns::ComplexUnion>>(std::move(promise), recv_wrapped_union_ret_i32_i32_param, channel_);
union_ret_i32_i32_param(rpcOptions, std::move(callback), p_param1, p_param2);
return future;
}
folly::SemiFuture<::some::valid::ns::ComplexUnion> ParamServiceAsyncClient::semifuture_union_ret_i32_i32_param(apache::thrift::RpcOptions& rpcOptions, ::std::int32_t p_param1, ::std::int32_t p_param2) {
auto callbackAndFuture = makeSemiFutureCallback(recv_wrapped_union_ret_i32_i32_param, channel_);
auto callback = std::move(callbackAndFuture.first);
union_ret_i32_i32_param(rpcOptions, std::move(callback), p_param1, p_param2);
return std::move(callbackAndFuture.second);
}
folly::Future<std::pair<::some::valid::ns::ComplexUnion, std::unique_ptr<apache::thrift::transport::THeader>>> ParamServiceAsyncClient::header_future_union_ret_i32_i32_param(apache::thrift::RpcOptions& rpcOptions, ::std::int32_t p_param1, ::std::int32_t p_param2) {
folly::Promise<std::pair<::some::valid::ns::ComplexUnion, std::unique_ptr<apache::thrift::transport::THeader>>> promise;
auto future = promise.getFuture();
auto callback = std::make_unique<apache::thrift::HeaderFutureCallback<::some::valid::ns::ComplexUnion>>(std::move(promise), recv_wrapped_union_ret_i32_i32_param, channel_);
union_ret_i32_i32_param(rpcOptions, std::move(callback), p_param1, p_param2);
return future;
}
folly::SemiFuture<std::pair<::some::valid::ns::ComplexUnion, std::unique_ptr<apache::thrift::transport::THeader>>> ParamServiceAsyncClient::header_semifuture_union_ret_i32_i32_param(apache::thrift::RpcOptions& rpcOptions, ::std::int32_t p_param1, ::std::int32_t p_param2) {
auto callbackAndFuture = makeHeaderSemiFutureCallback(recv_wrapped_union_ret_i32_i32_param, channel_);
auto callback = std::move(callbackAndFuture.first);
union_ret_i32_i32_param(rpcOptions, std::move(callback), p_param1, p_param2);
return std::move(callbackAndFuture.second);
}
void ParamServiceAsyncClient::union_ret_i32_i32_param(folly::Function<void (::apache::thrift::ClientReceiveState&&)> callback, ::std::int32_t p_param1, ::std::int32_t p_param2) {
union_ret_i32_i32_param(std::make_unique<apache::thrift::FunctionReplyCallback>(std::move(callback)), p_param1, p_param2);
}
#if FOLLY_HAS_COROUTINES
#endif // FOLLY_HAS_COROUTINES
folly::exception_wrapper ParamServiceAsyncClient::recv_wrapped_union_ret_i32_i32_param(::some::valid::ns::ComplexUnion& _return, ::apache::thrift::ClientReceiveState& state) {
if (state.isException()) {
return std::move(state.exception());
}
if (!state.hasResponseBuffer()) {
return folly::make_exception_wrapper<apache::thrift::TApplicationException>("recv_ called without result");
}
using result = ParamService_union_ret_i32_i32_param_presult;
switch (state.protocolId()) {
case apache::thrift::protocol::T_BINARY_PROTOCOL:
{
apache::thrift::BinaryProtocolReader reader;
return apache::thrift::detail::ac::recv_wrapped<result>(
&reader, state, _return);
}
case apache::thrift::protocol::T_COMPACT_PROTOCOL:
{
apache::thrift::CompactProtocolReader reader;
return apache::thrift::detail::ac::recv_wrapped<result>(
&reader, state, _return);
}
default:
{
}
}
return folly::make_exception_wrapper<apache::thrift::TApplicationException>("Could not find Protocol");
}
void ParamServiceAsyncClient::recv_union_ret_i32_i32_param(::some::valid::ns::ComplexUnion& _return, ::apache::thrift::ClientReceiveState& state) {
auto ew = recv_wrapped_union_ret_i32_i32_param(_return, state);
if (ew) {
ew.throw_exception();
}
}
void ParamServiceAsyncClient::recv_instance_union_ret_i32_i32_param(::some::valid::ns::ComplexUnion& _return, ::apache::thrift::ClientReceiveState& state) {
return recv_union_ret_i32_i32_param(_return, state);
}
folly::exception_wrapper ParamServiceAsyncClient::recv_instance_wrapped_union_ret_i32_i32_param(::some::valid::ns::ComplexUnion& _return, ::apache::thrift::ClientReceiveState& state) {
return recv_wrapped_union_ret_i32_i32_param(_return, state);
}
void ParamServiceAsyncClient::listunion_string_param(std::unique_ptr<apache::thrift::RequestCallback> callback, const ::std::string& p_param1) {
::apache::thrift::RpcOptions rpcOptions;
listunion_string_param(rpcOptions, std::move(callback), p_param1);
}
void ParamServiceAsyncClient::listunion_string_param(apache::thrift::RpcOptions& rpcOptions, std::unique_ptr<apache::thrift::RequestCallback> callback, const ::std::string& p_param1) {
auto [ctx, header] = listunion_string_paramCtx(&rpcOptions);
apache::thrift::RequestCallback::Context callbackContext;
callbackContext.protocolId =
apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId();
auto* contextStack = ctx.get();
if (callback) {
callbackContext.ctx = std::move(ctx);
}
auto wrappedCallback = apache::thrift::toRequestClientCallbackPtr(std::move(callback), std::move(callbackContext));
listunion_string_paramImpl(rpcOptions, std::move(header), contextStack, std::move(wrappedCallback), p_param1);
}
void ParamServiceAsyncClient::listunion_string_paramImpl(const apache::thrift::RpcOptions& rpcOptions, std::shared_ptr<apache::thrift::transport::THeader> header, apache::thrift::ContextStack* contextStack, apache::thrift::RequestClientCallback::Ptr callback, const ::std::string& p_param1) {
switch (apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId()) {
case apache::thrift::protocol::T_BINARY_PROTOCOL:
{
apache::thrift::BinaryProtocolWriter writer;
listunion_string_paramT(&writer, rpcOptions, std::move(header), contextStack, std::move(callback), p_param1);
break;
}
case apache::thrift::protocol::T_COMPACT_PROTOCOL:
{
apache::thrift::CompactProtocolWriter writer;
listunion_string_paramT(&writer, rpcOptions, std::move(header), contextStack, std::move(callback), p_param1);
break;
}
default:
{
apache::thrift::detail::ac::throw_app_exn("Could not find Protocol");
}
}
}
std::pair<std::unique_ptr<::apache::thrift::ContextStack>, std::shared_ptr<::apache::thrift::transport::THeader>> ParamServiceAsyncClient::listunion_string_paramCtx(apache::thrift::RpcOptions* rpcOptions) {
auto header = std::make_shared<apache::thrift::transport::THeader>(
apache::thrift::transport::THeader::ALLOW_BIG_FRAMES);
header->setProtocolId(channel_->getProtocolId());
if (rpcOptions) {
header->setHeaders(rpcOptions->releaseWriteHeaders());
}
auto ctx = apache::thrift::ContextStack::createWithClientContext(
handlers_,
getServiceName(),
"ParamService.listunion_string_param",
*header);
return {std::move(ctx), std::move(header)};
}
void ParamServiceAsyncClient::sync_listunion_string_param(::std::vector<::some::valid::ns::ComplexUnion>& _return, const ::std::string& p_param1) {
::apache::thrift::RpcOptions rpcOptions;
sync_listunion_string_param(rpcOptions, _return, p_param1);
}
void ParamServiceAsyncClient::sync_listunion_string_param(apache::thrift::RpcOptions& rpcOptions, ::std::vector<::some::valid::ns::ComplexUnion>& _return, const ::std::string& p_param1) {
apache::thrift::ClientReceiveState returnState;
apache::thrift::ClientSyncCallback<false> callback(&returnState);
auto protocolId = apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId();
auto evb = apache::thrift::GeneratedAsyncClient::getChannel()->getEventBase();
auto [ctx, header] = listunion_string_paramCtx(&rpcOptions);
auto wrappedCallback = apache::thrift::RequestClientCallback::Ptr(&callback);
listunion_string_paramImpl(rpcOptions, std::move(header), ctx.get(), std::move(wrappedCallback), p_param1);
callback.waitUntilDone(evb);
if (returnState.isException()) {
returnState.exception().throw_exception();
}
returnState.resetProtocolId(protocolId);
returnState.resetCtx(std::move(ctx));
SCOPE_EXIT {
if (returnState.header() && !returnState.header()->getHeaders().empty()) {
rpcOptions.setReadHeaders(returnState.header()->releaseHeaders());
}
};
return folly::fibers::runInMainContext([&] {
recv_listunion_string_param(_return, returnState);
});
}
folly::Future<::std::vector<::some::valid::ns::ComplexUnion>> ParamServiceAsyncClient::future_listunion_string_param(const ::std::string& p_param1) {
::apache::thrift::RpcOptions rpcOptions;
return future_listunion_string_param(rpcOptions, p_param1);
}
folly::SemiFuture<::std::vector<::some::valid::ns::ComplexUnion>> ParamServiceAsyncClient::semifuture_listunion_string_param(const ::std::string& p_param1) {
::apache::thrift::RpcOptions rpcOptions;
return semifuture_listunion_string_param(rpcOptions, p_param1);
}
folly::Future<::std::vector<::some::valid::ns::ComplexUnion>> ParamServiceAsyncClient::future_listunion_string_param(apache::thrift::RpcOptions& rpcOptions, const ::std::string& p_param1) {
folly::Promise<::std::vector<::some::valid::ns::ComplexUnion>> promise;
auto future = promise.getFuture();
auto callback = std::make_unique<apache::thrift::FutureCallback<::std::vector<::some::valid::ns::ComplexUnion>>>(std::move(promise), recv_wrapped_listunion_string_param, channel_);
listunion_string_param(rpcOptions, std::move(callback), p_param1);
return future;
}
folly::SemiFuture<::std::vector<::some::valid::ns::ComplexUnion>> ParamServiceAsyncClient::semifuture_listunion_string_param(apache::thrift::RpcOptions& rpcOptions, const ::std::string& p_param1) {
auto callbackAndFuture = makeSemiFutureCallback(recv_wrapped_listunion_string_param, channel_);
auto callback = std::move(callbackAndFuture.first);
listunion_string_param(rpcOptions, std::move(callback), p_param1);
return std::move(callbackAndFuture.second);
}
folly::Future<std::pair<::std::vector<::some::valid::ns::ComplexUnion>, std::unique_ptr<apache::thrift::transport::THeader>>> ParamServiceAsyncClient::header_future_listunion_string_param(apache::thrift::RpcOptions& rpcOptions, const ::std::string& p_param1) {
folly::Promise<std::pair<::std::vector<::some::valid::ns::ComplexUnion>, std::unique_ptr<apache::thrift::transport::THeader>>> promise;
auto future = promise.getFuture();
auto callback = std::make_unique<apache::thrift::HeaderFutureCallback<::std::vector<::some::valid::ns::ComplexUnion>>>(std::move(promise), recv_wrapped_listunion_string_param, channel_);
listunion_string_param(rpcOptions, std::move(callback), p_param1);
return future;
}
folly::SemiFuture<std::pair<::std::vector<::some::valid::ns::ComplexUnion>, std::unique_ptr<apache::thrift::transport::THeader>>> ParamServiceAsyncClient::header_semifuture_listunion_string_param(apache::thrift::RpcOptions& rpcOptions, const ::std::string& p_param1) {
auto callbackAndFuture = makeHeaderSemiFutureCallback(recv_wrapped_listunion_string_param, channel_);
auto callback = std::move(callbackAndFuture.first);
listunion_string_param(rpcOptions, std::move(callback), p_param1);
return std::move(callbackAndFuture.second);
}
void ParamServiceAsyncClient::listunion_string_param(folly::Function<void (::apache::thrift::ClientReceiveState&&)> callback, const ::std::string& p_param1) {
listunion_string_param(std::make_unique<apache::thrift::FunctionReplyCallback>(std::move(callback)), p_param1);
}
#if FOLLY_HAS_COROUTINES
#endif // FOLLY_HAS_COROUTINES
folly::exception_wrapper ParamServiceAsyncClient::recv_wrapped_listunion_string_param(::std::vector<::some::valid::ns::ComplexUnion>& _return, ::apache::thrift::ClientReceiveState& state) {
if (state.isException()) {
return std::move(state.exception());
}
if (!state.hasResponseBuffer()) {
return folly::make_exception_wrapper<apache::thrift::TApplicationException>("recv_ called without result");
}
using result = ParamService_listunion_string_param_presult;
switch (state.protocolId()) {
case apache::thrift::protocol::T_BINARY_PROTOCOL:
{
apache::thrift::BinaryProtocolReader reader;
return apache::thrift::detail::ac::recv_wrapped<result>(
&reader, state, _return);
}
case apache::thrift::protocol::T_COMPACT_PROTOCOL:
{
apache::thrift::CompactProtocolReader reader;
return apache::thrift::detail::ac::recv_wrapped<result>(
&reader, state, _return);
}
default:
{
}
}
return folly::make_exception_wrapper<apache::thrift::TApplicationException>("Could not find Protocol");
}
void ParamServiceAsyncClient::recv_listunion_string_param(::std::vector<::some::valid::ns::ComplexUnion>& _return, ::apache::thrift::ClientReceiveState& state) {
auto ew = recv_wrapped_listunion_string_param(_return, state);
if (ew) {
ew.throw_exception();
}
}
void ParamServiceAsyncClient::recv_instance_listunion_string_param(::std::vector<::some::valid::ns::ComplexUnion>& _return, ::apache::thrift::ClientReceiveState& state) {
return recv_listunion_string_param(_return, state);
}
folly::exception_wrapper ParamServiceAsyncClient::recv_instance_wrapped_listunion_string_param(::std::vector<::some::valid::ns::ComplexUnion>& _return, ::apache::thrift::ClientReceiveState& state) {
return recv_wrapped_listunion_string_param(_return, state);
}
}}} // some::valid::ns
|
/***************************************************************************
* Copyright (c) 2016, Johan Mabille and Sylvain Corlay *
* *
* Distributed under the terms of the BSD 3-Clause License. *
* *
* The full license is in the file LICENSE, distributed with this software. *
****************************************************************************/
#include "gtest/gtest.h"
#include <cstddef>
#include <iostream>
#include <stdexcept>
#include <string>
#include "test_utils.hpp"
#include "xproperty/xobserved.hpp"
struct Foo : xp::xobserved<Foo>
{
XPROPERTY(double, Foo, bar);
XPROPERTY(double, Foo, baz);
XPROPERTY(std::vector<std::string>, Foo, boz, {"Test"});
};
TEST(xproperty, basic)
{
Foo foo;
foo.bar = 1.0;
ASSERT_EQ(1.0, double(foo.bar));
foo.bar = 2.0;
ASSERT_EQ(2.0, double(foo.bar));
}
struct Wrapper : xp::xobserved<Wrapper>
{
XPROPERTY(Foo, Wrapper, foo);
};
TEST(xproperty, nested)
{
Wrapper wrapper;
wrapper.foo().bar = 1.;
ASSERT_EQ(1.0, double(wrapper.foo().bar));
}
struct Bat : xp::xobserved<Bat>
{
XPROPERTY(double, Bat, man, 1.0);
};
TEST(xproperty, default_values)
{
Bat bat;
ASSERT_EQ(1.0, double(bat.man));
}
template <class D>
struct str_base : xp::xobserved<D>
{
using derived_type = D;
XPROPERTY(std::string, derived_type, name);
};
struct str_final : str_base<str_final>
{
};
TEST(xproperty, string_conversion)
{
str_final str;
str.name = "test";
}
struct Ro : xp::xobserved<Ro>
{
XPROPERTY(double, Ro, bin, 1.0, [](double& i) { if (i < 0.0) i = 0.0; });
};
TEST(xproperty, lambda_validation)
{
Ro ro;
ASSERT_EQ(1.0, ro.bin());
ro.bin = -1.0;
ASSERT_EQ(0.0, ro.bin());
}
|
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <poll.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include "V4l2.h"
static int get_pixel_depth(unsigned int fmt)
{
int depth = 0;
switch (fmt)
{
case V4L2_PIX_FMT_NV12:
case V4L2_PIX_FMT_NV21:
case V4L2_PIX_FMT_YUV420:
case V4L2_PIX_FMT_YVU420:
depth = 12;
break;
case V4L2_PIX_FMT_RGB565:
case V4L2_PIX_FMT_YUYV:
case V4L2_PIX_FMT_YVYU:
case V4L2_PIX_FMT_UYVY:
case V4L2_PIX_FMT_VYUY:
case V4L2_PIX_FMT_NV16:
case V4L2_PIX_FMT_NV61:
case V4L2_PIX_FMT_YUV422P:
depth = 16;
break;
case V4L2_PIX_FMT_RGB32:
depth = 32;
break;
}
return depth;
}
int v4l2_open(const char* name, int flag)
{
int fd = open(name, flag);
if(fd < 0)
{
printf("ERR(%s):failed to open %s\n", __func__, name);
return -1;
}
return fd;
}
int v4l2_close(int fd)
{
if(close(fd))
{
printf("ERR(%s):failed to close v4l2 dev\n", __func__);
return -1;
}
return 0;
}
int v4l2_querycap(int fd, struct v4l2_capability* cap)
{
if (ioctl(fd, VIDIOC_QUERYCAP, cap) < 0)
{
printf("ERR(%s):VIDIOC_QUERYCAP failed\n", __func__);
return -1;
}
return 0;
}
int v4l2_enuminput(int fd, int index, char* name)
{
struct v4l2_input input;
int found = 0;
input.index = 0;
while(!ioctl(fd, VIDIOC_ENUMINPUT, &input))
{
//printf("input:%s\n", input.name);
if(input.index == index)
{
found = 1;
strcpy(name, (char*)input.name);
}
++input.index;
}
if(!found)
{
printf("%s:can't find input dev\n", __func__);
return -1;
}
return 0;
}
int v4l2_s_input(int fd, int index)
{
struct v4l2_input input;
input.index = index;
if (ioctl(fd, VIDIOC_S_INPUT, &input) < 0)
{
printf("ERR(%s):VIDIOC_S_INPUT failed\n", __func__);
return -1;
}
return 0;
}
int v4l2_enum_fmt(int fd, unsigned int fmt, enum v4l2_buf_type type)
{
struct v4l2_fmtdesc fmtdesc;
int found = 0;
fmtdesc.type = type;
fmtdesc.index = 0;
while (!ioctl(fd, VIDIOC_ENUM_FMT, &fmtdesc))
{
//printf("fmt:%s\n", fmtdesc.description);
if (fmtdesc.pixelformat == fmt)
{
found = 1;
break;
}
fmtdesc.index++;
}
if (!found)
{
printf("%s:unsupported pixel format\n", __func__);
return -1;
}
return 0;
}
int v4l2_s_fmt(int fd, int* width, int* height, unsigned int fmt, enum v4l2_buf_type type)
{
struct v4l2_format v4l2_fmt;
struct v4l2_pix_format pixfmt;
memset(&v4l2_fmt, 0, sizeof(struct v4l2_format));
v4l2_fmt.type = type;
memset(&pixfmt, 0, sizeof(pixfmt));
pixfmt.width = *width;
pixfmt.height = *height;
pixfmt.pixelformat = fmt;
pixfmt.sizeimage = (*width * *height * get_pixel_depth(fmt)) / 8;
pixfmt.field = V4L2_FIELD_ANY;
v4l2_fmt.fmt.pix = pixfmt;
if (ioctl(fd, VIDIOC_S_FMT, &v4l2_fmt) < 0)
{
printf("ERR(%s):VIDIOC_S_FMT failed\n", __func__);
return -1;
}
*width = v4l2_fmt.fmt.pix.width;
*height = v4l2_fmt.fmt.pix.height;
return 0;
}
struct v4l2_buf* v4l2_reqbufs(int fd, enum v4l2_buf_type type, int nr_bufs)
{
struct v4l2_requestbuffers req;
struct v4l2_buf* v4l2_buf;
int i;
req.count = nr_bufs;
req.type = type;
req.memory = V4L2_MEMORY_MMAP;
if (ioctl(fd, VIDIOC_REQBUFS, &req) < 0)
{
printf("ERR(%s):VIDIOC_REQBUFS failed\n", __func__);
return NULL;
}
v4l2_buf = (struct v4l2_buf*)malloc(sizeof(struct v4l2_buf));
v4l2_buf->nr_bufs = req.count;
v4l2_buf->buf = (struct v4l2_buf_unit*)malloc(sizeof(struct v4l2_buf_unit) * v4l2_buf->nr_bufs);
v4l2_buf->type = type;
memset(v4l2_buf->buf, 0, sizeof(struct v4l2_buf_unit) * v4l2_buf->nr_bufs);
return v4l2_buf;
}
int v4l2_querybuf(int fd, struct v4l2_buf* v4l2_buf)
{
struct v4l2_buffer buf;
struct v4l2_buf_unit* buf_unit;
int i;
for(i = 0; i < v4l2_buf->nr_bufs; ++i)
{
buf.type = v4l2_buf->type;
buf.memory = V4L2_MEMORY_MMAP;
buf.index = i;
if (ioctl(fd , VIDIOC_QUERYBUF, &buf) < 0)
{
printf("ERR(%s):VIDIOC_QUERYBUF failed\n", __func__);
return -1;
}
buf_unit = &v4l2_buf->buf[i];
buf_unit->index = i;
buf_unit->offset = buf.m.offset;
buf_unit->length = buf.length;
buf_unit->start = NULL;
}
return 0;
}
int v4l2_mmap(int fd, struct v4l2_buf* v4l2_buf)
{
int i;
struct v4l2_buf_unit* buf_unit;
for(i = 0; i < v4l2_buf->nr_bufs; ++i)
{
buf_unit = &v4l2_buf->buf[i];
buf_unit->start = mmap(0, buf_unit->length, PROT_READ | PROT_WRITE, MAP_SHARED,
fd, buf_unit->offset);
if(buf_unit->start < 0)
{
printf("ERR(%s):v4l2_mmap failed\n", __func__);
goto err;
}
}
return 0;
err:
while(--i >= 0)
{
buf_unit = &v4l2_buf->buf[i];
munmap(buf_unit->start, buf_unit->length);
buf_unit->start = NULL;
}
return -1;
}
int v4l2_munmap(int fd, struct v4l2_buf* v4l2_buf)
{
int i;
struct v4l2_buf_unit* buf_unit;
for(i = 0; i < v4l2_buf->nr_bufs; ++i)
{
buf_unit = &v4l2_buf->buf[i];
munmap(buf_unit->start, buf_unit->length);
buf_unit->start = NULL;
}
return 0;
}
int v4l2_relbufs(struct v4l2_buf* v4l2_buf)
{
int i = 0;
free(v4l2_buf->buf);
free(v4l2_buf);
return 0;
}
int v4l2_streamon(int fd)
{
enum v4l2_buf_type type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
if (ioctl(fd, VIDIOC_STREAMON, &type) < 0)
{
printf("ERR(%s):VIDIOC_STREAMON failed\n", __func__);
return -1;
}
if(v4l2_poll(fd) < 0)
return -1;
return 0;
}
int v4l2_streamoff(int fd)
{
enum v4l2_buf_type type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
if (ioctl(fd, VIDIOC_STREAMOFF, &type) < 0)
{
printf("ERR(%s):VIDIOC_STREAMOFF failed\n", __func__);
return -1;
}
return 0;
}
int v4l2_qbuf(int fd, struct v4l2_buf_unit* buf)
{
struct v4l2_buffer v4l2_buf;
v4l2_buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
v4l2_buf.memory = V4L2_MEMORY_MMAP;
v4l2_buf.index = buf->index;
if (ioctl(fd, VIDIOC_QBUF, &v4l2_buf) < 0)
{
printf("ERR(%s):VIDIOC_QBUF failed\n", __func__);
return -1;
}
return 0;
}
int v4l2_qbuf_all(int fd, struct v4l2_buf* v4l2_buf)
{
int i;
for(i = 0; i < v4l2_buf->nr_bufs; ++i)
{
if(v4l2_qbuf(fd, &v4l2_buf->buf[i]))
return -1;
}
return 0;
}
struct v4l2_buf_unit* v4l2_dqbuf(int fd, struct v4l2_buf* v4l2_buf)
{
struct v4l2_buffer buffer;
buffer.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
buffer.memory = V4L2_MEMORY_MMAP;
if (ioctl(fd, VIDIOC_DQBUF, &buffer) < 0)
{
printf("ERR(%s):VIDIOC_DQBUF failed, dropped frame\n", __func__);
return NULL;
}
return &v4l2_buf->buf[buffer.index];
}
int v4l2_g_ctrl(int fd, unsigned int id)
{
struct v4l2_control ctrl;
ctrl.id = id;
if (ioctl(fd, VIDIOC_G_CTRL, &ctrl) < 0)
{
printf("ERR(%s): VIDIOC_G_CTRL(id = 0x%x (%d)) failed\n",
__func__, id, id-V4L2_CID_PRIVATE_BASE);
return -1;
}
return ctrl.value;
}
int v4l2_s_ctrl(int fd, unsigned int id, unsigned int value)
{
struct v4l2_control ctrl;
ctrl.id = id;
ctrl.value = value;
if (ioctl(fd, VIDIOC_S_CTRL, &ctrl) < 0)
{
printf("ERR(%s):VIDIOC_S_CTRL(id = %#x (%d), value = %d) failed\n",
__func__, id, id-V4L2_CID_PRIVATE_BASE, value);
return -1;
}
return ctrl.value;
}
int v4l2_g_parm(int fd, struct v4l2_streamparm* streamparm)
{
streamparm->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
if (ioctl(fd, VIDIOC_G_PARM, streamparm) < 0)
{
printf("ERR(%s):VIDIOC_G_PARM failed\n", __func__);
return -1;
}
return 0;
}
int v4l2_s_parm(int fd, struct v4l2_streamparm *streamparm)
{
streamparm->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
if (ioctl(fd, VIDIOC_S_PARM, streamparm) < 0)
{
printf("ERR(%s):VIDIOC_S_PARM failed\n", __func__);
return -1;
}
return 0;
}
int v4l2_poll(int fd)
{
int ret;
struct pollfd poll_fds[1];
poll_fds[0].fd = fd;
poll_fds[0].events = POLLIN;
ret = poll(poll_fds, 1, 10000);
if (ret < 0)
{
printf("ERR(%s):poll error\n", __func__);
return -1;
}
if (ret == 0)
{
printf("ERR(%s):No data in 10 secs..\n", __func__);
return -1;
}
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.